'use client'; import { useEffect, useMemo, useState } from 'react'; import { useParams, useRouter } from 'next/navigation'; import { ChevronLeft, Package, Calendar, Clock, Users, Tag, ChevronDown } from 'lucide-react'; import { useProductStore } from '@/stores/useProductStore'; import { useRequirementStore } from '@/stores/useRequirementStore'; import { useOvertimeStore } from '@/stores/useOvertimeStore'; import { useVersionPlanStore } from '@/stores/useVersionPlanStore'; import { useDevTaskStore } from '@/stores/useDevTaskStore'; import { useTestCaseStore } from '@/stores/useTestCaseStore'; import { useBugStore } from '@/stores/useBugStore'; import { useAuthStore } from '@/stores/useAuthStore'; import { useMemberStore } from '@/stores/useMemberStore'; import { getProjectDetail, VersionWithContext } from '@/lib/derive'; import { Stage, Role, STAGES, ROLES, STAGE_INDEX, ROLE_LABEL } from '@/lib/stage'; import { VersionStatus, VERSION_STATUS_LABEL, VERSION_STATUS_BG } from '@/lib/version-status'; 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 type { DevTask } from '@/lib/dev-task'; import type { TestCase } from '@/lib/test-case'; import type { Bug } from '@/lib/bug'; /* ─── StatCard ─── */ function StatCard({ value, label }: { value: number | string; label: string }) { return (
{value}
{label}
); } function HoursStatCard({ estimate, actual }: { estimate: number; actual: number }) { const overrun = actual > estimate && estimate > 0; const underrun = actual > 0 && actual < estimate; const tone = overrun ? 'text-red-600' : underrun ? 'text-emerald-600' : 'text-[var(--ink)]'; const dayStr = (h: number) => { const d = h / 8; return Number.isInteger(d) ? String(d) : d.toFixed(1).replace(/\.0$/, ''); }; return (
{actual > 0 ? `${actual}h` : '—'} / {estimate}h
实际 / 预计耗时{estimate > 0 && ({actual > 0 ? `${dayStr(actual)} / ` : ''}{dayStr(estimate)}天)}
); } /* ─── ProgressBar (for expanded released cards) ─── */ function ProgressBar({ role, percent, daysSpent }: { role: Role; percent: number; daysSpent: number }) { return (
{ROLE_LABEL[role]}
{percent}% {daysSpent === 0 ? '-' : `${daysSpent}天`}
); } /* ─── VersionCard ─── */ function VersionCard({ version, progress, plans, devTasks, testCases, bugs, requirements, onNavigate }: { version: VersionWithContext; progress: number; plans: VersionPlan[]; devTasks: DevTask[]; testCases: TestCase[]; bugs: Bug[]; requirements: { id: string; versionId?: string }[]; onNavigate: (id: string) => void; }) { const [expanded, setExpanded] = useState(false); // 与版本详情一致:取所有阶段最早的实际开始 const versionData = useMemo(() => { const vPlans = plans.filter((p) => p.versionId === version.id); const vReqIds = new Set(requirements.filter((r) => r.versionId === version.id).map((r) => r.id)); const vDevTasks = devTasks.filter((t) => vReqIds.has(t.requirementId)); const vTCs = testCases.filter((c) => c.versionId === version.id); const vBugs = bugs.filter((b) => b.versionId === version.id); const startDates: string[] = []; vPlans.forEach((p) => { if (p.actualStartAt) startDates.push(p.actualStartAt); else if (p.status === 'pending' && p.startTime && new Date(p.startTime) <= new Date()) startDates.push(p.startTime); }); vDevTasks.forEach((t) => { if (t.actualStartAt) startDates.push(t.actualStartAt); }); vTCs.forEach((c) => { if (c.startedAt) startDates.push(c.startedAt); }); const earliestStart = startDates.length > 0 ? startDates.sort()[0] : version.startDate; const actualStartDisplay = startDates.length > 0 ? startDates.sort()[0].slice(0, 10) : (version.startDate ?? null); // 实际截止:取所有阶段最晚完成 const endDates: string[] = []; vPlans.forEach((p) => { if (p.completedAt) endDates.push(p.completedAt); }); vDevTasks.forEach((t) => { if (t.actualEndAt) endDates.push(t.actualEndAt); }); vTCs.forEach((c) => { if (c.completedAt) endDates.push(c.completedAt); }); vBugs.forEach((b) => { if (b.closedAt) endDates.push(b.closedAt); }); const actualEndDisplay = endDates.length > 0 ? endDates.sort().reverse()[0].slice(0, 10) : null; let totalDays = 0; if (earliestStart) { const start = new Date(earliestStart); start.setHours(0, 0, 0, 0); const end = version.status === 'released' && version.releaseDate ? new Date(version.releaseDate) : new Date(); end.setHours(0, 0, 0, 0); totalDays = Math.max(0, Math.floor((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))); } return { vPlans, vDevTasks, vTCs, vBugs, totalDays, actualStart: actualStartDisplay, actualEnd: actualEndDisplay }; }, [version, plans, devTasks, testCases, bugs, requirements]); // 状态胶囊数据 — 与版本详情一致 const stageProgress = useMemo(() => { const { vPlans, vDevTasks, vTCs, vBugs } = versionData; const sp: any = {}; const calcGroupProgress = (group: VersionPlan[], type: 'research' | 'product' | 'ui') => { if (group.length === 0) return 0; let totalItems = 0; let doneItems = 0; for (const p of group) { if (type === 'research') { const tasks = p.tasks || []; const count = Math.max(tasks.length, 1); totalItems += count; 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); totalItems += count; if (p.status === 'completed') doneItems += count; else { const completed = p.completedRequirementIds || []; doneItems += completed.filter((id) => linked.includes(id)).length; } } } return totalItems > 0 ? Math.round((doneItems / totalItems) * 100) : 0; }; const getPlanStatus = (group: VersionPlan[]): 'idle' | 'active' | 'done' => { if (group.length === 0) return 'idle'; if (group.every((p) => p.status === 'completed')) return 'done'; if (group.some((p) => p.status === 'in_progress')) return 'active'; return 'idle'; }; const research = vPlans.filter((p) => p.type === 'research'); const product = vPlans.filter((p) => p.type === 'product'); const ui = vPlans.filter((p) => p.type === 'ui'); if (research.length > 0) sp['requirement'] = { percent: calcGroupProgress(research, 'research'), status: getPlanStatus(research) }; if (product.length > 0) sp['product_design'] = { percent: calcGroupProgress(product, 'product'), status: getPlanStatus(product) }; if (ui.length > 0) sp['ui_design'] = { percent: calcGroupProgress(ui, 'ui'), status: getPlanStatus(ui) }; if (vDevTasks.length > 0) { const devProgress = calcDevTaskProgress(vDevTasks); const allSubmitted = vDevTasks.every((t) => t.status === 'submitted'); const hasActive = vDevTasks.some((t) => t.status === 'in_progress' || t.status === 'testing'); sp['dev'] = { percent: devProgress, status: allSubmitted ? 'done' : hasActive ? 'active' : 'idle' }; } if (vTCs.length > 0) { const executed = vTCs.filter((c) => c.status === 'passed' || c.status === 'failed' || c.status === 'blocked').length; const tp = Math.round((executed / vTCs.length) * 100); const allPassed = vTCs.every((c) => c.status === 'passed'); const hasRunning = vTCs.some((c) => c.status === 'running'); sp['testing'] = { percent: tp, status: allPassed ? 'done' : (hasRunning || executed > 0) ? 'active' : 'idle' }; } if (vBugs.length > 0) { const closedBugs = vBugs.filter((b) => b.status === 'closed' || b.status === 'rejected').length; const bp = Math.round((closedBugs / vBugs.length) * 100); const allClosed = vBugs.every((b) => b.status === 'closed' || b.status === 'rejected'); sp['bug'] = { percent: bp, status: allClosed ? 'done' : closedBugs > 0 || vBugs.length > 0 ? 'active' : 'idle' }; } return sp; }, [versionData]); const totalDays = versionData.totalDays; const displayStatus = VERSION_STATUS_LABEL[version.status] ?? '开发中'; const displayBg = VERSION_STATUS_BG[version.status] ?? 'bg-blue-500/10 text-blue-600'; if (version.status === 'planned') { return (
onNavigate(version.id)} className="text-sm font-medium text-[var(--ink)] cursor-pointer hover:text-[var(--accent)]">{version.name} {displayStatus} 暂无详情
); } if (version.status === 'released') { return (
{expanded && (
)}
); } return (
onNavigate(version.id)} className="text-sm font-medium text-[var(--ink)] cursor-pointer hover:text-[var(--accent)]">{version.name} {displayStatus}
{progress}%
{versionData.actualStart ?? version.startDate ?? '-'} 预计 {version.expectedReleaseDate ?? '-'} {versionData.actualEnd && ( <> | 实际 {versionData.actualEnd} )} 已耗时 {totalDays} 天
); } /* ─── TeamSection (compact, overflow with tooltip) ─── */ function TeamSection({ teamByRole }: { teamByRole: Record> }) { const MAX_VISIBLE = 4; return (

项目人员

{ROLES.map((role) => { const peopleMap = teamByRole[role.key] || {}; const people = Object.entries(peopleMap).sort((a, b) => (b[1] as number) - (a[1] as number)); if (people.length === 0) return null; const visible = people.slice(0, MAX_VISIBLE); const hidden = people.slice(MAX_VISIBLE); return (
{role.label}
{visible.map(([name, count]) => ( {name}{'×'}{count as number} ))} {hidden.length > 0 && ( +{hidden.length} {hidden.map(([n, c]) => `${n}(×${c})`).join(', ')} )}
); })}
); } /* ─── Status Filter ─── */ const FILTER_OPTIONS: { key: string; label: string }[] = [ { key: 'all', label: '全部' }, { key: 'requirement', label: '调研' }, { key: 'product_design', label: '产品设计' }, { key: 'ui_design', label: 'UI设计' }, { key: 'dev', label: '开发' }, { key: 'testing', label: '测试' }, { key: 'released', label: '已发布' }, { key: 'planned', label: '规划中' }, ]; /* ─── Main Page ─── */ export default function ProjectDetailPage() { const params = useParams(); const router = useRouter(); const projectId = params.id as string; const { overview, fetchOverview } = useProductStore(); const { requirements, fetchRequirements } = useRequirementStore(); const { records, fetchRecords } = useOvertimeStore(); const { plans, fetchPlans } = useVersionPlanStore(); const { tasks: devTasks, fetchTasks: fetchDevTasks } = useDevTaskStore(); const { testCases, fetchTestCases } = useTestCaseStore(); const { bugs, fetchBugs } = useBugStore(); const [statusFilter, setStatusFilter] = useState('all'); useEffect(() => { fetchOverview(); }, [fetchOverview]); useEffect(() => { fetchRequirements(); }, [fetchRequirements]); useEffect(() => { fetchRecords(); }, [fetchRecords]); useEffect(() => { fetchPlans(); }, [fetchPlans]); useEffect(() => { fetchDevTasks(); }, [fetchDevTasks]); useEffect(() => { fetchTestCases(); }, [fetchTestCases]); const project = useMemo(() => getProjectDetail(overview, projectId), [overview, projectId]); const user = useAuthStore((s) => s.user); const currentUserName = user?.name || ''; const { roles } = useMemberStore(); const isSuperAdmin = useMemo(() => { const r = roles.find((x) => x.id === user?.roleId); return !!r && r.permissions.includes('*'); }, [roles, user?.roleId]); const sortedVersions = useMemo(() => { if (!project) return []; let list = [...project.versions]; // 只显示当前用户参与的版本(members为空时所有人可见;超管可见全部) if (!isSuperAdmin) { list = list.filter((v) => { const ms = v.members ?? []; if (ms.length === 0) return true; return ms.some((m) => m.name === currentUserName); }); } if (statusFilter !== 'all') { if (statusFilter === 'planned') { list = list.filter((v) => v.status === 'planned'); } else if (statusFilter === 'released') { list = list.filter((v) => v.status === 'released'); } else { list = list.filter((v) => v.status === 'developing' && v.currentStage === statusFilter); } } return list.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()); }, [project, statusFilter, isSuperAdmin, currentUserName]); // Compute actual overall progress per version const versionProgressMap = useMemo(() => { if (!project) return {} as Record; const map: Record = {}; for (const v of project.versions) { const vPlans = plans.filter((p) => p.versionId === v.id); const vReqs = requirements.filter((r) => r.versionId === v.id); const vReqIds = new Set(vReqs.map((r) => r.id)); const vDevTasks = devTasks.filter((t) => vReqIds.has(t.requirementId)); const vTestCases = testCases.filter((c) => c.versionId === v.id); const segments: number[] = []; const researchPlans = vPlans.filter((p) => p.type === 'research'); if (researchPlans.length > 0) { const totals = researchPlans.reduce((acc, p) => { const tasks = p.tasks || []; acc.total += tasks.length; acc.done += tasks.filter((t) => t.status === 'completed').length; return acc; }, { total: 0, done: 0 }); segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0); } 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; return acc; }, { total: 0, done: 0 }); segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0); } 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; return acc; }, { total: 0, done: 0 }); segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0); } if (vDevTasks.length > 0) { const totalEstimate = vDevTasks.reduce((sum, t) => sum + getEstimateHours(t), 0); let devProgress: number; if (totalEstimate === 0) { devProgress = vDevTasks.reduce((sum, t) => sum + STATUS_PROGRESS[t.status], 0) / vDevTasks.length; } else { const weighted = vDevTasks.reduce((sum, t) => sum + getEstimateHours(t) * STATUS_PROGRESS[t.status], 0); devProgress = weighted / totalEstimate; } segments.push(devProgress); } if (vTestCases.length > 0) { const executed = vTestCases.filter((c) => c.status === 'passed' || c.status === 'failed' || c.status === 'blocked').length; segments.push((executed / vTestCases.length) * 100); } map[v.id] = segments.length > 0 ? Math.round(segments.reduce((s, x) => s + x, 0) / segments.length) : 0; } return map; }, [project, plans, requirements, devTasks, testCases]); const stats = useMemo(() => { if (!project) return { total: 0, released: 0, reqCount: 0, bugCount: 0, estimateHours: 0, actualHours: 0 }; const total = project.versions.length; const released = project.versions.filter((v) => v.status === 'released').length; const reqCount = requirements.filter((r) => r.projectId === projectId).length; const versionIds = new Set(project.versions.map((v) => v.id)); const bugCount = bugs.filter((b) => versionIds.has(b.versionId)).length; const projectReqIds = new Set(requirements.filter((r) => r.projectId === projectId).map((r) => r.id)); const projectDevTasks = devTasks.filter((t) => projectReqIds.has(t.requirementId)); const { estimate, actual } = aggregateDevTaskHours(projectDevTasks); return { total, released, reqCount, bugCount, estimateHours: estimate, actualHours: actual }; }, [project, requirements, bugs, devTasks, projectId]); const teamByRole = useMemo(() => { if (!project) return {} as Record>; const map: Record> = {}; ROLES.forEach((r) => (map[r.key] = {})); project.versions.forEach((v) => { (v.members ?? []).forEach((m) => { if (!map[m.role]) map[m.role] = {}; map[m.role][m.name] = (map[m.role][m.name] || 0) + 1; }); }); return map; }, [project]); if (!project) { return (

项目不存在

); } return (
/ {project.name}
{project.productName}

版本记录

{FILTER_OPTIONS.map((opt) => ( ))}
{sortedVersions.length === 0 ? (
暂无版本
) : ( sortedVersions.map((v) => router.push(`/versions/${id}`)} />) )}
); }