fix: force dynamic for meeting page
This commit is contained in:
332
app/admin/metrics/page.tsx
Normal file
332
app/admin/metrics/page.tsx
Normal file
@@ -0,0 +1,332 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { DIRECTION_LABELS } from '@/lib/constants';
|
||||
import type { Metric } from '@/types/database';
|
||||
import { toast } from 'sonner';
|
||||
import { Plus, Pencil, Trash2, Gauge, Loader2, TrendingUp, TrendingDown } from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
const metricSchema = z.object({
|
||||
name: z.string().min(1, '名称不能为空'),
|
||||
unit: z.string().min(1, '单位不能为空'),
|
||||
direction: z.enum(['increase', 'decrease']),
|
||||
category: z.string().optional(),
|
||||
});
|
||||
|
||||
type MetricFormValues = z.infer<typeof metricSchema>;
|
||||
|
||||
export default function AdminMetricsPage() {
|
||||
const { currentUser } = useUser();
|
||||
const [metrics, setMetrics] = useState<Metric[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [editingMetric, setEditingMetric] = useState<Metric | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const form = useForm<MetricFormValues>({
|
||||
resolver: zodResolver(metricSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
unit: '',
|
||||
direction: 'increase',
|
||||
category: '',
|
||||
},
|
||||
});
|
||||
|
||||
const fetchMetrics = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/metrics');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setMetrics(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch metrics:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchMetrics();
|
||||
}, []);
|
||||
|
||||
const onSubmit = async (values: MetricFormValues) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const url = editingMetric ? `/api/metrics/${editingMetric.id}` : '/api/metrics';
|
||||
const method = editingMetric ? 'PATCH' : 'POST';
|
||||
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '操作失败');
|
||||
}
|
||||
|
||||
toast.success(editingMetric ? '指标已更新' : '指标已创建');
|
||||
setIsDialogOpen(false);
|
||||
setEditingMetric(null);
|
||||
form.reset();
|
||||
fetchMetrics();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (metric: Metric) => {
|
||||
setEditingMetric(metric);
|
||||
form.reset({
|
||||
name: metric.name,
|
||||
unit: metric.unit,
|
||||
direction: metric.direction,
|
||||
category: metric.category || '',
|
||||
});
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleToggleActive = async (metric: Metric) => {
|
||||
try {
|
||||
const res = await fetch(`/api/metrics/${metric.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_active: !metric.is_active }),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('操作失败');
|
||||
|
||||
toast.success(metric.is_active ? '已停用' : '已启用');
|
||||
fetchMetrics();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (metricId: string) => {
|
||||
if (!confirm('确定要删除此指标吗?')) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/metrics/${metricId}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('删除失败');
|
||||
|
||||
toast.success('指标已删除');
|
||||
fetchMetrics();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDialogClose = () => {
|
||||
setIsDialogOpen(false);
|
||||
setEditingMetric(null);
|
||||
form.reset();
|
||||
};
|
||||
|
||||
if (currentUser?.role !== 'owner') {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8 text-center">
|
||||
<p className="text-muted-foreground">仅老板可访问此页面</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-4xl 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="h-64 bg-slate-200 rounded-lg" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const categories = Array.from(new Set(metrics.map(m => m.category).filter(Boolean)));
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl 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">
|
||||
<Gauge className="h-6 w-6 text-teal-600" />
|
||||
指标库管理
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">管理可复用的 KR 指标</p>
|
||||
</div>
|
||||
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-teal-600 hover:bg-teal-700">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
新建指标
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingMetric ? '编辑指标' : '新建指标'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>指标名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:页面加载时间" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="unit"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>单位 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:秒、个、%" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="direction"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>方向</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(DIRECTION_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="category"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>分类</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:技术性能、业务" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex gap-2 pt-4">
|
||||
<Button type="submit" disabled={isSubmitting} className="bg-teal-600 hover:bg-teal-700">
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{editingMetric ? '保存' : '创建'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={handleDialogClose}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>指标名称</TableHead>
|
||||
<TableHead>单位</TableHead>
|
||||
<TableHead>方向</TableHead>
|
||||
<TableHead>分类</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead className="text-right">操作</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{metrics.map(metric => (
|
||||
<TableRow key={metric.id} className={!metric.is_active ? 'opacity-50' : ''}>
|
||||
<TableCell className="font-medium">{metric.name}</TableCell>
|
||||
<TableCell>{metric.unit}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-1">
|
||||
{metric.direction === 'increase' ? (
|
||||
<TrendingUp className="h-4 w-4 text-emerald-500" />
|
||||
) : (
|
||||
<TrendingDown className="h-4 w-4 text-rose-500" />
|
||||
)}
|
||||
{DIRECTION_LABELS[metric.direction]}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{metric.category || '-'}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Switch
|
||||
checked={metric.is_active}
|
||||
onCheckedChange={() => handleToggleActive(metric)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Button variant="ghost" size="sm" onClick={() => handleEdit(metric)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => handleDelete(metric.id)}>
|
||||
<Trash2 className="h-4 w-4 text-rose-500" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
|
||||
{metrics.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
|
||||
暂无指标
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
436
app/admin/templates/page.tsx
Normal file
436
app/admin/templates/page.tsx
Normal file
@@ -0,0 +1,436 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm, useFieldArray } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { DIRECTION_LABELS } from '@/lib/constants';
|
||||
import type { Template } from '@/types/database';
|
||||
import { toast } from 'sonner';
|
||||
import { Plus, Pencil, Trash2, Files, Loader2, X } from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
const templateItemSchema = z.object({
|
||||
title: z.string().min(1, '标题不能为空'),
|
||||
metricName: z.string().min(1, '指标名称不能为空'),
|
||||
unit: z.string().min(1, '单位不能为空'),
|
||||
direction: z.enum(['increase', 'decrease']),
|
||||
targetValue: z.number().positive('目标值必须大于0'),
|
||||
});
|
||||
|
||||
const templateSchema = z.object({
|
||||
name: z.string().min(1, '名称不能为空'),
|
||||
description: z.string().optional(),
|
||||
project_type: z.string().optional(),
|
||||
items: z.array(templateItemSchema).min(1, '至少需要一个模板项'),
|
||||
});
|
||||
|
||||
type TemplateFormValues = z.infer<typeof templateSchema>;
|
||||
|
||||
export default function AdminTemplatesPage() {
|
||||
// Force re-compile
|
||||
const { currentUser } = useUser();
|
||||
const [templates, setTemplates] = useState<Template[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [editingTemplate, setEditingTemplate] = useState<Template | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const form = useForm<TemplateFormValues>({
|
||||
resolver: zodResolver(templateSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
description: '',
|
||||
project_type: '',
|
||||
items: [{ title: '', metricName: '', unit: '', direction: 'increase', targetValue: 0 }],
|
||||
},
|
||||
});
|
||||
|
||||
const { fields, append, remove } = useFieldArray({
|
||||
control: form.control,
|
||||
name: 'items',
|
||||
});
|
||||
|
||||
const fetchTemplates = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/templates');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setTemplates(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch templates:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchTemplates();
|
||||
}, []);
|
||||
|
||||
const onSubmit = async (values: TemplateFormValues) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const url = editingTemplate ? `/api/templates/${editingTemplate.id}` : '/api/templates';
|
||||
const method = editingTemplate ? 'PATCH' : 'POST';
|
||||
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '操作失败');
|
||||
}
|
||||
|
||||
toast.success(editingTemplate ? '模板已更新' : '模板已创建');
|
||||
setIsDialogOpen(false);
|
||||
setEditingTemplate(null);
|
||||
form.reset();
|
||||
fetchTemplates();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (template: Template) => {
|
||||
setEditingTemplate(template);
|
||||
form.reset({
|
||||
name: template.name,
|
||||
description: template.description || '',
|
||||
project_type: template.project_type || '',
|
||||
items: template.items,
|
||||
});
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleToggleActive = async (template: Template) => {
|
||||
try {
|
||||
const res = await fetch(`/api/templates/${template.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_active: !template.is_active }),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('操作失败');
|
||||
|
||||
toast.success(template.is_active ? '已停用' : '已启用');
|
||||
fetchTemplates();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (templateId: string) => {
|
||||
if (!confirm('确定要删除此模板吗?')) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/templates/${templateId}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('删除失败');
|
||||
|
||||
toast.success('模板已删除');
|
||||
fetchTemplates();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDialogClose = () => {
|
||||
setIsDialogOpen(false);
|
||||
setEditingTemplate(null);
|
||||
form.reset();
|
||||
};
|
||||
|
||||
if (currentUser?.role !== 'owner') {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8 text-center">
|
||||
<p className="text-muted-foreground">仅老板可访问此页面</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-5xl 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].map(i => (
|
||||
<div key={i} className="h-48 bg-slate-200 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl 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">
|
||||
<Files className="h-6 w-6 text-teal-600" />
|
||||
模板库管理
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">管理可复用的 KR 模板</p>
|
||||
</div>
|
||||
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-teal-600 hover:bg-teal-700">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
新建模板
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingTemplate ? '编辑模板' : '新建模板'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>模板名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:产品迭代模板" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>描述</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="模板描述" rows={2} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="project_type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>适用项目类型</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:产品研发" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<FormLabel>模板项 *</FormLabel>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => append({ title: '', metricName: '', unit: '', direction: 'increase', targetValue: 0 })}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
添加项
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{fields.map((field, index) => (
|
||||
<div key={field.id} className="p-4 bg-slate-50 rounded-lg relative">
|
||||
{fields.length > 1 && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute top-2 right-2"
|
||||
onClick={() => remove(index)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.title`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>KR 标题</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.metricName`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>指标名称</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.unit`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>单位</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.direction`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>方向</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(DIRECTION_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={`items.${index}.targetValue`}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>默认目标值</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
{...field}
|
||||
onChange={e => field.onChange(parseFloat(e.target.value) || 0)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-4">
|
||||
<Button type="submit" disabled={isSubmitting} className="bg-teal-600 hover:bg-teal-700">
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{editingTemplate ? '保存' : '创建'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={handleDialogClose}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{templates.map(template => (
|
||||
<Card key={template.id} className={!template.is_active ? 'opacity-50' : ''}>
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<CardTitle className="text-lg">{template.name}</CardTitle>
|
||||
{template.project_type && (
|
||||
<span className="text-xs text-muted-foreground bg-slate-100 px-2 py-0.5 rounded mt-1 inline-block">
|
||||
{template.project_type}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
checked={template.is_active}
|
||||
onCheckedChange={() => handleToggleActive(template)}
|
||||
/>
|
||||
<Button variant="ghost" size="sm" onClick={() => handleEdit(template)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => handleDelete(template.id)}>
|
||||
<Trash2 className="h-4 w-4 text-rose-500" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{template.description && (
|
||||
<p className="text-sm text-muted-foreground mb-3">{template.description}</p>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
{template.items.slice(0, 3).map((item, index) => (
|
||||
<div key={index} className="flex items-center justify-between text-sm p-2 bg-slate-50 rounded">
|
||||
<span>{item.title}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{item.targetValue} {item.unit}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{template.items.length > 3 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
+ {template.items.length - 3} 更多项
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
|
||||
{templates.length === 0 && (
|
||||
<div className="col-span-full text-center py-12">
|
||||
<Files className="h-12 w-12 text-slate-300 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">暂无模板</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
251
app/admin/users/page.tsx
Normal file
251
app/admin/users/page.tsx
Normal file
@@ -0,0 +1,251 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { ROLE_LABELS } from '@/lib/constants';
|
||||
import type { User } from '@/types/database';
|
||||
import { toast } from 'sonner';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
import { Plus, Pencil, Trash2, Users, Loader2, Crown, Briefcase, User as UserIcon } from 'lucide-react';
|
||||
|
||||
const userSchema = z.object({
|
||||
name: z.string().min(1, '名称不能为空'),
|
||||
role: z.enum(['owner', 'pm', 'member']),
|
||||
});
|
||||
|
||||
type UserFormValues = z.infer<typeof userSchema>;
|
||||
|
||||
const roleIcons = {
|
||||
owner: Crown,
|
||||
pm: Briefcase,
|
||||
member: UserIcon,
|
||||
};
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { currentUser, users, refreshUsers } = useUser();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const form = useForm<UserFormValues>({
|
||||
resolver: zodResolver(userSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
role: 'member',
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: UserFormValues) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const url = editingUser ? `/api/users/${editingUser.id}` : '/api/users';
|
||||
const method = editingUser ? 'PATCH' : 'POST';
|
||||
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(values),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '操作失败');
|
||||
}
|
||||
|
||||
toast.success(editingUser ? '用户已更新' : '用户已创建');
|
||||
setIsDialogOpen(false);
|
||||
setEditingUser(null);
|
||||
form.reset();
|
||||
refreshUsers();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : '操作失败');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (user: User) => {
|
||||
setEditingUser(user);
|
||||
form.reset({
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
});
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (userId: string) => {
|
||||
if (!confirm('确定要删除此用户吗?')) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/users/${userId}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('删除失败');
|
||||
|
||||
toast.success('用户已删除');
|
||||
refreshUsers();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
}
|
||||
};
|
||||
|
||||
const handleDialogClose = () => {
|
||||
setIsDialogOpen(false);
|
||||
setEditingUser(null);
|
||||
form.reset();
|
||||
};
|
||||
|
||||
if (currentUser?.role !== 'owner') {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8 text-center">
|
||||
<p className="text-muted-foreground">仅老板可访问此页面</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl 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">
|
||||
<Users className="h-6 w-6 text-teal-600" />
|
||||
用户管理
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">管理系统用户</p>
|
||||
</div>
|
||||
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-teal-600 hover:bg-teal-700">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
新建用户
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingUser ? '编辑用户' : '新建用户'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="输入用户名称" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="role"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>角色 *</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(ROLE_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex gap-2 pt-4">
|
||||
<Button type="submit" disabled={isSubmitting} className="bg-teal-600 hover:bg-teal-700">
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{editingUser ? '保存' : '创建'}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={handleDialogClose}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>用户</TableHead>
|
||||
<TableHead>角色</TableHead>
|
||||
<TableHead>创建时间</TableHead>
|
||||
<TableHead className="text-right">操作</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users.map(user => {
|
||||
const RoleIcon = roleIcons[user.role];
|
||||
return (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarFallback className="bg-slate-100">
|
||||
{user.name.charAt(0)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="font-medium">{user.name}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-2">
|
||||
<RoleIcon className="h-4 w-4 text-muted-foreground" />
|
||||
{ROLE_LABELS[user.role]}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{new Date(user.created_at).toLocaleDateString('zh-CN')}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<Button variant="ghost" size="sm" onClick={() => handleEdit(user)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDelete(user.id)}
|
||||
disabled={user.id === currentUser?.id}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-rose-500" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
411
app/analysis/page.tsx
Normal file
411
app/analysis/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
136
app/api/checkins/route.ts
Normal file
136
app/api/checkins/route.ts
Normal file
@@ -0,0 +1,136 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
import { determineKRStatus, determineProjectStatus } from '@/lib/kr-utils';
|
||||
import type { KR, Checkin } from '@/types/database';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const krId = searchParams.get('kr_id');
|
||||
const projectId = searchParams.get('project_id');
|
||||
const userId = searchParams.get('user_id');
|
||||
const limit = searchParams.get('limit');
|
||||
|
||||
let query = supabase
|
||||
.from('checkins')
|
||||
.select(`
|
||||
*,
|
||||
user:users(id, name, avatar_url),
|
||||
kr:krs(id, title, metric_name, unit)
|
||||
`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (krId) query = query.eq('kr_id', krId);
|
||||
if (projectId) query = query.eq('project_id', projectId);
|
||||
if (userId) query = query.eq('user_id', userId);
|
||||
if (limit) query = query.limit(parseInt(limit));
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { kr_id, project_id, user_id, date, current_value, confidence, reason_code, note } = body;
|
||||
|
||||
if (!kr_id || !project_id || current_value === undefined || confidence === undefined) {
|
||||
return NextResponse.json(
|
||||
{ error: 'KR ID、项目ID、当前值和信心度为必填项' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { data: krData, error: krError } = await supabase
|
||||
.from('krs')
|
||||
.select('*')
|
||||
.eq('id', kr_id)
|
||||
.single();
|
||||
|
||||
if (krError || !krData) {
|
||||
return NextResponse.json({ error: 'KR不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
const kr = krData as KR;
|
||||
|
||||
const { data: recentCheckins } = await supabase
|
||||
.from('checkins')
|
||||
.select('*')
|
||||
.eq('kr_id', kr_id)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(2);
|
||||
|
||||
const delta_value = current_value - kr.current_value;
|
||||
|
||||
const updatedKR: KR = {
|
||||
...kr,
|
||||
current_value,
|
||||
confidence,
|
||||
reason_code: reason_code || kr.reason_code,
|
||||
note: note || kr.note,
|
||||
};
|
||||
|
||||
const newStatus = determineKRStatus(updatedKR, (recentCheckins as Checkin[]) || []);
|
||||
|
||||
if ((newStatus === 'yellow' || newStatus === 'red') && !reason_code) {
|
||||
return NextResponse.json(
|
||||
{ error: '黄色或红色状态必须提供原因代码' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const checkinDate = date || new Date().toISOString().split('T')[0];
|
||||
|
||||
const { data: checkin, error: checkinError } = await supabase
|
||||
.from('checkins')
|
||||
.insert({
|
||||
kr_id,
|
||||
project_id,
|
||||
user_id,
|
||||
date: checkinDate,
|
||||
current_value,
|
||||
delta_value,
|
||||
confidence,
|
||||
status_snapshot: newStatus,
|
||||
reason_code,
|
||||
note,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (checkinError) {
|
||||
return NextResponse.json({ error: checkinError.message }, { status: 500 });
|
||||
}
|
||||
|
||||
await supabase
|
||||
.from('krs')
|
||||
.update({
|
||||
current_value,
|
||||
confidence,
|
||||
status: newStatus,
|
||||
reason_code: reason_code || (newStatus === 'green' ? null : kr.reason_code),
|
||||
note: note || kr.note,
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', kr_id);
|
||||
|
||||
const { data: projectKRs } = await supabase
|
||||
.from('krs')
|
||||
.select('status')
|
||||
.eq('project_id', project_id);
|
||||
|
||||
if (projectKRs) {
|
||||
const projectStatus = determineProjectStatus(projectKRs as KR[]);
|
||||
await supabase
|
||||
.from('projects')
|
||||
.update({ status: projectStatus, updated_at: new Date().toISOString() })
|
||||
.eq('id', project_id);
|
||||
}
|
||||
|
||||
return NextResponse.json(checkin, { status: 201 });
|
||||
}
|
||||
109
app/api/krs/[id]/route.ts
Normal file
109
app/api/krs/[id]/route.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('krs')
|
||||
.select(`
|
||||
*,
|
||||
owner:users!krs_owner_user_id_fkey(id, name, role, avatar_url),
|
||||
project:projects(id, name, status),
|
||||
objective:objectives(id, title, period_start, period_end)
|
||||
`)
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: 'KR不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const {
|
||||
title,
|
||||
metric_name,
|
||||
unit,
|
||||
direction,
|
||||
target_value,
|
||||
current_value,
|
||||
confidence,
|
||||
status,
|
||||
reason_code,
|
||||
note,
|
||||
need_owner_help,
|
||||
period_start,
|
||||
period_end,
|
||||
period_type,
|
||||
period_name,
|
||||
objective_id,
|
||||
} = body;
|
||||
|
||||
if ((status === 'yellow' || status === 'red') && !reason_code && !body.skipReasonCodeCheck) {
|
||||
return NextResponse.json(
|
||||
{ error: '黄色或红色状态必须提供原因代码' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
|
||||
if (title !== undefined) updateData.title = title;
|
||||
if (metric_name !== undefined) updateData.metric_name = metric_name;
|
||||
if (unit !== undefined) updateData.unit = unit;
|
||||
if (direction !== undefined) updateData.direction = direction;
|
||||
if (target_value !== undefined) updateData.target_value = target_value;
|
||||
if (current_value !== undefined) updateData.current_value = current_value;
|
||||
if (confidence !== undefined) updateData.confidence = confidence;
|
||||
if (status !== undefined) updateData.status = status;
|
||||
if (reason_code !== undefined) updateData.reason_code = reason_code;
|
||||
if (note !== undefined) updateData.note = note;
|
||||
if (need_owner_help !== undefined) updateData.need_owner_help = need_owner_help;
|
||||
if (period_start !== undefined) updateData.period_start = period_start;
|
||||
if (period_end !== undefined) updateData.period_end = period_end;
|
||||
if (period_type !== undefined) updateData.period_type = period_type;
|
||||
if (period_name !== undefined) updateData.period_name = period_name;
|
||||
if (objective_id !== undefined) updateData.objective_id = objective_id;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('krs')
|
||||
.update(updateData)
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('krs')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
114
app/api/krs/route.ts
Normal file
114
app/api/krs/route.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const projectId = searchParams.get('project_id');
|
||||
const objectiveId = searchParams.get('objective_id');
|
||||
const ownerUserId = searchParams.get('owner_user_id');
|
||||
const status = searchParams.get('status');
|
||||
|
||||
let query = supabase
|
||||
.from('krs')
|
||||
.select(`
|
||||
*,
|
||||
owner:users!krs_owner_user_id_fkey(id, name, role, avatar_url),
|
||||
project:projects(id, name, status)
|
||||
`)
|
||||
.order('period_start', { ascending: false });
|
||||
|
||||
if (projectId) query = query.eq('project_id', projectId);
|
||||
if (objectiveId) query = query.eq('objective_id', objectiveId);
|
||||
if (ownerUserId) query = query.eq('owner_user_id', ownerUserId);
|
||||
if (status) query = query.eq('status', status);
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const {
|
||||
project_id,
|
||||
objective_id,
|
||||
period_type,
|
||||
period_name,
|
||||
period_start,
|
||||
period_end,
|
||||
title,
|
||||
metric_name,
|
||||
unit,
|
||||
direction,
|
||||
target_value,
|
||||
owner_user_id,
|
||||
confidence,
|
||||
note,
|
||||
} = body;
|
||||
|
||||
if (!project_id || !title || !metric_name || !unit || !target_value || !period_start || !period_end) {
|
||||
return NextResponse.json(
|
||||
{ error: '项目ID、标题、指标名称、单位、目标值、开始和结束日期为必填项' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (target_value <= 0) {
|
||||
return NextResponse.json({ error: '目标值必须大于0' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (new Date(period_end) < new Date(period_start)) {
|
||||
return NextResponse.json({ error: '结束日期不能早于开始日期' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (owner_user_id) {
|
||||
const { data: existingKRs } = await supabase
|
||||
.from('krs')
|
||||
.select('id')
|
||||
.eq('owner_user_id', owner_user_id)
|
||||
.eq('period_start', period_start)
|
||||
.eq('period_end', period_end);
|
||||
|
||||
if (existingKRs && existingKRs.length >= 3) {
|
||||
return NextResponse.json(
|
||||
{ error: '该用户在此周期内已有3个KR,无法继续创建' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('krs')
|
||||
.insert({
|
||||
project_id,
|
||||
objective_id,
|
||||
period_type: period_type || 'custom',
|
||||
period_name,
|
||||
period_start,
|
||||
period_end,
|
||||
title,
|
||||
metric_name,
|
||||
unit,
|
||||
direction: direction || 'increase',
|
||||
target_value,
|
||||
current_value: 0,
|
||||
owner_user_id,
|
||||
confidence: confidence || 80,
|
||||
status: 'green',
|
||||
note,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
70
app/api/meetings/[id]/route.ts
Normal file
70
app/api/meetings/[id]/route.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('meetings')
|
||||
.select(`
|
||||
*,
|
||||
created_by_user:users!meetings_created_by_fkey(id, name, avatar_url),
|
||||
project:projects(id, name)
|
||||
`)
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: '会议记录不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { summary, decisions, risks, next_period_commitments } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
|
||||
if (summary !== undefined) updateData.summary = summary;
|
||||
if (decisions !== undefined) updateData.decisions = decisions;
|
||||
if (risks !== undefined) updateData.risks = risks;
|
||||
if (next_period_commitments !== undefined) updateData.next_period_commitments = next_period_commitments;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('meetings')
|
||||
.update(updateData)
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('meetings')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
59
app/api/meetings/route.ts
Normal file
59
app/api/meetings/route.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const projectId = searchParams.get('project_id');
|
||||
|
||||
let query = supabase
|
||||
.from('meetings')
|
||||
.select(`
|
||||
*,
|
||||
created_by_user:users!meetings_created_by_fkey(id, name, avatar_url),
|
||||
project:projects(id, name)
|
||||
`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (projectId) query = query.eq('project_id', projectId);
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { project_id, period_start, period_end, summary, decisions, risks, next_period_commitments, created_by } = body;
|
||||
|
||||
if (!project_id || !period_start || !period_end || !summary) {
|
||||
return NextResponse.json(
|
||||
{ error: '项目ID、周期开始日期、周期结束日期和总结为必填项' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('meetings')
|
||||
.insert({
|
||||
project_id,
|
||||
period_start,
|
||||
period_end,
|
||||
summary,
|
||||
decisions,
|
||||
risks,
|
||||
next_period_commitments,
|
||||
created_by,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
67
app/api/metrics/[id]/route.ts
Normal file
67
app/api/metrics/[id]/route.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('metrics')
|
||||
.select('*')
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: '指标不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { name, unit, direction, category, is_active } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (unit !== undefined) updateData.unit = unit;
|
||||
if (direction !== undefined) updateData.direction = direction;
|
||||
if (category !== undefined) updateData.category = category;
|
||||
if (is_active !== undefined) updateData.is_active = is_active;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('metrics')
|
||||
.update(updateData)
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('metrics')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
48
app/api/metrics/route.ts
Normal file
48
app/api/metrics/route.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const activeOnly = searchParams.get('active_only') === 'true';
|
||||
const category = searchParams.get('category');
|
||||
|
||||
let query = supabase.from('metrics').select('*').order('name', { ascending: true });
|
||||
|
||||
if (activeOnly) query = query.eq('is_active', true);
|
||||
if (category) query = query.eq('category', category);
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { name, unit, direction, category } = body;
|
||||
|
||||
if (!name || !unit) {
|
||||
return NextResponse.json({ error: '名称和单位为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('metrics')
|
||||
.insert({
|
||||
name,
|
||||
unit,
|
||||
direction: direction || 'increase',
|
||||
category,
|
||||
is_active: true,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
68
app/api/objectives/[id]/route.ts
Normal file
68
app/api/objectives/[id]/route.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('objectives')
|
||||
.select('*')
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: '目标不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { title, description, period_start, period_end } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
|
||||
if (title !== undefined) updateData.title = title;
|
||||
if (description !== undefined) updateData.description = description;
|
||||
if (period_start !== undefined) updateData.period_start = period_start;
|
||||
if (period_end !== undefined) updateData.period_end = period_end;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('objectives')
|
||||
.update(updateData)
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('objectives')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
48
app/api/objectives/route.ts
Normal file
48
app/api/objectives/route.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const projectId = searchParams.get('project_id');
|
||||
|
||||
let query = supabase.from('objectives').select('*').order('period_start', { ascending: false });
|
||||
|
||||
if (projectId) {
|
||||
query = query.eq('project_id', projectId);
|
||||
}
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { project_id, title, description, period_start, period_end, created_by } = body;
|
||||
|
||||
if (!project_id || !title || !period_start || !period_end) {
|
||||
return NextResponse.json({ error: '项目ID、标题、开始日期和结束日期为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (new Date(period_end) < new Date(period_start)) {
|
||||
return NextResponse.json({ error: '结束日期不能早于开始日期' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('objectives')
|
||||
.insert({ project_id, title, description, period_start, period_end, created_by })
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
66
app/api/projects/[id]/members/route.ts
Normal file
66
app/api/projects/[id]/members/route.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('project_members')
|
||||
.select('user_id, users(id, name, role, avatar_url)')
|
||||
.eq('project_id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { user_id } = body;
|
||||
|
||||
if (!user_id) {
|
||||
return NextResponse.json({ error: '用户ID为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('project_members')
|
||||
.insert({ project_id: params.id, user_id })
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const userId = searchParams.get('user_id');
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: '用户ID为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from('project_members')
|
||||
.delete()
|
||||
.eq('project_id', params.id)
|
||||
.eq('user_id', userId);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
91
app/api/projects/[id]/route.ts
Normal file
91
app/api/projects/[id]/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('projects')
|
||||
.select(`
|
||||
*,
|
||||
owner:users!projects_owner_id_fkey(id, name, role, avatar_url),
|
||||
pm:users!projects_pm_id_fkey(id, name, role, avatar_url)
|
||||
`)
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: '项目不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
const { data: members } = await supabase
|
||||
.from('project_members')
|
||||
.select('user_id, users(id, name, role, avatar_url)')
|
||||
.eq('project_id', params.id);
|
||||
|
||||
return NextResponse.json({ ...data, members: members || [] });
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { name, description, owner_id, pm_id, project_type, status, member_ids } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (description !== undefined) updateData.description = description;
|
||||
if (owner_id !== undefined) updateData.owner_id = owner_id;
|
||||
if (pm_id !== undefined) updateData.pm_id = pm_id;
|
||||
if (project_type !== undefined) updateData.project_type = project_type;
|
||||
if (status !== undefined) updateData.status = status;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('projects')
|
||||
.update(updateData)
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (member_ids !== undefined) {
|
||||
await supabase.from('project_members').delete().eq('project_id', params.id);
|
||||
|
||||
if (member_ids.length > 0) {
|
||||
const memberRecords = member_ids.map((userId: string) => ({
|
||||
project_id: params.id,
|
||||
user_id: userId,
|
||||
}));
|
||||
await supabase.from('project_members').insert(memberRecords);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('projects')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
58
app/api/projects/route.ts
Normal file
58
app/api/projects/route.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET() {
|
||||
const { data, error } = await supabase
|
||||
.from('projects')
|
||||
.select(`
|
||||
*,
|
||||
owner:users!projects_owner_id_fkey(id, name, role, avatar_url),
|
||||
pm:users!projects_pm_id_fkey(id, name, role, avatar_url)
|
||||
`)
|
||||
.order('created_at', { ascending: false });
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { name, description, owner_id, pm_id, project_type, member_ids } = body;
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: '项目名称为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { data: project, error: projectError } = await supabase
|
||||
.from('projects')
|
||||
.insert({
|
||||
name,
|
||||
description,
|
||||
owner_id,
|
||||
pm_id,
|
||||
project_type: project_type || 'general',
|
||||
status: 'green',
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (projectError) {
|
||||
return NextResponse.json({ error: projectError.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (member_ids && member_ids.length > 0) {
|
||||
const memberRecords = member_ids.map((userId: string) => ({
|
||||
project_id: project.id,
|
||||
user_id: userId,
|
||||
}));
|
||||
|
||||
await supabase.from('project_members').insert(memberRecords);
|
||||
}
|
||||
|
||||
return NextResponse.json(project, { status: 201 });
|
||||
}
|
||||
284
app/api/seed/route.ts
Normal file
284
app/api/seed/route.ts
Normal file
@@ -0,0 +1,284 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
function addDays(date: Date, days: number): string {
|
||||
const result = new Date(date);
|
||||
result.setDate(result.getDate() + days);
|
||||
return result.toISOString().split('T')[0];
|
||||
}
|
||||
|
||||
export async function POST() {
|
||||
const today = new Date();
|
||||
const todayStr = today.toISOString().split('T')[0];
|
||||
|
||||
const ownerUser = {
|
||||
name: '老板',
|
||||
role: 'owner' as const,
|
||||
avatar_url: null,
|
||||
};
|
||||
|
||||
const pmUser = {
|
||||
name: '张项目经理',
|
||||
role: 'pm' as const,
|
||||
avatar_url: null,
|
||||
};
|
||||
|
||||
const memberUser = {
|
||||
name: '李工程师',
|
||||
role: 'member' as const,
|
||||
avatar_url: null,
|
||||
};
|
||||
|
||||
const { data: users, error: usersError } = await supabase
|
||||
.from('users')
|
||||
.insert([ownerUser, pmUser, memberUser])
|
||||
.select();
|
||||
|
||||
if (usersError || !users) {
|
||||
return NextResponse.json({ error: usersError?.message || '创建用户失败' }, { status: 500 });
|
||||
}
|
||||
|
||||
const [owner, pm, member] = users;
|
||||
|
||||
const project1 = {
|
||||
name: '产品升级项目',
|
||||
description: '核心产品功能升级与优化',
|
||||
owner_id: owner.id,
|
||||
pm_id: pm.id,
|
||||
project_type: '产品研发',
|
||||
status: 'green' as const,
|
||||
};
|
||||
|
||||
const project2 = {
|
||||
name: '市场拓展计划',
|
||||
description: '新市场开拓与客户获取',
|
||||
owner_id: owner.id,
|
||||
pm_id: pm.id,
|
||||
project_type: '市场营销',
|
||||
status: 'yellow' as const,
|
||||
};
|
||||
|
||||
const { data: projects, error: projectsError } = await supabase
|
||||
.from('projects')
|
||||
.insert([project1, project2])
|
||||
.select();
|
||||
|
||||
if (projectsError || !projects) {
|
||||
return NextResponse.json({ error: projectsError?.message || '创建项目失败' }, { status: 500 });
|
||||
}
|
||||
|
||||
const [proj1, proj2] = projects;
|
||||
|
||||
await supabase.from('project_members').insert([
|
||||
{ project_id: proj1.id, user_id: owner.id },
|
||||
{ project_id: proj1.id, user_id: pm.id },
|
||||
{ project_id: proj1.id, user_id: member.id },
|
||||
{ project_id: proj2.id, user_id: owner.id },
|
||||
{ project_id: proj2.id, user_id: pm.id },
|
||||
]);
|
||||
|
||||
const objective1 = {
|
||||
project_id: proj1.id,
|
||||
title: '提升产品用户体验和性能',
|
||||
description: '通过优化核心功能,提升用户满意度和系统性能',
|
||||
period_start: addDays(today, -15),
|
||||
period_end: addDays(today, 15),
|
||||
created_by: owner.id,
|
||||
};
|
||||
|
||||
const { data: objectives, error: objectivesError } = await supabase
|
||||
.from('objectives')
|
||||
.insert([objective1])
|
||||
.select();
|
||||
|
||||
if (objectivesError || !objectives) {
|
||||
return NextResponse.json({ error: objectivesError?.message || '创建目标失败' }, { status: 500 });
|
||||
}
|
||||
|
||||
const [obj1] = objectives;
|
||||
|
||||
const krs = [
|
||||
{
|
||||
project_id: proj1.id,
|
||||
objective_id: obj1.id,
|
||||
period_type: '1w' as const,
|
||||
period_name: '本周',
|
||||
period_start: addDays(today, -3),
|
||||
period_end: addDays(today, 4),
|
||||
title: '完成首页加载速度优化',
|
||||
metric_name: '页面加载时间',
|
||||
unit: '秒',
|
||||
direction: 'decrease' as const,
|
||||
target_value: 2,
|
||||
current_value: 2.8,
|
||||
owner_user_id: member.id,
|
||||
confidence: 85,
|
||||
status: 'green' as const,
|
||||
reason_code: null,
|
||||
note: null,
|
||||
need_owner_help: false,
|
||||
},
|
||||
{
|
||||
project_id: proj1.id,
|
||||
objective_id: obj1.id,
|
||||
period_type: '3d' as const,
|
||||
period_name: '紧急任务',
|
||||
period_start: todayStr,
|
||||
period_end: addDays(today, 3),
|
||||
title: '修复关键Bug',
|
||||
metric_name: 'Bug修复数',
|
||||
unit: '个',
|
||||
direction: 'increase' as const,
|
||||
target_value: 5,
|
||||
current_value: 2,
|
||||
owner_user_id: member.id,
|
||||
confidence: 70,
|
||||
status: 'yellow' as const,
|
||||
reason_code: 'RESOURCE' as const,
|
||||
note: '需要更多测试资源',
|
||||
},
|
||||
{
|
||||
project_id: proj1.id,
|
||||
objective_id: obj1.id,
|
||||
period_type: '2w' as const,
|
||||
period_name: '双周迭代',
|
||||
period_start: addDays(today, -7),
|
||||
period_end: addDays(today, 7),
|
||||
title: '提升用户满意度评分',
|
||||
metric_name: 'NPS评分',
|
||||
unit: '分',
|
||||
direction: 'increase' as const,
|
||||
target_value: 50,
|
||||
current_value: 35,
|
||||
owner_user_id: pm.id,
|
||||
confidence: 60,
|
||||
status: 'yellow' as const,
|
||||
reason_code: 'DEPENDENCY' as const,
|
||||
note: '依赖功能还未上线',
|
||||
need_owner_help: false,
|
||||
},
|
||||
{
|
||||
project_id: proj2.id,
|
||||
objective_id: null,
|
||||
period_type: 'monthly' as const,
|
||||
period_name: '月度目标',
|
||||
period_start: addDays(today, -10),
|
||||
period_end: addDays(today, 20),
|
||||
title: '新客户获取',
|
||||
metric_name: '新签客户数',
|
||||
unit: '家',
|
||||
direction: 'increase' as const,
|
||||
target_value: 10,
|
||||
current_value: 3,
|
||||
owner_user_id: pm.id,
|
||||
confidence: 45,
|
||||
status: 'red' as const,
|
||||
reason_code: 'EXECUTION' as const,
|
||||
note: '市场推广效果不及预期',
|
||||
need_owner_help: true,
|
||||
},
|
||||
];
|
||||
|
||||
const { data: krsData, error: krsError } = await supabase
|
||||
.from('krs')
|
||||
.insert(krs)
|
||||
.select();
|
||||
|
||||
if (krsError || !krsData) {
|
||||
return NextResponse.json({ error: krsError?.message || '创建KR失败' }, { status: 500 });
|
||||
}
|
||||
|
||||
const checkins = krsData.flatMap((kr) => {
|
||||
const baseCheckins = [];
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const checkinDate = addDays(today, -i - 1);
|
||||
const progressMultiplier = (20 - i) / 21;
|
||||
baseCheckins.push({
|
||||
kr_id: kr.id,
|
||||
project_id: kr.project_id,
|
||||
user_id: kr.owner_user_id,
|
||||
date: checkinDate,
|
||||
current_value: kr.current_value * progressMultiplier,
|
||||
delta_value: kr.current_value * 0.1,
|
||||
confidence: kr.confidence + (i * 5),
|
||||
status_snapshot: i === 0 ? kr.status : 'green',
|
||||
reason_code: i === 0 ? kr.reason_code : null,
|
||||
note: i === 0 ? `进度更新 - ${kr.title}` : null,
|
||||
});
|
||||
}
|
||||
return baseCheckins;
|
||||
});
|
||||
|
||||
await supabase.from('checkins').insert(checkins);
|
||||
|
||||
const meeting = {
|
||||
project_id: proj1.id,
|
||||
period_start: addDays(today, -7),
|
||||
period_end: addDays(today, -1),
|
||||
summary: `本周期完成情况总结:
|
||||
- 页面加载优化进展顺利,预计可按时完成
|
||||
- Bug修复进度略有滞后,需要协调测试资源
|
||||
- 用户满意度提升依赖新功能上线
|
||||
|
||||
完成率:约65%`,
|
||||
decisions: `1. 协调测试团队支援Bug修复
|
||||
2. 推动依赖功能优先上线
|
||||
3. 下周进行用户回访收集反馈`,
|
||||
risks: `- 测试资源紧张可能影响交付质量
|
||||
- 依赖功能延期风险`,
|
||||
next_period_commitments: `- 完成所有关键Bug修复
|
||||
- 页面加载时间降至2秒以内
|
||||
- 收集至少20份用户反馈`,
|
||||
created_by: pm.id,
|
||||
};
|
||||
|
||||
await supabase.from('meetings').insert([meeting]);
|
||||
|
||||
const metrics = [
|
||||
{ name: '页面加载时间', unit: '秒', direction: 'decrease' as const, category: '技术性能' },
|
||||
{ name: 'Bug修复数', unit: '个', direction: 'increase' as const, category: '质量' },
|
||||
{ name: 'NPS评分', unit: '分', direction: 'increase' as const, category: '用户体验' },
|
||||
{ name: '新签客户数', unit: '家', direction: 'increase' as const, category: '业务' },
|
||||
{ name: '活跃用户数', unit: '人', direction: 'increase' as const, category: '业务' },
|
||||
{ name: '客户流失率', unit: '%', direction: 'decrease' as const, category: '业务' },
|
||||
{ name: '代码覆盖率', unit: '%', direction: 'increase' as const, category: '质量' },
|
||||
{ name: '响应时间', unit: 'ms', direction: 'decrease' as const, category: '技术性能' },
|
||||
];
|
||||
|
||||
await supabase.from('metrics').insert(metrics);
|
||||
|
||||
const templates = [
|
||||
{
|
||||
name: '产品迭代模板',
|
||||
description: '适用于产品功能迭代的KR模板',
|
||||
project_type: '产品研发',
|
||||
tags: ['产品', '迭代', '功能'],
|
||||
items: [
|
||||
{ title: '功能上线', metricName: '功能完成数', unit: '个', direction: 'increase', targetValue: 3 },
|
||||
{ title: '性能优化', metricName: '响应时间', unit: 'ms', direction: 'decrease', targetValue: 200 },
|
||||
{ title: '质量保障', metricName: 'Bug数', unit: '个', direction: 'decrease', targetValue: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '市场拓展模板',
|
||||
description: '适用于市场营销项目的KR模板',
|
||||
project_type: '市场营销',
|
||||
tags: ['市场', '营销', '客户'],
|
||||
items: [
|
||||
{ title: '客户获取', metricName: '新客户数', unit: '家', direction: 'increase', targetValue: 10 },
|
||||
{ title: '线索转化', metricName: '转化率', unit: '%', direction: 'increase', targetValue: 30 },
|
||||
{ title: '客户留存', metricName: '续约率', unit: '%', direction: 'increase', targetValue: 85 },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
await supabase.from('templates').insert(templates);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
ownerId: owner.id,
|
||||
message: '演示数据已成功创建',
|
||||
});
|
||||
}
|
||||
68
app/api/templates/[id]/route.ts
Normal file
68
app/api/templates/[id]/route.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('templates')
|
||||
.select('*')
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: '模板不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { name, description, project_type, tags, items, is_active } = body;
|
||||
|
||||
const updateData: Record<string, unknown> = { updated_at: new Date().toISOString() };
|
||||
if (name !== undefined) updateData.name = name;
|
||||
if (description !== undefined) updateData.description = description;
|
||||
if (project_type !== undefined) updateData.project_type = project_type;
|
||||
if (tags !== undefined) updateData.tags = tags;
|
||||
if (items !== undefined) updateData.items = items;
|
||||
if (is_active !== undefined) updateData.is_active = is_active;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('templates')
|
||||
.update(updateData)
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('templates')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
49
app/api/templates/route.ts
Normal file
49
app/api/templates/route.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const activeOnly = searchParams.get('active_only') === 'true';
|
||||
const projectType = searchParams.get('project_type');
|
||||
|
||||
let query = supabase.from('templates').select('*').order('name', { ascending: true });
|
||||
|
||||
if (activeOnly) query = query.eq('is_active', true);
|
||||
if (projectType) query = query.eq('project_type', projectType);
|
||||
|
||||
const { data, error } = await query;
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { name, description, project_type, tags, items } = body;
|
||||
|
||||
if (!name || !items || items.length === 0) {
|
||||
return NextResponse.json({ error: '名称和至少一个模板项为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('templates')
|
||||
.insert({
|
||||
name,
|
||||
description,
|
||||
project_type,
|
||||
tags: tags || [],
|
||||
items,
|
||||
is_active: true,
|
||||
})
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
60
app/api/users/[id]/route.ts
Normal file
60
app/api/users/[id]/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { data, error } = await supabase
|
||||
.from('users')
|
||||
.select('*')
|
||||
.eq('id', params.id)
|
||||
.maybeSingle();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const body = await request.json();
|
||||
const { name, role, avatar_url } = body;
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('users')
|
||||
.update({ name, role, avatar_url, updated_at: new Date().toISOString() })
|
||||
.eq('id', params.id)
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
const { error } = await supabase
|
||||
.from('users')
|
||||
.delete()
|
||||
.eq('id', params.id);
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
38
app/api/users/route.ts
Normal file
38
app/api/users/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
|
||||
export async function GET() {
|
||||
const { data, error } = await supabase
|
||||
.from('users')
|
||||
.select('*')
|
||||
.order('created_at', { ascending: true });
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const body = await request.json();
|
||||
const { name, role, avatar_url } = body;
|
||||
|
||||
if (!name || !role) {
|
||||
return NextResponse.json({ error: '名称和角色为必填项' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('users')
|
||||
.insert({ name, role, avatar_url })
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json(data, { status: 201 });
|
||||
}
|
||||
82
app/globals.css
Normal file
82
app/globals.css
Normal file
@@ -0,0 +1,82 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--foreground-rgb: 0, 0, 0;
|
||||
--background-start-rgb: 214, 219, 220;
|
||||
--background-end-rgb: 255, 255, 255;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--foreground-rgb: 255, 255, 255;
|
||||
--background-start-rgb: 0, 0, 0;
|
||||
--background-end-rgb: 0, 0, 0;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 0 0% 3.9%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 3.9%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 0 0% 3.9%;
|
||||
--primary: 0 0% 9%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 0 0% 96.1%;
|
||||
--secondary-foreground: 0 0% 9%;
|
||||
--muted: 0 0% 96.1%;
|
||||
--muted-foreground: 0 0% 45.1%;
|
||||
--accent: 0 0% 96.1%;
|
||||
--accent-foreground: 0 0% 9%;
|
||||
--destructive: 0 84.2% 60.2%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 89.8%;
|
||||
--input: 0 0% 89.8%;
|
||||
--ring: 0 0% 3.9%;
|
||||
--chart-1: 12 76% 61%;
|
||||
--chart-2: 173 58% 39%;
|
||||
--chart-3: 197 37% 24%;
|
||||
--chart-4: 43 74% 66%;
|
||||
--chart-5: 27 87% 67%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
.dark {
|
||||
--background: 0 0% 3.9%;
|
||||
--foreground: 0 0% 98%;
|
||||
--card: 0 0% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 0 0% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 0 0% 9%;
|
||||
--secondary: 0 0% 14.9%;
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 0 0% 14.9%;
|
||||
--muted-foreground: 0 0% 63.9%;
|
||||
--accent: 0 0% 14.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 14.9%;
|
||||
--input: 0 0% 14.9%;
|
||||
--ring: 0 0% 83.1%;
|
||||
--chart-1: 220 70% 50%;
|
||||
--chart-2: 160 60% 45%;
|
||||
--chart-3: 30 80% 55%;
|
||||
--chart-4: 280 65% 60%;
|
||||
--chart-5: 340 75% 55%;
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
651
app/krs/[id]/client-page.tsx
Normal file
651
app/krs/[id]/client-page.tsx
Normal file
@@ -0,0 +1,651 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { StatusBadge, StatusDot } from '@/components/status-badge';
|
||||
import { ProgressRing } from '@/components/progress-ring';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
calculateProgress,
|
||||
calculateExpectedProgress,
|
||||
getDaysRemaining,
|
||||
formatDateRange,
|
||||
isKRActive,
|
||||
} from '@/lib/kr-utils';
|
||||
import { REASON_CODES, PERIOD_TYPES, DIRECTION_LABELS } from '@/lib/constants';
|
||||
import type { KR, User, Checkin, Objective } from '@/types/database';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Clock,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
Target,
|
||||
AlertTriangle,
|
||||
Calendar,
|
||||
User as UserIcon,
|
||||
HandHelping,
|
||||
Loader2,
|
||||
Pencil,
|
||||
Trash2,
|
||||
} from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
interface KRWithRelations extends KR {
|
||||
owner: User | null;
|
||||
project: { id: string; name: string; status: string } | null;
|
||||
objective: Objective | null;
|
||||
}
|
||||
|
||||
interface CheckinWithRelations extends Checkin {
|
||||
user: User | null;
|
||||
}
|
||||
|
||||
const checkinSchema = z.object({
|
||||
current_value: z.number(),
|
||||
confidence: z.number().min(0).max(100),
|
||||
reason_code: z.string().optional(),
|
||||
note: z.string().optional(),
|
||||
});
|
||||
|
||||
type CheckinFormValues = z.infer<typeof checkinSchema>;
|
||||
|
||||
export default function KRDetailPage({ krId }: { krId: string }) {
|
||||
const router = useRouter();
|
||||
const { currentUser } = useUser();
|
||||
|
||||
const [kr, setKR] = useState<KRWithRelations | null>(null);
|
||||
const [checkins, setCheckins] = useState<CheckinWithRelations[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isCheckinOpen, setIsCheckinOpen] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [krRes, checkinsRes] = await Promise.all([
|
||||
fetch(`/api/krs/${krId}`),
|
||||
fetch(`/api/checkins?kr_id=${krId}`),
|
||||
]);
|
||||
|
||||
if (krRes.ok) {
|
||||
const krData = await krRes.json();
|
||||
setKR(krData);
|
||||
}
|
||||
|
||||
if (checkinsRes.ok) {
|
||||
const checkinsData = await checkinsRes.json();
|
||||
setCheckins(checkinsData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch KR data:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [krId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const form = useForm<CheckinFormValues>({
|
||||
resolver: zodResolver(checkinSchema),
|
||||
defaultValues: {
|
||||
current_value: kr?.current_value || 0,
|
||||
confidence: kr?.confidence || 80,
|
||||
reason_code: '',
|
||||
note: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (kr) {
|
||||
form.reset({
|
||||
current_value: kr.current_value,
|
||||
confidence: kr.confidence,
|
||||
reason_code: kr.reason_code || '',
|
||||
note: '',
|
||||
});
|
||||
}
|
||||
}, [kr, form]);
|
||||
|
||||
const onCheckinSubmit = async (values: CheckinFormValues) => {
|
||||
if (!kr) return;
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/checkins', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
kr_id: kr.id,
|
||||
project_id: kr.project_id,
|
||||
user_id: currentUser?.id,
|
||||
current_value: values.current_value,
|
||||
confidence: values.confidence,
|
||||
reason_code: values.reason_code || null,
|
||||
note: values.note || null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '打卡失败');
|
||||
}
|
||||
|
||||
toast.success('打卡成功');
|
||||
setIsCheckinOpen(false);
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleNeedHelp = async () => {
|
||||
if (!kr) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/krs/${kr.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
need_owner_help: !kr.need_owner_help,
|
||||
skipReasonCodeCheck: true,
|
||||
}),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
toast.success(kr.need_owner_help ? '已取消求助' : '已发送求助请求');
|
||||
fetchData();
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error('操作失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteKR = async () => {
|
||||
if (!kr) return;
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/krs/${kr.id}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('删除失败');
|
||||
toast.success('KR 已删除');
|
||||
router.push(`/projects/${kr.project_id}`);
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditKR = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!kr) return;
|
||||
|
||||
setIsEditing(true);
|
||||
const formData = new FormData(e.currentTarget);
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/krs/${kr.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: formData.get('title'),
|
||||
metric_name: formData.get('metric_name'),
|
||||
unit: formData.get('unit'),
|
||||
target_value: parseFloat(formData.get('target_value') as string),
|
||||
period_start: formData.get('period_start'),
|
||||
period_end: formData.get('period_end'),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('更新失败');
|
||||
|
||||
toast.success('KR 已更新');
|
||||
setIsEditDialogOpen(false);
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsEditing(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8">
|
||||
<div className="animate-pulse space-y-6">
|
||||
<div className="h-6 bg-slate-200 rounded w-24" />
|
||||
<div className="h-10 bg-slate-200 rounded w-64" />
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 h-96 bg-slate-200 rounded-lg" />
|
||||
<div className="h-64 bg-slate-200 rounded-lg" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!kr) {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8 text-center">
|
||||
<p className="text-muted-foreground">KR 不存在</p>
|
||||
<Button asChild className="mt-4" variant="outline">
|
||||
<Link href="/my-krs">返回我的 KR</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const progress = calculateProgress(kr);
|
||||
const expectedProgress = calculateExpectedProgress(kr);
|
||||
const daysLeft = getDaysRemaining(kr.period_end);
|
||||
const isActive = isKRActive(kr);
|
||||
const isOwner = currentUser?.id === kr.owner_user_id;
|
||||
const TrendIcon = kr.direction === 'increase' ? TrendingUp : TrendingDown;
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4 py-8">
|
||||
<div className="mb-6">
|
||||
<Link
|
||||
href="/my-krs"
|
||||
className="inline-flex items-center text-sm text-muted-foreground hover:text-slate-800 mb-4"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
返回我的 KR
|
||||
</Link>
|
||||
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<h1 className="text-2xl font-bold text-slate-800">{kr.title}</h1>
|
||||
<StatusBadge status={kr.status} />
|
||||
{kr.need_owner_help && (
|
||||
<span className="text-xs bg-amber-100 text-amber-700 px-2 py-1 rounded flex items-center gap-1">
|
||||
<HandHelping className="h-3 w-3" />
|
||||
需要帮助
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
||||
<Link href={`/projects/${kr.project_id}`} className="hover:text-slate-800">
|
||||
{kr.project?.name}
|
||||
</Link>
|
||||
<span>|</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<UserIcon className="h-4 w-4" />
|
||||
{kr.owner?.name || '未分配'}
|
||||
</span>
|
||||
<span>|</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
{formatDateRange(kr.period_start, kr.period_end)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isActive && (
|
||||
<div className="flex gap-2">
|
||||
{currentUser?.role === 'owner' && (
|
||||
<>
|
||||
<Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>编辑 KR</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleEditKR} className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="kr-title">KR 标题</Label>
|
||||
<Input id="kr-title" name="title" defaultValue={kr.title} required />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="kr-metric">指标名称</Label>
|
||||
<Input id="kr-metric" name="metric_name" defaultValue={kr.metric_name} required />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="kr-unit">单位</Label>
|
||||
<Input id="kr-unit" name="unit" defaultValue={kr.unit} required />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="kr-target">目标值</Label>
|
||||
<Input type="number" step="any" id="kr-target" name="target_value" defaultValue={kr.target_value} required />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="kr-start">开始日期</Label>
|
||||
<Input type="date" id="kr-start" name="period_start" defaultValue={kr.period_start} required />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="kr-end">结束日期</Label>
|
||||
<Input type="date" id="kr-end" name="period_end" defaultValue={kr.period_end} required />
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" disabled={isEditing} className="w-full">
|
||||
{isEditing && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
保存修改
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="icon" className="text-rose-500 hover:text-rose-600">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定要删除此 KR 吗?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
此操作无法撤销。这将永久删除 KR 及其所有打卡记录。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteKR}
|
||||
className="bg-rose-600 hover:bg-rose-700"
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)}
|
||||
<Dialog open={isCheckinOpen} onOpenChange={setIsCheckinOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button className="bg-teal-600 hover:bg-teal-700">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
打卡更新
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>KR 进度打卡</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onCheckinSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="current_value"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>当前值 ({kr.unit})</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
step="any"
|
||||
{...field}
|
||||
onChange={e => field.onChange(parseFloat(e.target.value) || 0)}
|
||||
/>
|
||||
</FormControl>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
目标值: {kr.target_value} {kr.unit}
|
||||
</p>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="confidence"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>信心度 ({field.value}%)</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="range"
|
||||
min="0"
|
||||
max="100"
|
||||
{...field}
|
||||
onChange={e => field.onChange(parseInt(e.target.value))}
|
||||
className="w-full"
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="flex justify-between text-xs text-muted-foreground">
|
||||
<span>0%</span>
|
||||
<span>50%</span>
|
||||
<span>100%</span>
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="reason_code"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>问题原因 (如有)</FormLabel>
|
||||
<Select
|
||||
onValueChange={(value) => field.onChange(value === "unspecified" ? "" : value)}
|
||||
value={field.value || "unspecified"}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择原因类型" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="unspecified">无问题</SelectItem>
|
||||
{Object.entries(REASON_CODES).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="note"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>备注</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="补充说明" rows={2} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isSubmitting}>
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
提交打卡
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div className="flex items-center gap-6">
|
||||
<ProgressRing progress={progress} status={kr.status} size={100} strokeWidth={8} />
|
||||
<div>
|
||||
<p className="text-3xl font-bold text-slate-800">
|
||||
{kr.current_value} / {kr.target_value}
|
||||
</p>
|
||||
<p className="text-muted-foreground">{kr.unit}</p>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
<TrendIcon className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{DIRECTION_LABELS[kr.direction]}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-muted-foreground mb-1">期望进度</p>
|
||||
<p className="text-2xl font-semibold text-slate-600">
|
||||
{Math.round(expectedProgress * 100)}%
|
||||
</p>
|
||||
{isActive && (
|
||||
<p className={`text-sm ${daysLeft <= 3 ? 'text-amber-600' : 'text-muted-foreground'}`}>
|
||||
<Clock className="h-3 w-3 inline mr-1" />
|
||||
剩余 {daysLeft} 天
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{kr.reason_code && kr.status !== 'green' && (
|
||||
<div className="bg-amber-50 rounded-lg p-4 flex items-start gap-3">
|
||||
<AlertTriangle className="h-5 w-5 text-amber-500 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-amber-800">{REASON_CODES[kr.reason_code]}</p>
|
||||
{kr.note && <p className="text-sm text-amber-700 mt-1">{kr.note}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">打卡记录</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{checkins.length === 0 ? (
|
||||
<p className="text-center text-muted-foreground py-8">暂无打卡记录</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{checkins.map((checkin, index) => (
|
||||
<div key={checkin.id} className="flex items-start gap-4">
|
||||
<div className="flex flex-col items-center">
|
||||
<StatusDot status={checkin.status_snapshot} size="md" />
|
||||
{index < checkins.length - 1 && (
|
||||
<div className="w-0.5 h-12 bg-slate-200 mt-2" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex-1 pb-4">
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="font-medium">
|
||||
{checkin.current_value} {kr.unit}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{new Date(checkin.created_at).toLocaleString('zh-CN', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{checkin.user?.name} | 信心度 {checkin.confidence}%
|
||||
{checkin.delta_value !== null && checkin.delta_value !== 0 && (
|
||||
<span className={checkin.delta_value > 0 ? 'text-emerald-600' : 'text-rose-600'}>
|
||||
{' '}({checkin.delta_value > 0 ? '+' : ''}{checkin.delta_value})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{checkin.reason_code && (
|
||||
<p className="text-sm text-amber-600 mt-1">
|
||||
{REASON_CODES[checkin.reason_code]}
|
||||
</p>
|
||||
)}
|
||||
{checkin.note && (
|
||||
<p className="text-sm text-slate-600 mt-1">{checkin.note}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">KR 详情</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">周期类型</p>
|
||||
<p className="font-medium">{PERIOD_TYPES[kr.period_type]}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">指标名称</p>
|
||||
<p className="font-medium">{kr.metric_name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">信心度</p>
|
||||
<p className="font-medium">{kr.confidence}%</p>
|
||||
</div>
|
||||
{kr.objective && (
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">关联目标</p>
|
||||
<p className="font-medium">{kr.objective.title}</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{isOwner && isActive && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">快捷操作</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="font-medium">请求老板帮助</p>
|
||||
<p className="text-sm text-muted-foreground">遇到困难时发送求助</p>
|
||||
</div>
|
||||
<Switch checked={kr.need_owner_help} onCheckedChange={toggleNeedHelp} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
8
app/krs/[id]/page.tsx
Normal file
8
app/krs/[id]/page.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
|
||||
import KRDetailPage from './client-page';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function Page({ params }: { params: { id: string } }) {
|
||||
return <KRDetailPage krId={params.id} />;
|
||||
}
|
||||
27
app/layout.tsx
Normal file
27
app/layout.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
import './globals.css';
|
||||
import type { Metadata } from 'next';
|
||||
import { Inter } from 'next/font/google';
|
||||
import { AppShell } from '@/components/app-shell';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
|
||||
const inter = Inter({ subsets: ['latin'] });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'OKR 执行系统 - 目标管理',
|
||||
description: '让目标被持续看见、被拆解、被跟进、被纠偏、被完成',
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body className={inter.className}>
|
||||
<AppShell>{children}</AppShell>
|
||||
<Toaster position="top-right" />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
550
app/meeting/page.tsx
Normal file
550
app/meeting/page.tsx
Normal file
@@ -0,0 +1,550 @@
|
||||
'use client';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { useEffect, useState, useMemo } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { StatusDot } from '@/components/status-badge';
|
||||
import { ProgressRing } from '@/components/progress-ring';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { calculateProgress, formatDateRange } from '@/lib/kr-utils';
|
||||
import { REASON_CODES } from '@/lib/constants';
|
||||
import type { Project, KR, User, Meeting } from '@/types/database';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
CalendarClock,
|
||||
FileText,
|
||||
AlertTriangle,
|
||||
CheckCircle,
|
||||
Loader2,
|
||||
Save,
|
||||
Presentation,
|
||||
} from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
interface ProjectWithRelations extends Project {
|
||||
owner: User | null;
|
||||
pm: User | null;
|
||||
}
|
||||
|
||||
interface KRWithRelations extends KR {
|
||||
owner: User | null;
|
||||
}
|
||||
|
||||
const meetingSchema = z.object({
|
||||
summary: z.string().min(1, '总结不能为空'),
|
||||
decisions: z.string().optional(),
|
||||
risks: z.string().optional(),
|
||||
next_period_commitments: z.string().optional(),
|
||||
});
|
||||
|
||||
type MeetingFormValues = z.infer<typeof meetingSchema>;
|
||||
|
||||
export default function MeetingPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const initialProjectId = searchParams.get('project_id');
|
||||
const { currentUser } = useUser();
|
||||
|
||||
const [projects, setProjects] = useState<ProjectWithRelations[]>([]);
|
||||
const [krs, setKRs] = useState<KRWithRelations[]>([]);
|
||||
const [meetings, setMeetings] = useState<Meeting[]>([]);
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string>(initialProjectId || '');
|
||||
const [periodStart, setPeriodStart] = useState<string>('');
|
||||
const [periodEnd, setPeriodEnd] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [showPresentation, setShowPresentation] = useState(false);
|
||||
|
||||
const form = useForm<MeetingFormValues>({
|
||||
resolver: zodResolver(meetingSchema),
|
||||
defaultValues: {
|
||||
summary: '',
|
||||
decisions: '',
|
||||
risks: '',
|
||||
next_period_commitments: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
try {
|
||||
const [projectsRes, krsRes, meetingsRes] = await Promise.all([
|
||||
fetch('/api/projects'),
|
||||
fetch('/api/krs'),
|
||||
fetch('/api/meetings'),
|
||||
]);
|
||||
|
||||
if (projectsRes.ok) {
|
||||
const data = await projectsRes.json();
|
||||
setProjects(data);
|
||||
}
|
||||
|
||||
if (krsRes.ok) {
|
||||
const data = await krsRes.json();
|
||||
setKRs(data);
|
||||
}
|
||||
|
||||
if (meetingsRes.ok) {
|
||||
const data = await meetingsRes.json();
|
||||
setMeetings(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch data:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchData();
|
||||
|
||||
const today = new Date();
|
||||
const weekAgo = new Date(today);
|
||||
weekAgo.setDate(weekAgo.getDate() - 7);
|
||||
|
||||
setPeriodStart(weekAgo.toISOString().split('T')[0]);
|
||||
setPeriodEnd(today.toISOString().split('T')[0]);
|
||||
}, []);
|
||||
|
||||
const periodKRs = useMemo(() => {
|
||||
if (!selectedProjectId || !periodStart || !periodEnd) return [];
|
||||
|
||||
return krs.filter(kr => {
|
||||
if (kr.project_id !== selectedProjectId) return false;
|
||||
return kr.period_start <= periodEnd && kr.period_end >= periodStart;
|
||||
});
|
||||
}, [krs, selectedProjectId, periodStart, periodEnd]);
|
||||
|
||||
const completedKRs = periodKRs.filter(kr => calculateProgress(kr) >= 1);
|
||||
const incompleteKRs = periodKRs.filter(kr => calculateProgress(kr) < 1);
|
||||
const riskKRs = periodKRs.filter(kr => kr.status === 'red' || kr.status === 'yellow');
|
||||
|
||||
const generateSummary = () => {
|
||||
const totalCount = periodKRs.length;
|
||||
const completedCount = completedKRs.length;
|
||||
const completionRate = totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0;
|
||||
|
||||
let summary = `本周期完成情况总结:\n`;
|
||||
summary += `- 共 ${totalCount} 个 KR,完成 ${completedCount} 个\n`;
|
||||
summary += `- 完成率:${completionRate}%\n\n`;
|
||||
|
||||
if (completedKRs.length > 0) {
|
||||
summary += `已完成:\n`;
|
||||
completedKRs.forEach(kr => {
|
||||
summary += `- ${kr.title} (${kr.current_value}/${kr.target_value} ${kr.unit})\n`;
|
||||
});
|
||||
summary += '\n';
|
||||
}
|
||||
|
||||
if (incompleteKRs.length > 0) {
|
||||
summary += `未完成:\n`;
|
||||
incompleteKRs.forEach(kr => {
|
||||
const progress = Math.round(calculateProgress(kr) * 100);
|
||||
summary += `- ${kr.title} (进度 ${progress}%`;
|
||||
if (kr.reason_code) {
|
||||
summary += ` - ${REASON_CODES[kr.reason_code]}`;
|
||||
}
|
||||
summary += `)\n`;
|
||||
});
|
||||
}
|
||||
|
||||
form.setValue('summary', summary);
|
||||
|
||||
if (riskKRs.length > 0) {
|
||||
let risks = '';
|
||||
riskKRs.forEach(kr => {
|
||||
risks += `- ${kr.title}`;
|
||||
if (kr.reason_code) {
|
||||
risks += `: ${REASON_CODES[kr.reason_code]}`;
|
||||
}
|
||||
if (kr.note) {
|
||||
risks += ` (${kr.note})`;
|
||||
}
|
||||
risks += '\n';
|
||||
});
|
||||
form.setValue('risks', risks);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (values: MeetingFormValues) => {
|
||||
if (!selectedProjectId || !periodStart || !periodEnd) {
|
||||
toast.error('请选择项目和周期');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/meetings', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
project_id: selectedProjectId,
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
...values,
|
||||
created_by: currentUser?.id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '保存失败');
|
||||
}
|
||||
|
||||
toast.success('会议纪要已保存');
|
||||
form.reset();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : '保存失败');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const selectedProject = projects.find(p => p.id === selectedProjectId);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-6xl 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="h-64 bg-slate-200 rounded-lg" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (showPresentation) {
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-900 text-white p-8">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowPresentation(false)}
|
||||
className="mb-8 text-white border-white hover:bg-slate-800"
|
||||
>
|
||||
退出演示模式
|
||||
</Button>
|
||||
|
||||
<div className="max-w-4xl mx-auto space-y-8">
|
||||
<div className="text-center mb-12">
|
||||
<h1 className="text-4xl font-bold mb-4">{selectedProject?.name} 例会</h1>
|
||||
<p className="text-xl text-slate-400">
|
||||
{formatDateRange(periodStart, periodEnd)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-6 mb-12">
|
||||
<Card className="bg-slate-800 border-slate-700">
|
||||
<CardContent className="pt-6 text-center">
|
||||
<p className="text-5xl font-bold text-white">{periodKRs.length}</p>
|
||||
<p className="text-slate-400">总 KR 数</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="bg-emerald-900 border-emerald-700">
|
||||
<CardContent className="pt-6 text-center">
|
||||
<p className="text-5xl font-bold text-emerald-400">{completedKRs.length}</p>
|
||||
<p className="text-emerald-300">已完成</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="bg-rose-900 border-rose-700">
|
||||
<CardContent className="pt-6 text-center">
|
||||
<p className="text-5xl font-bold text-rose-400">{riskKRs.length}</p>
|
||||
<p className="text-rose-300">需关注</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="bg-slate-800 border-slate-700">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-white">KR 完成情况</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{periodKRs.map(kr => (
|
||||
<div key={kr.id} className="flex items-center gap-4 p-3 bg-slate-700 rounded-lg">
|
||||
<ProgressRing progress={calculateProgress(kr)} status={kr.status} size={48} />
|
||||
<div className="flex-1">
|
||||
<p className="font-medium text-white">{kr.title}</p>
|
||||
<p className="text-sm text-slate-400">{kr.owner?.name}</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-lg font-semibold text-white">
|
||||
{kr.current_value}/{kr.target_value} {kr.unit}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{form.getValues('risks') && (
|
||||
<Card className="bg-amber-900 border-amber-700">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-amber-100 flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5" />
|
||||
风险与阻塞
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<pre className="text-amber-100 whitespace-pre-wrap text-lg">
|
||||
{form.getValues('risks')}
|
||||
</pre>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
|
||||
<CalendarClock className="h-6 w-6 text-teal-600" />
|
||||
例会模式
|
||||
</h1>
|
||||
<p className="text-muted-foreground mt-1">选择项目和周期,自动生成会议总结</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">会议设置</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">选择项目</label>
|
||||
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择项目" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{projects.map(project => (
|
||||
<SelectItem key={project.id} value={project.id}>
|
||||
{project.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">开始日期</label>
|
||||
<Input
|
||||
type="date"
|
||||
value={periodStart}
|
||||
onChange={e => setPeriodStart(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium mb-2 block">结束日期</label>
|
||||
<Input
|
||||
type="date"
|
||||
value={periodEnd}
|
||||
onChange={e => setPeriodEnd(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={generateSummary}
|
||||
disabled={!selectedProjectId}
|
||||
variant="outline"
|
||||
>
|
||||
<FileText className="h-4 w-4 mr-2" />
|
||||
自动生成总结
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setShowPresentation(true)}
|
||||
disabled={!selectedProjectId || periodKRs.length === 0}
|
||||
variant="outline"
|
||||
>
|
||||
<Presentation className="h-4 w-4 mr-2" />
|
||||
演示模式
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedProjectId && periodKRs.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">
|
||||
周期内 KR ({periodKRs.length})
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{periodKRs.map(kr => (
|
||||
<div key={kr.id} className="flex items-center gap-4 p-3 bg-slate-50 rounded-lg">
|
||||
<ProgressRing progress={calculateProgress(kr)} status={kr.status} size={48} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-slate-800 truncate">{kr.title}</p>
|
||||
<p className="text-sm text-muted-foreground">{kr.owner?.name}</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="font-medium">
|
||||
{kr.current_value}/{kr.target_value} {kr.unit}
|
||||
</p>
|
||||
{kr.reason_code && (
|
||||
<p className="text-xs text-amber-600">{REASON_CODES[kr.reason_code]}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">会议纪要</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="summary"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>总结 *</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="本周期完成情况总结" rows={8} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="decisions"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>决议</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="会议决议" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="risks"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>风险</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="风险与阻塞" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="next_period_commitments"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>下周期承诺</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="下周期承诺事项" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || !selectedProjectId}
|
||||
className="bg-teal-600 hover:bg-teal-700"
|
||||
>
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
保存会议纪要
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">周期统计</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between p-3 bg-slate-50 rounded-lg">
|
||||
<span className="text-muted-foreground">总 KR 数</span>
|
||||
<span className="text-xl font-bold">{periodKRs.length}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between p-3 bg-emerald-50 rounded-lg">
|
||||
<span className="flex items-center gap-2 text-emerald-700">
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
已完成
|
||||
</span>
|
||||
<span className="text-xl font-bold text-emerald-700">{completedKRs.length}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between p-3 bg-amber-50 rounded-lg">
|
||||
<span className="flex items-center gap-2 text-amber-700">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
需关注
|
||||
</span>
|
||||
<span className="text-xl font-bold text-amber-700">{riskKRs.length}</span>
|
||||
</div>
|
||||
{periodKRs.length > 0 && (
|
||||
<div className="pt-4 border-t">
|
||||
<p className="text-sm text-muted-foreground mb-2">完成率</p>
|
||||
<p className="text-3xl font-bold text-slate-800">
|
||||
{Math.round((completedKRs.length / periodKRs.length) * 100)}%
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">历史会议</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{meetings.filter(m => m.project_id === selectedProjectId).length === 0 ? (
|
||||
<p className="text-center text-muted-foreground py-4">暂无历史记录</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{meetings
|
||||
.filter(m => m.project_id === selectedProjectId)
|
||||
.slice(0, 5)
|
||||
.map(meeting => (
|
||||
<div key={meeting.id} className="p-3 bg-slate-50 rounded-lg">
|
||||
<p className="text-sm font-medium">
|
||||
{formatDateRange(meeting.period_start, meeting.period_end)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground line-clamp-2 mt-1">
|
||||
{meeting.summary.split('\n')[0]}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
202
app/my-krs/page.tsx
Normal file
202
app/my-krs/page.tsx
Normal file
@@ -0,0 +1,202 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { StatusDot } from '@/components/status-badge';
|
||||
import { ProgressRing } from '@/components/progress-ring';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { calculateProgress, getDaysRemaining, formatDateRange, isKRActive, getTodayInTokyo } from '@/lib/kr-utils';
|
||||
import { PERIOD_TYPES, REASON_CODES } from '@/lib/constants';
|
||||
import type { KR, User } from '@/types/database';
|
||||
import { Target, Clock, AlertTriangle, CheckCircle, History } from 'lucide-react';
|
||||
|
||||
interface KRWithRelations extends KR {
|
||||
owner: User | null;
|
||||
project: { id: string; name: string; status: string } | null;
|
||||
}
|
||||
|
||||
export default function MyKRsPage() {
|
||||
const { currentUser } = useUser();
|
||||
const [krs, setKRs] = useState<KRWithRelations[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchKRs() {
|
||||
try {
|
||||
const res = await fetch('/api/krs');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setKRs(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch KRs:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchKRs();
|
||||
}, []);
|
||||
|
||||
const myKRs = krs.filter(kr => kr.owner_user_id === currentUser?.id);
|
||||
const activeKRs = myKRs.filter(isKRActive);
|
||||
const completedKRs = activeKRs.filter(kr => calculateProgress(kr) >= 1);
|
||||
const pastKRs = myKRs.filter(kr => !isKRActive(kr));
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-5xl 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="space-y-4">
|
||||
{[1, 2, 3].map(i => (
|
||||
<div key={i} className="h-24 bg-slate-200 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto px-4 py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold text-slate-800">我的 KR</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{currentUser?.name} 负责的执行目标
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 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">进行中</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<CheckCircle className="h-8 w-8 text-emerald-300 mx-auto mb-2" />
|
||||
<p className="text-3xl font-bold text-emerald-600">{completedKRs.length}</p>
|
||||
<p className="text-sm text-muted-foreground">已达标</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<AlertTriangle className="h-8 w-8 text-rose-300 mx-auto mb-2" />
|
||||
<p className="text-3xl font-bold text-rose-600">
|
||||
{activeKRs.filter(kr => kr.status === 'red').length}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">需关注</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="active" className="space-y-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="active">进行中 ({activeKRs.length})</TabsTrigger>
|
||||
<TabsTrigger value="past">已结束 ({pastKRs.length})</TabsTrigger>
|
||||
<TabsTrigger value="all">全部 ({myKRs.length})</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="active" className="space-y-4">
|
||||
{activeKRs.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center">
|
||||
<Target className="h-12 w-12 text-slate-300 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">暂无进行中的 KR</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
activeKRs.map(kr => <KRCard key={kr.id} kr={kr} />)
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="past" className="space-y-4">
|
||||
{pastKRs.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center">
|
||||
<History className="h-12 w-12 text-slate-300 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">暂无已结束的 KR</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
pastKRs.map(kr => <KRCard key={kr.id} kr={kr} showEnded />)
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="all" className="space-y-4">
|
||||
{myKRs.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center">
|
||||
<Target className="h-12 w-12 text-slate-300 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">暂无 KR</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
myKRs.map(kr => <KRCard key={kr.id} kr={kr} showEnded={!isKRActive(kr)} />)
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KRCard({ kr, showEnded }: { kr: KRWithRelations; showEnded?: boolean }) {
|
||||
const progress = calculateProgress(kr);
|
||||
const daysLeft = getDaysRemaining(kr.period_end);
|
||||
const isActive = isKRActive(kr);
|
||||
|
||||
return (
|
||||
<Link href={`/krs/${kr.id}`}>
|
||||
<Card className={`hover:shadow-md transition-shadow ${!isActive ? 'opacity-70' : ''}`}>
|
||||
<CardContent className="py-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<ProgressRing progress={progress} status={kr.status} size={64} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-medium text-slate-800 truncate">{kr.title}</h3>
|
||||
{showEnded && (
|
||||
<span className="text-xs bg-slate-200 text-slate-600 px-2 py-0.5 rounded">已结束</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground mb-2">
|
||||
<span>{kr.project?.name}</span>
|
||||
<span className="text-xs bg-slate-100 px-2 py-0.5 rounded">
|
||||
{PERIOD_TYPES[kr.period_type]}
|
||||
</span>
|
||||
<span>{formatDateRange(kr.period_start, kr.period_end)}</span>
|
||||
</div>
|
||||
{kr.reason_code && kr.status !== 'green' && (
|
||||
<div className="flex items-center gap-1 text-xs text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{REASON_CODES[kr.reason_code]}
|
||||
{kr.note && ` - ${kr.note}`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-lg font-semibold">
|
||||
{kr.current_value}/{kr.target_value}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{kr.unit}</p>
|
||||
{isActive && (
|
||||
<p className={`text-xs mt-1 ${daysLeft <= 3 ? 'text-amber-600 font-medium' : 'text-muted-foreground'}`}>
|
||||
<Clock className="h-3 w-3 inline mr-1" />
|
||||
剩余 {daysLeft} 天
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="outline" size="sm">
|
||||
打卡
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
311
app/page.tsx
Normal file
311
app/page.tsx
Normal file
@@ -0,0 +1,311 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { StatusDot } from '@/components/status-badge';
|
||||
import { ProgressRing } from '@/components/progress-ring';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { calculateProgress, getDaysRemaining, isKRActive } from '@/lib/kr-utils';
|
||||
import { REASON_CODES, ROLE_LABELS } from '@/lib/constants';
|
||||
import type { Project, KR, User } from '@/types/database';
|
||||
import {
|
||||
FolderKanban,
|
||||
Target,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
ArrowRight,
|
||||
AlertCircle,
|
||||
HandHelping,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface ProjectWithRelations extends Project {
|
||||
owner: User | null;
|
||||
pm: User | null;
|
||||
}
|
||||
|
||||
interface KRWithRelations extends KR {
|
||||
owner: User | null;
|
||||
project: { id: string; name: string; status: string } | null;
|
||||
}
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { currentUser } = useUser();
|
||||
const [projects, setProjects] = useState<ProjectWithRelations[]>([]);
|
||||
const [krs, setKRs] = useState<KRWithRelations[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
try {
|
||||
const [projectsRes, krsRes] = await Promise.all([
|
||||
fetch('/api/projects'),
|
||||
fetch('/api/krs'),
|
||||
]);
|
||||
|
||||
if (projectsRes.ok) {
|
||||
const projectsData = await projectsRes.json();
|
||||
setProjects(projectsData);
|
||||
}
|
||||
|
||||
if (krsRes.ok) {
|
||||
const krsData = await krsRes.json();
|
||||
setKRs(krsData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch data:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const activeKRs = krs.filter(isKRActive);
|
||||
const redKRs = activeKRs.filter(kr => kr.status === 'red');
|
||||
const yellowKRs = activeKRs.filter(kr => kr.status === 'yellow');
|
||||
const helpNeededKRs = activeKRs.filter(kr => kr.need_owner_help);
|
||||
const urgentKRs = activeKRs.filter(kr => getDaysRemaining(kr.period_end) <= 3 && kr.status !== 'green');
|
||||
|
||||
const stats = {
|
||||
totalProjects: projects.length,
|
||||
greenProjects: projects.filter(p => p.status === 'green').length,
|
||||
yellowProjects: projects.filter(p => p.status === 'yellow').length,
|
||||
redProjects: projects.filter(p => p.status === 'red').length,
|
||||
totalKRs: activeKRs.length,
|
||||
completedKRs: activeKRs.filter(kr => calculateProgress(kr) >= 1).length,
|
||||
};
|
||||
|
||||
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-48" />
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
{[1, 2, 3, 4].map(i => (
|
||||
<div key={i} className="h-32 bg-slate-200 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-8">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-bold text-slate-800">目标驾驶舱</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
{currentUser?.role === 'owner' ? '全局视角 - 所有项目健康度一览' : `${ROLE_LABELS[currentUser?.role || 'member']}视角`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">项目总数</p>
|
||||
<p className="text-3xl font-bold text-slate-800">{stats.totalProjects}</p>
|
||||
</div>
|
||||
<FolderKanban className="h-10 w-10 text-slate-300" />
|
||||
</div>
|
||||
<div className="flex gap-2 mt-3 text-xs">
|
||||
<span className="text-emerald-600">{stats.greenProjects} 正常</span>
|
||||
<span className="text-amber-600">{stats.yellowProjects} 警告</span>
|
||||
<span className="text-rose-600">{stats.redProjects} 风险</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">进行中 KR</p>
|
||||
<p className="text-3xl font-bold text-slate-800">{stats.totalKRs}</p>
|
||||
</div>
|
||||
<Target className="h-10 w-10 text-slate-300" />
|
||||
</div>
|
||||
<div className="flex gap-2 mt-3 text-xs">
|
||||
<span className="text-emerald-600">{stats.completedKRs} 已达标</span>
|
||||
<span className="text-slate-500">{stats.totalKRs - stats.completedKRs} 进行中</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className={redKRs.length > 0 ? 'border-rose-200 bg-rose-50/50' : ''}>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">风险 KR</p>
|
||||
<p className="text-3xl font-bold text-rose-600">{redKRs.length}</p>
|
||||
</div>
|
||||
<AlertTriangle className={`h-10 w-10 ${redKRs.length > 0 ? 'text-rose-300' : 'text-slate-300'}`} />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-3">需要立即关注</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className={helpNeededKRs.length > 0 ? 'border-amber-200 bg-amber-50/50' : ''}>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">需要帮助</p>
|
||||
<p className="text-3xl font-bold text-amber-600">{helpNeededKRs.length}</p>
|
||||
</div>
|
||||
<HandHelping className={`h-10 w-10 ${helpNeededKRs.length > 0 ? 'text-amber-300' : 'text-slate-300'}`} />
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-3">成员请求老板支援</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{(redKRs.length > 0 || urgentKRs.length > 0 || helpNeededKRs.length > 0) && (
|
||||
<Card className="mb-8 border-l-4 border-l-rose-500">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-rose-500" />
|
||||
风险预警
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{redKRs.map(kr => (
|
||||
<Link key={kr.id} href={`/krs/${kr.id}`} className="block">
|
||||
<div className="flex items-center gap-4 p-3 bg-rose-50 rounded-lg hover:bg-rose-100 transition-colors">
|
||||
<StatusDot status="red" pulse />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-slate-800 truncate">{kr.title}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{kr.project?.name} | {kr.owner?.name || '未分配'}
|
||||
{kr.reason_code && ` | ${REASON_CODES[kr.reason_code]}`}
|
||||
</p>
|
||||
</div>
|
||||
<ProgressRing progress={calculateProgress(kr)} status={kr.status} size={48} />
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{urgentKRs.filter(kr => kr.status !== 'red').map(kr => (
|
||||
<Link key={kr.id} href={`/krs/${kr.id}`} className="block">
|
||||
<div className="flex items-center gap-4 p-3 bg-amber-50 rounded-lg hover:bg-amber-100 transition-colors">
|
||||
<Clock className="h-5 w-5 text-amber-500" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-slate-800 truncate">{kr.title}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{kr.project?.name} | 剩余 {getDaysRemaining(kr.period_end)} 天
|
||||
</p>
|
||||
</div>
|
||||
<ProgressRing progress={calculateProgress(kr)} status={kr.status} size={48} />
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{helpNeededKRs.filter(kr => kr.status === 'green').map(kr => (
|
||||
<Link key={kr.id} href={`/krs/${kr.id}`} className="block">
|
||||
<div className="flex items-center gap-4 p-3 bg-sky-50 rounded-lg hover:bg-sky-100 transition-colors">
|
||||
<HandHelping className="h-5 w-5 text-sky-500" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-slate-800 truncate">{kr.title}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{kr.owner?.name} 请求支援
|
||||
</p>
|
||||
</div>
|
||||
<ProgressRing progress={calculateProgress(kr)} status={kr.status} size={48} />
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-lg">项目健康度</CardTitle>
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href="/projects" className="flex items-center gap-1">
|
||||
查看全部 <ArrowRight className="h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{projects.slice(0, 5).map(project => {
|
||||
const projectKRs = krs.filter(kr => kr.project_id === project.id && isKRActive(kr));
|
||||
const completedCount = projectKRs.filter(kr => calculateProgress(kr) >= 1).length;
|
||||
|
||||
return (
|
||||
<Link key={project.id} href={`/projects/${project.id}`} className="block">
|
||||
<div className="flex items-center gap-4 p-3 rounded-lg hover:bg-slate-100 transition-colors">
|
||||
<StatusDot status={project.status} size="lg" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-slate-800">{project.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{project.pm?.name || '未指定PM'} | {projectKRs.length} 个 KR
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm font-medium">
|
||||
{completedCount}/{projectKRs.length}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">已达标</p>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
|
||||
{projects.length === 0 && (
|
||||
<p className="text-center text-muted-foreground py-8">暂无项目</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-lg">近期 KR 动态</CardTitle>
|
||||
<Button variant="ghost" size="sm" asChild>
|
||||
<Link href="/my-krs" className="flex items-center gap-1">
|
||||
我的 KR <ArrowRight className="h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{activeKRs.slice(0, 5).map(kr => {
|
||||
const progress = calculateProgress(kr);
|
||||
const daysLeft = getDaysRemaining(kr.period_end);
|
||||
|
||||
return (
|
||||
<Link key={kr.id} href={`/krs/${kr.id}`} className="block">
|
||||
<div className="flex items-center gap-4 p-3 rounded-lg hover:bg-slate-100 transition-colors">
|
||||
<ProgressRing progress={progress} status={kr.status} size={44} strokeWidth={3} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-slate-800 truncate">{kr.title}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{kr.project?.name} | {kr.owner?.name || '未分配'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm">
|
||||
{kr.current_value}/{kr.target_value} {kr.unit}
|
||||
</p>
|
||||
<p className={`text-xs ${daysLeft <= 3 ? 'text-amber-600' : 'text-muted-foreground'}`}>
|
||||
剩余 {daysLeft} 天
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
|
||||
{activeKRs.length === 0 && (
|
||||
<p className="text-center text-muted-foreground py-8">暂无进行中的 KR</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
546
app/projects/[id]/client-page.tsx
Normal file
546
app/projects/[id]/client-page.tsx
Normal file
@@ -0,0 +1,546 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { StatusBadge, StatusDot } from '@/components/status-badge';
|
||||
import { ProgressRing } from '@/components/progress-ring';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { calculateProgress, getDaysRemaining, formatDateRange, isKRActive } from '@/lib/kr-utils';
|
||||
import { REASON_CODES, PERIOD_TYPES } from '@/lib/constants';
|
||||
import type { Project, User, Objective, KR } from '@/types/database';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
ArrowLeft,
|
||||
Plus,
|
||||
Target,
|
||||
Calendar,
|
||||
Users,
|
||||
AlertTriangle,
|
||||
Clock,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Loader2
|
||||
} from 'lucide-react';
|
||||
|
||||
interface ProjectWithRelations extends Project {
|
||||
owner: User | null;
|
||||
pm: User | null;
|
||||
members: { user_id: string; users: User }[];
|
||||
}
|
||||
|
||||
interface KRWithRelations extends KR {
|
||||
owner: User | null;
|
||||
}
|
||||
|
||||
export default function ProjectDetailPage({ projectId }: { projectId: string }) {
|
||||
// Force re-compile
|
||||
const { currentUser } = useUser();
|
||||
const router = useRouter();
|
||||
|
||||
const [project, setProject] = useState<ProjectWithRelations | null>(null);
|
||||
const [objectives, setObjectives] = useState<Objective[]>([]);
|
||||
const [krs, setKRs] = useState<KRWithRelations[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isObjectiveDialogOpen, setIsObjectiveDialogOpen] = useState(false);
|
||||
const [editingObjective, setEditingObjective] = useState<Objective | null>(null);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [projectRes, objectivesRes, krsRes] = await Promise.all([
|
||||
fetch(`/api/projects/${projectId}`),
|
||||
fetch(`/api/objectives?project_id=${projectId}`),
|
||||
fetch(`/api/krs?project_id=${projectId}`),
|
||||
]);
|
||||
|
||||
if (projectRes.ok) {
|
||||
const projectData = await projectRes.json();
|
||||
setProject(projectData);
|
||||
}
|
||||
|
||||
if (objectivesRes.ok) {
|
||||
const objectivesData = await objectivesRes.json();
|
||||
setObjectives(objectivesData);
|
||||
}
|
||||
|
||||
if (krsRes.ok) {
|
||||
const krsData = await krsRes.json();
|
||||
setKRs(krsData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch project data:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const canEdit = currentUser?.role === 'owner' || currentUser?.id === project?.pm_id;
|
||||
|
||||
const handleDeleteProject = async () => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
const res = await fetch(`/api/projects/${projectId}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('删除失败');
|
||||
toast.success('项目已删除');
|
||||
router.push('/projects');
|
||||
} catch (error) {
|
||||
toast.error('删除失败');
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditProject = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsEditing(true);
|
||||
const formData = new FormData(e.currentTarget);
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/projects/${projectId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: formData.get('name'),
|
||||
description: formData.get('description'),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('更新失败');
|
||||
|
||||
toast.success('项目已更新');
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error('更新失败');
|
||||
} finally {
|
||||
setIsEditing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteObjective = async (objectiveId: string) => {
|
||||
if (!confirm('确定要删除此目标吗?关联的 KR 也会被解除关联。')) return;
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/objectives/${objectiveId}`, { method: 'DELETE' });
|
||||
if (!res.ok) throw new Error('删除失败');
|
||||
toast.success('目标已删除');
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error('删除失败');
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditObjective = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (!editingObjective) return;
|
||||
|
||||
setIsEditing(true);
|
||||
const formData = new FormData(e.currentTarget);
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/objectives/${editingObjective.id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: formData.get('title'),
|
||||
description: formData.get('description'),
|
||||
period_start: formData.get('period_start'),
|
||||
period_end: formData.get('period_end'),
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error('更新失败');
|
||||
|
||||
toast.success('目标已更新');
|
||||
setIsObjectiveDialogOpen(false);
|
||||
setEditingObjective(null);
|
||||
fetchData();
|
||||
} catch (error) {
|
||||
toast.error('更新失败');
|
||||
} finally {
|
||||
setIsEditing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const activeKRs = krs.filter(isKRActive);
|
||||
const completedKRs = activeKRs.filter(kr => calculateProgress(kr) >= 1);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-8">
|
||||
<div className="animate-pulse space-y-6">
|
||||
<div className="h-6 bg-slate-200 rounded w-24" />
|
||||
<div className="h-8 bg-slate-200 rounded w-64" />
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 space-y-4">
|
||||
{[1, 2, 3].map(i => (
|
||||
<div key={i} className="h-32 bg-slate-200 rounded-lg" />
|
||||
))}
|
||||
</div>
|
||||
<div className="h-64 bg-slate-200 rounded-lg" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!project) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-8 text-center">
|
||||
<p className="text-muted-foreground">项目不存在</p>
|
||||
<Button asChild className="mt-4" variant="outline">
|
||||
<Link href="/projects">返回项目列表</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-8">
|
||||
<div className="mb-6">
|
||||
<Link
|
||||
href="/projects"
|
||||
className="inline-flex items-center text-sm text-muted-foreground hover:text-slate-800 mb-4"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
返回项目列表
|
||||
</Link>
|
||||
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-2xl font-bold text-slate-800">{project.name}</h1>
|
||||
<StatusBadge status={project.status} />
|
||||
</div>
|
||||
{project.description && (
|
||||
<p className="text-muted-foreground mt-2">{project.description}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{canEdit && (
|
||||
<div className="flex gap-2">
|
||||
{currentUser?.role === 'owner' && (
|
||||
<>
|
||||
<Dialog>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>编辑项目</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleEditProject} className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="name">项目名称</Label>
|
||||
<Input id="name" name="name" defaultValue={project.name} required />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="description">项目描述</Label>
|
||||
<Textarea id="description" name="description" defaultValue={project.description || ''} />
|
||||
</div>
|
||||
<Button type="submit" disabled={isEditing} className="w-full">
|
||||
{isEditing && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
保存修改
|
||||
</Button>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="text-rose-500 hover:text-rose-600">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>确定要删除项目吗?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
此操作无法撤销。这将永久删除项目及其所有关联的目标、KR 和打卡记录。
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteProject}
|
||||
className="bg-rose-600 hover:bg-rose-700"
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{isDeleting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
删除
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)}
|
||||
<Button asChild variant="outline">
|
||||
<Link href={`/projects/${projectId}/objectives/new`}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
新建目标
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild className="bg-teal-600 hover:bg-teal-700">
|
||||
<Link href={`/projects/${projectId}/krs/new`}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
新建 KR
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<Dialog open={isObjectiveDialogOpen} onOpenChange={setIsObjectiveDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>编辑目标</DialogTitle>
|
||||
</DialogHeader>
|
||||
{editingObjective && (
|
||||
<form onSubmit={handleEditObjective} className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="obj-title">目标标题</Label>
|
||||
<Input id="obj-title" name="title" defaultValue={editingObjective.title} required />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="obj-desc">描述</Label>
|
||||
<Textarea id="obj-desc" name="description" defaultValue={editingObjective.description || ''} />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="obj-start">开始日期</Label>
|
||||
<Input type="date" id="obj-start" name="period_start" defaultValue={editingObjective.period_start} required />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="obj-end">结束日期</Label>
|
||||
<Input type="date" id="obj-end" name="period_end" defaultValue={editingObjective.period_end} required />
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" disabled={isEditing} className="w-full">
|
||||
{isEditing && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
保存修改
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<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">
|
||||
<p className="text-3xl font-bold text-emerald-600">{completedKRs.length}</p>
|
||||
<p className="text-sm text-muted-foreground">已达标</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-6 text-center">
|
||||
<p className="text-3xl font-bold text-rose-600">
|
||||
{activeKRs.filter(kr => kr.status === 'red').length}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">风险 KR</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{objectives.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Target className="h-5 w-5 text-teal-600" />
|
||||
阶段目标 (Objectives)
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{objectives.map(obj => {
|
||||
const objKRs = krs.filter(kr => kr.objective_id === obj.id);
|
||||
return (
|
||||
<div key={obj.id} className="p-4 bg-slate-50 rounded-lg">
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<h3 className="font-medium text-slate-800">{obj.title}</h3>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Calendar className="h-3 w-3" />
|
||||
{formatDateRange(obj.period_start, obj.period_end)}
|
||||
</span>
|
||||
{currentUser?.role === 'owner' && (
|
||||
<div className="flex items-center">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0"
|
||||
onClick={() => {
|
||||
setEditingObjective(obj);
|
||||
setIsObjectiveDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<Pencil className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 text-rose-500 hover:text-rose-600"
|
||||
onClick={() => handleDeleteObjective(obj.id)}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{obj.description && (
|
||||
<p className="text-sm text-muted-foreground mb-3">{obj.description}</p>
|
||||
)}
|
||||
<div className="text-xs text-muted-foreground">
|
||||
关联 {objKRs.length} 个 KR
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">执行目标 (Key Results)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{krs.length === 0 ? (
|
||||
<p className="text-center text-muted-foreground py-8">暂无 KR</p>
|
||||
) : (
|
||||
krs.map(kr => {
|
||||
const progress = calculateProgress(kr);
|
||||
const daysLeft = getDaysRemaining(kr.period_end);
|
||||
const isActive = isKRActive(kr);
|
||||
|
||||
return (
|
||||
<Link key={kr.id} href={`/krs/${kr.id}`} className="block">
|
||||
<div className={`flex items-center gap-4 p-4 rounded-lg border hover:bg-slate-50 transition-colors ${!isActive ? 'opacity-60' : ''}`}>
|
||||
<ProgressRing progress={progress} status={kr.status} size={56} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<p className="font-medium text-slate-800 truncate">{kr.title}</p>
|
||||
{!isActive && (
|
||||
<span className="text-xs bg-slate-200 text-slate-600 px-2 py-0.5 rounded">已结束</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-sm text-muted-foreground">
|
||||
<span>{kr.owner?.name || '未分配'}</span>
|
||||
<span className="text-xs bg-slate-100 px-2 py-0.5 rounded">
|
||||
{PERIOD_TYPES[kr.period_type]}
|
||||
</span>
|
||||
<span>{formatDateRange(kr.period_start, kr.period_end)}</span>
|
||||
</div>
|
||||
{kr.reason_code && kr.status !== 'green' && (
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{REASON_CODES[kr.reason_code]}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm font-medium">
|
||||
{kr.current_value}/{kr.target_value} {kr.unit}
|
||||
</p>
|
||||
{isActive && (
|
||||
<p className={`text-xs ${daysLeft <= 3 ? 'text-amber-600' : 'text-muted-foreground'}`}>
|
||||
<Clock className="h-3 w-3 inline mr-1" />
|
||||
剩余 {daysLeft} 天
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">项目信息</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">项目类型</p>
|
||||
<p className="font-medium">{project.project_type || '通用'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">负责人</p>
|
||||
<p className="font-medium">{project.owner?.name || '未指定'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">项目经理</p>
|
||||
<p className="font-medium">{project.pm?.name || '未指定'}</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Users className="h-5 w-5" />
|
||||
团队成员
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{project.members && project.members.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{project.members.map(m => (
|
||||
<div key={m.user_id} className="flex items-center gap-2 p-2 rounded bg-slate-50">
|
||||
<div className="w-8 h-8 rounded-full bg-slate-200 flex items-center justify-center text-sm font-medium">
|
||||
{m.users.name.charAt(0)}
|
||||
</div>
|
||||
<span className="text-sm">{m.users.name}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">暂无成员</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">快速操作</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<Button asChild variant="outline" className="w-full justify-start">
|
||||
<Link href={`/meeting?project_id=${projectId}`}>
|
||||
<Calendar className="h-4 w-4 mr-2" />
|
||||
发起例会
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
435
app/projects/[id]/krs/new/page.tsx
Normal file
435
app/projects/[id]/krs/new/page.tsx
Normal file
@@ -0,0 +1,435 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter, useParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescription } from '@/components/ui/form';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { toast } from 'sonner';
|
||||
import { PERIOD_TYPES, DIRECTION_LABELS } from '@/lib/constants';
|
||||
import type { Objective, Metric, Template } from '@/types/database';
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
const formSchema = z.object({
|
||||
title: z.string().min(1, 'KR标题不能为空'),
|
||||
objective_id: z.string().optional(),
|
||||
period_type: z.enum(['custom', '3d', '1w', '2w', 'monthly']),
|
||||
period_start: z.string().min(1, '开始日期不能为空'),
|
||||
period_end: z.string().min(1, '结束日期不能为空'),
|
||||
metric_name: z.string().min(1, '指标名称不能为空'),
|
||||
unit: z.string().min(1, '单位不能为空'),
|
||||
direction: z.enum(['increase', 'decrease']),
|
||||
target_value: z.number().positive('目标值必须大于0'),
|
||||
owner_user_id: z.string().optional(),
|
||||
note: z.string().optional(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export default function NewKRPage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const projectId = params.id as string;
|
||||
const { currentUser, users } = useUser();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [objectives, setObjectives] = useState<Objective[]>([]);
|
||||
const [metrics, setMetrics] = useState<Metric[]>([]);
|
||||
const [templates, setTemplates] = useState<Template[]>([]);
|
||||
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
title: '',
|
||||
objective_id: '',
|
||||
period_type: 'custom',
|
||||
period_start: today,
|
||||
period_end: today,
|
||||
metric_name: '',
|
||||
unit: '',
|
||||
direction: 'increase',
|
||||
target_value: 0,
|
||||
owner_user_id: currentUser?.id || '',
|
||||
note: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
const [objRes, metricsRes, templatesRes] = await Promise.all([
|
||||
fetch(`/api/objectives?project_id=${projectId}`),
|
||||
fetch('/api/metrics?active_only=true'),
|
||||
fetch('/api/templates?active_only=true'),
|
||||
]);
|
||||
|
||||
if (objRes.ok) {
|
||||
const data = await objRes.json();
|
||||
setObjectives(data);
|
||||
}
|
||||
|
||||
if (metricsRes.ok) {
|
||||
const data = await metricsRes.json();
|
||||
setMetrics(data);
|
||||
}
|
||||
|
||||
if (templatesRes.ok) {
|
||||
const data = await templatesRes.json();
|
||||
setTemplates(data);
|
||||
}
|
||||
}
|
||||
|
||||
fetchData();
|
||||
}, [projectId]);
|
||||
|
||||
const handlePeriodTypeChange = (value: string) => {
|
||||
form.setValue('period_type', value as FormValues['period_type']);
|
||||
const start = new Date(form.getValues('period_start'));
|
||||
|
||||
let endDate: Date;
|
||||
switch (value) {
|
||||
case '3d':
|
||||
endDate = new Date(start);
|
||||
endDate.setDate(start.getDate() + 2);
|
||||
break;
|
||||
case '1w':
|
||||
endDate = new Date(start);
|
||||
endDate.setDate(start.getDate() + 6);
|
||||
break;
|
||||
case '2w':
|
||||
endDate = new Date(start);
|
||||
endDate.setDate(start.getDate() + 13);
|
||||
break;
|
||||
case 'monthly':
|
||||
endDate = new Date(start);
|
||||
endDate.setMonth(start.getMonth() + 1);
|
||||
endDate.setDate(endDate.getDate() - 1);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
form.setValue('period_end', endDate.toISOString().split('T')[0]);
|
||||
};
|
||||
|
||||
const handleMetricSelect = (metricId: string) => {
|
||||
const metric = metrics.find(m => m.id === metricId);
|
||||
if (metric) {
|
||||
form.setValue('metric_name', metric.name);
|
||||
form.setValue('unit', metric.unit);
|
||||
form.setValue('direction', metric.direction);
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
if (new Date(values.period_end) < new Date(values.period_start)) {
|
||||
toast.error('结束日期不能早于开始日期');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/krs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...values,
|
||||
project_id: projectId,
|
||||
objective_id: values.objective_id || null,
|
||||
owner_user_id: values.owner_user_id || currentUser?.id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '创建失败');
|
||||
}
|
||||
|
||||
const kr = await res.json();
|
||||
toast.success('KR 创建成功');
|
||||
router.push(`/krs/${kr.id}`);
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
<Link
|
||||
href={`/projects/${projectId}`}
|
||||
className="inline-flex items-center text-sm text-muted-foreground hover:text-slate-800 mb-6"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
返回项目
|
||||
</Link>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>新建 KR (Key Result)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>KR 标题 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:完成首页加载速度优化" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
{objectives.length > 0 && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="objective_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>关联目标 (Objective)</FormLabel>
|
||||
<Select
|
||||
onValueChange={(value) => field.onChange(value === "unspecified" ? "" : value)}
|
||||
value={field.value || "unspecified"}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择关联的目标" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="unspecified">不关联</SelectItem>
|
||||
{objectives.map(obj => (
|
||||
<SelectItem key={obj.id} value={obj.id}>
|
||||
{obj.title}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="period_type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>周期类型</FormLabel>
|
||||
<Select onValueChange={handlePeriodTypeChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(PERIOD_TYPES).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="period_start"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>开始日期 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="date" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="period_end"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>结束日期 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="date" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{metrics.length > 0 && (
|
||||
<div>
|
||||
<FormLabel>从指标库选择</FormLabel>
|
||||
<Select onValueChange={handleMetricSelect}>
|
||||
<SelectTrigger className="mt-2">
|
||||
<SelectValue placeholder="选择预设指标" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{metrics.map(metric => (
|
||||
<SelectItem key={metric.id} value={metric.id}>
|
||||
{metric.name} ({metric.unit})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="metric_name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>指标名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:页面加载时间" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="unit"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>单位 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:秒、个、%" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="direction"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>方向</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{Object.entries(DIRECTION_LABELS).map(([key, label]) => (
|
||||
<SelectItem key={key} value={key}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="target_value"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标值 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
step="any"
|
||||
{...field}
|
||||
onChange={e => field.onChange(parseFloat(e.target.value) || 0)}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="owner_user_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>负责人</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择负责人" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{users.map(user => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormDescription>
|
||||
每人每个周期最多 3 个 KR
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="note"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>备注</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="补充说明" rows={2} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<Button type="submit" disabled={isSubmitting} className="bg-teal-600 hover:bg-teal-700">
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
创建 KR
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
171
app/projects/[id]/objectives/new/page.tsx
Normal file
171
app/projects/[id]/objectives/new/page.tsx
Normal file
@@ -0,0 +1,171 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter, useParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { toast } from 'sonner';
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
const formSchema = z.object({
|
||||
title: z.string().min(1, '目标标题不能为空'),
|
||||
description: z.string().optional(),
|
||||
period_start: z.string().min(1, '开始日期不能为空'),
|
||||
period_end: z.string().min(1, '结束日期不能为空'),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export default function NewObjectivePage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const projectId = params.id as string;
|
||||
const { currentUser } = useUser();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const today = new Date();
|
||||
const nextMonth = new Date(today);
|
||||
nextMonth.setMonth(nextMonth.getMonth() + 1);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
title: '',
|
||||
description: '',
|
||||
period_start: today.toISOString().split('T')[0],
|
||||
period_end: nextMonth.toISOString().split('T')[0],
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
if (new Date(values.period_end) < new Date(values.period_start)) {
|
||||
toast.error('结束日期不能早于开始日期');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/objectives', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...values,
|
||||
project_id: projectId,
|
||||
created_by: currentUser?.id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '创建失败');
|
||||
}
|
||||
|
||||
toast.success('目标创建成功');
|
||||
router.push(`/projects/${projectId}`);
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
<Link
|
||||
href={`/projects/${projectId}`}
|
||||
className="inline-flex items-center text-sm text-muted-foreground hover:text-slate-800 mb-6"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
返回项目
|
||||
</Link>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>新建阶段目标 (Objective)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="title"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标标题 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:提升产品用户体验和性能" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>目标描述</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="详细描述这个目标" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="period_start"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>开始日期 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="date" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="period_end"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>结束日期 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="date" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<Button type="submit" disabled={isSubmitting} className="bg-teal-600 hover:bg-teal-700">
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
创建目标
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
8
app/projects/[id]/page.tsx
Normal file
8
app/projects/[id]/page.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
|
||||
import ProjectDetailPage from './client-page';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function Page({ params }: { params: { id: string } }) {
|
||||
return <ProjectDetailPage projectId={params.id} />;
|
||||
}
|
||||
215
app/projects/new/page.tsx
Normal file
215
app/projects/new/page.tsx
Normal file
@@ -0,0 +1,215 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import { toast } from 'sonner';
|
||||
import type { User } from '@/types/database';
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react';
|
||||
import { getErrorMessage } from '@/lib/error-utils';
|
||||
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(1, '项目名称不能为空'),
|
||||
description: z.string().optional(),
|
||||
project_type: z.string().optional(),
|
||||
pm_id: z.string().optional(),
|
||||
member_ids: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
|
||||
export default function NewProjectPage() {
|
||||
const router = useRouter();
|
||||
const { currentUser, users } = useUser();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
description: '',
|
||||
project_type: '',
|
||||
pm_id: '',
|
||||
member_ids: [],
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await fetch('/api/projects', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
...values,
|
||||
owner_id: currentUser?.id,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error || '创建失败');
|
||||
}
|
||||
|
||||
const project = await res.json();
|
||||
toast.success('项目创建成功');
|
||||
router.push(`/projects/${project.id}`);
|
||||
} catch (error) {
|
||||
toast.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const pmCandidates = users.filter(u => u.role === 'owner' || u.role === 'pm');
|
||||
const memberCandidates = users;
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
<Link
|
||||
href="/projects"
|
||||
className="inline-flex items-center text-sm text-muted-foreground hover:text-slate-800 mb-6"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
返回项目列表
|
||||
</Link>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>新建项目</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>项目名称 *</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="输入项目名称" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="description"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>项目描述</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea placeholder="输入项目描述" rows={3} {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="project_type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>项目类型</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="如:产品研发、市场营销" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="pm_id"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>项目经理</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="选择项目经理" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{pmCandidates.map(user => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="member_ids"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>项目成员</FormLabel>
|
||||
<div className="space-y-2">
|
||||
{memberCandidates.map(user => (
|
||||
<FormField
|
||||
key={user.id}
|
||||
control={form.control}
|
||||
name="member_ids"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center space-x-2 space-y-0">
|
||||
<FormControl>
|
||||
<Checkbox
|
||||
checked={field.value?.includes(user.id)}
|
||||
onCheckedChange={(checked) => {
|
||||
const current = field.value || [];
|
||||
if (checked) {
|
||||
field.onChange([...current, user.id]);
|
||||
} else {
|
||||
field.onChange(current.filter(id => id !== user.id));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<span className="text-sm">{user.name}</span>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex gap-4">
|
||||
<Button type="submit" disabled={isSubmitting} className="bg-teal-600 hover:bg-teal-700">
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
创建项目
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
129
app/projects/page.tsx
Normal file
129
app/projects/page.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { StatusBadge, StatusDot } from '@/components/status-badge';
|
||||
import { useUser } from '@/components/user-context';
|
||||
import type { Project, User } from '@/types/database';
|
||||
import { Plus, Users, Target, ArrowRight } from 'lucide-react';
|
||||
|
||||
interface ProjectWithRelations extends Project {
|
||||
owner: User | null;
|
||||
pm: User | null;
|
||||
}
|
||||
|
||||
export default function ProjectsPage() {
|
||||
const { currentUser } = useUser();
|
||||
const [projects, setProjects] = useState<ProjectWithRelations[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchProjects() {
|
||||
try {
|
||||
const res = await fetch('/api/projects');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setProjects(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch projects:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchProjects();
|
||||
}, []);
|
||||
|
||||
const canCreate = currentUser?.role === 'owner' || currentUser?.role === 'pm';
|
||||
|
||||
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 lg:grid-cols-3 gap-6">
|
||||
{[1, 2, 3].map(i => (
|
||||
<div key={i} className="h-48 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">项目列表</h1>
|
||||
<p className="text-muted-foreground mt-1">共 {projects.length} 个项目</p>
|
||||
</div>
|
||||
{canCreate && (
|
||||
<Button asChild className="bg-teal-600 hover:bg-teal-700">
|
||||
<Link href="/projects/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
新建项目
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{projects.map(project => (
|
||||
<Link key={project.id} href={`/projects/${project.id}`}>
|
||||
<Card className="h-full hover:shadow-md transition-shadow cursor-pointer">
|
||||
<CardHeader className="pb-2">
|
||||
<div className="flex items-start justify-between">
|
||||
<CardTitle className="text-lg">{project.name}</CardTitle>
|
||||
<StatusBadge status={project.status} size="sm" />
|
||||
</div>
|
||||
{project.project_type && (
|
||||
<span className="text-xs text-muted-foreground bg-slate-100 px-2 py-0.5 rounded">
|
||||
{project.project_type}
|
||||
</span>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{project.description && (
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{project.description}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-4 text-sm">
|
||||
<div className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Users className="h-4 w-4" />
|
||||
<span>{project.pm?.name || '未指定PM'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between pt-2 border-t">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
负责人: {project.owner?.name || '未指定'}
|
||||
</span>
|
||||
<ArrowRight className="h-4 w-4 text-muted-foreground" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
|
||||
{projects.length === 0 && (
|
||||
<div className="col-span-full text-center py-12">
|
||||
<Target className="h-12 w-12 text-slate-300 mx-auto mb-4" />
|
||||
<p className="text-muted-foreground">暂无项目</p>
|
||||
{canCreate && (
|
||||
<Button asChild className="mt-4" variant="outline">
|
||||
<Link href="/projects/new">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
创建第一个项目
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user