- Implemented BlogBodySanitizer to clean HTML content before saving articles, ensuring security against XSS attacks. - Added tests for BlogBodySanitizer to verify that unsafe tags and attributes are stripped from the content. - Introduced ApiLeastPrivilegeTest to ensure that unauthorized users cannot access sensitive API routes, maintaining strict access control.
233 lines
9.5 KiB
TypeScript
233 lines
9.5 KiB
TypeScript
import React, { useState } from 'react';
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { TrashIcon, PencilIcon, MagnifyingGlassIcon, CurrencyDollarIcon } from '@heroicons/react/24/outline';
|
|
import { Link } from 'react-router';
|
|
import { toast } from 'sonner';
|
|
import { api } from '../lib/api';
|
|
import { useUrlState, pageOf } from '../hooks/useUrlState';
|
|
import type { ApiResponse, PaginatedResponse } from '../lib/api';
|
|
import type { Secretary, SecretaryPermissions } from '../types';
|
|
import { formatDate, formatNumber, maskMobile } from '../lib/utils';
|
|
import DataTable, { Column } from '../components/ui/DataTable';
|
|
import { ActiveBadge } from '../components/ui/StatusBadge';
|
|
import Pagination from '../components/ui/Pagination';
|
|
import ConfirmDialog from '../components/ui/ConfirmDialog';
|
|
import Modal from '../components/ui/Modal';
|
|
import Switch from '../components/ui/Switch';
|
|
import { usePermissionCatalog, alignPermissions } from '../hooks/usePermissionCatalog';
|
|
import type { CatalogResource } from '../hooks/usePermissionCatalog';
|
|
|
|
const ACTION_COLUMNS = ['view', 'create', 'update', 'delete', 'cancel', 'update_status'];
|
|
const ACTION_HEADERS = ['مشاهده', 'ایجاد', 'ویرایش', 'حذف', 'لغو', 'تغییر وضعیت'];
|
|
|
|
function PermissionsMatrix({
|
|
permissions,
|
|
onChange,
|
|
resources,
|
|
}: {
|
|
permissions: SecretaryPermissions;
|
|
onChange: (p: SecretaryPermissions) => void;
|
|
resources: CatalogResource[];
|
|
}) {
|
|
const toggle = (section: string, action: string) => {
|
|
onChange({
|
|
...permissions,
|
|
[section]: { ...permissions[section], [action]: !permissions[section]?.[action] },
|
|
});
|
|
};
|
|
|
|
const allActions = ACTION_COLUMNS;
|
|
const actionHeaders = ACTION_HEADERS;
|
|
|
|
return (
|
|
<div style={{ overflowX: 'auto' }}>
|
|
<table className="t">
|
|
<thead>
|
|
<tr>
|
|
<th>بخش</th>
|
|
{actionHeaders.map((h) => (
|
|
<th key={h} style={{ textAlign: 'center', fontSize: 12 }}>{h}</th>
|
|
))}
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{resources.map((resource) => {
|
|
const available = new Set(resource.actions.map((a) => a.key));
|
|
return (
|
|
<tr key={resource.key}>
|
|
<td><b>{resource.label}</b></td>
|
|
{allActions.map((action) => {
|
|
if (!available.has(action)) {
|
|
return <td key={action} style={{ textAlign: 'center', color: 'var(--border)' }}>—</td>;
|
|
}
|
|
return (
|
|
<td key={action}>
|
|
<div style={{ display: 'flex', justifyContent: 'center' }}>
|
|
<Switch
|
|
checked={permissions[resource.key]?.[action] ?? false}
|
|
onChange={() => toggle(resource.key, action)}
|
|
ariaLabel={`${resource.label} — ${ACTION_HEADERS[ACTION_COLUMNS.indexOf(action)]}`}
|
|
/>
|
|
</div>
|
|
</td>
|
|
);
|
|
})}
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function SecretariesPage() {
|
|
const qc = useQueryClient();
|
|
// وضعیت لیست در URL میماند تا «بازگشت» از صفحهٔ جزئیات، همین جستجو و صفحه را برگرداند.
|
|
const [urlState, setUrlState] = useUrlState({ page: '1', search: '' });
|
|
const page = pageOf(urlState.page);
|
|
const search = urlState.search;
|
|
const setPage = (p: number) => setUrlState({ page: String(p) });
|
|
const setSearch = (v: string) => setUrlState({ search: v, page: '1' });
|
|
const [editTarget, setEditTarget] = useState<Secretary | null>(null);
|
|
const [editPerms, setEditPerms] = useState<SecretaryPermissions>({});
|
|
const catalog = usePermissionCatalog();
|
|
const [deleteTarget, setDeleteTarget] = useState<Secretary | null>(null);
|
|
const limit = 15;
|
|
|
|
const { data, isLoading } = useQuery({
|
|
queryKey: ['secretaries', page, search],
|
|
queryFn: () => {
|
|
const params = new URLSearchParams({ page: String(page), limit: String(limit) });
|
|
if (search) params.set('search', search);
|
|
return api.get<PaginatedResponse<Secretary>>(`/api/v1/admin/secretaries?${params}`);
|
|
},
|
|
});
|
|
|
|
const updatePermsMutation = useMutation({
|
|
mutationFn: ({ uuid, permissions }: { uuid: string; permissions: SecretaryPermissions }) =>
|
|
api.patch<ApiResponse<null>>(`/api/v1/secretary/${uuid}`, { permissions }),
|
|
onSuccess: () => {
|
|
toast.success('دسترسیها بروزرسانی شد');
|
|
setEditTarget(null);
|
|
qc.invalidateQueries({ queryKey: ['secretaries'] });
|
|
},
|
|
onError: (err: Error) => toast.error(err.message),
|
|
});
|
|
|
|
const deleteMutation = useMutation({
|
|
mutationFn: (s: Secretary) => api.delete<ApiResponse<null>>(`/api/v1/secretary/${s.uuid}`),
|
|
onSuccess: () => {
|
|
toast.success('منشی حذف شد');
|
|
setDeleteTarget(null);
|
|
qc.invalidateQueries({ queryKey: ['secretaries'] });
|
|
},
|
|
onError: (err: Error) => toast.error(err.message),
|
|
});
|
|
|
|
const openEdit = (s: Secretary) => {
|
|
setEditTarget(s);
|
|
// شکل را کاتالوگ میدهد؛ منبعی که در JSONِ ذخیرهشده نیست خاموش نمایش داده میشود.
|
|
setEditPerms(alignPermissions(s.permissions, catalog.resources));
|
|
};
|
|
|
|
const columns: Column<Secretary>[] = [
|
|
{ key: 'user_name', header: 'نام', render: (s) => <b>{s.user_name}</b> },
|
|
{ key: 'mobile_number', header: 'موبایل', render: (s) => <span dir="ltr">{maskMobile(s.mobile_number)}</span> },
|
|
{ key: 'doctor_name', header: 'پزشک', render: (s) => s.doctor_name },
|
|
{ key: 'is_active', header: 'وضعیت', render: (s) => <ActiveBadge active={s.is_active} /> },
|
|
{ key: 'online_share_percent', header: 'سهم آنلاین', render: (s) => (
|
|
s.online_share_enabled
|
|
? <span style={{ fontSize: 12.5, color: 'var(--primary)', fontWeight: 700 }}>{formatNumber(s.online_share_percent ?? 0)}٪</span>
|
|
: <span className="muted">—</span>
|
|
) },
|
|
{ key: 'created_at', header: 'تاریخ ثبت', render: (s) => formatDate(s.created_at) },
|
|
];
|
|
|
|
const items = data?.data ?? [];
|
|
const total = data?.meta?.totalRecords ?? 0;
|
|
|
|
return (
|
|
<div className="fade-in">
|
|
<div className="card-title-row" style={{ marginBottom: 'var(--gap)' }}>
|
|
<div>
|
|
<h1 className="section-title">منشیها</h1>
|
|
<div className="muted">{total} منشی ثبتشده</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="card">
|
|
<div className="card-pad" style={{ paddingBottom: 0 }}>
|
|
<div className="toolbar">
|
|
<div className="field" style={{ minWidth: 240 }}>
|
|
<MagnifyingGlassIcon style={{ width: 17, height: 17 }} />
|
|
<input
|
|
value={search}
|
|
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
|
|
placeholder="جستجو بر اساس نام یا پزشک..."
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<DataTable<Secretary>
|
|
columns={columns}
|
|
data={items}
|
|
loading={isLoading}
|
|
emptyMessage="هیچ منشیای یافت نشد"
|
|
actions={(sec) => (
|
|
<>
|
|
<Link to={`/admin/secretaries/${sec.uuid}`} className="mini-btn" title="جزئیات و سهم درآمد">
|
|
<CurrencyDollarIcon style={{ width: 15, height: 15 }} />
|
|
</Link>
|
|
<button onClick={() => openEdit(sec)} className="mini-btn" title="ویرایش دسترسیها">
|
|
<PencilIcon style={{ width: 15, height: 15 }} />
|
|
</button>
|
|
<button onClick={() => setDeleteTarget(sec)} className="mini-btn danger" title="حذف">
|
|
<TrashIcon style={{ width: 15, height: 15 }} />
|
|
</button>
|
|
</>
|
|
)}
|
|
/>
|
|
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
|
|
</div>
|
|
|
|
<Modal
|
|
open={!!editTarget}
|
|
title={`دسترسیهای ${editTarget?.user_name}`}
|
|
size="lg"
|
|
onClose={() => setEditTarget(null)}
|
|
footer={
|
|
<>
|
|
<button onClick={() => setEditTarget(null)} className="btn ghost sm">لغو</button>
|
|
<button
|
|
onClick={() => editTarget && updatePermsMutation.mutate({ uuid: editTarget.uuid, permissions: editPerms })}
|
|
disabled={updatePermsMutation.isPending || catalog.isLoading}
|
|
className="btn primary sm">
|
|
{updatePermsMutation.isPending ? 'در حال ذخیره...' : 'ذخیره دسترسیها'}
|
|
</button>
|
|
</>
|
|
}
|
|
>
|
|
{catalog.isLoading ? (
|
|
<p className="muted">در حال بارگذاری فهرست دسترسیها...</p>
|
|
) : catalog.isError ? (
|
|
<p className="muted">فهرست دسترسیها خوانده نشد. صفحه را دوباره باز کنید.</p>
|
|
) : (
|
|
<PermissionsMatrix permissions={editPerms} onChange={setEditPerms} resources={catalog.resources} />
|
|
)}
|
|
</Modal>
|
|
|
|
<ConfirmDialog
|
|
open={!!deleteTarget}
|
|
title="حذف منشی"
|
|
message={`آیا از حذف منشی "${deleteTarget?.user_name}" اطمینان دارید؟`}
|
|
confirmLabel="حذف"
|
|
danger
|
|
loading={deleteMutation.isPending}
|
|
onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget)}
|
|
onCancel={() => setDeleteTarget(null)}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|