feat: add CategoryImportController for bulk JSON import and export of categories

- Implemented export functionality to retrieve all rows from specified category tables.
- Developed import functionality with strict validation and referential integrity checks.
- Added error handling for various import scenarios including invalid formats and duplicate entries.
- Introduced tests for import functionality to ensure correct behavior and validation.
This commit is contained in:
hamed
2026-06-30 21:51:06 +03:30
parent 803196108c
commit 22937dfa56
22 changed files with 2473 additions and 835 deletions
+104 -9
View File
@@ -1,9 +1,9 @@
import React, { useState } from 'react';
import React, { useState, useRef } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
TrashIcon, PlusIcon, PencilIcon, TagIcon, MapPinIcon,
BuildingOffice2Icon, HeartIcon, ShieldCheckIcon, WrenchScrewdriverIcon,
PhotoIcon, XMarkIcon, ArrowDownTrayIcon,
PhotoIcon, XMarkIcon, ArrowDownTrayIcon, ArrowUpTrayIcon, ExclamationTriangleIcon,
} from '@heroicons/react/24/outline';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
@@ -21,6 +21,8 @@ import SearchableSelect from '../components/ui/SearchableSelect';
type TabKey = 'provinces' | 'cities' | 'specialties' | 'doctor_services' | 'insurances' | 'tags';
interface ImportError { row?: number; field?: string; message: string }
interface TabConfig {
key: TabKey;
label: string;
@@ -131,14 +133,21 @@ async function exportJson(url: string, filename: string, token: string | null) {
// ── Tab sub-component wrapper ──────────────────────────────────────────────────
function TabActions({ label, onClick, exportUrl, exportFile }: {
function TabActions({ label, onClick, exportUrl, exportFile, bundle, entityLabel, onImported }: {
label: string;
onClick: () => void;
exportUrl: string;
exportFile: string;
bundle: TabKey;
entityLabel: string;
onImported: () => void;
}) {
const token = useAuthStore((s) => s.token);
const [exporting, setExporting] = useState(false);
const [importing, setImporting] = useState(false);
const [errors, setErrors] = useState<ImportError[] | null>(null);
const [pendingItems, setPendingItems] = useState<unknown[] | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const handleExport = async () => {
setExporting(true);
@@ -151,8 +160,62 @@ function TabActions({ label, onClick, exportUrl, exportFile }: {
}
};
const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = '';
if (!file) return;
let parsed: unknown;
try {
parsed = JSON.parse(await file.text());
} catch {
setErrors([{ message: 'فایل یک JSON معتبر نیست' }]);
return;
}
let items: unknown[] | null = null;
if (Array.isArray(parsed)) items = parsed;
else if (parsed && typeof parsed === 'object' && Array.isArray((parsed as { items?: unknown[] }).items)) {
items = (parsed as { items: unknown[] }).items;
}
if (!items || items.length === 0) {
setErrors([{ message: 'فایل باید یک آرایه‌ی غیرخالی از رکوردها باشد' }]);
return;
}
setPendingItems(items);
};
const doImport = async () => {
if (!pendingItems) return;
setImporting(true);
try {
const res = await fetch(`/api/v1/admin/categories/${bundle}/import`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
body: JSON.stringify(pendingItems),
});
const json = await res.json().catch(() => ({}));
if (res.ok && json.success) {
toast.success(`${json.data?.imported ?? 0} رکورد با موفقیت وارد شد`);
setPendingItems(null);
onImported();
} else {
setErrors(json.errors?.length ? json.errors : [{ message: json.errors?.[0]?.message ?? 'خطا در ورود اطلاعات' }]);
setPendingItems(null);
}
} catch {
setErrors([{ message: 'خطا در ارتباط با سرور' }]);
setPendingItems(null);
} finally {
setImporting(false);
}
};
return (
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, padding: 'var(--card-pad)' }}>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={handleFile} />
<button onClick={() => fileRef.current?.click()} className="btn ghost sm">
<ArrowUpTrayIcon style={{ width: 15, height: 15 }} />
ورود JSON
</button>
<button onClick={handleExport} disabled={exporting} className="btn ghost sm">
<ArrowDownTrayIcon style={{ width: 15, height: 15 }} />
{exporting ? 'در حال دانلود...' : 'خروجی JSON'}
@@ -160,6 +223,38 @@ function TabActions({ label, onClick, exportUrl, exportFile }: {
<button onClick={onClick} className="btn primary sm">
<PlusIcon style={{ width: 15, height: 15 }} /> {label}
</button>
<ConfirmDialog
open={!!pendingItems}
title={`ورود ${entityLabel} از فایل`}
message={`این عملیات همه‌ی رکوردهای فعلی این بخش را حذف و با ${pendingItems?.length ?? 0} رکورد فایل جایگزین می‌کند. این کار بازگشت‌ناپذیر است. ادامه می‌دهید؟`}
confirmLabel="حذف و جایگزینی"
danger
loading={importing}
onConfirm={doImport}
onCancel={() => setPendingItems(null)}
/>
<Modal
open={!!errors}
title="فایل وارد نشد — خطاهای اعتبارسنجی"
size="md"
onClose={() => setErrors(null)}
footer={<button onClick={() => setErrors(null)} className="btn ghost sm">بستن</button>}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, color: 'var(--danger)' }}>
<ExclamationTriangleIcon style={{ width: 18, height: 18, flexShrink: 0 }} />
<span style={{ fontSize: 13 }}>به دلیل خطاهای زیر هیچ تغییری اعمال نشد. فایل را اصلاح و دوباره تلاش کنید.</span>
</div>
<div style={{ maxHeight: 360, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
{(errors ?? []).map((er, idx) => (
<div key={idx} style={{ fontSize: 12, padding: '8px 10px', borderRadius: 8, background: 'var(--surface-2)', display: 'flex', gap: 8 }}>
{er.field && <span className="chip" style={{ flexShrink: 0 }}>{er.field}</span>}
<span style={{ color: 'var(--text-2)' }}>{er.message}</span>
</div>
))}
</div>
</Modal>
</div>
);
}
@@ -228,7 +323,7 @@ function ProvincesTab() {
return (
<>
<TabActions label="افزودن استان" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/provinces?limit=9999" exportFile="state.json" />
<TabActions label="افزودن استان" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/categories/provinces/export" exportFile="state.json" bundle="provinces" entityLabel="استان‌ها" onImported={() => qc.invalidateQueries({ queryKey: ['admin-provinces'] })} />
<DataTable<Province> columns={columns} data={items} loading={isLoading} searchValue={search} onSearchChange={(v) => { setSearch(v); setPage(1); }} searchPlaceholder="جستجو در استان‌ها..." emptyMessage="هیچ استانی یافت نشد"
actions={(p) => (
<>
@@ -388,7 +483,7 @@ function CitiesTab() {
return (
<>
<TabActions label="افزودن شهر" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/cities?limit=9999" exportFile="city.json" />
<TabActions label="افزودن شهر" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/categories/cities/export" exportFile="city.json" bundle="cities" entityLabel="شهرها" onImported={() => qc.invalidateQueries({ queryKey: ['admin-cities'] })} />
<DataTable<City> columns={columns} data={items} loading={isLoading} searchValue={search} onSearchChange={(v) => { setSearch(v); setPage(1); }} searchPlaceholder="جستجو در شهرها..." emptyMessage="هیچ شهری یافت نشد"
actions={(c) => (
<>
@@ -548,7 +643,7 @@ function SpecialtiesTab() {
return (
<>
<TabActions label="افزودن تخصص" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/specialties?limit=9999" exportFile="specialties.json" />
<TabActions label="افزودن تخصص" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/categories/specialties/export" exportFile="specialties.json" bundle="specialties" entityLabel="تخصص‌ها" onImported={() => { qc.invalidateQueries({ queryKey: ['admin-specialties'] }); qc.invalidateQueries({ queryKey: ['admin-specialties-roots'] }); }} />
<DataTable<SpecialtyFull> columns={columns} data={items} loading={isLoading} searchValue={search} onSearchChange={(v) => { setSearch(v); setPage(1); }} searchPlaceholder="جستجو در تخصص‌ها..." emptyMessage="هیچ تخصصی یافت نشد"
actions={(s) => (
<>
@@ -669,7 +764,7 @@ function DoctorServicesTab() {
return (
<>
<TabActions label="افزودن خدمت" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/doctor-services?limit=9999" exportFile="doctor-services.json" />
<TabActions label="افزودن خدمت" onClick={() => { reset({ status: '1', weight: '0' }); setAddOpen(true); }} exportUrl="/api/v1/admin/categories/doctor_services/export" exportFile="doctor-services.json" bundle="doctor_services" entityLabel="خدمات پزشک" onImported={() => qc.invalidateQueries({ queryKey: ['admin-doctor-services'] })} />
<DataTable<DoctorService> columns={columns} data={items} loading={isLoading} searchValue={search} onSearchChange={(v) => { setSearch(v); setPage(1); }} searchPlaceholder="جستجو در خدمات..." emptyMessage="هیچ خدمتی یافت نشد"
actions={(s) => (
<>
@@ -795,7 +890,7 @@ function InsurancesTab() {
return (
<>
<TabActions label="افزودن بیمه" onClick={() => { reset({ status: '1', type: 'basic' }); setLogoUrl(null); setUploadTarget(null); setAddOpen(true); }} exportUrl="/api/v1/admin/insurances?limit=9999" exportFile="insurances.json" />
<TabActions label="افزودن بیمه" onClick={() => { reset({ status: '1', type: 'basic' }); setLogoUrl(null); setUploadTarget(null); setAddOpen(true); }} exportUrl="/api/v1/admin/categories/insurances/export" exportFile="insurances.json" bundle="insurances" entityLabel="بیمه‌ها" onImported={() => qc.invalidateQueries({ queryKey: ['admin-insurances'] })} />
<DataTable<Insurance> columns={columns} data={items} loading={isLoading} searchValue={search} onSearchChange={(v) => { setSearch(v); setPage(1); }} searchPlaceholder="جستجو در بیمه‌ها..." emptyMessage="هیچ بیمه‌ای یافت نشد"
actions={(i) => (
<>
@@ -909,7 +1004,7 @@ function TagsTab() {
return (
<>
<TabActions label="افزودن تگ" onClick={() => { reset({ status: '1' }); setAddOpen(true); }} exportUrl="/api/v1/admin/tags?limit=9999" exportFile="tags.json" />
<TabActions label="افزودن تگ" onClick={() => { reset({ status: '1' }); setAddOpen(true); }} exportUrl="/api/v1/admin/categories/tags/export" exportFile="tags.json" bundle="tags" entityLabel="تگ‌ها" onImported={() => qc.invalidateQueries({ queryKey: ['admin-tags'] })} />
<DataTable<Tag> columns={columns} data={items} loading={isLoading} searchValue={search} onSearchChange={(v) => { setSearch(v); setPage(1); }} searchPlaceholder="جستجو در تگ‌ها..." emptyMessage="هیچ تگی یافت نشد"
actions={(t) => (
<>