'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'; import { fetchApi } from '@/lib/api-client'; 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; 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({ 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 fetchApi('/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 (
返回项目 新建阶段目标 (Objective)
( 目标标题 * )} /> ( 目标描述