161 lines
12 KiB
TypeScript
161 lines
12 KiB
TypeScript
import { ArrowRight, Plus, Save, Trash2 } from "lucide-react";
|
||
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
|
||
import { useEffect, useState, type FormEvent, type ReactNode } 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 { 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 [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||
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();
|
||
if (!validateAdminForm(event.currentTarget, setActiveTab)) return;
|
||
setBusy(true); setError(""); setFieldErrors({});
|
||
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) {
|
||
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>;
|
||
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} noValidate key={id ?? "new"}>
|
||
<FormErrorProvider errors={fieldErrors}>
|
||
<Card dataTab="info" 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="لینک مستقیم" type="url" dir="ltr" maxLength={2048} 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="لینک مستقیم" type="url" dir="ltr" maxLength={2048} 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>
|
||
</FormErrorProvider>
|
||
</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>;
|
||
}
|