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

109 lines
8.5 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, Download, FileText, Paperclip, Trash2, Upload } from "lucide-react";
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { Link, useParams } from "react-router";
import { Button, Card, EmptyState, ErrorBanner, PageTitle, Select } from "../components/Ui";
import { api, apiOrigin } from "../lib/api";
import type { AttachmentItem } from "../types";
import { ListToolbar, PaginationControls } from "../components/ListControls";
const entityRoutes: Record<string, string> = {
Project: "/admin/projects", Idea: "/admin/ideas", EcosystemActor: "/admin/ecosystem", FinancialYear: "/admin/financial",
Publication: "/admin/content", EventActivity: "/admin/content", Book: "/admin/content", InnovativePerformer: "/admin/content",
PublishedArticle: "/admin/achievements", RegisteredPatent: "/admin/achievements"
};
const entityLabels: Record<string, string> = {
Project: "پروژه", Idea: "ایده", EcosystemActor: "بازیگر زیست‌بوم", FinancialYear: "سال مالی",
Publication: "انتشار", EventActivity: "رویداد", Book: "کتاب", InnovativePerformer: "نوآور برتر",
PublishedArticle: "مقاله", RegisteredPatent: "اختراع"
};
const roleOptions: Record<string, Array<[string,string]>> = {
Idea: [["InnovatorPhoto", "تصویر ایده‌پرداز"]],
PublishedArticle: [["FirstPage", "صفحه اول مقاله"]],
RegisteredPatent: [["FirstPage", "صفحه اول اختراع"]],
EcosystemActor: [["Image", "تصویر/لوگو"]],
InnovativePerformer: [["Image", "تصویر نوآور"]],
};
const roleLabels: Record<string,string> = { InnovatorPhoto: "تصویر ایده‌پرداز", FirstPage: "صفحه اول", Image: "تصویر/لوگو" };
export function FileManagementPage() {
const { entityType = "", entityId = "" } = useParams();
const [items, setItems] = useState<AttachmentItem[]>([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [role, setRole] = useState("");
const input = useRef<HTMLInputElement>(null);
const [search,setSearch]=useState(""); const [roleFilter,setRoleFilter]=useState("");
const [page,setPage]=useState(1); const [pageSize,setPageSize]=useState(25);
const singleImage = Boolean(roleOptions[entityType]?.length);
const imageLabel = roleOptions[entityType]?.[0]?.[1] ?? "تصویر";
const returnPath = entityRoutes[entityType] ?? "/admin";
const filtered=useMemo(()=>{const q=search.trim().toLocaleLowerCase("fa");return items.filter(x=>(!q||x.originalName.toLocaleLowerCase("fa").includes(q)||x.contentType.toLocaleLowerCase().includes(q))&&(!roleFilter||(x.role??"")===roleFilter));},[items,search,roleFilter]);
const visible=useMemo(()=>filtered.slice((page-1)*pageSize,page*pageSize),[filtered,page,pageSize]);
const availableRoles=useMemo(()=>[...new Set(items.map(x=>x.role).filter((x):x is string=>Boolean(x)))], [items]);
useEffect(()=>setPage(1),[search,roleFilter,pageSize,entityType,entityId]);
async function load() {
setLoading(true); setError("");
try { setItems(await api<AttachmentItem[]>(`/api/v1/files?entityType=${encodeURIComponent(entityType)}&entityId=${entityId}`)); }
catch (reason) { setError(reason instanceof Error ? reason.message : "دریافت فایل‌ها ناموفق بود."); }
finally { setLoading(false); }
}
useEffect(() => { void load(); }, [entityType, entityId]);
async function upload(event: FormEvent) {
event.preventDefault();
const file = input.current?.files?.[0];
if (!file) return;
const body = new FormData();
body.append("entityType", entityType); body.append("entityId", entityId); body.append("file", file);
if (singleImage) body.append("role", roleOptions[entityType]![0][0]);
else if (role) body.append("role", role);
setBusy(true); setError("");
try { await api("/api/v1/files", { method: "POST", body }); if (input.current) input.current.value = ""; await load(); }
catch (reason) { setError(reason instanceof Error ? reason.message : "بارگذاری فایل ناموفق بود."); }
finally { setBusy(false); }
}
async function remove(item: AttachmentItem) {
if (!window.confirm(`پیوند فایل «${item.originalName}» حذف شود؟`)) return;
setBusy(true); setError("");
try { await api(`/api/v1/files/${item.id}/links/${item.linkId}`, { method: "DELETE" }); await load(); }
catch (reason) { setError(reason instanceof Error ? reason.message : "حذف فایل ناموفق بود."); }
finally { setBusy(false); }
}
return <>
<PageTitle title={singleImage ? imageLabel : `فایل‌های ${entityLabels[entityType] ?? "رکورد"}`} description={singleImage ? "برای هر رکورد فقط یک تصویر قابل ثبت است؛ برای تغییر، ابتدا تصویر فعلی را حذف کنید." : "ذخیره امن خارج از web root؛ حداکثر ۱۰ مگابایت و فقط PDF یا تصویر"}
action={<Link to={returnPath} className="text-link"><ArrowRight size={17}/>بازگشت</Link>}/>
{error && <ErrorBanner message={error}/>}
<Card>
{(!singleImage || items.length === 0) && <form className="file-upload" onSubmit={upload}>
<div><strong><Paperclip size={18}/> {singleImage ? `ثبت ${imageLabel}` : "افزودن فایل"}</strong><small>{singleImage ? "JPEG، PNG، WebP، AVIF یا SVG" : "PDF یا تصویر"}</small></div>
<input ref={input} className="input" type="file" required accept={singleImage ? "image/jpeg,image/png,image/webp,image/avif,image/svg+xml" : "application/pdf,image/jpeg,image/png,image/webp,image/avif,image/svg+xml"}/>
{!singleImage && (roleOptions[entityType]?.length ?? 0) > 0 && <Select value={role} onChange={e => setRole(e.target.value)}><option value="">فایل عمومی</option>{roleOptions[entityType].map(([value,label])=><option key={value} value={value}>{label}</option>)}</Select>}
<Button type="submit" disabled={busy}><Upload size={17}/>{busy ? "در حال ارسال…" : singleImage ? "ثبت تصویر" : "بارگذاری"}</Button>
</form>}
{!loading&&!singleImage&&<ListToolbar search={search} onSearch={setSearch} total={filtered.length} placeholder="نام یا نوع فایل…">{availableRoles.length>0&&<Select value={roleFilter} onChange={e=>setRoleFilter(e.target.value)}><option value="">همه نقش‌ها</option>{availableRoles.map(x=><option key={x} value={x}>{roleLabels[x]??x}</option>)}</Select>}</ListToolbar>}
{loading ? <div className="loading-line">در حال دریافت فایل‌ها…</div> : filtered.length === 0
? <EmptyState title={singleImage ? "تصویری ثبت نشده است" : "فایلی یافت نشد"} description={items.length?"عبارت جست‌وجو یا فیلتر را تغییر دهید.":singleImage?`${imageLabel} را با فرم بالا ثبت کنید.`:"فایل مستند این رکورد را با فرم بالا بارگذاری کنید."}/>
: <><div className="attachment-list">{visible.map(item => <div key={item.linkId} className="attachment-row with-preview">
<div className="attachment-preview">
{item.contentType.startsWith("image/")
? <img src={`${apiOrigin}/api/v1/files/${item.id}/preview`} alt={item.originalName} loading="lazy"/>
: item.contentType === "application/pdf"
? <iframe src={`${apiOrigin}/api/v1/files/${item.id}/preview#toolbar=0`} title={item.originalName}/>
: <span className="attachment-icon"><FileText size={24}/></span>}
</div>
<div><strong>{item.originalName}{item.role && <span className="file-role">{roleLabels[item.role] ?? item.role}</span>}</strong><small>{formatSize(item.size)} · {item.contentType} · SHA-256: {item.sha256.slice(0, 12)}…</small></div>
<a className="icon-action" href={`${apiOrigin}/api/v1/files/${item.id}`}><Download size={17}/><span>دریافت</span></a>
<button className="icon-action danger-text" type="button" disabled={busy} onClick={() => void remove(item)}><Trash2 size={17}/><span>{singleImage ? "حذف تصویر" : "حذف پیوند"}</span></button>
</div>)}</div>{!singleImage&&<PaginationControls page={page} pageSize={pageSize} total={filtered.length} loading={false} onPage={setPage} onPageSize={setPageSize}/>}</>}
</Card>
</>;
}
function formatSize(size: number) { return size < 1024 * 1024 ? `${Math.ceil(size / 1024)} KB` : `${(size / 1024 / 1024).toFixed(1)} MB`; }