feat(dev-task): 开发任务模块 V1 完整实现

- 核心库:dev-task.ts(类型+状态机+进度计算)、task-worklog.ts(工时)、task-category.ts(字典)、work-item.ts(聚合契约)
- Store:useDevTaskStore(CRUD+状态流转)、useTaskWorklogStore(工时记录)、useTaskCategoryStore(字典管理)
- UI组件:DevTaskTab、DevTaskCreateModal、DevTaskDetailDrawer、DevTaskRow、WorklogPanel、StatusBadge、CategoryChip
- 集成:版本详情页"开发任务"Tab、"与我相关"工作台开发任务分组、任务类型管理页
- 设计文档:spec + 实施计划

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Script Generator
2026-06-11 18:02:07 +08:00
parent 8bc23fbf3d
commit a560634091
20 changed files with 3054 additions and 6 deletions

View File

@@ -0,0 +1,73 @@
'use client';
import { useState, useEffect } from 'react';
import { Plus, Pencil, Trash2, Shield } from 'lucide-react';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { CATEGORY_GROUP_LABEL } from '@/lib/task-category';
import type { CategoryGroup } from '@/lib/task-category';
export default function CategoriesPage() {
const { categories, fetchCategories, addCategory, updateCategory, deleteCategory } = useTaskCategoryStore();
useEffect(() => { fetchCategories(); }, [fetchCategories]);
const [newName, setNewName] = useState('');
const [newGroup, setNewGroup] = useState<CategoryGroup>('development');
const [editingId, setEditingId] = useState<string | null>(null);
const [editName, setEditName] = useState('');
const groups: CategoryGroup[] = ['development', 'testing', 'implementation', 'other'];
const handleAdd = () => {
if (!newName.trim()) return;
addCategory(newName.trim(), newGroup);
setNewName('');
};
const handleSaveEdit = (id: string) => {
if (editName.trim()) updateCategory(id, { name: editName.trim() });
setEditingId(null);
};
return (
<div className="p-6 max-w-2xl mx-auto space-y-6">
<h1 className="text-[16px] font-semibold text-[var(--ink)]"></h1>
<div className="flex gap-2">
<input value={newName} onChange={(e) => setNewName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleAdd(); }} placeholder="新类型名称" className="flex-1 h-9 rounded-lg border border-[var(--line)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
<select value={newGroup} onChange={(e) => setNewGroup(e.target.value as CategoryGroup)} className="h-9 rounded-lg border border-[var(--line)] px-3 text-[13px]">
{groups.map((g) => <option key={g} value={g}>{CATEGORY_GROUP_LABEL[g]}</option>)}
</select>
<button onClick={handleAdd} className="h-9 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]"><Plus className="h-3.5 w-3.5 inline mr-1" /></button>
</div>
{groups.map((g) => {
const items = categories.filter((c) => c.group === g);
if (items.length === 0) return null;
return (
<div key={g}>
<h2 className="text-[13px] font-medium text-[var(--ink-soft)] mb-2">{CATEGORY_GROUP_LABEL[g]}</h2>
<div className="rounded-lg border border-[var(--line)] divide-y divide-[var(--line)]">
{items.map((cat) => (
<div key={cat.id} className="flex items-center gap-3 px-4 py-2.5">
{cat.color && <span className="h-3 w-3 rounded-full shrink-0" style={{ backgroundColor: cat.color }} />}
{editingId === cat.id ? (
<input value={editName} onChange={(e) => setEditName(e.target.value)} onBlur={() => handleSaveEdit(cat.id)} onKeyDown={(e) => { if (e.key === 'Enter') handleSaveEdit(cat.id); }} autoFocus className="flex-1 h-7 rounded border border-[var(--line)] px-2 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
) : (
<span className="flex-1 text-[13px] text-[var(--ink)]">{cat.name}</span>
)}
{cat.isSystem && <span title="系统预置"><Shield className="h-3 w-3 text-[var(--ink-muted)]" /></span>}
{!cat.isSystem && (
<>
<button onClick={() => { setEditingId(cat.id); setEditName(cat.name); }} className="p-1 rounded hover:bg-[var(--bg-subtle)]"><Pencil className="h-3 w-3 text-[var(--ink-muted)]" /></button>
<button onClick={() => deleteCategory(cat.id)} className="p-1 rounded hover:bg-red-50"><Trash2 className="h-3 w-3 text-[var(--ink-muted)] hover:text-red-500" /></button>
</>
)}
</div>
))}
</div>
</div>
);
})}
</div>
);
}

View File

@@ -17,6 +17,7 @@ import { REQ_STATUS_LABEL, REQ_STATUS_COLOR } from '@/lib/requirement';
import { OVERTIME_REASON_LABEL } from '@/lib/overtime'; import { OVERTIME_REASON_LABEL } from '@/lib/overtime';
import { VersionRequirementsTab } from '@/components/version/VersionRequirementsTab'; import { VersionRequirementsTab } from '@/components/version/VersionRequirementsTab';
import { PlanTab } from '@/components/version/PlanTab'; import { PlanTab } from '@/components/version/PlanTab';
import { DevTaskTab } from '@/components/dev-task/DevTaskTab';
import { useVersionPlanStore } from '@/stores/useVersionPlanStore'; import { useVersionPlanStore } from '@/stores/useVersionPlanStore';
import { useAuthStore } from '@/stores/useAuthStore'; import { useAuthStore } from '@/stores/useAuthStore';
@@ -450,6 +451,16 @@ export default function VersionDetailPage() {
/> />
); );
})() })()
) : activeTab === 'tasks' ? (
(() => {
const versionReqs = requirements.filter((r) => r.versionId === version.id);
return (
<DevTaskTab
versionId={version.id}
requirementIds={versionReqs.map((r) => r.id)}
/>
);
})()
) : ( ) : (
<div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-12 flex items-center justify-center"> <div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-12 flex items-center justify-center">
<span className="text-[13px] text-[var(--ink-muted)]"></span> <span className="text-[13px] text-[var(--ink-muted)]"></span>

View File

@@ -2,22 +2,27 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { Search, FileText, Palette, Layout, ClipboardList, Check, ExternalLink, Link2, FileUp } from 'lucide-react'; import { Search, FileText, Palette, Layout, ClipboardList, Check, ExternalLink, Link2, FileUp, Code2 } from 'lucide-react';
import { useProductStore } from '@/stores/useProductStore'; import { useProductStore } from '@/stores/useProductStore';
import { useVersionPlanStore } from '@/stores/useVersionPlanStore'; import { useVersionPlanStore } from '@/stores/useVersionPlanStore';
import { useRequirementStore } from '@/stores/useRequirementStore'; import { useRequirementStore } from '@/stores/useRequirementStore';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { useAuthStore } from '@/stores/useAuthStore'; import { useAuthStore } from '@/stores/useAuthStore';
import { flattenVersions } from '@/lib/derive'; import { flattenVersions } from '@/lib/derive';
import { calcPlanProgress, calcLinkedReqProgress } from '@/lib/version-plan'; import { calcPlanProgress, calcLinkedReqProgress } from '@/lib/version-plan';
import { DEV_TASK_STATUS_LABEL, DEV_TASK_STATUS_COLOR, formatHours } from '@/lib/dev-task';
import type { PlanTask, VersionPlan } from '@/lib/version-plan'; import type { PlanTask, VersionPlan } from '@/lib/version-plan';
import type { DevTask } from '@/lib/dev-task';
type TabKey = 'all' | 'research' | 'product' | 'ui'; type TabKey = 'all' | 'research' | 'product' | 'ui' | 'devTask';
const TABS: { key: TabKey; label: string; icon: any }[] = [ const TABS: { key: TabKey; label: string; icon: any }[] = [
{ key: 'all', label: '全部待办', icon: ClipboardList }, { key: 'all', label: '全部待办', icon: ClipboardList },
{ key: 'research', label: '调研', icon: Search }, { key: 'research', label: '调研', icon: Search },
{ key: 'product', label: '产品方案', icon: FileText }, { key: 'product', label: '产品方案', icon: FileText },
{ key: 'ui', label: 'UI设计', icon: Palette }, { key: 'ui', label: 'UI设计', icon: Palette },
{ key: 'devTask', label: '开发任务', icon: Code2 },
]; ];
export default function WorkspacePage() { export default function WorkspacePage() {
@@ -25,6 +30,8 @@ export default function WorkspacePage() {
const { overview, fetchOverview } = useProductStore(); const { overview, fetchOverview } = useProductStore();
const { plans, fetchPlans, updatePlan, completePlan } = useVersionPlanStore(); const { plans, fetchPlans, updatePlan, completePlan } = useVersionPlanStore();
const { requirements, fetchRequirements } = useRequirementStore(); const { requirements, fetchRequirements } = useRequirementStore();
const { tasks: devTasks, fetchTasks } = useDevTaskStore();
const { categories, fetchCategories } = useTaskCategoryStore();
const user = useAuthStore((s) => s.user); const user = useAuthStore((s) => s.user);
const [activeTab, setActiveTab] = useState<TabKey>('all'); const [activeTab, setActiveTab] = useState<TabKey>('all');
const [completingPlan, setCompletingPlan] = useState<VersionPlan | null>(null); const [completingPlan, setCompletingPlan] = useState<VersionPlan | null>(null);
@@ -32,6 +39,8 @@ export default function WorkspacePage() {
useEffect(() => { fetchOverview(); }, [fetchOverview]); useEffect(() => { fetchOverview(); }, [fetchOverview]);
useEffect(() => { fetchPlans(); }, [fetchPlans]); useEffect(() => { fetchPlans(); }, [fetchPlans]);
useEffect(() => { fetchRequirements(); }, [fetchRequirements]); useEffect(() => { fetchRequirements(); }, [fetchRequirements]);
useEffect(() => { fetchTasks(); }, [fetchTasks]);
useEffect(() => { fetchCategories(); }, [fetchCategories]);
const userName = user?.name ?? ''; const userName = user?.name ?? '';
const allVersions = useMemo(() => flattenVersions(overview), [overview]); const allVersions = useMemo(() => flattenVersions(overview), [overview]);
@@ -42,14 +51,21 @@ export default function WorkspacePage() {
[plans, userName] [plans, userName]
); );
// 我负责的所有未完成开发任务
const myDevTasks = useMemo(() =>
devTasks.filter((t) => t.assigneeId === userName && t.status !== 'done'),
[devTasks, userName]
);
const counts = { const counts = {
all: myPlans.length, all: myPlans.length + myDevTasks.length,
research: myPlans.filter((p) => p.type === 'research').length, research: myPlans.filter((p) => p.type === 'research').length,
product: myPlans.filter((p) => p.type === 'product').length, product: myPlans.filter((p) => p.type === 'product').length,
ui: myPlans.filter((p) => p.type === 'ui').length, ui: myPlans.filter((p) => p.type === 'ui').length,
devTask: myDevTasks.length,
}; };
const filtered = activeTab === 'all' ? myPlans : myPlans.filter((p) => p.type === activeTab); const filtered = activeTab === 'all' ? myPlans : activeTab === 'devTask' ? [] : myPlans.filter((p) => p.type === activeTab);
const today = new Date().toISOString().slice(0, 10); const today = new Date().toISOString().slice(0, 10);
const toggleTask = (plan: VersionPlan, task: PlanTask) => { const toggleTask = (plan: VersionPlan, task: PlanTask) => {
@@ -97,11 +113,44 @@ export default function WorkspacePage() {
<h2 className="text-[14px] font-semibold text-[var(--ink)]"> <h2 className="text-[14px] font-semibold text-[var(--ink)]">
{TABS.find((t) => t.key === activeTab)?.label} {TABS.find((t) => t.key === activeTab)?.label}
</h2> </h2>
<span className="ml-2 text-[12px] text-[var(--ink-muted)]">{filtered.length} </span> <span className="ml-2 text-[12px] text-[var(--ink-muted)]">{activeTab === 'devTask' ? myDevTasks.length : filtered.length} </span>
</header> </header>
<div className="flex-1 overflow-y-auto p-5 bg-[var(--bg)] space-y-3"> <div className="flex-1 overflow-y-auto p-5 bg-[var(--bg)] space-y-3">
{filtered.length === 0 ? ( {activeTab === 'devTask' ? (
myDevTasks.length === 0 ? (
<div className="rounded-xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] p-12 text-center">
<p className="text-[13px] text-[var(--ink-muted)]"></p>
</div>
) : (
myDevTasks.map((task) => {
const cat = categories.find((c) => c.id === task.categoryId);
const req = requirements.find((r) => r.id === task.requirementId);
return (
<div key={task.id} className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4">
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<span className={`text-[10px] font-medium px-2 py-0.5 rounded-full ${DEV_TASK_STATUS_COLOR[task.status]}`}>
{DEV_TASK_STATUS_LABEL[task.status]}
</span>
{task.isBlocked && <span className="text-[10px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded"></span>}
<span className="text-[11px] font-mono text-[var(--ink-muted)]">{task.taskNo}</span>
<span className="text-[14px] font-medium text-[var(--ink)]">{task.title}</span>
</div>
<span className="text-[11px] text-[var(--ink-muted)]">{task.priority}</span>
</div>
<div className="flex items-center gap-4 text-[11px] text-[var(--ink-muted)]">
{req && <span>{req.code} {req.title}</span>}
{cat && <span className="px-1.5 py-0.5 rounded text-[10px]" style={{ backgroundColor: cat.color ? `${cat.color}15` : undefined, color: cat.color }}>{cat.name}</span>}
<span> {formatHours(task.estimateHours)}</span>
{task.actualHours > 0 && <span> {task.actualHours}h</span>}
{task.dueDate && <span> {task.dueDate}</span>}
</div>
</div>
);
})
)
) : filtered.length === 0 ? (
<div className="rounded-xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] p-12 text-center"> <div className="rounded-xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] p-12 text-center">
<p className="text-[13px] text-[var(--ink-muted)]"></p> <p className="text-[13px] text-[var(--ink-muted)]"></p>
</div> </div>

View File

@@ -0,0 +1,18 @@
'use client';
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>;
return (
<span
className="inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium"
style={{
backgroundColor: category.color ? `${category.color}15` : 'var(--bg-subtle)',
color: category.color || 'var(--ink-soft)',
}}
>
{category.name}
</span>
);
}

View File

@@ -0,0 +1,148 @@
'use client';
import { useState, useMemo } from 'react';
import { X } from 'lucide-react';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useMemberStore } from '@/stores/useMemberStore';
import { useAuthStore } from '@/stores/useAuthStore';
import type { Priority } from '@/lib/derive';
interface Props {
versionId: string;
requirementIds: string[];
onClose: () => void;
onCreated?: () => void;
}
export function DevTaskCreateModal({ versionId, requirementIds, onClose, onCreated }: Props) {
const { createTask, tasks } = useDevTaskStore();
const { categories } = useTaskCategoryStore();
const { requirements } = useRequirementStore();
const { members } = useMemberStore();
const user = useAuthStore((s) => s.user);
const versionReqs = useMemo(
() => requirements.filter((r) => requirementIds.includes(r.id)),
[requirements, requirementIds],
);
const versionTasks = useMemo(
() => tasks.filter((t) => requirementIds.includes(t.requirementId)),
[tasks, requirementIds],
);
const [title, setTitle] = useState('');
const [requirementId, setRequirementId] = useState(versionReqs[0]?.id || '');
const [categoryId, setCategoryId] = useState(categories[0]?.id || '');
const [assigneeId, setAssigneeId] = useState('');
const [priority, setPriority] = useState<Priority>('P2');
const [estimateHours, setEstimateHours] = useState<number>(8);
const [dueDate, setDueDate] = useState('');
const [predecessorIds, setPredecessorIds] = useState<string[]>([]);
const [description, setDescription] = useState('');
const selectedReq = versionReqs.find((r) => r.id === requirementId);
const effectivePriority = selectedReq?.priority || priority;
const canSubmit = title.trim() && requirementId && categoryId && assigneeId && estimateHours > 0;
const handleSubmit = () => {
if (!canSubmit) return;
createTask({
requirementId,
title: title.trim(),
description: description.trim() || undefined,
categoryId,
assigneeId,
reviewerId: undefined,
priority: effectivePriority,
estimateHours,
startDate: undefined,
dueDate: dueDate || undefined,
completedAt: undefined,
status: 'todo',
blockReason: undefined,
blockedById: undefined,
predecessorIds: predecessorIds.length > 0 ? predecessorIds : undefined,
riskLevel: undefined,
createdBy: user?.name || '系统',
});
onCreated?.();
onClose();
};
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onClose}>
<div className="w-full max-w-lg rounded-2xl bg-[var(--bg-card)] border border-[var(--line)] p-6 shadow-[var(--shadow-md)]" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between mb-4">
<h3 className="text-[14px] font-semibold text-[var(--ink)]"></h3>
<button onClick={onClose} className="rounded-md p-1 hover:bg-[var(--bg-subtle)]"><X className="h-4 w-4 text-[var(--ink-muted)]" /></button>
</div>
<div className="space-y-3 max-h-[60vh] overflow-y-auto">
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"> *</label>
<input value={title} onChange={(e) => setTitle(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" placeholder="例如:排班界面开发" />
</div>
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"> *</label>
<select value={requirementId} onChange={(e) => { setRequirementId(e.target.value); const r = versionReqs.find((x) => x.id === e.target.value); if (r) setPriority(r.priority); }} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
{versionReqs.map((r) => <option key={r.id} value={r.id}>{r.code} {r.title}</option>)}
</select>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"> *</label>
<select value={categoryId} onChange={(e) => setCategoryId(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
{categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
</select>
</div>
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"> *</label>
<select value={assigneeId} onChange={(e) => setAssigneeId(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
<option value=""></option>
{members.map((m) => <option key={m.id} value={m.name}>{m.name}</option>)}
</select>
</div>
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"></label>
<select value={effectivePriority} onChange={(e) => setPriority(e.target.value as Priority)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none">
{(['P0','P1','P2','P3'] as Priority[]).map((p) => <option key={p} value={p}>{p}</option>)}
</select>
</div>
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1">(h) *</label>
<input type="number" min={0.5} step={0.5} value={estimateHours} onChange={(e) => setEstimateHours(parseFloat(e.target.value) || 0)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
</div>
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"></label>
<input type="date" value={dueDate} onChange={(e) => setDueDate(e.target.value)} className="h-9 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 text-[13px] focus:border-[var(--accent)] focus:outline-none" />
</div>
</div>
{versionTasks.length > 0 && (
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"></label>
<div className="space-y-1 max-h-28 overflow-y-auto border border-[var(--line)] rounded-lg p-2">
{versionTasks.map((t) => (
<label key={t.id} className="flex items-center gap-2 text-[12px] text-[var(--ink)]">
<input type="checkbox" checked={predecessorIds.includes(t.id)} onChange={(e) => setPredecessorIds(e.target.checked ? [...predecessorIds, t.id] : predecessorIds.filter((x) => x !== t.id))} />
<span className="text-[var(--ink-muted)] font-mono">{t.taskNo}</span> {t.title}
</label>
))}
</div>
</div>
)}
<div>
<label className="block text-[12px] text-[var(--ink-soft)] mb-1"></label>
<textarea rows={3} 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="任务描述(可选)" />
</div>
</div>
<div className="flex justify-end gap-2 pt-4 border-t border-[var(--line)] mt-4">
<button onClick={onClose} className="h-8 px-3 rounded-lg text-[12px] font-medium border border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]"></button>
<button onClick={handleSubmit} disabled={!canSubmit} className="h-8 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)] disabled:opacity-50"></button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,131 @@
'use client';
import { useState } from 'react';
import { X, AlertTriangle, Link2 } from 'lucide-react';
import { StatusBadge } from './StatusBadge';
import { CategoryChip } from './CategoryChip';
import { WorklogPanel } from './WorklogPanel';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { ALLOWED_TRANSITIONS, DEV_TASK_STATUS_LABEL, formatHours } from '@/lib/dev-task';
import type { DevTask, DevTaskStatus } from '@/lib/dev-task';
interface Props {
task: DevTask;
allTasks: DevTask[];
onClose: () => void;
}
export function DevTaskDetailDrawer({ task, allTasks, onClose }: Props) {
const { changeStatus, setBlocked } = useDevTaskStore();
const { categories } = useTaskCategoryStore();
const category = categories.find((c) => c.id === task.categoryId);
const [blockReason, setBlockReason] = useState(task.blockReason || '');
const [showBlockInput, setShowBlockInput] = useState(false);
const nextStatuses = ALLOWED_TRANSITIONS[task.status];
const predecessors = (task.predecessorIds || []).map((id) => allTasks.find((t) => t.id === id)).filter(Boolean) as DevTask[];
const handleTransition = (to: DevTaskStatus) => {
const result = changeStatus(task.id, to);
if (!result.ok) alert(result.message);
};
const handleBlock = () => {
if (!blockReason.trim()) return;
setBlocked(task.id, true, blockReason.trim());
setShowBlockInput(false);
};
const handleUnblock = () => {
setBlocked(task.id, false);
setBlockReason('');
};
return (
<div className="fixed inset-0 z-50 flex justify-end" onClick={onClose}>
<div className="w-full max-w-md h-full bg-[var(--bg-card)] border-l border-[var(--line)] shadow-[var(--shadow-lg)] flex flex-col" onClick={(e) => e.stopPropagation()}>
{/* Header */}
<div className="flex items-center justify-between h-14 px-5 border-b border-[var(--line)] shrink-0">
<div className="flex items-center gap-2">
<span className="text-[12px] font-mono text-[var(--ink-muted)]">{task.taskNo}</span>
<StatusBadge status={task.status} />
{task.isBlocked && <span className="text-[10px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded"></span>}
</div>
<button onClick={onClose} className="p-1 rounded hover:bg-[var(--bg-subtle)]"><X className="h-4 w-4" /></button>
</div>
{/* Body */}
<div className="flex-1 overflow-y-auto p-5 space-y-5">
<h2 className="text-[15px] font-semibold text-[var(--ink)]">{task.title}</h2>
{task.description && <p className="text-[12px] text-[var(--ink-soft)]">{task.description}</p>}
{/* 状态流转 */}
{nextStatuses.length > 0 && (
<div className="flex items-center gap-2">
<span className="text-[11px] text-[var(--ink-muted)]"></span>
{nextStatuses.map((s) => (
<button key={s} onClick={() => handleTransition(s)} className="h-7 px-3 rounded-md text-[11px] font-medium border border-[var(--line)] hover:border-[var(--accent)] hover:text-[var(--accent)] transition-colors">
{DEV_TASK_STATUS_LABEL[s]}
</button>
))}
</div>
)}
{/* 阻塞管理 */}
<div className="rounded-lg border border-[var(--line)] p-3 space-y-2">
<div className="flex items-center justify-between">
<span className="text-[12px] font-medium text-[var(--ink)]"></span>
{task.isBlocked ? (
<button onClick={handleUnblock} className="text-[11px] text-emerald-600 hover:underline"></button>
) : (
<button onClick={() => setShowBlockInput(true)} className="text-[11px] text-red-500 hover:underline"></button>
)}
</div>
{task.isBlocked && (
<div className="flex items-start gap-1.5 text-[12px] text-red-600 bg-red-50 rounded px-2 py-1.5">
<AlertTriangle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
<span>{task.blockReason}</span>
</div>
)}
{showBlockInput && !task.isBlocked && (
<div className="flex gap-2">
<input value={blockReason} onChange={(e) => setBlockReason(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleBlock(); }} placeholder="阻塞原因" className="flex-1 h-8 rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
<button onClick={handleBlock} className="h-8 px-3 rounded-md text-[11px] font-medium bg-red-500 text-white"></button>
</div>
)}
</div>
{/* 基本信息 */}
<div className="grid grid-cols-2 gap-3 text-[12px]">
<div><span className="text-[var(--ink-muted)]"></span><CategoryChip category={category} /></div>
<div><span className="text-[var(--ink-muted)]"></span><span className="text-[var(--ink)]">{task.assigneeId}</span></div>
<div><span className="text-[var(--ink-muted)]"></span><span className="text-[var(--ink)]">{task.priority}</span></div>
<div><span className="text-[var(--ink-muted)]"></span><span className="text-[var(--ink)]">{formatHours(task.estimateHours)}</span></div>
{task.dueDate && <div><span className="text-[var(--ink-muted)]"></span><span className="text-[var(--ink)]">{task.dueDate}</span></div>}
{task.completedAt && <div><span className="text-[var(--ink-muted)]"></span><span className="text-[var(--ink)]">{task.completedAt}</span></div>}
</div>
{/* 前置任务 */}
{predecessors.length > 0 && (
<div className="space-y-1.5">
<span className="text-[12px] font-medium text-[var(--ink)]"></span>
{predecessors.map((p) => (
<div key={p.id} className="flex items-center gap-2 text-[12px] px-2 py-1 rounded bg-[var(--bg-subtle)]">
<Link2 className="h-3 w-3 text-[var(--ink-muted)]" />
<span className="font-mono text-[var(--ink-muted)]">{p.taskNo}</span>
<span className="text-[var(--ink)]">{p.title}</span>
<StatusBadge status={p.status} />
</div>
))}
</div>
)}
{/* 工时记录 */}
<WorklogPanel taskId={task.id} />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,47 @@
'use client';
import { AlertTriangle } from 'lucide-react';
import { StatusBadge } from './StatusBadge';
import { CategoryChip } from './CategoryChip';
import { formatHours } from '@/lib/dev-task';
import type { DevTask } from '@/lib/dev-task';
import type { TaskCategory } from '@/lib/task-category';
interface Props {
task: DevTask;
category?: TaskCategory;
onClick?: () => void;
}
const PRIORITY_DOT: Record<string, string> = {
P0: 'bg-red-500',
P1: 'bg-orange-400',
P2: 'bg-blue-400',
P3: 'bg-zinc-300',
};
export function DevTaskRow({ task, category, onClick }: Props) {
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[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.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}>
<AlertTriangle className="h-2.5 w-2.5" />
</span>
)}
</div>
<CategoryChip category={category} />
<StatusBadge status={task.status} />
<span className="text-[11px] text-[var(--ink-muted)] w-20 text-right tabular-nums">
{task.actualHours > 0 ? `${task.actualHours}h/` : ''}{formatHours(task.estimateHours).split('')[0]}
</span>
<span className="text-[11px] text-[var(--ink-soft)] w-14 text-right truncate">{task.assigneeId}</span>
</div>
);
}

View File

@@ -0,0 +1,104 @@
'use client';
import { useState, useMemo, useEffect } from 'react';
import { Plus, Code2 } from 'lucide-react';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { useTaskWorklogStore } from '@/stores/useTaskWorklogStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { DevTaskRow } from './DevTaskRow';
import { DevTaskCreateModal } from './DevTaskCreateModal';
import { DevTaskDetailDrawer } from './DevTaskDetailDrawer';
import { calcGroupProgress } from '@/lib/dev-task';
import type { DevTask } from '@/lib/dev-task';
interface Props {
versionId: string;
requirementIds: string[];
}
export function DevTaskTab({ versionId, requirementIds }: Props) {
const { tasks, fetchTasks } = useDevTaskStore();
const { categories, fetchCategories } = useTaskCategoryStore();
const { fetchWorklogs } = useTaskWorklogStore();
const { requirements } = useRequirementStore();
useEffect(() => { fetchTasks(); }, [fetchTasks]);
useEffect(() => { fetchCategories(); }, [fetchCategories]);
useEffect(() => { fetchWorklogs(); }, [fetchWorklogs]);
const versionTasks = useMemo(
() => tasks.filter((t) => requirementIds.includes(t.requirementId)),
[tasks, requirementIds],
);
const progress = calcGroupProgress(versionTasks);
const totalEstimate = versionTasks.reduce((s, t) => s + t.estimateHours, 0);
const totalActual = versionTasks.reduce((s, t) => s + t.actualHours, 0);
const blockedCount = versionTasks.filter((t) => t.isBlocked).length;
const [showCreate, setShowCreate] = useState(false);
const [selectedTask, setSelectedTask] = useState<DevTask | null>(null);
const groupedByReq = useMemo(() => {
const map = new Map<string, DevTask[]>();
for (const t of versionTasks) {
const list = map.get(t.requirementId) || [];
list.push(t);
map.set(t.requirementId, list);
}
return map;
}, [versionTasks]);
return (
<div className="space-y-4">
{/* 统计栏 */}
<div className="flex items-center gap-4 px-4 py-3 rounded-lg bg-[var(--bg-subtle)] border border-[var(--line)]">
<div className="flex items-center gap-2">
<Code2 className="h-4 w-4 text-[var(--accent)]" />
<span className="text-[13px] font-medium text-[var(--ink)]"> {progress}%</span>
</div>
<div className="h-2 flex-1 rounded-full bg-[var(--bg)] overflow-hidden">
<div className="h-full rounded-full bg-[var(--accent)] transition-all" style={{ width: `${progress}%` }} />
</div>
<span className="text-[11px] text-[var(--ink-muted)] tabular-nums">
{versionTasks.length} · {totalActual}h / {totalEstimate}h
</span>
{blockedCount > 0 && (
<span className="text-[11px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded">{blockedCount} </span>
)}
<button onClick={() => setShowCreate(true)} className="ml-auto flex items-center gap-1 h-7 px-3 rounded-md text-[11px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]">
<Plus className="h-3 w-3" />
</button>
</div>
{/* 按需求分组列表 */}
{versionTasks.length === 0 ? (
<div className="rounded-xl border border-dashed border-[var(--line)] bg-[var(--bg-card)] p-12 text-center">
<p className="text-[13px] text-[var(--ink-muted)]"></p>
<button onClick={() => setShowCreate(true)} className="mt-3 text-[12px] text-[var(--accent)] hover:underline"></button>
</div>
) : (
Array.from(groupedByReq.entries()).map(([reqId, reqTasks]) => {
const req = requirements.find((r) => r.id === reqId);
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)]">
<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>
{reqTasks.map((t) => (
<DevTaskRow key={t.id} task={t} category={categories.find((c) => c.id === t.categoryId)} onClick={() => setSelectedTask(t)} />
))}
</div>
);
})
)}
{showCreate && <DevTaskCreateModal versionId={versionId} requirementIds={requirementIds} onClose={() => setShowCreate(false)} />}
{selectedTask && <DevTaskDetailDrawer task={selectedTask} allTasks={versionTasks} onClose={() => setSelectedTask(null)} />}
</div>
);
}

View File

@@ -0,0 +1,12 @@
'use client';
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 }) {
return (
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${DEV_TASK_STATUS_COLOR[status]}`}>
{DEV_TASK_STATUS_LABEL[status]}
</span>
);
}

View File

@@ -0,0 +1,85 @@
'use client';
import { useState } from 'react';
import { Plus, Trash2 } from 'lucide-react';
import { useTaskWorklogStore } from '@/stores/useTaskWorklogStore';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { getTaskWorklogs } from '@/lib/task-worklog';
interface Props {
taskId: string;
}
export function WorklogPanel({ taskId }: Props) {
const { worklogs, addWorklog, deleteWorklog } = useTaskWorklogStore();
const { syncActualHours } = useDevTaskStore();
const user = useAuthStore((s) => s.user);
const taskLogs = getTaskWorklogs(worklogs, taskId);
const totalHours = taskLogs.reduce((sum, w) => sum + w.hours, 0);
const today = new Date().toISOString().slice(0, 10);
const [date, setDate] = useState(today);
const [hours, setHours] = useState<number>(1);
const [workContent, setWorkContent] = useState('');
const [adding, setAdding] = useState(false);
const handleAdd = () => {
if (!workContent.trim() || hours <= 0) return;
addWorklog({ taskId, userId: user?.name || '', date, hours, workContent: workContent.trim() });
const newTotal = totalHours + hours;
syncActualHours(taskId, newTotal);
setWorkContent('');
setHours(1);
setAdding(false);
};
const handleDelete = (id: string, logHours: number) => {
deleteWorklog(id);
syncActualHours(taskId, Math.max(0, totalHours - logHours));
};
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-[12px] font-medium text-[var(--ink)]"> {totalHours}h</span>
{!adding && (
<button onClick={() => setAdding(true)} className="flex items-center gap-1 text-[11px] text-[var(--accent)] hover:underline">
<Plus className="h-3 w-3" />
</button>
)}
</div>
{adding && (
<div className="rounded-lg border border-[var(--line)] bg-[var(--bg)] p-3 space-y-2">
<div className="grid grid-cols-2 gap-2">
<input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="h-8 rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
<input type="number" min={0.5} step={0.5} value={hours} onChange={(e) => setHours(parseFloat(e.target.value) || 0)} placeholder="小时" className="h-8 rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
</div>
<input value={workContent} onChange={(e) => setWorkContent(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleAdd(); }} placeholder="工作内容(必填)" className="h-8 w-full rounded-md border border-[var(--line)] px-2 text-[12px] focus:border-[var(--accent)] focus:outline-none" />
<div className="flex justify-end gap-2">
<button onClick={() => setAdding(false)} className="h-7 px-2 text-[11px] text-[var(--ink-muted)] hover:text-[var(--ink)]"></button>
<button onClick={handleAdd} disabled={!workContent.trim() || hours <= 0} className="h-7 px-3 rounded-md text-[11px] font-medium bg-[var(--accent)] text-white disabled:opacity-50"></button>
</div>
</div>
)}
{taskLogs.length === 0 && !adding && (
<p className="text-[12px] text-[var(--ink-muted)] py-2"></p>
)}
{taskLogs.map((log) => (
<div key={log.id} className="flex items-start gap-2 py-1.5 border-b border-[var(--line)] last:border-0">
<div className="flex-1">
<p className="text-[12px] text-[var(--ink)]">{log.workContent}</p>
<p className="text-[10px] text-[var(--ink-muted)]">{log.date} · {log.hours}h · {log.userId}</p>
</div>
<button onClick={() => handleDelete(log.id, log.hours)} className="p-1 rounded hover:bg-red-50">
<Trash2 className="h-3 w-3 text-[var(--ink-muted)] hover:text-red-500" />
</button>
</div>
))}
</div>
);
}

93
apps/web/lib/dev-task.ts Normal file
View File

@@ -0,0 +1,93 @@
import type { Priority } from './derive';
export type DevTaskStatus = 'todo' | 'in_progress' | 'testing' | 'submitted' | 'done';
export interface DevTask {
id: string;
taskNo: string;
requirementId: string;
title: string;
description?: string;
categoryId: string;
assigneeId: string;
reviewerId?: string;
priority: Priority;
estimateHours: number;
actualHours: number;
startDate?: string;
dueDate?: string;
completedAt?: string;
status: DevTaskStatus;
isBlocked: boolean;
blockReason?: string;
blockedById?: string;
predecessorIds?: string[];
riskLevel?: 'low' | 'medium' | 'high';
createdBy: string;
createdAt: string;
updatedAt: string;
}
export const DEV_TASK_STATUS_LABEL: Record<DevTaskStatus, string> = {
todo: '待开发',
in_progress: '开发中',
testing: '自测',
submitted: '提测',
done: '已完成',
};
export const DEV_TASK_STATUS_COLOR: Record<DevTaskStatus, string> = {
todo: 'bg-zinc-100 text-zinc-600',
in_progress: 'bg-blue-50 text-blue-600',
testing: 'bg-purple-50 text-purple-600',
submitted: 'bg-orange-50 text-orange-600',
done: 'bg-emerald-50 text-emerald-600',
};
export const STATUS_PROGRESS: Record<DevTaskStatus, number> = {
todo: 0,
in_progress: 50,
testing: 80,
submitted: 90,
done: 100,
};
export const ALLOWED_TRANSITIONS: Record<DevTaskStatus, DevTaskStatus[]> = {
todo: ['in_progress'],
in_progress: ['testing'],
testing: ['submitted', 'in_progress'],
submitted: ['done', 'in_progress'],
done: [],
};
export function canTransition(from: DevTaskStatus, to: DevTaskStatus): boolean {
return ALLOWED_TRANSITIONS[from].includes(to);
}
export function calcTaskProgress(task: DevTask): number {
return STATUS_PROGRESS[task.status];
}
export function calcGroupProgress(tasks: DevTask[]): number {
if (tasks.length === 0) return 0;
const totalEstimate = tasks.reduce((sum, t) => sum + t.estimateHours, 0);
if (totalEstimate === 0) return 0;
const weighted = tasks.reduce((sum, t) => sum + t.estimateHours * STATUS_PROGRESS[t.status], 0);
return Math.round(weighted / totalEstimate);
}
export function formatHours(hours: number): string {
if (hours < 8) return `${hours}h`;
const days = Math.floor(hours / 8);
const remainder = hours % 8;
if (remainder === 0) return `${hours}h${days}人天)`;
return `${hours}h${days}人天)`;
}
export function generateTaskNo(existingTasks: DevTask[]): string {
const maxNum = existingTasks.reduce((max, t) => {
const num = parseInt(t.taskNo.replace('DEV-', ''), 10);
return isNaN(num) ? max : Math.max(max, num);
}, 0);
return `DEV-${String(maxNum + 1).padStart(3, '0')}`;
}

View File

@@ -0,0 +1,36 @@
export type CategoryGroup = 'development' | 'testing' | 'implementation' | 'other';
export interface TaskCategory {
id: string;
name: string;
group: CategoryGroup;
color?: string;
sortOrder: number;
isSystem: boolean;
}
export const CATEGORY_GROUP_LABEL: Record<CategoryGroup, string> = {
development: '开发',
testing: '测试',
implementation: '实施',
other: '其他',
};
export const PRESET_CATEGORIES: TaskCategory[] = [
{ id: 'cat-1', name: '前端开发', group: 'development', color: '#3b82f6', sortOrder: 1, isSystem: true },
{ id: 'cat-2', name: '后端开发', group: 'development', color: '#6366f1', sortOrder: 2, isSystem: true },
{ id: 'cat-3', name: '数据库设计', group: 'development', color: '#8b5cf6', sortOrder: 3, isSystem: true },
{ id: 'cat-4', name: '接口联调', group: 'development', color: '#0ea5e9', sortOrder: 4, isSystem: true },
{ id: 'cat-5', name: '测试验证', group: 'testing', color: '#a855f7', sortOrder: 5, isSystem: true },
{ id: 'cat-6', name: '缺陷修复', group: 'testing', color: '#ef4444', sortOrder: 6, isSystem: true },
{ id: 'cat-7', name: '数据处理', group: 'implementation', color: '#f59e0b', sortOrder: 7, isSystem: true },
{ id: 'cat-8', name: '实施支持', group: 'implementation', color: '#10b981', sortOrder: 8, isSystem: true },
];
export function getCategoryById(categories: TaskCategory[], id: string): TaskCategory | undefined {
return categories.find((c) => c.id === id);
}
export function getCategoriesByGroup(categories: TaskCategory[], group: CategoryGroup): TaskCategory[] {
return categories.filter((c) => c.group === group).sort((a, b) => a.sortOrder - b.sortOrder);
}

View File

@@ -0,0 +1,33 @@
export interface TaskWorklog {
id: string;
taskId: string;
userId: string;
date: string;
hours: number;
workContent: string;
createdAt: string;
}
export function calcActualHours(worklogs: TaskWorklog[], taskId: string): number {
return worklogs
.filter((w) => w.taskId === taskId)
.reduce((sum, w) => sum + w.hours, 0);
}
export function getTaskWorklogs(worklogs: TaskWorklog[], taskId: string): TaskWorklog[] {
return worklogs
.filter((w) => w.taskId === taskId)
.sort((a, b) => b.date.localeCompare(a.date));
}
export function getUserDailyWorklogs(worklogs: TaskWorklog[], userId: string, date: string): TaskWorklog[] {
return worklogs.filter((w) => w.userId === userId && w.date === date);
}
export function getUserDailySummary(worklogs: TaskWorklog[], userId: string, date: string): { total: number; items: { taskId: string; hours: number; workContent: string }[] } {
const items = getUserDailyWorklogs(worklogs, userId, date);
return {
total: items.reduce((sum, w) => sum + w.hours, 0),
items: items.map((w) => ({ taskId: w.taskId, hours: w.hours, workContent: w.workContent })),
};
}

49
apps/web/lib/work-item.ts Normal file
View File

@@ -0,0 +1,49 @@
import type { DevTask } from './dev-task';
import type { VersionPlan } from './version-plan';
import type { Priority } from './derive';
export type WorkItemEntityType = 'plan' | 'devTask' | 'testCase' | 'bug';
export interface WorkItem {
entityType: WorkItemEntityType;
entityId: string;
title: string;
status: string;
isBlocked?: boolean;
assigneeId: string;
reviewerId?: string;
versionId: string;
versionName?: string;
priority?: Priority;
dueDate?: string;
categoryLabel?: string;
}
export function planToWorkItem(plan: VersionPlan): WorkItem {
return {
entityType: 'plan',
entityId: plan.id,
title: plan.title,
status: plan.status,
assigneeId: plan.owner,
versionId: plan.versionId,
dueDate: plan.endTime.slice(0, 10),
categoryLabel: plan.type === 'research' ? '调研' : plan.type === 'product' ? '产品方案' : 'UI设计',
};
}
export function devTaskToWorkItem(task: DevTask, versionId: string, categoryLabel?: string): WorkItem {
return {
entityType: 'devTask',
entityId: task.id,
title: task.title,
status: task.status,
isBlocked: task.isBlocked,
assigneeId: task.assigneeId,
reviewerId: task.reviewerId,
versionId,
priority: task.priority,
dueDate: task.dueDate,
categoryLabel,
};
}

View File

@@ -0,0 +1,109 @@
'use client';
import { create } from 'zustand';
import type { DevTask, DevTaskStatus } from '@/lib/dev-task';
import { canTransition, generateTaskNo } from '@/lib/dev-task';
const STORAGE_KEY = 'ftb_dev_tasks_v1';
function saveLocal(items: DevTask[]) {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(items)); } catch {}
}
function loadLocal(): DevTask[] | null {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw);
} catch {}
return null;
}
interface DevTaskState {
tasks: DevTask[];
fetchTasks: () => void;
createTask: (data: Omit<DevTask, 'id' | 'taskNo' | 'createdAt' | 'updatedAt' | 'actualHours' | 'isBlocked'>) => DevTask;
updateTask: (id: string, data: Partial<DevTask>) => void;
deleteTask: (id: string) => void;
changeStatus: (id: string, to: DevTaskStatus) => { ok: boolean; message?: string };
setBlocked: (id: string, blocked: boolean, reason?: string, blockedById?: string) => void;
syncActualHours: (taskId: string, hours: number) => void;
getByRequirement: (requirementId: string) => DevTask[];
getByVersionViaRequirements: (requirementIds: string[]) => DevTask[];
getByAssignee: (assigneeId: string) => DevTask[];
}
export const useDevTaskStore = create<DevTaskState>((set, get) => ({
tasks: [],
fetchTasks: () => {
const cached = loadLocal();
if (cached) set({ tasks: cached });
},
createTask: (data) => {
const list = get().tasks;
const now = new Date().toISOString();
const task: DevTask = {
...data,
id: `task-${Date.now()}`,
taskNo: generateTaskNo(list),
actualHours: 0,
isBlocked: false,
createdAt: now,
updatedAt: now,
};
const updated = [...list, task];
set({ tasks: updated });
saveLocal(updated);
return task;
},
updateTask: (id, data) => {
const updated = get().tasks.map((t) =>
t.id === id ? { ...t, ...data, updatedAt: new Date().toISOString() } : t,
);
set({ tasks: updated });
saveLocal(updated);
},
deleteTask: (id) => {
const updated = get().tasks.filter((t) => t.id !== id);
set({ tasks: updated });
saveLocal(updated);
},
changeStatus: (id, to) => {
const task = get().tasks.find((t) => t.id === id);
if (!task) return { ok: false, message: '任务不存在' };
if (!canTransition(task.status, to)) {
return { ok: false, message: `不允许从「${task.status}」流转到「${to}` };
}
const completedAt = to === 'done' ? new Date().toISOString().slice(0, 10) : task.completedAt;
get().updateTask(id, { status: to, completedAt });
return { ok: true };
},
setBlocked: (id, blocked, reason, blockedById) => {
get().updateTask(id, {
isBlocked: blocked,
blockReason: blocked ? reason : undefined,
blockedById: blocked ? blockedById : undefined,
});
},
syncActualHours: (taskId, hours) => {
get().updateTask(taskId, { actualHours: hours });
},
getByRequirement: (requirementId) => {
return get().tasks.filter((t) => t.requirementId === requirementId);
},
getByVersionViaRequirements: (requirementIds) => {
const idSet = new Set(requirementIds);
return get().tasks.filter((t) => idSet.has(t.requirementId));
},
getByAssignee: (assigneeId) => {
return get().tasks.filter((t) => t.assigneeId === assigneeId);
},
}));

View File

@@ -0,0 +1,65 @@
'use client';
import { create } from 'zustand';
import type { TaskCategory, CategoryGroup } from '@/lib/task-category';
import { PRESET_CATEGORIES } from '@/lib/task-category';
const STORAGE_KEY = 'ftb_task_categories_v1';
function saveLocal(items: TaskCategory[]) {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(items)); } catch {}
}
function loadLocal(): TaskCategory[] | null {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw);
} catch {}
return null;
}
interface TaskCategoryState {
categories: TaskCategory[];
fetchCategories: () => void;
addCategory: (name: string, group: CategoryGroup, color?: string) => void;
updateCategory: (id: string, data: Partial<TaskCategory>) => void;
deleteCategory: (id: string) => boolean;
}
export const useTaskCategoryStore = create<TaskCategoryState>((set, get) => ({
categories: PRESET_CATEGORIES,
fetchCategories: () => {
const cached = loadLocal();
if (cached) set({ categories: cached });
},
addCategory: (name, group, color) => {
const list = get().categories;
const item: TaskCategory = {
id: `cat-${Date.now()}`,
name,
group,
color,
sortOrder: list.length + 1,
isSystem: false,
};
const updated = [...list, item];
set({ categories: updated });
saveLocal(updated);
},
updateCategory: (id, data) => {
const updated = get().categories.map((c) => (c.id === id ? { ...c, ...data } : c));
set({ categories: updated });
saveLocal(updated);
},
deleteCategory: (id) => {
const target = get().categories.find((c) => c.id === id);
if (!target || target.isSystem) return false;
const updated = get().categories.filter((c) => c.id !== id);
set({ categories: updated });
saveLocal(updated);
return true;
},
}));

View File

@@ -0,0 +1,57 @@
'use client';
import { create } from 'zustand';
import type { TaskWorklog } from '@/lib/task-worklog';
const STORAGE_KEY = 'ftb_task_worklogs_v1';
function saveLocal(items: TaskWorklog[]) {
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(items)); } catch {}
}
function loadLocal(): TaskWorklog[] | null {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw);
} catch {}
return null;
}
interface TaskWorklogState {
worklogs: TaskWorklog[];
fetchWorklogs: () => void;
addWorklog: (data: Omit<TaskWorklog, 'id' | 'createdAt'>) => void;
deleteWorklog: (id: string) => void;
getActualHours: (taskId: string) => number;
}
export const useTaskWorklogStore = create<TaskWorklogState>((set, get) => ({
worklogs: [],
fetchWorklogs: () => {
const cached = loadLocal();
if (cached) set({ worklogs: cached });
},
addWorklog: (data) => {
const item: TaskWorklog = {
...data,
id: `wl-${Date.now()}`,
createdAt: new Date().toISOString(),
};
const updated = [...get().worklogs, item];
set({ worklogs: updated });
saveLocal(updated);
},
deleteWorklog: (id) => {
const updated = get().worklogs.filter((w) => w.id !== id);
set({ worklogs: updated });
saveLocal(updated);
},
getActualHours: (taskId) => {
return get().worklogs
.filter((w) => w.taskId === taskId)
.reduce((sum, w) => sum + w.hours, 0);
},
}));

View File

@@ -0,0 +1,187 @@
---
title: 版本模块 Phase 1 设计规格
date: 2026-06-09
module: versions
---
# 版本模块 Phase 1 — 列表增强 + 详情页 + 生命周期
## 1. 版本生命周期状态机
```
规划中 → 进行中(各阶段) → 已发布
已暂停 已关闭
```
- 规划中(planned):已创建但未开始
- 进行中(developing):有 currentStage 标识具体阶段(调研/产品设计/UI设计/开发/联调/测试)
- 已暂停(paused):手动暂停,可恢复为进行中
- 已关闭(closed):手动关闭,终态不可恢复
- 已发布(released):上线完成,终态
操作:
- 开始:规划中 → 进行中
- 暂停:进行中 → 已暂停
- 恢复:已暂停 → 进行中
- 关闭:规划中/进行中/已暂停 → 已关闭
- 发布:进行中 → 已发布
## 2. 新增字段
### 版本数据结构扩展
```typescript
interface VersionItem {
// 已有
id: string;
name: string;
status: 'planned' | 'developing' | 'paused' | 'closed' | 'released';
currentStage?: Stage;
startDate?: string | null;
expectedReleaseDate?: string | null; // 截止日期
releaseDate: string | null;
createdAt: string;
members?: VersionMember[];
progress?: RoleProgress[];
// 新增
priority: 'P0' | 'P1' | 'P2' | 'P3' | 'P4';
riskLevel?: 'low' | 'medium' | 'high'; // 系统自动计算
delayStatus?: 'normal' | 'warning' | 'delayed'; // 系统自动计算
links?: {
research?: string; // 调研报告地址
prototype?: string; // 原型地址
ui?: string; // UI 设计稿地址
};
}
```
### 风险等级自动计算规则
- **低风险(low/绿)**:一切正常
- **中风险(medium/橙)**
- 整体进度落后于时间进度 20%+
- 即将延期(截止日期 - 3天内
- 版本被暂停
- **高风险(high/红)**
- 已延期(当前日期 > 截止日期 且未发布/关闭)
- 整体进度落后于时间进度 40%+
计算公式:
- 时间进度 = (当前日期 - 开始日期) / (截止日期 - 开始日期) × 100%
- 整体进度 = 各角色进度百分比的平均值
- 落后比 = 时间进度 - 整体进度
### 延期状态自动计算规则
- **正常(normal/绿)**:当前日期 < 截止日期 - 3天
- **即将延期(warning/)**截止日期 - 3天 当前日期 截止日期
- **已延期(delayed/)**当前日期 > 截止日期 且状态不是已发布/已关闭
已发布和已关闭的版本不计算延期状态,统一显示"-"。
### 优先级
P0(紧急) / P1(高) / P2(中) / P3(低) / P4(最低)
手动设置,默认 P2。列表可按优先级排序。
## 3. 版本列表页改造
### 列定义
| 列 | 宽度 | 说明 |
|---|---|---|
| 版本号 | auto | 如"考勤V1.2",点击进详情 |
| 优先级 | 60px | P0-P4 标签,颜色区分 |
| 当前阶段 | 100px | 显示胶囊对应的阶段名,跟项目详情一致 |
| 整体进度 | 120px | 进度条 + 百分比 |
| 风险等级 | 70px | 颜色点 + 文字(低/中/高) |
| 延期状态 | 80px | 颜色标签(正常/即将延期/已延期) |
| 截止日期 | 100px | YYYY-MM-DD |
| 负责人 | auto | 紧凑展示:产品:张三 前端:赵六... |
| 操作 | 80px | 下拉菜单(编辑/暂停/恢复/关闭) |
### 筛选条件
- 搜索:版本号模糊匹配
- 状态筛选:全部 / 调研 / 产品设计 / UI设计 / 开发 / 联调 / 测试 / 已发布 / 已暂停 / 已关闭 / 规划中
- 项目筛选:下拉选择
- 优先级筛选P0-P4 多选
- 风险等级筛选:低/中/高
### 排序
默认按优先级降序 > 创建时间倒序。可点击表头切换排序。
## 4. 版本详情页 `/versions/[id]`
### 页面结构
```
┌─────────────────────────────────────────────────────┐
│ Header: ← 版本 / 考勤V1.2 [编辑] [暂停] [关闭]│
├─────────────────────────────────────────────────────┤
│ 标签行: P1标签 风险:中 即将延期 产品:翻台宝 │
├─────────────────────────────────────────────────────┤
│ 胶囊分段条CapsuleStages 组件复用) │
├─────────────────────────────────────────────────────┤
│ 信息网格 (3列) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │开始日期 │ │截止日期 │ │已耗时 │ │
│ │2024-04-15│ │2024-06-10│ │34天 │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ 负责人区域 │
│ 产品:张三 UI:王五 前端:赵六 后端:孙八 测试:周九 │
│ │
│ 外链区域 │
│ 📄 调研报告 🎨 原型地址 🖼 UI设计稿 │
├─────────────────────────────────────────────────────┤
│ 下半部分Phase 2 占位) │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Tabs: 需求 | 开发任务 | 测试用例 | Bug │ │
│ │ │ │
│ │ 功能开发中,敬请期待 │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────┘
```
### 上半部分详细说明
- **Header**:面包屑导航 + 版本名 + 操作按钮组
- **标签行**:优先级(P0-P4) + 风险等级(颜色点) + 延期状态(标签) + 所属产品/项目
- **胶囊分段条**:复用 CapsuleStages 组件,展示各阶段进度和耗时
- **信息网格**:开始日期、截止日期、已耗时天数
- **负责人**:复用 MemberChips 组件
- **外链**:调研报告/原型/UI 设计稿链接,点击新窗口打开,无链接显示"未设置"
### 下半部分Phase 2 占位)
Tab 栏显示:需求 / 开发任务 / 测试用例 / Bug
Phase 1 内容为空占位:"功能开发中"
## 5. 项目详情页同步调整
项目详情页的版本记录卡片同步增加优先级标签显示。
## 6. 新建版本弹窗扩展
在现有字段基础上增加:
- 优先级选择(默认 P2
- 截止日期选择(日期选择器)
- 负责人选择(按角色分组,后续可从历史推荐)
## 7. 涉及文件变更
| 文件 | 变更 |
|---|---|
| `apps/web/lib/stage.ts` | 无变更 |
| `apps/web/lib/version-status.ts` | 新增 paused/closed 状态 |
| `apps/web/stores/useProductStore.ts` | VersionItem 扩展字段MOCK数据补充 |
| `apps/web/app/versions/page.tsx` | 列表页重构 |
| `apps/web/app/versions/[id]/page.tsx` | 新增详情页 |
| `apps/web/app/projects/[id]/page.tsx` | 版本卡片加优先级 |
| `apps/web/lib/risk.ts` | 新增:风险等级和延期状态计算函数 |

View File

@@ -0,0 +1,357 @@
---
title: 开发任务模块DevTask设计规格
date: 2026-06-11
module: dev-task
status: approved
---
# 开发任务模块DevTask— 设计规格
## 1. 定位与层级
DevTask 是"执行层"实体,归属于版本下某条需求,代表一个可分配、可追踪工时的开发工作项。
```
Version版本
├── VersionPlan计划层调研/产品/UI← 已有
├── DevTask执行层开发任务← 本文档
│ └── 归属于 Requirement需求
│ └── TaskWorklog工时记录
└── TestCase / Bug后续
```
### 归属关系
- DevTask **必须**归属于一条需求(`requirementId` 必填)
- `versionId` 从需求推导,不冗余存储
- 通过 `Requirement → Version` 链路追溯到版本和产品
## 2. 数据模型
### 2.1 DevTask开发任务
```typescript
interface DevTask {
id: string;
taskNo: string; // 自动生成DEV-001、DEV-002...
requirementId: string; // 所属需求(必填)
title: string;
description?: string;
categoryId: string; // 任务类型(字典表 TaskCategory
assigneeId: string; // 负责人
reviewerId?: string; // 验收人预留V1 可选不填)
priority: 'P0' | 'P1' | 'P2' | 'P3'; // 默认继承需求优先级,允许覆盖
estimateHours: number; // 预计工时(小时)
actualHours: number; // 实际工时(只读,= Σ TaskWorklog.hours
startDate?: string; // 开始日期 YYYY-MM-DD
dueDate?: string; // 截止日期 YYYY-MM-DD
completedAt?: string; // 完成日期 YYYY-MM-DD
status: DevTaskStatus;
isBlocked: boolean; // 阻塞标记(正交于 status
blockReason?: string; // 阻塞原因
blockedById?: string; // 造成阻塞的任务 ID可选
predecessorIds?: string[]; // 前置任务 ID 列表
riskLevel?: 'low' | 'medium' | 'high'; // 系统计算字段,不可手动编辑
createdBy: string;
createdAt: string;
updatedAt: string;
}
type DevTaskStatus = 'todo' | 'in_progress' | 'testing' | 'submitted' | 'done';
```
### 2.2 TaskWorklog工时记录
```typescript
interface TaskWorklog {
id: string;
taskId: string; // 所属 DevTask
userId: string; // 登记人
date: string; // YYYY-MM-DD
hours: number; // 当日投入小时数
workContent: string; // 工作内容(必填,为日报系统提供数据源)
createdAt: string;
}
```
- DevTask.actualHours = 该任务下所有 TaskWorklog.hours 的累加
- actualHours 字段只读,不允许直接编辑
- workContent 必填,格式示例:"完成排班页面基础布局"、"对接排班接口"
- V2 与加班记录、日报模块打通,统一为"工时记录中心"
- 日报可直接聚合当日 workContent 生成:`排班页面布局4h+ 接口联调2h= 6h`
### 2.3 TaskCategory任务类型字典
```typescript
interface TaskCategory {
id: string;
name: string; // 显示名称
group: 'development' | 'testing' | 'implementation' | 'other'; // 分组,用于报表统计
color?: string; // 图表配色
sortOrder: number; // 排列顺序
isSystem: boolean; // 系统预置不可删除
}
```
系统预置值:
| 名称 | 分组 | 说明 |
|------|------|------|
| 前端开发 | development | Web/移动端页面 |
| 后端开发 | development | API/服务层 |
| 数据库设计 | development | 表结构/迁移 |
| 接口联调 | development | 前后端对接 |
| 测试验证 | testing | 测试执行 |
| 缺陷修复 | testing | Bug 修复 |
| 数据处理 | implementation | ETL/数据清洗 |
| 实施支持 | implementation | 部署/实施 |
管理员可在"系统管理"中增删自定义类型。
## 3. 状态机
```
todo → in_progress → testing → submitted → done
↑ │ │
└─────────┘ │
↑ │
└────────────────────┘
```
| 状态 | 含义 | 推导进度 |
|------|------|---------|
| todo | 待开发 | 0% |
| in_progress | 开发中 | 50% |
| testing | 自测 | 80% |
| submitted | 提测 | 90% |
| done | 已完成 | 100% |
### 状态流转规则
正向流转:
- todo → in_progress → testing → submitted → done
允许回退(有限):
- testing → in_progress自测发现需要返工
- submitted → in_progress测试打回
禁止回退:
- done → 任何状态(完成是终态,返工走新任务或 Bug
- todo → 非 in_progress不能跳级
回退时记录操作日志(操作人、时间、原因)。
## 4. 阻塞设计(正交标记)
阻塞不是状态枚举值,而是叠加在任何状态之上的标记:
| 字段 | 类型 | 说明 |
|------|------|------|
| isBlocked | boolean | 是否被阻塞 |
| blockReason | string? | 阻塞原因描述 |
| blockedById | string? | 造成阻塞的任务 ID |
示例场景:
- `status=in_progress + isBlocked=true`:开发中但等后端接口
- `status=testing + isBlocked=true`:自测发现问题等需求确认
- `status=todo + isBlocked=true`:依赖的前置任务未完成
工作台筛选 `isBlocked=true` 可一键拉出所有阻塞项。
## 5. 进度计算规则
### 5.1 单任务进度
由 status 推导(见状态机表),不设人工填写的百分比字段。
### 5.2 需求级开发进度
```
需求开发进度 = Σ(任务.estimateHours × 任务状态推导进度) / Σ(任务.estimateHours)
```
示例:
| 任务 | 预计工时 | 状态 | 推导进度 | 加权 |
|------|---------|------|---------|------|
| 排班界面 | 16h | done | 100% | 16 |
| 排班规则组件 | 8h | in_progress | 50% | 4 |
| 排班算法接口 | 24h | todo | 0% | 0 |
需求进度 = (16 + 4 + 0) / (16 + 8 + 24) = 20 / 48 = **41.7%**
### 5.3 版本开发进度
```
版本开发进度 = Σ(版本下所有 DevTask.estimateHours × 状态推导进度) / Σ(estimateHours)
```
### 5.4 工时投入展示(辅助指标,不参与进度)
```
工时投入比 = Σ actualHours / Σ estimateHours
```
展示为:`已投入 32h / 预计 56h (57%)`
用途:工时偏差分析、健康度评估、加班趋势关联。
## 6. 工时展示规则
存储单位始终为**小时(h)**。展示时自动转换:
| 值 | 展示 |
|---|---|
| 4h | 4h |
| 8h | 8h1人天 |
| 16h | 16h2人天 |
| 24h | 24h3人天 |
转换规则:`1人天 = 8h`,仅当 ≥ 8h 时附带人天标注。
## 7. 优先级继承
```
Requirement.priority = P1
↓ 创建任务时默认继承
DevTask.priority = P1可覆盖为 P0/P2/P3
```
UI 行为:创建任务弹窗中,优先级字段预填为需求优先级,允许手动修改。
## 8. 前置任务(依赖)
| 字段 | 说明 |
|------|------|
| predecessorIds | string[],前置任务 ID 列表 |
V1 功能范围:
- 创建/编辑时可选择同版本内的其他 DevTask 作为前置
- 详情页展示前置任务列表,可跳转
- 前置任务未完成时,系统不阻止本任务开始(仅展示提示)
V2 扩展:
- 甘特图依赖线
- 关键路径计算
- 自动阻塞提醒
## 9. 风险等级(系统自动计算,不可手动编辑)
V1 预留 `riskLevel` 字段由系统自动计算UI 上不提供手动编辑入口。
V2 自动规则:
| 条件 | 风险等级 |
|------|---------|
| actualHours > estimateHours × 1.5 | high |
| today > dueDate 且 status ≠ done | high |
| isBlocked 持续超过 2 天 | high |
| actualHours > estimateHours × 1.2 | medium |
| today > dueDate - 3天 | medium |
| 其他 | low |
风险逐层汇总:任务 → 需求 → 版本 → 项目,与已有 `version.riskLevel` 计算保持一致。
设计原则:风险等级反映客观数据,不允许人为干预(避免"明明很危险但负责人填低风险")。
## 10. "与我相关"统一聚合层
### 10.1 统一工作项模型(锁定契约)
所有可分配实体必须遵守以下统一语义,新增实体类型时不得打破此契约:
```typescript
type WorkItem = {
entityType: 'plan' | 'devTask' | 'testCase' | 'bug';
entityId: string;
title: string;
status: string;
isBlocked?: boolean;
assigneeId: string; // 必须:负责人
reviewerId?: string; // 可选:验收人
versionId: string; // 必须:从各实体推导
versionName?: string;
priority?: string; // 必须:优先级
dueDate?: string; // 必须:截止日期
categoryLabel?: string; // 任务类型名称
};
```
未来新增实体(发布任务、实施任务、运维任务等)只需实现此接口,即可自动接入工作台,无需修改聚合逻辑。
### 10.2 工作台分组
左侧导航扩展:
| 分组 | 数据来源 | 状态 |
|------|---------|------|
| 全部待办 | 所有 entityType | — |
| 调研 | VersionPlan(type=research) | 已有 |
| 产品方案 | VersionPlan(type=product) | 已有 |
| UI设计 | VersionPlan(type=ui) | 已有 |
| 开发任务 | DevTask | 本次新增 |
| 测试/Bug | TestCase + Bug | 后续 |
### 10.3 右侧状态视图
按状态分列展示:
- 待处理todo / pending
- 进行中in_progress
- 阻塞isBlocked = true跨所有状态
- 待验收testing / submitted
### 10.4 联动规则
- 创建 DevTask 并指定 assigneeId → 自动出现在该成员"与我相关"
- 变更 assigneeId → 从原负责人工作台移除,加入新负责人工作台
- 状态变更 → 自动在工作台内移动列
## 11. 与加班模块的关系
已有加班记录存储小时数。未来数据链路:
```
TaskWorklog任务工时
↓ 当日工时 > 8h 部分
OvertimeRecord加班记录
↓ 按月汇总
加班统计仪表盘
```
V1 两个模块独立运行。V2 建立工时 → 加班自动关联。
## 12. 涉及新增文件(预估)
| 路径 | 说明 |
|------|------|
| `apps/web/lib/dev-task.ts` | DevTask 类型定义 + 进度计算函数 |
| `apps/web/lib/task-worklog.ts` | TaskWorklog 类型 + 聚合函数 |
| `apps/web/lib/task-category.ts` | TaskCategory 类型 + 预置数据 |
| `apps/web/stores/useDevTaskStore.ts` | DevTask 状态管理localStorage V1 |
| `apps/web/stores/useTaskWorklogStore.ts` | 工时记录状态管理 |
| `apps/web/components/dev-task/` | DevTask 相关组件目录 |
| `apps/web/app/versions/[id]/` | 版本详情页 DevTask Tab |
## 13. 不在本次范围
- 甘特图依赖线渲染
- 风险等级自动计算
- 工时 → 加班自动关联
- 测试用例 / Bug 模块
- 后端 API 实现V1 全部 localStorage

File diff suppressed because it is too large Load Diff