inogen/app/admin/pages/IdeaFormPage.tsx
2026-10-18 18:12:59 +03:30

152 lines
11 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ArrowRight, Plus, Save, Trash2 } from "lucide-react";
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { Button, Card, ErrorBanner, Field, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, api } from "../lib/api";
import { isMoneyField, unitHint } from "../lib/fieldUnits";
import type { IdeaDetails } from "../types";
import { FormTabs } from "../components/FormTabs";
type Article = { title: string; publicationPlace: string; directLink: string; publishedDate: string };
type Patent = { title: string; registrationPlace: string; directLink: string; registeredDate: string };
type Definition = [keyof IdeaDetails, string, "text" | "date" | "decimal"];
const article = (): Article => ({ title: "", publicationPlace: "", directLink: "", publishedDate: "" });
const patent = (): Patent => ({ title: "", registrationPlace: "", directLink: "", registeredDate: "" });
const ideaStatuses = ["تایید شده", "رد شده", "در حال بررسی", "اجرا شده"];
const axes = [
"افزایش بهره‌وری و کاهش مصرف انرژی", "نوآوری در حوزه محیط زیست و پایداری",
"کاربرد فناوری‌های نوین در تولید و عملیات", "ارتقاء توان رقابتی و چابکی سازمانی",
"توسعه منابع انسانی با رویکرد نوآورانه", "فرهنگ‌سازی و نهادینه‌سازی نوآوری",
"تشویق همکاری بین‌بخشی و هم‌افزایی تیمی", "مدیریت ریسک و تاب‌آوری در شرایط بحرانی",
"بهبود مستمر کیفیت محصولات و خدمات",
];
const innovationTypes = [
"نوآوری در محصول", "نوآوری در فرآیند", "نوآوری در کسب وکار", "نوآوری دیجیتال",
"نوآوری اجتماعی", "نوآوری سبز", "نوآوری ساخت داخل", "نوآوری نرم",
];
const originalities = ["کپی شده", "الهام داخلی", "الهام بین المللی", "اصیل"];
const selectOptions: Partial<Record<keyof IdeaDetails, string[]>> = {
axis: axes, innovationType: innovationTypes, originality: originalities,
};
const fields: Definition[] = [
["title", "عنوان ایده", "text"], ["innovatorFullName", "نام و نام خانوادگی ایده‌پرداز", "text"],
["personnelNumber", "شماره پرسنلی", "text"], ["registrationDate", "تاریخ ثبت ایده", "date"],
["deputy", "معاونت", "text"], ["management", "مدیریت", "text"], ["axis", "محور ایده", "text"],
["innovationType", "نوع نوآوری", "text"], ["originality", "اصالت ایده", "text"],
["teamMembers", "اعضای تیم", "text"], ["baseRevenueBefore", "درآمد پایه قبل", "decimal"],
["incomeAfter", "درآمد بعد از ایده", "decimal"], ["currentStatusDescription", "شرح وضعیت موجود", "text"],
["description", "شرح ایده", "text"], ["executionBenefits", "منافع اجرای ایده", "text"],
["processImprovements", "بهبودهای فرایندی", "text"],
];
export function IdeaFormPage() {
const { id } = useParams();
const editing = Boolean(id);
const navigate = useNavigate();
const [details, setDetails] = useState<IdeaDetails | null>(null);
const [articles, setArticles] = useState<Article[]>([]);
const [patents, setPatents] = useState<Patent[]>([]);
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(editing);
const [error, setError] = useState("");
const [activeTab, setActiveTab] = useState("info");
useEffect(() => {
if (!editing) return;
setLoading(true);
void api<IdeaDetails>(`/api/v1/ideas/${id}`).then(setDetails).catch((e) => setError(e.message)).finally(() => setLoading(false));
}, [editing, id]);
const value = (key: keyof IdeaDetails) => details?.[key] == null ? "" : String(details[key]);
function update<T>(items: T[], set: (x: T[]) => void, index: number, key: keyof T, next: string) {
set(items.map((x, i) => i === index ? { ...x, [key]: next } : x));
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); setBusy(true); setError("");
const f = new FormData(event.currentTarget);
const read = (name: string) => f.get(name) || null;
const data = {
innovatorFullName: f.get("innovatorFullName"), personnelNumber: read("personnelNumber"),
registrationDate: f.get("registrationDate"), deputy: read("deputy"), ideaStatus: f.get("ideaStatus"),
management: read("management"), title: f.get("title"), teamMembers: read("teamMembers"), axis: read("axis"),
currentStatusDescription: read("currentStatusDescription"), description: read("description"),
executionBenefits: read("executionBenefits"), innovationType: read("innovationType"), originality: read("originality"),
baseRevenueBefore: read("baseRevenueBefore"), incomeAfter: read("incomeAfter"),
processImprovements: read("processImprovements"), status: Number(f.get("status")),
...(editing ? { rowVersion: details?.rowVersion } : {
articles: articles.map((x) => ({ ...x, directLink: x.directLink || null })),
patents: patents.map((x) => ({ ...x, directLink: x.directLink || null })),
}),
};
try {
await api(editing ? `/api/v1/ideas/${id}` : "/api/v1/ideas", { method: editing ? "PUT" : "POST", body: JSON.stringify(data) });
navigate("/admin/ideas", { replace: true });
} catch (reason) {
setError(reason instanceof ApiError ? reason.message : "ذخیره ایده ناموفق بود.");
} finally { setBusy(false); }
}
if (loading) return <Card><p>در حال دریافت اطلاعات…</p></Card>;
return <>
<PageTitle title={editing ? "ویرایش ایده" : "ثبت ایده و دستاوردها"}
description={editing ? "ویرایش اطلاعات ایده با کنترل هم‌زمانی" : "ثبت ایده، مقاله‌ها و اختراع‌ها در یک تراکنش اتمیک"}
action={<Link className="text-link" to="/admin/ideas"><ArrowRight size={17}/>بازگشت</Link>}/>
{error && <ErrorBanner message={error}/>}
{editing && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[
{id:"info",label:"اطلاعات ایده"},{id:"related",label:"دستاوردها و تصویر"},
]}/>}
<form className="form-stack" onSubmit={submit} key={id ?? "new"}>
<Card className={editing && activeTab !== "info" ? "tab-hidden" : ""}>
<div className="section-heading"><span>۰۱</span><div><h3>اطلاعات ایده</h3><p>فیلدهای مستند فرایند ۱۲۳۰</p></div></div>
<div className="form-grid cols-3">
{fields.map(([key, label, kind]) => <Field key={key} label={label} hint={unitHint("idea", String(key))}>
{selectOptions[key] ? <Select name={key} required defaultValue={value(key)}>
<option value="">انتخاب کنید</option>{selectOptions[key]!.map((option) => <option key={option}>{option}</option>)}
</Select> : <Input name={key} required={key !== "baseRevenueBefore"} defaultValue={value(key)}
groupDigits={isMoneyField("idea", String(key))}
type={kind === "date" ? "date" : "text"} inputMode={kind === "decimal" ? "decimal" : undefined}
dir={kind === "decimal" ? "ltr" : undefined}/>}
</Field>)}
<Field label="وضعیت ایده"><Select name="ideaStatus" required defaultValue={value("ideaStatus")}>
<option value="">انتخاب کنید</option>{ideaStatuses.map((option) => <option key={option}>{option}</option>)}
</Select></Field>
<Field label="وضعیت انتشار"><Select name="status" defaultValue={value("status") || "0"}>
<option value="0">پیش‌نویس</option><option value="1">انتشار</option>
</Select></Field>
</div>
</Card>
{!editing && <AchievementCard title="مقاله‌های چاپ‌شده" add={() => setArticles([...articles, article()])}>
{articles.map((x, i) => <div className="child-row" key={i}>
<Input placeholder="عنوان مقاله" value={x.title} onChange={(e) => update(articles, setArticles, i, "title", e.target.value)} required/>
<Input placeholder="محل چاپ" value={x.publicationPlace} onChange={(e) => update(articles, setArticles, i, "publicationPlace", e.target.value)} required/>
<Input type="date" value={x.publishedDate} onChange={(e) => update(articles, setArticles, i, "publishedDate", e.target.value)} required/>
<Input placeholder="لینک مستقیم" dir="ltr" value={x.directLink} onChange={(e) => update(articles, setArticles, i, "directLink", e.target.value)} required/>
<button type="button" className="icon-remove" aria-label="حذف مقاله" onClick={() => setArticles(articles.filter((_, j) => j !== i))}><Trash2 size={17}/></button>
</div>)}
</AchievementCard>}
{!editing && <AchievementCard title="اختراع‌های ثبت‌شده" add={() => setPatents([...patents, patent()])}>
{patents.map((x, i) => <div className="child-row" key={i}>
<Input placeholder="عنوان اختراع" value={x.title} onChange={(e) => update(patents, setPatents, i, "title", e.target.value)} required/>
<Input placeholder="محل ثبت" value={x.registrationPlace} onChange={(e) => update(patents, setPatents, i, "registrationPlace", e.target.value)} required/>
<Input type="date" value={x.registeredDate} onChange={(e) => update(patents, setPatents, i, "registeredDate", e.target.value)} required/>
<Input placeholder="لینک مستقیم" dir="ltr" value={x.directLink} onChange={(e) => update(patents, setPatents, i, "directLink", e.target.value)} required/>
<button type="button" className="icon-remove" aria-label="حذف اختراع" onClick={() => setPatents(patents.filter((_, j) => j !== i))}><Trash2 size={17}/></button>
</div>)}
</AchievementCard>}
{editing && <Card className={activeTab !== "related" ? "tab-hidden" : "nested-section"}><div className="row-actions"><Link className="text-link" to="/admin/achievements">مدیریت مقاله‌ها و اختراع‌ها</Link>
<Link className="text-link" to={`/admin/files/Idea/${id}`}>مدیریت تصویر ایده‌پرداز</Link></div></Card>}
<div className={`form-actions${editing && activeTab === "related" ? " tab-hidden" : ""}`}><span>{editing ? "ویرایش با کنترل نسخه رکورد" : `ثبت اتمیک ایده و ${articles.length + patents.length} دستاورد`}</span>
<Button type="submit" disabled={busy}><Save size={18}/>{busy ? "در حال ذخیره…" : editing ? "ذخیره تغییرات" : "ثبت ایده"}</Button></div>
</form>
</>;
}
function AchievementCard({ title, add, children }: { title: string; add: () => void; children: ReactNode }) {
return <Card className="nested-section"><div className="card-heading"><div><h3>{title}</h3><p>رابطه با شناسه ایده ذخیره می‌شود.</p></div>
<Button type="button" className="secondary" onClick={add}><Plus size={16}/>افزودن</Button></div>{children}</Card>;
}