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

95 lines
12 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 { ArchiveRestore, Eye, ShieldAlert, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Button, Card, ErrorBanner, Field, Input, PageTitle, Select } from "../components/Ui";
import { api } from "../lib/api";
import type { ReferenceItem } from "../types";
import { ListToolbar, PaginationControls } from "../components/ListControls";
type Batch = { id: string; name: string; sourceSystem: string; status: string; recordCount: number; issueCount?: number; unresolvedIssueCount?: number; createdAtUtc?: string };
type Preview = { batchId: string; deletableCount: number; blockedCount: number; records: Array<{ entityType: string; entityId: string; canDelete: boolean; blockReason?: string }> };
type Issue = { id: string; processId?: number; sourceIdentity?: string; code: string; message: string; rawValue?: string; resolved: boolean; resolution?: string };
type Details = { batch: Batch; records: unknown[]; issues: Issue[] };
type Family = { processId: number; sourceTable: string; sourceCount: number; migratedSourceCount: number; quarantinedSourceCount: number; difference: number; isBalanced: boolean };
type Reconciliation = { trackedRecordCount: number; existingRecordCount: number; missingRecordCount: number; legacyMapCount: number; unresolvedIssueCount: number; families: Family[]; isConsistent: boolean };
export function TestBatchesPage() {
const [themes, setThemes] = useState<ReferenceItem[]>([]); const [values, setValues] = useState<ReferenceItem[]>([]);
const [themeId, setThemeId] = useState(""); const [valueId, setValueId] = useState("");
const [batches, setBatches] = useState<Batch[]>([]); const [batch, setBatch] = useState<Batch | null>(null);
const [preview, setPreview] = useState<Preview | null>(null); const [details, setDetails] = useState<Details | null>(null);
const [reconciliation, setReconciliation] = useState<Reconciliation | null>(null); const [error, setError] = useState("");
const [resolutions, setResolutions] = useState<Record<string, string>>({});
const [search,setSearch]=useState(""); const [statusFilter,setStatusFilter]=useState("");
const [page,setPage]=useState(1); const [pageSize,setPageSize]=useState(25);
const filteredBatches=useMemo(()=>{const q=search.trim().toLocaleLowerCase("fa");return batches.filter(x=>(!q||x.name.toLocaleLowerCase("fa").includes(q)||x.sourceSystem.toLocaleLowerCase().includes(q))&&(!statusFilter||x.status===statusFilter));},[batches,search,statusFilter]);
const visibleBatches=useMemo(()=>filteredBatches.slice((page-1)*pageSize,page*pageSize),[filteredBatches,page,pageSize]);
const statuses=useMemo(()=>[...new Set(batches.map(x=>x.status))].sort(),[batches]);
useEffect(()=>setPage(1),[search,statusFilter,pageSize]);
async function refresh() { setBatches(await api<Batch[]>("/api/v1/test-data-batches")); }
useEffect(() => { void api<ReferenceItem[]>("/api/v1/strategic-themes").then(setThemes).catch(e => setError(e.message)); }, []);
useEffect(() => { void refresh().catch(e => setError(e.message)); }, []);
useEffect(() => { if (themeId) void api<ReferenceItem[]>(`/api/v1/innovation-values?strategicThemeId=${themeId}`).then(setValues); }, [themeId]);
async function loadBatch(selected: Batch) {
setBatch(selected); setPreview(null);
const [loadedDetails, loadedReconciliation] = await Promise.all([
api<Details>(`/api/v1/test-data-batches/${selected.id}`),
api<Reconciliation>(`/api/v1/test-data-batches/${selected.id}/reconciliation`)
]);
setDetails(loadedDetails); setReconciliation(loadedReconciliation);
}
async function create(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); const form = new FormData(event.currentTarget);
const result = await api<Batch>("/api/v1/test-data-batches/synthetic-project", { method: "POST", body: JSON.stringify({ batchName: form.get("batchName"), idempotencyKey: form.get("idempotencyKey"), strategicThemeId: themeId, innovationValueId: valueId, projectNumber: form.get("projectNumber"), projectTitle: form.get("projectTitle") }) });
await refresh(); await loadBatch(result);
}
async function createAcceptancePackage() {
if (!themeId || !valueId) { setError("برای بسته پذیرش، مضمون و ارزش را انتخاب کنید."); return; }
const result = await api<Batch>("/api/v1/test-data-batches/synthetic-acceptance-package", { method: "POST", body: JSON.stringify({ batchName: "پذیرش مهاجرت چندخانواده‌ای", idempotencyKey: crypto.randomUUID(), strategicThemeId: themeId, innovationValueId: valueId }) });
await refresh(); await loadBatch(result);
}
async function inspect() { if (batch) { setPreview(await api(`/api/v1/test-data-batches/${batch.id}/deletion-preview`)); } }
async function remove() { if (!batch || !preview || preview.blockedCount) return; await api(`/api/v1/test-data-batches/${batch.id}/delete`, { method: "POST" }); await refresh(); await loadBatch({ ...batch, status: "Deleted" }); }
async function resolve(issue: Issue) {
if (!batch || !resolutions[issue.id]?.trim()) return;
await api(`/api/v1/test-data-batches/${batch.id}/issues/${issue.id}/resolve`, { method: "POST", body: JSON.stringify({ resolution: resolutions[issue.id] }) });
await loadBatch(batch); await refresh();
}
return <>
<PageTitle title="بسته‌های داده آزمایشی" description="اثبات idempotency، provenance، تطبیق و حذف کنترل‌شده در دیتابیس مقصد"/>
<div className="notice"><ShieldAlert size={20}/><span>داده مصنوعی هرگز داده منتقل‌شده واقعی معرفی نمی‌شود. اتصال APADANA فقط با حساب SELECT-only مجاز است.</span></div>
{error && <ErrorBanner message={error}/>}
<div className="two-column batch-layout"><Card><div className="card-heading"><div><h3>ایجاد بسته مصنوعی</h3><p>مسیر ساده یا بسته پذیرش چندخانواده‌ای</p></div><ArchiveRestore/></div>
<form className="form-stack compact" onSubmit={e => void create(e).catch(x => setError(x.message))}>
<Field label="نام بسته"><Input name="batchName" required defaultValue="آزمون مسیر سبز"/></Field>
<Field label="کلید تکرارپذیری"><Input name="idempotencyKey" required defaultValue={crypto.randomUUID()}/></Field>
<Field label="مضمون"><Select value={themeId} onChange={e => { setThemeId(e.target.value); setValueId(""); }} required><option value="">انتخاب کنید</option>{themes.map(x => <option key={x.id} value={x.id}>{x.title}</option>)}</Select></Field>
<Field label="ارزش"><Select value={valueId} onChange={e => setValueId(e.target.value)} required><option value="">انتخاب کنید</option>{values.map(x => <option key={x.id} value={x.id}>{x.title}</option>)}</Select></Field>
<Field label="شماره پروژه"><Input name="projectNumber" required defaultValue={`TEST-${Date.now()}`}/></Field>
<Field label="عنوان پروژه"><Input name="projectTitle" required defaultValue="پروژه مصنوعی نوآوری سبز"/></Field>
<Button>ایجاد بسته ساده</Button>
<Button type="button" className="secondary" onClick={() => void createAcceptancePackage().catch(x => setError(x.message))}>ایجاد بسته پذیرش ۱۲ خانواده</Button>
</form></Card>
<Card><div className="card-heading"><div><h3>وضعیت و حذف</h3><p>وضعیت در لحظه حذف دوباره بررسی می‌شود</p></div></div>
{!batch ? <div className="empty-state"><strong>بسته‌ای انتخاب نشده</strong></div> : <div className="batch-result"><dl><div><dt>شناسه</dt><dd className="latin">{batch.id}</dd></div><div><dt>وضعیت</dt><dd>{batch.status}</dd></div><div><dt>تعداد رکورد</dt><dd>{batch.recordCount}</dd></div><div><dt>تطبیق</dt><dd>{reconciliation?.isConsistent ? "سازگار" : "نیازمند بررسی"}</dd></div></dl>
<Button className="secondary" onClick={() => void inspect().catch(x => setError(x.message))}><Eye size={17}/>پیش‌نمایش حذف</Button>
{preview && <div className="preview-box"><p><b>{preview.deletableCount}</b> قابل حذف · <b>{preview.blockedCount}</b> مسدود</p>{preview.records.map(x => <div key={`${x.entityType}-${x.entityId}`} className={x.canDelete ? "ok" : "blocked"}><span>{x.entityType}</span><small>{x.canDelete ? "قابل حذف" : x.blockReason}</small></div>)}
<Button className="danger" disabled={preview.blockedCount > 0 || batch.status === "Deleted"} onClick={() => void remove().catch(x => setError(x.message))}><Trash2 size={17}/>حذف کنترل‌شده بسته</Button></div>}
</div>}
</Card></div>
{reconciliation && <Card><div className="card-heading"><div><h3>تطبیق خانواده‌های منبع</h3><p>source = migrated + quarantined</p></div></div>
{reconciliation.families.length === 0 ? <div className="empty-state"><strong>آمار منبع برای این بسته ثبت نشده است</strong></div> : <div className="table-wrap"><table><thead><tr><th>ProcessID</th><th>جدول</th><th>منبع</th><th>مهاجرت</th><th>قرنطینه</th><th>اختلاف</th></tr></thead><tbody>{reconciliation.families.map(x => <tr key={x.processId}><td>{x.processId}</td><td className="latin">{x.sourceTable}</td><td>{x.sourceCount}</td><td>{x.migratedSourceCount}</td><td>{x.quarantinedSourceCount}</td><td className={x.isBalanced ? "ok" : "blocked"}>{x.difference}</td></tr>)}</tbody></table></div>}
</Card>}
{details && details.issues.length > 0 && <Card><div className="card-heading"><div><h3>قرنطینه و خطاهای داده</h3><p>تعیین تکلیف هر مورد با نام راهبر و زمان ثبت می‌شود</p></div></div>
<div className="form-stack">{details.issues.map(x => <div className="preview-box" key={x.id}><b>{x.code} · Process {x.processId ?? "-"}</b><p>{x.message}</p><small className="latin">{x.sourceIdentity}</small>{x.resolved ? <p className="ok">تعیین تکلیف شد: {x.resolution}</p> : <div className="form-stack compact"><Input value={resolutions[x.id] ?? ""} onChange={e => setResolutions(v => ({ ...v, [x.id]: e.target.value }))} placeholder="شرح تعیین تکلیف"/><Button type="button" onClick={() => void resolve(x).catch(e => setError(e.message))}>ثبت تعیین تکلیف</Button></div>}</div>)}</div>
</Card>}
<Card><div className="card-heading"><div><h3>بسته‌های ثبت‌شده</h3><p>بسته‌های مصنوعی و انتقالی، همراه شمار خطاهای قرنطینه</p></div><Button className="secondary" onClick={() => void refresh().catch(e => setError(e.message))}>به‌روزرسانی</Button></div>
<ListToolbar search={search} onSearch={setSearch} total={filteredBatches.length} placeholder="نام بسته یا منشأ…"><Select value={statusFilter} onChange={e=>setStatusFilter(e.target.value)}><option value="">همه وضعیت‌ها</option>{statuses.map(x=><option key={x} value={x}>{batchStatusLabel(x)}</option>)}</Select></ListToolbar>
{filteredBatches.length === 0 ? <div className="empty-state"><strong>بسته‌ای با این فیلتر یافت نشد</strong></div> : <><div className="table-wrap"><table><thead><tr><th>نام</th><th>منشأ</th><th>وضعیت</th><th>رکورد</th><th>خطای باز</th><th></th></tr></thead><tbody>{visibleBatches.map(x => <tr key={x.id}><td>{x.name}</td><td>{x.sourceSystem}</td><td>{batchStatusLabel(x.status)}</td><td>{x.recordCount}</td><td>{x.unresolvedIssueCount ?? 0}</td><td><Button className="secondary" onClick={() => void loadBatch(x).catch(e => setError(e.message))}>انتخاب</Button></td></tr>)}</tbody></table></div><PaginationControls page={page} pageSize={pageSize} total={filteredBatches.length} loading={false} onPage={setPage} onPageSize={setPageSize}/></>}
</Card>
</>;
}
function batchStatusLabel(value:string){return ({Previewed:"پیش‌نمایش‌شده",Importing:"در حال انتقال",Completed:"تکمیل‌شده",PartiallyBlocked:"دارای مورد مسدود",Deleted:"حذف‌شده",Failed:"ناموفق"} as Record<string,string>)[value]??value;}