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

444 lines
16 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, Pencil, Plus, Save, Trash2, X } from "lucide-react";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Link, useParams } from "react-router";
import {
Button,
Card,
EmptyState,
ErrorBanner,
Field,
Input,
PageTitle,
Select,
} from "../components/Ui";
import { ApiError, api } from "../lib/api";
import { isMoneyField, unitHint } from "../lib/fieldUnits";
import type { ProjectExportItem, TechnologyParameterItem } from "../types";
import { ListToolbar, PaginationControls } from "../components/ListControls";
type TechDraft = { title: string; domesticValue: string; foreignValue: string };
type ExportDraft = {
persianYear: string;
season: string;
exportVolume: string;
exportedCapacity: string;
importVolumeBefore: string;
importVolumeAfter: string;
pricePerUnit: string;
exportRevenueBefore: string;
exportRevenueAfter: string;
};
const emptyTech: TechDraft = { title: "", domesticValue: "", foreignValue: "" };
const emptyExport: ExportDraft = {
persianYear: "1405",
season: "بهار",
exportVolume: "",
exportedCapacity: "",
importVolumeBefore: "",
importVolumeAfter: "",
pricePerUnit: "",
exportRevenueBefore: "",
exportRevenueAfter: "",
};
export function ProjectChildrenPage({
embeddedProjectId,
}: {
embeddedProjectId?: string;
} = {}) {
const { projectId: routeProjectId = "" } = useParams();
const projectId = embeddedProjectId ?? routeProjectId;
const [technology, setTechnology] = useState<TechnologyParameterItem[]>([]);
const [exports, setExports] = useState<ProjectExportItem[]>([]);
const [techDraft, setTechDraft] = useState<TechDraft>(emptyTech);
const [exportDraft, setExportDraft] = useState<ExportDraft>(emptyExport);
const [editingTech, setEditingTech] =
useState<TechnologyParameterItem | null>(null);
const [editingExport, setEditingExport] = useState<ProjectExportItem | null>(
null,
);
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [techSearch,setTechSearch]=useState(""); const [techPage,setTechPage]=useState(1); const [techPageSize,setTechPageSize]=useState(25);
const [exportSearch,setExportSearch]=useState(""); const [exportPage,setExportPage]=useState(1); const [exportPageSize,setExportPageSize]=useState(25);
const filteredTechnology=useMemo(()=>{const q=techSearch.trim().toLocaleLowerCase("fa");return technology.filter(x=>!q||x.title.toLocaleLowerCase("fa").includes(q));},[technology,techSearch]);
const visibleTechnology=useMemo(()=>filteredTechnology.slice((techPage-1)*techPageSize,techPage*techPageSize),[filteredTechnology,techPage,techPageSize]);
const filteredExports=useMemo(()=>{const q=exportSearch.trim().toLocaleLowerCase("fa");return exports.filter(x=>!q||`${x.persianYear} ${x.season}`.toLocaleLowerCase("fa").includes(q));},[exports,exportSearch]);
const visibleExports=useMemo(()=>filteredExports.slice((exportPage-1)*exportPageSize,exportPage*exportPageSize),[filteredExports,exportPage,exportPageSize]);
useEffect(()=>setTechPage(1),[techSearch,techPageSize,projectId]); useEffect(()=>setExportPage(1),[exportSearch,exportPageSize,projectId]);
async function load() {
setLoading(true);
setError("");
try {
const [techRows, exportRows] = await Promise.all([
api<TechnologyParameterItem[]>(
`/api/v1/projects/${projectId}/technology-parameters`,
),
api<ProjectExportItem[]>(`/api/v1/projects/${projectId}/exports`),
]);
setTechnology(techRows);
setExports(exportRows);
} catch (reason) {
setError(
reason instanceof Error
? reason.message
: "دریافت پارامترهای فناوری و اطلاعات صادرات ناموفق بود.",
);
} finally {
setLoading(false);
}
}
useEffect(() => {
void load();
}, [projectId]);
async function saveTech(event: FormEvent) {
event.preventDefault();
setBusy(true);
setError("");
try {
const path = `/api/v1/projects/${projectId}/technology-parameters${editingTech ? `/${editingTech.id}` : ""}`;
const body = editingTech
? { data: techDraft, rowVersion: editingTech.rowVersion }
: techDraft;
await api(path, {
method: editingTech ? "PUT" : "POST",
body: JSON.stringify(body),
});
setTechDraft(emptyTech);
setEditingTech(null);
await load();
} catch (reason) {
showError(reason, setError);
} finally {
setBusy(false);
}
}
async function saveExport(event: FormEvent) {
event.preventDefault();
setBusy(true);
setError("");
const data = {
...exportDraft,
persianYear: Number(exportDraft.persianYear),
exportVolume: Number(exportDraft.exportVolume),
};
try {
const path = `/api/v1/projects/${projectId}/exports${editingExport ? `/${editingExport.id}` : ""}`;
const body = editingExport
? { data, rowVersion: editingExport.rowVersion }
: data;
await api(path, {
method: editingExport ? "PUT" : "POST",
body: JSON.stringify(body),
});
setExportDraft(emptyExport);
setEditingExport(null);
await load();
} catch (reason) {
showError(reason, setError);
} finally {
setBusy(false);
}
}
function editTech(item: TechnologyParameterItem) {
setEditingTech(item);
setTechDraft({
title: item.title,
domesticValue: String(item.domesticValue),
foreignValue: String(item.foreignValue),
});
}
async function removeChild(kind: "technology-parameters" | "exports", id: string, rowVersion: string) {
const phrase = "حذف دائمی";
if (window.prompt(`این عملیات غیرقابل بازگشت است. برای ادامه دقیقاً بنویسید: ${phrase}`) !== phrase) return;
setBusy(true); setError("");
try {
await api(`/api/v1/projects/${projectId}/${kind}/${id}`, { method: "DELETE", body: JSON.stringify({ rowVersion }) });
if (kind === "technology-parameters") setTechnology(old => old.filter(x => x.id !== id));
else setExports(old => old.filter(x => x.id !== id));
} catch (reason) { showError(reason, setError); }
finally { setBusy(false); }
}
function editExport(item: ProjectExportItem) {
setEditingExport(item);
setExportDraft({
persianYear: String(item.persianYear),
season: item.season,
exportVolume: String(item.exportVolume),
exportedCapacity: String(item.exportedCapacity),
importVolumeBefore: String(item.importVolumeBefore),
importVolumeAfter: String(item.importVolumeAfter),
pricePerUnit: String(item.pricePerUnit),
exportRevenueBefore: String(item.exportRevenueBefore),
exportRevenueAfter: String(item.exportRevenueAfter),
});
}
return (
<>
{!embeddedProjectId && (
<PageTitle
title="پارامترهای فناوری و صادرات پروژه"
description="مدیریت پارامترهای فناوری و رکوردهای صادرات با شناسه پروژه و کنترل هم‌زمانی"
action={
<Link to="/admin/projects" className="text-link">
<ArrowRight size={17} />
بازگشت
</Link>
}
/>
)}
{error && <ErrorBanner message={error} />}
<Card className="nested-section">
<div className="card-heading">
<div>
<h3>پارامترهای فناوری</h3>
<p>ارتباط با پروژه از طریق ProjectId حفظ می‌شود.</p>
</div>
</div>
<form onSubmit={saveTech} className="child-row tech-row">
<Input
required
placeholder="عنوان پارامتر"
value={techDraft.title}
onChange={(e) =>
setTechDraft({ ...techDraft, title: e.target.value })
}
/>
<Input
required
inputMode="decimal"
dir="ltr"
placeholder="مقدار داخلی"
value={techDraft.domesticValue}
onChange={(e) =>
setTechDraft({ ...techDraft, domesticValue: e.target.value })
}
/>
<Input
required
inputMode="decimal"
dir="ltr"
placeholder="مقدار خارجی"
value={techDraft.foreignValue}
onChange={(e) =>
setTechDraft({ ...techDraft, foreignValue: e.target.value })
}
/>
<Button disabled={busy}>
{editingTech ? <Save size={16} /> : <Plus size={16} />}
</Button>
{editingTech && (
<Button
type="button"
className="secondary"
onClick={() => {
setEditingTech(null);
setTechDraft(emptyTech);
}}
>
<X size={16} />
</Button>
)}
</form>
{!loading&&<ListToolbar search={techSearch} onSearch={setTechSearch} total={filteredTechnology.length} placeholder="جست‌وجوی عنوان پارامتر…"/>}
{loading ? (
<div className="loading-line">در حال دریافت…</div>
) : filteredTechnology.length === 0 ? (
<EmptyState
title="پارامتری ثبت نشده"
description="پارامتر جدید را از فرم بالا اضافه کنید."
/>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th>عنوان</th>
<th>داخلی</th>
<th>خارجی</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
{visibleTechnology.map((x) => (
<tr key={x.id}>
<td>{x.title}</td>
<td>{x.domesticValue}</td>
<td>{x.foreignValue}</td>
<td>
<div className="row-actions">
<button
type="button"
className="row-action"
onClick={() => editTech(x)}
>
<Pencil size={15} />
ویرایش
</button>
<button type="button" className="row-action danger-text" disabled={busy} onClick={() => void removeChild("technology-parameters", x.id, x.rowVersion)}><Trash2 size={15}/>حذف</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{!loading&&filteredTechnology.length>0&&<PaginationControls page={techPage} pageSize={techPageSize} total={filteredTechnology.length} loading={false} onPage={setTechPage} onPageSize={setTechPageSize}/>}
</Card>
<Card className="nested-section">
<div className="card-heading">
<div>
<h3>صادرات پروژه</h3>
<p>مقادیر مالی بدون تبدیل واحد و با دقت مقصد ذخیره می‌شوند.</p>
</div>
</div>
<form onSubmit={saveExport} className="form-stack">
<div className="form-grid cols-3">
<Field label="سال">
<Input
required
type="number"
min="1300"
max="1500"
value={exportDraft.persianYear}
onChange={(e) =>
setExportDraft({
...exportDraft,
persianYear: e.target.value,
})
}
/>
</Field>
<Field label="فصل">
<Select
value={exportDraft.season}
onChange={(e) =>
setExportDraft({ ...exportDraft, season: e.target.value })
}
>
<option>بهار</option>
<option>تابستان</option>
<option>پاییز</option>
<option>زمستان</option>
</Select>
</Field>
{exportFields.map(([key, label]) => (
<Field label={label} key={key} hint={unitHint("export", key)}>
<Input
required
groupDigits={isMoneyField("export", key)}
inputMode="decimal"
dir="ltr"
value={exportDraft[key]}
onChange={(e) =>
setExportDraft({ ...exportDraft, [key]: e.target.value })
}
/>
</Field>
))}
</div>
<div className="form-actions">
<span>
{editingExport ? "ویرایش رکورد انتخاب‌شده" : "ثبت فصل جدید"}
</span>
<div className="row-actions">
<Button disabled={busy}>
{editingExport ? <Save size={16} /> : <Plus size={16} />}ذخیره
</Button>
{editingExport && (
<Button
type="button"
className="secondary"
onClick={() => {
setEditingExport(null);
setExportDraft(emptyExport);
}}
>
<X size={16} />
انصراف
</Button>
)}
</div>
</div>
</form>
{!loading&&<ListToolbar search={exportSearch} onSearch={setExportSearch} total={filteredExports.length} placeholder="جست‌وجوی سال یا فصل…"/>}
{loading ? (
<div className="loading-line">در حال دریافت…</div>
) : filteredExports.length === 0 ? (
<EmptyState
title="صادراتی ثبت نشده"
description="رکورد فصل جدید را از فرم بالا اضافه کنید."
/>
) : (
<div className="table-wrap">
<table>
<thead>
<tr>
<th>سال/فصل</th>
<th>تعداد صادرات</th>
<th>ظرفیت</th>
<th>درآمد بعد</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
{visibleExports.map((x) => (
<tr key={x.id}>
<td>
{x.persianYear} / {x.season}
</td>
<td>{x.exportVolume}</td>
<td>{x.exportedCapacity}</td>
<td>{x.exportRevenueAfter}</td>
<td>
<div className="row-actions">
<button
type="button"
className="row-action"
onClick={() => editExport(x)}
>
<Pencil size={15} />
ویرایش
</button>
<button type="button" className="row-action danger-text" disabled={busy} onClick={() => void removeChild("exports", x.id, x.rowVersion)}><Trash2 size={15}/>حذف</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{!loading&&filteredExports.length>0&&<PaginationControls page={exportPage} pageSize={exportPageSize} total={filteredExports.length} loading={false} onPage={setExportPage} onPageSize={setExportPageSize}/>}
</Card>
</>
);
}
const exportFields: Array<
[keyof Omit<ExportDraft, "persianYear" | "season">, string]
> = [
["exportVolume", "تعداد صادرات"],
["exportedCapacity", "ظرفیت صادرشده"],
["importVolumeBefore", "واردات قبل"],
["importVolumeAfter", "واردات بعد"],
["pricePerUnit", "قیمت واحد"],
["exportRevenueBefore", "درآمد صادرات قبل"],
["exportRevenueAfter", "درآمد صادرات بعد"],
];
function showError(reason: unknown, setter: (message: string) => void) {
setter(
reason instanceof ApiError || reason instanceof Error
? reason.message
: "ذخیره اطلاعات ناموفق بود.",
);
}