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

110 lines
7.6 KiB
TypeScript
Raw Permalink 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 { CheckCircle2, Download, FileSpreadsheet, RefreshCw, ShieldAlert, Upload } from "lucide-react";
import { useState, type FormEvent } from "react";
import { Button, Card, ErrorBanner, PageTitle } from "../components/Ui";
import { api, apiOrigin } from "../lib/api";
type ImportError = { column: string; code: string; message: string };
type ImportRow = { sheet: string; rowNumber: number; rowKey?: string; mode: string; isValid: boolean;
action: string; errors: ImportError[]; resultEntityId?: string };
type ImportJob = { id: string; family: string; templateVersion: string; originalFileName: string;
fileSha256: string; status: number; totalRows: number; validRows: number; errorRows: number; rows: ImportRow[] };
type CommitResult = { jobId: string; status: number; createdCount: number; updatedCount: number; entityIds: string[] };
const families = [
{ key: "projects", title: "پروژه‌ها، پارامترهای فناوری و صادرات", version: "projects-v3", note: "پروژه، جزئیات انواع نوآوری، پارامترهای فناوری و صادرات" },
{ key: "ideas-achievements", title: "ایده‌ها و دستاوردها", version: "ideas-achievements-v1", note: "ایده‌ها، مقاله‌ها و اختراع‌های وابسته یا مستقل" },
{ key: "ecosystem", title: "زیست‌بوم", version: "ecosystem-v1", note: "تمام انواع بازیگران زیست‌بوم و اطلاعات اختصاصی آن‌ها" },
{ key: "financial", title: "اطلاعات مالی", version: "financial-v1", note: "سال مالی و چهار فصل وابسته با مبالغ دقیق" },
{ key: "content", title: "محتوا و نوآوران", version: "content-v1", note: "انتشارات، رویدادها، کتاب‌ها و نوآوران برتر" }
] as const;
export function ExcelImportsPage() {
const [family, setFamily] = useState<string>(families[0].key);
const [job, setJob] = useState<ImportJob | null>(null);
const [result, setResult] = useState<CommitResult | null>(null);
const [requestKey, setRequestKey] = useState(crypto.randomUUID());
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const selected = families.find(x => x.key === family)!;
const jobPath = (id: string) => family === "projects"
? `/api/v1/excel-imports/${id}` : `/api/v1/excel-imports/${family}/${id}`;
async function preview(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); setBusy(true); setError(""); setResult(null);
const form = new FormData(event.currentTarget); form.append("requestKey", requestKey);
try { setJob(await api<ImportJob>(`/api/v1/excel-imports/${family}/preview`, { method: "POST", body: form })); }
catch (reason) { setError(reason instanceof Error ? reason.message : "پیش‌نمایش فایل ناموفق بود."); }
finally { setBusy(false); }
}
async function commit() {
if (!job) return; setBusy(true); setError("");
try {
setResult(await api<CommitResult>(`${jobPath(job.id)}/commit`, { method: "POST" }));
setJob(await api<ImportJob>(jobPath(job.id)));
} catch (reason) { setError(reason instanceof Error ? reason.message : "ثبت اطلاعات ناموفق بود."); }
finally { setBusy(false); }
}
function reset(nextFamily = family) {
setFamily(nextFamily); setJob(null); setResult(null); setError(""); setRequestKey(crypto.randomUUID());
}
return <>
<PageTitle title="ورود اکسل اطلاعات" description="قالب‌های مستقل و نسخه‌دار با پیش‌نمایش، اعتبارسنجی و ثبت اتمیک"
action={<a className="button link-button" href={`${apiOrigin}/api/v1/excel-imports/${family}/template`}>
<Download size={17}/>دریافت {selected.version}
</a>}/>
<div className="notice"><ShieldAlert size={20}/><span>
این قابلیت برای ورود روزمره داده است و مهاجرت دیتابیس قدیمی نیست. تاریخ‌ها باید هجری شمسی با قالب <b>yyyy/MM/dd</b> باشند؛
فرمول، macro و external link پذیرفته نمی‌شود. در Update، شناسه و RowVersion الزامی و کل ردیف جایگزین می‌شود.
</span></div>
{error && <ErrorBanner message={error}/>}
<Card><div className="form-grid cols-3">
<label className="field"><span>خانواده اطلاعات</span><select className="input" value={family}
disabled={busy} onChange={event => reset(event.target.value)}>
{families.map(item => <option key={item.key} value={item.key}>{item.title}</option>)}
</select></label>
<div className="field"><span>نسخه قرارداد</span><strong className="input latin">{selected.version}</strong></div>
<div className="field"><span>محدوده قالب</span><strong className="input">{selected.note}</strong></div>
</div></Card>
<Card><form className="excel-upload" onSubmit={preview}>
<span className="excel-icon"><FileSpreadsheet size={25}/></span>
<div><strong>فایل تکمیل‌شده {selected.version}</strong><small>
حداکثر ۲۰ مگابایت و ۵۰۰۰ ردیف؛ ابتدا فقط پیش‌نمایش ذخیره می‌شود و هیچ داده دامنه‌ای تغییر نمی‌کند.
</small></div>
<input className="input" name="file" type="file" accept=".xlsx" required disabled={busy || job?.status === 2}/>
<Button type="submit" disabled={busy || job?.status === 2}><Upload size={17}/>{busy ? "در حال اعتبارسنجی…" : "پیش‌نمایش"}</Button>
</form></Card>
{job && <Card>
<div className="import-summary">
<div><small>نسخه قالب</small><strong>{job.templateVersion}</strong></div>
<div><small>کل ردیف‌ها</small><strong>{job.totalRows}</strong></div>
<div className="valid"><small>معتبر</small><strong>{job.validRows}</strong></div>
<div className={job.errorRows ? "invalid" : "valid"}><small>خطادار</small><strong>{job.errorRows}</strong></div>
<div><small>وضعیت</small><strong>{statusText(job.status)}</strong></div>
</div>
<div className="table-wrap"><table><thead><tr><th>Sheet</th><th>ردیف</th><th>RowKey</th><th>عملیات</th><th>نتیجه اعتبارسنجی</th></tr></thead>
<tbody>{job.rows.map(row => <tr key={`${row.sheet}-${row.rowNumber}`}><td>{row.sheet}</td><td>{row.rowNumber}</td>
<td className="latin">{row.rowKey ?? "—"}</td><td>{row.mode}</td><td>{row.isValid
? <span className="status status-1">معتبر</span>
: <div className="row-errors">{row.errors.map((x, index) => <span key={index}><b>{x.column}</b>: {x.message}</span>)}</div>}</td></tr>)}</tbody>
</table></div>
<div className="import-actions">
<Button className="secondary" type="button" onClick={() => reset()}><RefreshCw size={17}/>ورود مستقل جدید</Button>
<Button type="button" disabled={busy || job.errorRows > 0 || job.status === 2} onClick={() => void commit()}>
<CheckCircle2 size={17}/>{job.status === 2 ? "ثبت شده" : "تأیید و ثبت اتمیک"}</Button>
</div>
{result && <div className="success-banner"><CheckCircle2 size={18}/>{result.createdCount} رکورد ایجاد و {result.updatedCount} رکورد ویرایش شد. تکرار همین commit داده را دوباره ثبت نمی‌کند.</div>}
</Card>}
</>;
}
function statusText(status: number) { return ["دارای خطای اعتبارسنجی", "آماده ثبت", "ثبت‌شده", "ناموفق"][status] ?? "نامشخص"; }