148 lines
16 KiB
TypeScript
148 lines
16 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 { FormTabs } from "../components/FormTabs";
|
||
import { RelatedEntitySelect } from "../components/RelatedEntitySelect";
|
||
|
||
const names: Record<string, string> = { publication: "گزارش/انتشار", event: "فعالیت رویدادی", book: "کتاب", performer: "نوآور برتر" };
|
||
|
||
export function ContentFormPage() {
|
||
const { kind = "", id } = useParams();
|
||
const navigate = useNavigate();
|
||
const editing = Boolean(id);
|
||
const [busy, setBusy] = useState(false);
|
||
const [loading, setLoading] = useState(editing);
|
||
const [error, setError] = useState("");
|
||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||
const [details, setDetails] = useState<Record<string, unknown> | null>(null);
|
||
const [eventType, setEventType] = useState("1");
|
||
const [presence, setPresence] = useState("");
|
||
const [projectId, setProjectId] = useState("");
|
||
const [activeTab, setActiveTab] = useState("info");
|
||
|
||
useEffect(() => {
|
||
let active = true;
|
||
setError(""); setDetails(null); setLoading(editing);
|
||
const requests: Promise<void>[] = [];
|
||
if (editing) requests.push(api<Record<string, unknown>>(`${endpoint(kind)}/${id}`).then(x => {
|
||
if (!active) return;
|
||
setDetails(x); setEventType(String(x.activityType ?? 1)); setPresence(String(x.presenceType ?? ""));
|
||
setProjectId(String(x.projectId ?? ""));
|
||
}));
|
||
void Promise.all(requests).catch((reason: unknown) => {
|
||
if (active) setError(reason instanceof Error ? reason.message : "دریافت اطلاعات ناموفق بود.");
|
||
}).finally(() => { if (active) setLoading(false); });
|
||
return () => { active = false; };
|
||
}, [editing, id, kind]);
|
||
|
||
const value = (name: string, fallback: string | number = "") => {
|
||
const current = details?.[name];
|
||
return current == null ? String(fallback) : String(current);
|
||
};
|
||
|
||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
if (!validateAdminForm(e.currentTarget, setActiveTab)) return;
|
||
setBusy(true); setError(""); setFieldErrors({});
|
||
const data = payload(kind, new FormData(e.currentTarget), eventType);
|
||
try {
|
||
await api(editing ? `${endpoint(kind)}/${id}` : endpoint(kind), {
|
||
method: editing ? "PUT" : "POST",
|
||
body: JSON.stringify(editing ? { data, rowVersion: String(details?.rowVersion ?? "") } : data),
|
||
});
|
||
navigate("/admin/content", { replace: true });
|
||
} catch (reason) {
|
||
if (reason instanceof ApiError) {
|
||
setError(reason.message);
|
||
const errors = adminFieldErrors(reason.problem);
|
||
setFieldErrors(errors);
|
||
focusAdminServerError(errors, setActiveTab);
|
||
} else setError("ذخیره اطلاعات ناموفق بود.");
|
||
} finally { setBusy(false); }
|
||
}
|
||
|
||
return <>
|
||
<PageTitle title={`${editing ? "ویرایش" : "ثبت"} ${names[kind] ?? "محتوا"}`} description="فیلدها و شرطهای نمایش بر پایه شواهد APADANA" action={<Link to="/admin/content" className="text-link"><ArrowRight size={17}/>بازگشت</Link>}/>
|
||
{error && <ErrorBanner message={error}/>}
|
||
{editing && kind === "performer" && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[{id:"info",label:"اطلاعات نوآور"},{id:"image",label:"تصویر"}]}/>}
|
||
{loading ? <Card><p>در حال دریافت اطلاعات…</p></Card> : (!editing || details) &&
|
||
<form className="form-stack" onSubmit={submit} noValidate key={`${kind}-${id ?? "new"}`}>
|
||
<FormErrorProvider errors={fieldErrors}>
|
||
<Card dataTab="info" className={editing && kind === "performer" && activeTab !== "info" ? "tab-hidden" : ""}><div className="form-grid cols-3">
|
||
{kind === "publication" && <>
|
||
<Field label="عنوان گزارش" error={fieldErrors.title}><Input name="title" required defaultValue={value("title")}/></Field>
|
||
<Field label="نویسنده"><Input name="writer" required defaultValue={value("writer")}/></Field>
|
||
<Field label="سازمان منتشرکننده"><Input name="publishingOrganization" required defaultValue={value("publishingOrganization")}/></Field>
|
||
<Field label="تاریخ انتشار"><Input name="publishingDate" type="date" required defaultValue={value("publishingDate")}/></Field>
|
||
<Field label="نوع گزارش"><Select name="reportType" defaultValue={value("reportType", "فنی")}><option>فنی</option><option>تحقیقاتی</option></Select></Field>
|
||
<Field label="تعداد صفحات"><Input name="pageCount" type="number" min="1" required defaultValue={value("pageCount")}/></Field>
|
||
<Field label="زبان"><Select name="language" defaultValue={value("language", "فارسی")}><option>فارسی</option><option>انگلیسی</option><option>عربی</option></Select></Field>
|
||
<Field label="حوزه"><Input name="area" required defaultValue={value("area", "پتروشیمی و انرژی")}/></Field>
|
||
<UrlField defaultValue={value("link")}/>
|
||
</>}
|
||
{kind === "book" && <>
|
||
<Field label="عنوان کتاب"><Input name="title" required defaultValue={value("title")}/></Field>
|
||
<Field label="نوع کتاب"><Select name="bookType" defaultValue={value("bookType", "تألیفی")}><option>تألیفی</option><option>ترجمه</option></Select></Field>
|
||
<Field label="محل چاپ"><Input name="publicationPlace" required defaultValue={value("publicationPlace")}/></Field>
|
||
<Field label="تاریخ انتشار"><Input name="publicationDate" type="date" required defaultValue={value("publicationDate")}/></Field>
|
||
<Field label="نویسنده/مترجم"><Input name="writerOrTranslator" required defaultValue={value("writerOrTranslator")}/></Field>
|
||
<Field label="حوزه تخصصی"><Input name="specializedField" required defaultValue={value("specializedField")}/></Field>
|
||
<UrlField defaultValue={value("link")}/>
|
||
</>}
|
||
{kind === "event" && <>
|
||
<Field label="نوع فعالیت"><Select value={eventType} onChange={e => setEventType(e.target.value)}><option value="1">شرکت در رویداد</option><option value="2">برگزاری رویداد</option><option value="3">کنفرانس</option><option value="4">نمایشگاه</option></Select></Field>
|
||
<Field label="عنوان"><Input name="title" required defaultValue={value("title")}/></Field>
|
||
<Field label="تاریخ"><Input name="eventDate" type="date" required defaultValue={value("eventDate")}/></Field>
|
||
<Field label="محل"><Input name="place" required defaultValue={value("place")}/></Field>
|
||
<Field label="برگزارکننده"><Input name="organizer" required defaultValue={value("organizer")}/></Field>
|
||
<UrlField defaultValue={value("link")}/>
|
||
{eventType === "1" && <><Field label="نوع رویداد"><Select name="eventType" defaultValue={value("eventType", "وبینار")}><option>وبینار</option><option>کارگاه</option></Select></Field><Field label="نقش"><Select name="role" defaultValue={value("role", "سخنران")}><option>سخنران</option><option>شرکتکننده</option></Select></Field><Field label="دستاورد"><Input name="achievement" required defaultValue={value("achievement")}/></Field></>}
|
||
{eventType === "2" && <><Field label="مخاطبان"><Input name="audience" required defaultValue={value("audience")}/></Field><Field label="خلاصه"><Input name="summary" required defaultValue={value("summary")}/></Field></>}
|
||
{eventType === "3" && <><Field label="محور"><Input name="axis" required defaultValue={value("axis")}/></Field><Field label="نوع مشارکت"><Select name="participationType" defaultValue={value("participationType", "شرکتکننده")}><option>شرکتکننده</option><option>ارائه مقاله</option></Select></Field><Field label="عنوان ارائه"><Input name="presentationTitle" required defaultValue={value("presentationTitle")}/></Field><Field label="دستاورد"><Input name="achievement" required defaultValue={value("achievement")}/></Field></>}
|
||
{eventType === "4" && <><Field label="حوزه"><Input name="area" required defaultValue={value("area")}/></Field><Field label="نوع حضور"><Select name="presenceType" value={presence} onChange={e => setPresence(e.target.value)} required><option value="">انتخاب کنید</option><option>بازدیدکننده</option><option>غرفهدار</option></Select></Field>{presence === "غرفهدار" && <Field label="عنوان محصول"><Input name="productTitle" required defaultValue={value("productTitle")}/></Field>}<Field label="دستاورد"><Input name="achievement" required defaultValue={value("achievement")}/></Field></>}
|
||
</>}
|
||
{kind === "performer" && <>
|
||
<Field label="عنوان نوآور برتر"><Input name="title" required defaultValue={value("title")}/></Field>
|
||
<Field label="شماره پرسنلی"><Input name="personnelNumber" maxLength={100} required dir="ltr" defaultValue={value("personnelNumber")}/></Field>
|
||
<Field label="پروژه مرتبط"><RelatedEntitySelect name="projectId" path="/api/v1/projects" value={projectId} onChange={setProjectId} placeholder="جستوجوی شماره یا عنوان پروژه"/></Field>
|
||
<Field label="اصالت ایده"><Select name="ideaOriginality" defaultValue={value("ideaOriginality", "کپی")}><option>کپی</option><option>الهام داخلی</option><option>الهام بینالمللی</option><option>اصیل</option></Select></Field>
|
||
<Money name="revenueBefore" label="درآمد قبل" defaultValue={value("revenueBefore", 0)}/><Money name="revenueAfter" label="درآمد بعد" defaultValue={value("revenueAfter", 0)}/>
|
||
{initiativeKinds.map(x => <Field key={x.key} label={x.countLabel}><Input name={`${x.key}InitiativesCount`} type="number" min="0" required defaultValue={value(`${x.key}InitiativesCount`, 0)}/></Field>)}
|
||
<Field label="تعداد مقالات"><Input name="articlesCount" type="number" min="0" required defaultValue={value("articlesCount", 0)}/></Field>
|
||
<Field label="تعداد اختراعات"><Input name="inventionsCount" type="number" min="0" required defaultValue={value("inventionsCount", 0)}/></Field>
|
||
<Field label="بهبود فرآیندی"><Input name="processImprovement" defaultValue={value("processImprovement")}/></Field>
|
||
{initiativeKinds.map(x => <Money key={x.key} name={`${x.key}InitiativesAmount`} label={x.amountLabel} defaultValue={value(`${x.key}InitiativesAmount`, 0)}/>) }
|
||
</>}
|
||
<Field label="وضعیت"><Select name="status" defaultValue={value("status", 0)}><option value="0">پیشنویس</option><option value="1">انتشار</option></Select></Field>
|
||
</div></Card>
|
||
{editing && kind === "performer" && <Card className={activeTab !== "image" ? "tab-hidden" : "nested-section"}><Link className="text-link" to={`/admin/files/InnovativePerformer/${id}`}>
|
||
مدیریت تصویر نوآور برتر
|
||
</Link></Card>}
|
||
<div className={`form-actions${editing && kind === "performer" && activeTab === "image" ? " tab-hidden" : ""}`}><span>ذخیره در مدل typed مستقل با کنترل همزمانی</span><Button disabled={busy}><Save size={18}/>{busy ? "در حال ذخیره…" : editing ? "ذخیره تغییرات" : "ثبت اطلاعات"}</Button></div>
|
||
</FormErrorProvider>
|
||
</form>}
|
||
</>;
|
||
}
|
||
|
||
const initiativeKinds = [
|
||
{ key: "registered", countLabel: "ابتکارات ثبتشده", amountLabel: "مبلغ ثبتشده" },
|
||
{ key: "underReview", countLabel: "در حال بررسی", amountLabel: "مبلغ در بررسی" },
|
||
{ key: "inProgress", countLabel: "در حال اجرا", amountLabel: "مبلغ در اجرا" },
|
||
{ key: "completed", countLabel: "اتمامیافته", amountLabel: "مبلغ اتمامیافته" },
|
||
];
|
||
function UrlField({ defaultValue = "" }: { defaultValue?: string }) { return <Field label="لینک"><Input name="link" type="url" dir="ltr" required defaultValue={defaultValue}/></Field>; }
|
||
function Money({ name, label, defaultValue = "0" }: { name: string; label: string; defaultValue?: string }) { return <Field label={label} hint="واحد: میلیون ریال"><Input name={name} groupDigits inputMode="decimal" dir="ltr" required defaultValue={defaultValue}/></Field>; }
|
||
function endpoint(kind: string) { return ({ publication: "/api/v1/publications", event: "/api/v1/event-activities", book: "/api/v1/books", performer: "/api/v1/innovative-performers" } as Record<string, string>)[kind] ?? "/api/v1/invalid"; }
|
||
function str(form: FormData, name: string) { return String(form.get(name) ?? "") || null; }
|
||
function num(form: FormData, name: string) { return Number(form.get(name) ?? 0); }
|
||
function payload(kind: string, form: FormData, eventActivityType: string) {
|
||
const status = num(form, "status");
|
||
if (kind === "publication") return { title: str(form, "title"), writer: str(form, "writer"), publishingOrganization: str(form, "publishingOrganization"), publishingDate: str(form, "publishingDate"), reportType: str(form, "reportType"), link: str(form, "link"), pageCount: num(form, "pageCount"), language: str(form, "language"), area: str(form, "area"), status };
|
||
if (kind === "book") return { title: str(form, "title"), bookType: str(form, "bookType"), publicationPlace: str(form, "publicationPlace"), publicationDate: str(form, "publicationDate"), writerOrTranslator: str(form, "writerOrTranslator"), specializedField: str(form, "specializedField"), link: str(form, "link"), status };
|
||
if (kind === "event") return { activityType: Number(eventActivityType), title: str(form, "title"), eventDate: str(form, "eventDate"), place: str(form, "place"), organizer: str(form, "organizer"), link: str(form, "link"), eventType: str(form, "eventType"), role: str(form, "role"), audience: str(form, "audience"), summary: str(form, "summary"), achievement: str(form, "achievement"), axis: str(form, "axis"), participationType: str(form, "participationType"), presentationTitle: str(form, "presentationTitle"), area: str(form, "area"), presenceType: str(form, "presenceType"), productTitle: str(form, "productTitle"), status };
|
||
return { title: str(form, "title"), personnelNumber: str(form, "personnelNumber"), projectId: str(form, "projectId"), ideaOriginality: str(form, "ideaOriginality"), revenueBefore: str(form, "revenueBefore"), revenueAfter: str(form, "revenueAfter"), registeredInitiativesCount: num(form, "registeredInitiativesCount"), underReviewInitiativesCount: num(form, "underReviewInitiativesCount"), inProgressInitiativesCount: num(form, "inProgressInitiativesCount"), completedInitiativesCount: num(form, "completedInitiativesCount"), articlesCount: num(form, "articlesCount"), inventionsCount: num(form, "inventionsCount"), processImprovement: str(form, "processImprovement"), registeredInitiativesAmount: str(form, "registeredInitiativesAmount"), underReviewInitiativesAmount: str(form, "underReviewInitiativesAmount"), inProgressInitiativesAmount: str(form, "inProgressInitiativesAmount"), completedInitiativesAmount: str(form, "completedInitiativesAmount"), status };
|
||
}
|