81 lines
5.6 KiB
TypeScript
81 lines
5.6 KiB
TypeScript
import { ArrowRight, Save } from "lucide-react";
|
||
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
|
||
import { useEffect, useState, type FormEvent } from "react";
|
||
import { Link, useNavigate, useParams } from "react-router";
|
||
import { Button, Card, ErrorBanner, Field, FormErrorProvider, Input, PageTitle, Select } from "../components/Ui";
|
||
import { ApiError, adminFieldErrors, api } from "../lib/api";
|
||
import type { ArticleItem, PatentItem } from "../types";
|
||
import { FormTabs } from "../components/FormTabs";
|
||
import { RelatedEntitySelect } from "../components/RelatedEntitySelect";
|
||
|
||
export function AchievementFormPage() {
|
||
const { kind = "article", id } = useParams();
|
||
const editing = Boolean(id);
|
||
const article = kind === "article";
|
||
const navigate = useNavigate();
|
||
const [details, setDetails] = useState<ArticleItem | PatentItem | null>(null);
|
||
const [ideaId, setIdeaId] = useState("");
|
||
const [error, setError] = useState("");
|
||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||
const [busy, setBusy] = useState(false);
|
||
const [loading, setLoading] = useState(editing);
|
||
const [activeTab, setActiveTab] = useState("info");
|
||
|
||
useEffect(() => {
|
||
const requests: Promise<unknown>[] = [];
|
||
if (editing) requests.push(api<ArticleItem | PatentItem>(`/api/v1/${article ? "articles" : "patents"}/${id}`).then(setDetails));
|
||
void Promise.all(requests).catch((e) => setError(e.message)).finally(() => setLoading(false));
|
||
}, [article, editing, id]);
|
||
|
||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
if (!validateAdminForm(e.currentTarget, setActiveTab)) return;
|
||
setBusy(true); setError(""); setFieldErrors({});
|
||
const f = new FormData(e.currentTarget);
|
||
const data = article
|
||
? { title: f.get("title"), publicationPlace: f.get("place"), directLink: f.get("directLink"), publishedDate: f.get("date"), status: Number(f.get("status")) }
|
||
: { title: f.get("title"), registrationPlace: f.get("place"), directLink: f.get("directLink"), registeredDate: f.get("date"), status: Number(f.get("status")) };
|
||
if (!editing) Object.assign(data, { ideaId: f.get("ideaId") || null });
|
||
else Object.assign(data, { rowVersion: details?.rowVersion });
|
||
try {
|
||
await api(`/api/v1/${article ? "articles" : "patents"}${editing ? `/${id}` : ""}`, {
|
||
method: editing ? "PUT" : "POST", body: JSON.stringify(data),
|
||
});
|
||
navigate("/admin/achievements", { replace: true });
|
||
} catch (reason) {
|
||
if (reason instanceof ApiError) {
|
||
const errors = adminFieldErrors(reason.problem);
|
||
setFieldErrors(errors);
|
||
focusAdminServerError(errors, setActiveTab);
|
||
}
|
||
setError(reason instanceof ApiError ? reason.message : "ذخیره دستاورد ناموفق بود.");
|
||
} finally { setBusy(false); }
|
||
}
|
||
|
||
if (loading) return <Card><p>در حال دریافت…</p></Card>;
|
||
const value = (key: string) => details && key in details ? String((details as unknown as Record<string, unknown>)[key] ?? "") : "";
|
||
return <>
|
||
<PageTitle title={`${editing ? "ویرایش" : "ثبت"} ${article ? "مقاله" : "اختراع"}`}
|
||
description="رکورد میتواند مستقل باشد یا هنگام ایجاد با شناسه به ایده متصل شود"
|
||
action={<Link to="/admin/achievements" className="text-link"><ArrowRight size={17}/>بازگشت</Link>}/>
|
||
{error && <ErrorBanner message={error}/>}
|
||
{editing && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[{id:"info",label:"اطلاعات رکورد"},{id:"image",label:"تصویر"}]}/>}
|
||
<form className="form-stack" onSubmit={submit} noValidate>
|
||
<FormErrorProvider errors={fieldErrors}>
|
||
<Card dataTab="info" className={editing && activeTab !== "info" ? "tab-hidden" : ""}><div className="form-grid cols-3">
|
||
<Field label="عنوان"><Input name="title" required defaultValue={value("title")}/></Field>
|
||
<Field name={article ? "publicationPlace" : "registrationPlace"} label={article ? "محل چاپ" : "محل ثبت"}><Input name="place" required defaultValue={value(article ? "publicationPlace" : "registrationPlace")}/></Field>
|
||
<Field label="تاریخ"><Input name="date" type="date" required defaultValue={value(article ? "publishedDate" : "registeredDate")}/></Field>
|
||
<Field label="لینک مستقیم"><Input name="directLink" type="url" dir="ltr" required defaultValue={value("directLink")}/></Field>
|
||
{!editing && <Field label="ایده مرتبط" hint="اختیاری؛ برای رکورد مستقل خالی بگذارید"><RelatedEntitySelect name="ideaId" path="/api/v1/ideas" value={ideaId} onChange={setIdeaId} placeholder="جستوجوی ایده بر اساس عنوان یا ایدهپرداز" required={false}/></Field>}
|
||
<Field label="وضعیت انتشار"><Select name="status" defaultValue={value("status") || "0"}><option value="0">پیشنویس</option><option value="1">انتشار</option></Select></Field>
|
||
</div></Card>
|
||
{editing && <Card className={activeTab !== "image" ? "tab-hidden" : "nested-section"}><Link className="text-link" to={`/admin/files/${article ? "PublishedArticle" : "RegisteredPatent"}/${id}`}>
|
||
مدیریت تصویر صفحه اول {article ? "مقاله" : "اختراع"}
|
||
</Link></Card>}
|
||
<div className={`form-actions${editing && activeTab === "image" ? " tab-hidden" : ""}`}><span>رابطه اختیاری با شناسه ایده</span><Button disabled={busy}><Save size={17}/>{busy ? "در حال ذخیره…" : "ذخیره"}</Button></div>
|
||
</FormErrorProvider>
|
||
</form>
|
||
</>;
|
||
}
|