fix: force dynamic for meeting page

This commit is contained in:
李超14pro
2026-01-25 21:55:29 +08:00
commit e3e5e89df6
112 changed files with 19073 additions and 0 deletions

411
app/analysis/page.tsx Normal file
View File

@@ -0,0 +1,411 @@
'use client';
import { useEffect, useState, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ProgressRing } from '@/components/progress-ring';
import { calculateProgress, isKRActive } from '@/lib/kr-utils';
import { REASON_CODES } from '@/lib/constants';
import type { Project, KR, User, Checkin } from '@/types/database';
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
PieChart,
Pie,
Cell,
LineChart,
Line,
Legend,
} from 'recharts';
import { BarChart3, PieChart as PieChartIcon, TrendingUp, Users, Target } from 'lucide-react';
interface KRWithRelations extends KR {
owner: User | null;
project: { id: string; name: string } | null;
}
interface CheckinWithRelations extends Checkin {
user: User | null;
kr: { id: string; title: string } | null;
}
const COLORS = ['#10b981', '#f59e0b', '#ef4444', '#6366f1', '#8b5cf6', '#ec4899'];
export default function AnalysisPage() {
const [projects, setProjects] = useState<Project[]>([]);
const [krs, setKRs] = useState<KRWithRelations[]>([]);
const [checkins, setCheckins] = useState<CheckinWithRelations[]>([]);
const [users, setUsers] = useState<User[]>([]);
const [selectedProjectId, setSelectedProjectId] = useState<string>('all');
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
async function fetchData() {
try {
const [projectsRes, krsRes, checkinsRes, usersRes] = await Promise.all([
fetch('/api/projects'),
fetch('/api/krs'),
fetch('/api/checkins?limit=100'),
fetch('/api/users'),
]);
if (projectsRes.ok) setProjects(await projectsRes.json());
if (krsRes.ok) setKRs(await krsRes.json());
if (checkinsRes.ok) setCheckins(await checkinsRes.json());
if (usersRes.ok) setUsers(await usersRes.json());
} catch (error) {
console.error('Failed to fetch data:', error);
} finally {
setIsLoading(false);
}
}
fetchData();
}, []);
const filteredKRs = useMemo(() => {
if (selectedProjectId === 'all') return krs;
return krs.filter(kr => kr.project_id === selectedProjectId);
}, [krs, selectedProjectId]);
const activeKRs = filteredKRs.filter(isKRActive);
const statusDistribution = useMemo(() => {
const green = activeKRs.filter(kr => kr.status === 'green').length;
const yellow = activeKRs.filter(kr => kr.status === 'yellow').length;
const red = activeKRs.filter(kr => kr.status === 'red').length;
return [
{ name: '正常', value: green, color: '#10b981' },
{ name: '警告', value: yellow, color: '#f59e0b' },
{ name: '风险', value: red, color: '#ef4444' },
].filter(item => item.value > 0);
}, [activeKRs]);
const reasonDistribution = useMemo(() => {
const reasons: Record<string, number> = {};
activeKRs
.filter(kr => kr.reason_code)
.forEach(kr => {
const code = kr.reason_code!;
reasons[code] = (reasons[code] || 0) + 1;
});
return Object.entries(reasons).map(([code, count]) => ({
name: REASON_CODES[code as keyof typeof REASON_CODES],
value: count,
}));
}, [activeKRs]);
const userPerformance = useMemo(() => {
const userMap: Record<string, { name: string; total: number; completed: number }> = {};
users.forEach(user => {
userMap[user.id] = { name: user.name, total: 0, completed: 0 };
});
activeKRs.forEach(kr => {
if (kr.owner_user_id && userMap[kr.owner_user_id]) {
userMap[kr.owner_user_id].total++;
if (calculateProgress(kr) >= 1) {
userMap[kr.owner_user_id].completed++;
}
}
});
return Object.values(userMap)
.filter(u => u.total > 0)
.map(u => ({
name: u.name,
total: u.total,
completed: u.completed,
rate: Math.round((u.completed / u.total) * 100),
}))
.sort((a, b) => b.rate - a.rate);
}, [activeKRs, users]);
const projectHealth = useMemo(() => {
return projects.map(project => {
const projectKRs = krs.filter(kr => kr.project_id === project.id && isKRActive(kr));
const completed = projectKRs.filter(kr => calculateProgress(kr) >= 1).length;
const total = projectKRs.length;
return {
name: project.name.length > 10 ? project.name.substring(0, 10) + '...' : project.name,
fullName: project.name,
total,
completed,
rate: total > 0 ? Math.round((completed / total) * 100) : 0,
status: project.status,
};
});
}, [projects, krs]);
const checkinTrend = useMemo(() => {
const last7Days: Record<string, number> = {};
for (let i = 6; i >= 0; i--) {
const date = new Date();
date.setDate(date.getDate() - i);
const dateStr = date.toISOString().split('T')[0];
last7Days[dateStr] = 0;
}
checkins.forEach(checkin => {
const dateStr = checkin.date;
if (last7Days[dateStr] !== undefined) {
last7Days[dateStr]++;
}
});
return Object.entries(last7Days).map(([date, count]) => ({
date: new Date(date).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }),
count,
}));
}, [checkins]);
if (isLoading) {
return (
<div className="max-w-7xl mx-auto px-4 py-8">
<div className="animate-pulse space-y-6">
<div className="h-8 bg-slate-200 rounded w-32" />
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{[1, 2, 3, 4].map(i => (
<div key={i} className="h-64 bg-slate-200 rounded-lg" />
))}
</div>
</div>
</div>
);
}
return (
<div className="max-w-7xl mx-auto px-4 py-8">
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
<BarChart3 className="h-6 w-6 text-teal-600" />
数据分析
</h1>
<p className="text-muted-foreground mt-1">KR 执行情况分析与洞察</p>
</div>
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
<SelectTrigger className="w-48">
<SelectValue placeholder="选择项目" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">所有项目</SelectItem>
{projects.map(project => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
<Card>
<CardContent className="pt-6 text-center">
<Target className="h-8 w-8 text-slate-300 mx-auto mb-2" />
<p className="text-3xl font-bold text-slate-800">{activeKRs.length}</p>
<p className="text-sm text-muted-foreground">进行中 KR</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6 text-center">
<TrendingUp className="h-8 w-8 text-emerald-300 mx-auto mb-2" />
<p className="text-3xl font-bold text-emerald-600">
{activeKRs.filter(kr => calculateProgress(kr) >= 1).length}
</p>
<p className="text-sm text-muted-foreground">已达标</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6 text-center">
<Users className="h-8 w-8 text-sky-300 mx-auto mb-2" />
<p className="text-3xl font-bold text-sky-600">{userPerformance.length}</p>
<p className="text-sm text-muted-foreground">参与人数</p>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6 text-center">
<BarChart3 className="h-8 w-8 text-amber-300 mx-auto mb-2" />
<p className="text-3xl font-bold text-amber-600">
{activeKRs.length > 0
? Math.round(
(activeKRs.filter(kr => calculateProgress(kr) >= 1).length / activeKRs.length) * 100
)
: 0}%
</p>
<p className="text-sm text-muted-foreground">整体完成率</p>
</CardContent>
</Card>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<PieChartIcon className="h-5 w-5" />
KR 状态分布
</CardTitle>
</CardHeader>
<CardContent>
{statusDistribution.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<PieChart>
<Pie
data={statusDistribution}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
paddingAngle={2}
dataKey="value"
label={({ name, value }) => `${name}: ${value}`}
>
{statusDistribution.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip />
</PieChart>
</ResponsiveContainer>
) : (
<p className="text-center text-muted-foreground py-12">暂无数据</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">问题原因分布</CardTitle>
</CardHeader>
<CardContent>
{reasonDistribution.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<BarChart data={reasonDistribution} layout="vertical">
<CartesianGrid strokeDasharray="3 3" />
<XAxis type="number" />
<YAxis type="category" dataKey="name" width={80} />
<Tooltip />
<Bar dataKey="value" fill="#f59e0b" radius={[0, 4, 4, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<p className="text-center text-muted-foreground py-12">暂无问题记录</p>
)}
</CardContent>
</Card>
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
<Card>
<CardHeader>
<CardTitle className="text-lg">项目完成率</CardTitle>
</CardHeader>
<CardContent>
{projectHealth.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<BarChart data={projectHealth}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip
content={({ active, payload }) => {
if (active && payload && payload.length) {
const data = payload[0].payload;
return (
<div className="bg-white p-3 border rounded shadow-lg">
<p className="font-medium">{data.fullName}</p>
<p className="text-sm text-muted-foreground">
完成: {data.completed}/{data.total} ({data.rate}%)
</p>
</div>
);
}
return null;
}}
/>
<Bar dataKey="rate" fill="#10b981" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
) : (
<p className="text-center text-muted-foreground py-12">暂无数据</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">打卡趋势 (近7天)</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={250}>
<LineChart data={checkinTrend}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Line
type="monotone"
dataKey="count"
stroke="#0d9488"
strokeWidth={2}
dot={{ fill: '#0d9488' }}
/>
</LineChart>
</ResponsiveContainer>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle className="text-lg">成员完成率排行</CardTitle>
</CardHeader>
<CardContent>
{userPerformance.length > 0 ? (
<div className="space-y-4">
{userPerformance.map((user, index) => (
<div key={user.name} className="flex items-center gap-4">
<span className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold ${
index === 0 ? 'bg-amber-100 text-amber-700' :
index === 1 ? 'bg-slate-200 text-slate-700' :
index === 2 ? 'bg-orange-100 text-orange-700' :
'bg-slate-100 text-slate-600'
}`}>
{index + 1}
</span>
<div className="flex-1">
<div className="flex items-center justify-between mb-1">
<span className="font-medium">{user.name}</span>
<span className="text-sm text-muted-foreground">
{user.completed}/{user.total} ({user.rate}%)
</span>
</div>
<div className="w-full bg-slate-100 rounded-full h-2">
<div
className="bg-teal-500 h-2 rounded-full transition-all"
style={{ width: `${user.rate}%` }}
/>
</div>
</div>
</div>
))}
</div>
) : (
<p className="text-center text-muted-foreground py-8">暂无数据</p>
)}
</CardContent>
</Card>
</div>
);
}