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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user