Files
clinicpro/assets/admin/pages/CategoriesPage.tsx
T
hamed 147a2a894e feat: implement admin API for user and representation management
- Updated UsersPage to fetch users from the new admin endpoint.
- Enhanced user data structure to include 'name' and modified rendering logic.
- Added RepresentationDetailPage for detailed representation management.
- Created AdminApiController to handle user and representation CRUD operations.
- Implemented pagination and search functionality for users and representations.
- Updated user and representation data models to reflect new API structure.
2026-06-09 23:41:44 +03:30

252 lines
9.9 KiB
TypeScript

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { TrashIcon, PlusIcon, PencilIcon } from '@heroicons/react/24/outline';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Category, CategoryBundle } from '../types';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { Column } from '../components/ui/DataTable';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import Modal from '../components/ui/Modal';
const TABS: { key: CategoryBundle; label: string }[] = [
{ key: 'state', label: 'استان‌ها' },
{ key: 'city', label: 'شهرها' },
{ key: 'specially_doctor', label: 'تخصص‌ها' },
{ key: 'doctor_services', label: 'خدمات پزشک' },
{ key: 'insurance_type', label: 'نوع بیمه' },
{ key: 'supplementary_insurance', label: 'بیمه تکمیلی' },
{ key: 'tag', label: 'تگ‌های بلاگ' },
];
const schema = z.object({
label: z.string().min(1, 'نام الزامی است'),
parent_id: z.string().optional(),
});
type FormData = z.infer<typeof schema>;
export default function CategoriesPage() {
const qc = useQueryClient();
const [activeTab, setActiveTab] = useState<CategoryBundle>('state');
const [search, setSearch] = useState('');
const [addOpen, setAddOpen] = useState(false);
const [editTarget, setEditTarget] = useState<Category | null>(null);
const [deleteTarget, setDeleteTarget] = useState<Category | null>(null);
const { data, isLoading } = useQuery({
queryKey: ['categories', activeTab],
queryFn: () =>
api.get<ApiResponse<{ data: Category[] }>>(`/api/v1/categorys/${activeTab}`),
});
const { register, handleSubmit, reset, setValue, formState: { errors, isSubmitting } } = useForm<FormData>({
resolver: zodResolver(schema),
});
const createMutation = useMutation({
mutationFn: (d: FormData) =>
api.post<ApiResponse<Category>>('/api/v1/category', {
label: d.label,
bundle: activeTab,
...(d.parent_id ? { parent_id: parseInt(d.parent_id) } : {}),
}),
onSuccess: () => {
toast.success('دسته‌بندی اضافه شد');
setAddOpen(false);
reset();
qc.invalidateQueries({ queryKey: ['categories', activeTab] });
},
onError: (err: Error) => toast.error(err.message),
});
const updateMutation = useMutation({
mutationFn: ({ id, d }: { id: number; d: FormData }) =>
api.patch<ApiResponse<Category>>(`/api/v1/category/${id}`, { label: d.label }),
onSuccess: () => {
toast.success('دسته‌بندی بروزرسانی شد');
setEditTarget(null);
reset();
qc.invalidateQueries({ queryKey: ['categories', activeTab] });
},
onError: (err: Error) => toast.error(err.message),
});
const deleteMutation = useMutation({
mutationFn: (c: Category) => api.delete<ApiResponse<null>>(`/api/v1/category/${c.id}`),
onSuccess: () => {
toast.success('دسته‌بندی حذف شد');
setDeleteTarget(null);
qc.invalidateQueries({ queryKey: ['categories', activeTab] });
},
onError: (err: Error) => toast.error(err.message),
});
const openEdit = (c: Category) => {
setEditTarget(c);
setValue('label', c.label);
};
const allItems = data?.data?.data ?? [];
const filtered = search
? allItems.filter((c) => c.label.includes(search))
: allItems;
const columns: Column<Category>[] = [
{ key: 'label', header: 'نام', render: (c) => <span className="font-medium">{c.label}</span> },
{
key: 'bundle',
header: 'نوع',
render: (c) => (
<span className="text-xs bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full">{c.bundle}</span>
),
},
{
key: 'status',
header: 'وضعیت',
render: (c) => (
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
c.status === 1 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
}`}>
{c.status === 1 ? 'فعال' : 'غیرفعال'}
</span>
),
},
];
const handleTabChange = (tab: CategoryBundle) => {
setActiveTab(tab);
setSearch('');
};
return (
<div>
<PageHeader
title="دسته‌بندی‌ها"
breadcrumbs={[{ label: 'داشبورد', to: '/admin/dashboard' }, { label: 'دسته‌بندی‌ها' }]}
action={
<button onClick={() => setAddOpen(true)}
className="flex items-center gap-2 px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 transition-colors">
<PlusIcon className="w-4 h-4" />
افزودن
</button>
}
/>
<div className="bg-white rounded-2xl shadow-sm border border-gray-100">
<div className="flex flex-wrap border-b border-gray-200 px-6 pt-4 gap-1">
{TABS.map((t) => (
<button key={t.key} onClick={() => handleTabChange(t.key)}
className={`pb-3 px-4 text-sm font-medium border-b-2 transition-colors -mb-px ${
activeTab === t.key
? 'border-primary-600 text-primary-600'
: 'border-transparent text-gray-500 hover:text-gray-700'
}`}>
{t.label}
</button>
))}
</div>
<div className="p-6">
<DataTable<Category>
columns={columns}
data={filtered}
loading={isLoading}
searchValue={search}
onSearchChange={setSearch}
searchPlaceholder="جستجو..."
emptyMessage="هیچ موردی یافت نشد"
actions={(cat) => (
<>
<button onClick={() => openEdit(cat)}
className="p-1.5 text-gray-400 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors" title="ویرایش">
<PencilIcon className="w-4 h-4" />
</button>
<button onClick={() => setDeleteTarget(cat)}
className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors" title="حذف">
<TrashIcon className="w-4 h-4" />
</button>
</>
)}
/>
</div>
</div>
{/* Add Modal */}
<Modal open={addOpen} title={`افزودن — ${TABS.find((t) => t.key === activeTab)?.label}`}
onClose={() => { setAddOpen(false); reset(); }}
footer={
<>
<button onClick={() => { setAddOpen(false); reset(); }}
className="px-4 py-2 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
لغو
</button>
<button form="cat-form" type="submit" disabled={isSubmitting}
className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors">
ذخیره
</button>
</>
}
>
<form id="cat-form" onSubmit={handleSubmit((d) => createMutation.mutate(d))} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">نام</label>
<input {...register('label')}
className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500" />
{errors.label && <p className="text-red-500 text-xs mt-1">{errors.label.message}</p>}
</div>
{activeTab === 'city' && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">شناسه استان</label>
<input {...register('parent_id')} dir="ltr" placeholder="ID عددی استان"
className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500" />
</div>
)}
</form>
</Modal>
{/* Edit Modal */}
<Modal open={!!editTarget} title="ویرایش دسته‌بندی"
onClose={() => { setEditTarget(null); reset(); }}
footer={
<>
<button onClick={() => { setEditTarget(null); reset(); }}
className="px-4 py-2 border border-gray-300 text-sm text-gray-700 rounded-[10px] hover:bg-gray-50 transition-colors">
لغو
</button>
<button form="edit-cat-form" type="submit" disabled={isSubmitting}
className="px-4 py-2 bg-primary-600 text-white text-sm rounded-[10px] hover:bg-primary-700 disabled:opacity-50 transition-colors">
ذخیره
</button>
</>
}
>
<form id="edit-cat-form"
onSubmit={handleSubmit((d) => editTarget && updateMutation.mutate({ id: editTarget.id, d }))}
className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">نام</label>
<input {...register('label')}
className="w-full h-11 border border-gray-300 rounded-[10px] px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500" />
{errors.label && <p className="text-red-500 text-xs mt-1">{errors.label.message}</p>}
</div>
</form>
</Modal>
<ConfirmDialog
open={!!deleteTarget}
title="حذف دسته‌بندی"
message={`آیا از حذف "${deleteTarget?.label}" اطمینان دارید؟`}
confirmLabel="حذف"
danger
loading={deleteMutation.isPending}
onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
onCancel={() => setDeleteTarget(null)}
/>
</div>
);
}