feat: add Staff, Subscription, ClinicServices, SmsWallet pages (TASK-10,11,13,14)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-06-14 22:23:30 +03:30
co-authored by Claude Sonnet 4.6
parent 7ea3523830
commit ed18c260ca
7 changed files with 1125 additions and 0 deletions
+10
View File
@@ -33,6 +33,10 @@ import MyPatientsPage from './pages/MyPatientsPage';
import MyFinancialPage from './pages/MyFinancialPage';
import ClinicFormPage from './pages/ClinicFormPage';
import PreRegistrationsPage from './pages/PreRegistrationsPage';
import StaffPage from './pages/StaffPage';
import SubscriptionPage from './pages/SubscriptionPage';
import ClinicServicesPage from './pages/ClinicServicesPage';
import SmsWalletPage from './pages/SmsWalletPage';
import PwaInstallBanner from './components/ui/PwaInstallBanner';
// ── Guards ──────────────────────────────────────────────────────────────────
@@ -145,6 +149,12 @@ export default function App() {
<Route path="my-patients" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']}><MyPatientsPage /></RoleRoute>} />
<Route path="my-financial" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']}><MyFinancialPage /></RoleRoute>} />
{/* فاز ۲ — دکتر / کلینیک */}
<Route path="staff" element={<RoleRoute roles={['doctor', 'clinic']}><StaffPage /></RoleRoute>} />
<Route path="subscription" element={<RoleRoute roles={['doctor', 'clinic']}><SubscriptionPage /></RoleRoute>} />
<Route path="clinic-services" element={<RoleRoute roles={['doctor', 'clinic']}><ClinicServicesPage /></RoleRoute>} />
<Route path="sms-wallet" element={<RoleRoute roles={['doctor', 'clinic']}><SmsWalletPage /></RoleRoute>} />
{/* فقط ادمین */}
<Route path="clinics/new" element={<RoleRoute roles={['admin']}><ClinicFormPage /></RoleRoute>} />
<Route path="pre-registrations" element={<RoleRoute roles={['admin']}><PreRegistrationsPage /></RoleRoute>} />
@@ -18,6 +18,9 @@ import {
UserCircleIcon,
UserGroupIcon,
UsersIcon,
UserPlusIcon,
WrenchScrewdriverIcon,
FolderOpenIcon,
} from "@heroicons/react/24/outline";
import { NavLink, useNavigate } from "react-router-dom";
import { useAuthStore } from "../../stores/authStore";
@@ -82,6 +85,16 @@ function buildSections(primaryRole: string | null, dbUuid: string | null): Secti
label: 'مدیریت',
items: [
{ to: '/admin/appointments', icon: CalendarDaysIcon, label: 'نوبت‌ها' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران' },
{ to: '/admin/staff', icon: UserPlusIcon, label: 'پرسنل' },
{ to: '/admin/clinic-services', icon: WrenchScrewdriverIcon, label: 'سرویس‌ها' },
{ to: '/admin/sms-wallet', icon: DevicePhoneMobileIcon, label: 'کیف پول پیامک' },
],
},
{
label: 'اشتراک',
items: [
{ to: '/admin/subscription', icon: CreditCardIcon, label: 'پنل اشتراکی' },
],
},
];
@@ -105,6 +118,16 @@ function buildSections(primaryRole: string | null, dbUuid: string | null): Secti
label: 'مدیریت',
items: [
{ to: '/admin/appointments', icon: CalendarDaysIcon, label: 'نوبت‌های من' },
{ to: '/admin/my-patients', icon: FolderOpenIcon, label: 'پرونده بیماران' },
{ to: '/admin/staff', icon: UserPlusIcon, label: 'پرسنل' },
{ to: '/admin/clinic-services', icon: WrenchScrewdriverIcon, label: 'سرویس‌ها' },
{ to: '/admin/sms-wallet', icon: DevicePhoneMobileIcon, label: 'کیف پول پیامک' },
],
},
{
label: 'اشتراک',
items: [
{ to: '/admin/subscription', icon: CreditCardIcon, label: 'پنل اشتراکی' },
],
},
];
+312
View File
@@ -0,0 +1,312 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, PencilIcon, TrashIcon } 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 { ServiceSection, ServiceItem, ClinicStaff } from '../types';
import { formatRial } from '../lib/utils';
import Modal from '../components/ui/Modal';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import PageHeader from '../components/ui/PageHeader';
import SearchableSelect from '../components/ui/SearchableSelect';
const sectionSchema = z.object({ name: z.string().min(1, 'نام بخش الزامی است') });
const itemSchema = z.object({
name: z.string().min(1, 'نام سرویس الزامی است'),
price_rials: z.coerce.number().min(0, 'مبلغ نمی‌تواند منفی باشد'),
staff_uuid: z.string().optional(),
});
type SectionForm = z.infer<typeof sectionSchema>;
type ItemForm = z.infer<typeof itemSchema>;
const EMPTY_SECTIONS: ServiceSection[] = [];
const EMPTY_ITEMS: ServiceItem[] = [];
export default function ClinicServicesPage() {
const qc = useQueryClient();
const [selectedSection, setSelectedSection] = useState<ServiceSection | null>(null);
const [sectionModal, setSectionModal] = useState<'create' | ServiceSection | null>(null);
const [deleteSection, setDeleteSection] = useState<ServiceSection | null>(null);
const [itemModal, setItemModal] = useState<'create' | ServiceItem | null>(null);
const [deleteItem, setDeleteItem] = useState<ServiceItem | null>(null);
const { data: sectionsData, isLoading: sectionsLoading } = useQuery<ApiResponse<ServiceSection[]>>({
queryKey: ['service-sections'],
queryFn: () => api.get('/api/v1/service-sections'),
});
const { data: itemsData, isLoading: itemsLoading } = useQuery<ApiResponse<ServiceItem[]>>({
queryKey: ['service-items', selectedSection?.uuid],
queryFn: () => api.get(`/api/v1/service-items/${selectedSection!.uuid}`),
enabled: !!selectedSection,
});
const { data: staffData } = useQuery<ApiResponse<ClinicStaff[]>>({
queryKey: ['staff'],
queryFn: () => api.get('/api/v1/staff'),
});
const sections = sectionsData?.data ?? EMPTY_SECTIONS;
const items = itemsData?.data ?? EMPTY_ITEMS;
const staffOptions = (staffData?.data ?? []).filter((s) => s.active).map((s) => ({
value: s.uuid,
label: s.full_name,
}));
const sectionForm = useForm<SectionForm>({ resolver: zodResolver(sectionSchema) });
const itemForm = useForm<ItemForm>({ resolver: zodResolver(itemSchema) });
const createSection = useMutation({
mutationFn: (body: SectionForm) => api.post('/api/v1/service-section', body),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-sections'] }); setSectionModal(null); sectionForm.reset(); toast.success('بخش ایجاد شد'); },
onError: (e: any) => toast.error(e.message),
});
const editSection = useMutation({
mutationFn: ({ uuid, body }: { uuid: string; body: SectionForm }) =>
api.patch(`/api/v1/service-section/${uuid}`, body),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-sections'] }); setSectionModal(null); toast.success('بخش ویرایش شد'); },
onError: (e: any) => toast.error(e.message),
});
const delSection = useMutation({
mutationFn: (uuid: string) => api.delete(`/api/v1/service-section/${uuid}`),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['service-sections'] });
if (selectedSection?.uuid === deleteSection?.uuid) setSelectedSection(null);
setDeleteSection(null);
toast.success('بخش حذف شد');
},
onError: (e: any) => { toast.error(e.message); setDeleteSection(null); },
});
const createItem = useMutation({
mutationFn: (body: ItemForm & { section_uuid: string }) => api.post('/api/v1/service-item', body),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setItemModal(null); itemForm.reset(); toast.success('سرویس ایجاد شد'); },
onError: (e: any) => toast.error(e.message),
});
const editItem = useMutation({
mutationFn: ({ uuid, body }: { uuid: string; body: ItemForm }) =>
api.patch(`/api/v1/service-item/${uuid}`, body),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setItemModal(null); toast.success('سرویس ویرایش شد'); },
onError: (e: any) => toast.error(e.message),
});
const delItem = useMutation({
mutationFn: (uuid: string) => api.delete(`/api/v1/service-item/${uuid}`),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setDeleteItem(null); toast.success('سرویس حذف شد'); },
onError: (e: any) => {
if (e.code === 'ERR_SERVICE_ITEM_IN_USE') {
toast.error('این سرویس در پرونده بیمار استفاده شده و قابل حذف نیست');
} else {
toast.error(e.message);
}
setDeleteItem(null);
},
});
const openEditSection = (s: ServiceSection) => {
sectionForm.reset({ name: s.name });
setSectionModal(s);
};
const openEditItem = (item: ServiceItem) => {
itemForm.reset({
name: item.name,
price_rials: item.price_rials,
staff_uuid: item.staff?.uuid ?? '',
});
setItemModal(item);
};
return (
<>
<PageHeader title="سرویس‌های کلینیک" description="مدیریت بخش‌ها و سرویس‌های کلینیک" />
<div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 16, alignItems: 'start' }}>
{/* ستون بخش‌ها */}
<div className="card">
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<b style={{ fontSize: 14 }}>بخشها</b>
<button className="btn primary sm" onClick={() => { sectionForm.reset(); setSectionModal('create'); }}>
<PlusIcon style={{ width: 14 }} />
</button>
</div>
{sectionsLoading ? (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
) : sections.length === 0 ? (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>بخشی ثبت نشده است</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{sections.map((s) => (
<div
key={s.uuid}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '8px 10px', borderRadius: 6, cursor: 'pointer',
background: selectedSection?.uuid === s.uuid ? 'var(--primary-subtle)' : 'transparent',
border: selectedSection?.uuid === s.uuid ? '1px solid var(--primary)' : '1px solid transparent',
}}
onClick={() => setSelectedSection(s)}
>
<span style={{ fontSize: 13 }}>{s.name}</span>
<div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
<button className="btn sm" onClick={() => openEditSection(s)}><PencilIcon style={{ width: 13 }} /></button>
<button className="btn sm" onClick={() => setDeleteSection(s)}><TrashIcon style={{ width: 13 }} /></button>
</div>
</div>
))}
</div>
)}
</div>
{/* ستون آیتم‌ها */}
<div className="card">
{!selectedSection ? (
<div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--text-3)' }}>
یک بخش را از سمت راست انتخاب کنید
</div>
) : (
<>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
<b style={{ fontSize: 14 }}>سرویسهای «{selectedSection.name}»</b>
<button
className="btn primary sm"
onClick={() => { itemForm.reset({ price_rials: 0, staff_uuid: '' }); setItemModal('create'); }}
>
<PlusIcon style={{ width: 14 }} /> سرویس جدید
</button>
</div>
{itemsLoading ? (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
) : items.length === 0 ? (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>سرویسی ثبت نشده است</div>
) : (
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ borderBottom: '1px solid var(--border)' }}>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>نام سرویس</th>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>قیمت</th>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>پرسنل مسئول</th>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>عملیات</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.uuid} style={{ borderBottom: '1px solid var(--border)' }}>
<td style={{ padding: '8px 4px' }}>{item.name}</td>
<td style={{ padding: '8px 4px' }}>{formatRial(item.price_rials)}</td>
<td style={{ padding: '8px 4px' }}>{item.staff?.full_name ?? '—'}</td>
<td style={{ padding: '8px 4px' }}>
<div style={{ display: 'flex', gap: 4 }}>
<button className="btn sm" onClick={() => openEditItem(item)}><PencilIcon style={{ width: 13 }} /></button>
<button className="btn sm" onClick={() => setDeleteItem(item)}><TrashIcon style={{ width: 13 }} /></button>
</div>
</td>
</tr>
))}
</tbody>
</table>
)}
</>
)}
</div>
</div>
{/* Modal بخش */}
<Modal
open={sectionModal !== null}
onClose={() => setSectionModal(null)}
title={sectionModal === 'create' ? 'بخش جدید' : 'ویرایش بخش'}
>
<form onSubmit={sectionForm.handleSubmit((d) => {
if (sectionModal === 'create') createSection.mutate(d);
else if (sectionModal !== null && typeof sectionModal === 'object') editSection.mutate({ uuid: sectionModal.uuid, body: d });
})}>
<div className="field">
<label>نام بخش *</label>
<input {...sectionForm.register('name')} placeholder="مثلاً: تزریقات" />
{sectionForm.formState.errors.name && (
<span className="field-error">{sectionForm.formState.errors.name.message}</span>
)}
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button type="submit" className="btn primary" disabled={createSection.isPending || editSection.isPending}>ذخیره</button>
<button type="button" className="btn" onClick={() => setSectionModal(null)}>انصراف</button>
</div>
</form>
</Modal>
{/* Modal آیتم */}
<Modal
open={itemModal !== null}
onClose={() => setItemModal(null)}
title={itemModal === 'create' ? 'سرویس جدید' : 'ویرایش سرویس'}
>
<form onSubmit={itemForm.handleSubmit((d) => {
if (itemModal === 'create' && selectedSection) {
createItem.mutate({ ...d, section_uuid: selectedSection.uuid });
} else if (itemModal !== null && typeof itemModal === 'object') {
editItem.mutate({ uuid: itemModal.uuid, body: d });
}
})}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div className="field">
<label>نام سرویس *</label>
<input {...itemForm.register('name')} placeholder="مثلاً: سرم ۵۰۰cc" />
{itemForm.formState.errors.name && (
<span className="field-error">{itemForm.formState.errors.name.message}</span>
)}
</div>
<div className="field">
<label>قیمت (ریال) *</label>
<input {...itemForm.register('price_rials')} type="number" min={0} placeholder="85000" dir="ltr" />
</div>
<div className="field">
<label>پرسنل مسئول</label>
<SearchableSelect
options={staffOptions}
value={itemForm.watch('staff_uuid') ?? ''}
onChange={(v) => itemForm.setValue('staff_uuid', v != null ? String(v) : undefined)}
placeholder="انتخاب پرسنل (اختیاری)"
isClearable
/>
</div>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button type="submit" className="btn primary" disabled={createItem.isPending || editItem.isPending}>ذخیره</button>
<button type="button" className="btn" onClick={() => setItemModal(null)}>انصراف</button>
</div>
</form>
</Modal>
{/* Confirm حذف بخش */}
<ConfirmDialog
open={!!deleteSection}
title="حذف بخش"
message={`آیا مطمئن هستید که می‌خواهید بخش «${deleteSection?.name}» را حذف کنید؟`}
confirmLabel="حذف"
onConfirm={() => deleteSection && delSection.mutate(deleteSection.uuid)}
onCancel={() => setDeleteSection(null)}
loading={delSection.isPending}
/>
{/* Confirm حذف آیتم */}
<ConfirmDialog
open={!!deleteItem}
title="حذف سرویس"
message={`آیا مطمئن هستید که می‌خواهید سرویس «${deleteItem?.name}» را حذف کنید؟`}
confirmLabel="حذف"
onConfirm={() => deleteItem && delItem.mutate(deleteItem.uuid)}
onCancel={() => setDeleteItem(null)}
loading={delItem.isPending}
/>
</>
);
}
+231
View File
@@ -0,0 +1,231 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
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, PaginatedResponse } from '../lib/api';
import type { SmsWalletBalance, SmsWalletLog, SmsSettings } from '../types';
import { formatRial, formatNumber, formatDateTime } from '../lib/utils';
import Modal from '../components/ui/Modal';
import Pagination from '../components/ui/Pagination';
import PageHeader from '../components/ui/PageHeader';
const chargeSchema = z.object({
amount_rials: z.coerce.number().min(10000, 'حداقل مبلغ ۱۰,۰۰۰ ریال است'),
});
type ChargeForm = z.infer<typeof chargeSchema>;
const EMPTY_LOGS: SmsWalletLog[] = [];
export default function SmsWalletPage() {
const qc = useQueryClient();
const [chargeOpen, setChargeOpen] = useState(false);
const [gateway, setGateway] = useState<'mellat' | 'sep'>('mellat');
const [logPage, setLogPage] = useState(1);
const { data: balanceData, isLoading: balanceLoading } = useQuery<ApiResponse<SmsWalletBalance>>({
queryKey: ['sms-wallet-balance'],
queryFn: () => api.get('/api/v1/sms/wallet/balance'),
});
const { data: logsData, isLoading: logsLoading } = useQuery<PaginatedResponse<SmsWalletLog>>({
queryKey: ['sms-wallet-logs', logPage],
queryFn: () => api.get(`/api/v1/sms/wallet/logs?page=${logPage}&limit=20`),
});
const { data: settingsData } = useQuery<ApiResponse<SmsSettings>>({
queryKey: ['sms-settings'],
queryFn: () => api.get('/api/v1/sms/settings'),
});
const balance = balanceData?.data;
const logs = logsData?.data ?? EMPTY_LOGS;
const total = logsData?.meta?.totalRecords ?? 0;
const settings = settingsData?.data;
const chargeForm = useForm<ChargeForm>({ resolver: zodResolver(chargeSchema) });
const chargeMutation = useMutation({
mutationFn: ({ amount_rials }: ChargeForm) =>
api.post<{ data: { payment_url: string } }>('/api/v1/sms/wallet/charge', { gateway, amount_rials }),
onSuccess: (res: any) => {
const url = res?.data?.payment_url;
if (url) window.location.href = url;
else toast.error('خطا در دریافت لینک پرداخت');
},
onError: (e: any) => toast.error(e.message),
});
const [localSettings, setLocalSettings] = useState<SmsSettings | null>(null);
const currentSettings = localSettings ?? settings;
const saveMutation = useMutation({
mutationFn: (body: SmsSettings) => api.patch('/api/v1/sms/settings', body),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['sms-settings'] }); toast.success('تنظیمات ذخیره شد'); },
onError: (e: any) => toast.error(e.message),
});
return (
<>
<PageHeader title="کیف پول پیامک" description="مدیریت موجودی و تنظیمات ارسال پیامک" />
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
{/* کارت موجودی */}
<div className="card">
<div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 4 }}>موجودی کیف پول</div>
{balanceLoading ? (
<div style={{ height: 40 }} />
) : (
<>
<div style={{ fontSize: 28, fontWeight: 700, marginBottom: 4 }}>
{formatRial(balance?.balance_rials ?? 0)}
</div>
<div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 16 }}>
معادل {formatNumber(balance?.estimated_sms_count ?? 0)} پیامک
{balance?.sms_price_rials ? ` (هر پیامک ${formatRial(balance.sms_price_rials)})` : ''}
</div>
<button className="btn primary sm" onClick={() => setChargeOpen(true)}>
شارژ کیف پول
</button>
</>
)}
</div>
{/* تنظیمات پیامک */}
<div className="card">
<div style={{ fontWeight: 600, marginBottom: 12 }}>تنظیمات ارسال</div>
{currentSettings ? (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}>
<input
type="checkbox"
checked={currentSettings.reminder_enabled}
onChange={(e) => setLocalSettings({ ...currentSettings, reminder_enabled: e.target.checked })}
/>
یادآوری قبل از نوبت
</label>
{currentSettings.reminder_enabled && (
<div className="field" style={{ marginBottom: 0 }}>
<label style={{ fontSize: 13 }}>چند ساعت قبل</label>
<input
type="number"
min={1}
max={72}
value={currentSettings.reminder_hours_before}
onChange={(e) => setLocalSettings({ ...currentSettings, reminder_hours_before: +e.target.value })}
dir="ltr"
style={{ width: 80 }}
/>
</div>
)}
<label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, cursor: 'pointer' }}>
<input
type="checkbox"
checked={currentSettings.post_visit_enabled}
onChange={(e) => setLocalSettings({ ...currentSettings, post_visit_enabled: e.target.checked })}
/>
پیامک بعد از ویزیت
</label>
{currentSettings.post_visit_enabled && (
<div className="field" style={{ marginBottom: 0 }}>
<label style={{ fontSize: 13 }}>متن پیامک</label>
<textarea
value={currentSettings.post_visit_text ?? ''}
onChange={(e) => setLocalSettings({ ...currentSettings, post_visit_text: e.target.value })}
rows={3}
placeholder="ممنون از مراجعه شما..."
/>
</div>
)}
<button
className="btn primary sm"
style={{ alignSelf: 'flex-start' }}
disabled={saveMutation.isPending}
onClick={() => currentSettings && saveMutation.mutate(currentSettings)}
>
{saveMutation.isPending ? 'در حال ذخیره...' : 'ذخیره تنظیمات'}
</button>
</div>
) : (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
)}
</div>
</div>
{/* تاریخچه تراکنش‌ها */}
<div className="card">
<div style={{ fontWeight: 600, marginBottom: 12 }}>تاریخچه تراکنشها</div>
{logsLoading ? (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
) : logs.length === 0 ? (
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>تراکنشی ثبت نشده است</div>
) : (
<>
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ borderBottom: '1px solid var(--border)' }}>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>نوع</th>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>مبلغ</th>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>توضیحات</th>
<th style={{ textAlign: 'right', padding: '8px 4px' }}>تاریخ</th>
</tr>
</thead>
<tbody>
{logs.map((log) => (
<tr key={log.uuid} style={{ borderBottom: '1px solid var(--border)' }}>
<td style={{ padding: '8px 4px' }}>
<span className={`badge ${log.type === 'credit' ? 'green' : 'red'}`}>
{log.type === 'credit' ? 'شارژ' : 'کسر'}
</span>
</td>
<td style={{ padding: '8px 4px' }}>{formatRial(log.amount_rials)}</td>
<td style={{ padding: '8px 4px', color: 'var(--text-2)' }}>{log.description}</td>
<td style={{ padding: '8px 4px', color: 'var(--text-3)' }}>{formatDateTime(log.created_at)}</td>
</tr>
))}
</tbody>
</table>
<div style={{ marginTop: 12 }}>
<Pagination page={logPage} total={total} limit={20} onPageChange={setLogPage} />
</div>
</>
)}
</div>
{/* Modal شارژ */}
<Modal open={chargeOpen} onClose={() => setChargeOpen(false)} title="شارژ کیف پول پیامک">
<form onSubmit={chargeForm.handleSubmit((d) => chargeMutation.mutate(d))}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div style={{ display: 'flex', gap: 8 }}>
{(['mellat', 'sep'] as const).map((gw) => (
<button
key={gw}
type="button"
className={`btn ${gateway === gw ? 'primary' : ''}`}
onClick={() => setGateway(gw)}
>
{gw === 'mellat' ? 'ملت' : 'سپ'}
</button>
))}
</div>
<div className="field">
<label>مبلغ (ریال)</label>
<input {...chargeForm.register('amount_rials')} type="number" min={10000} placeholder="500000" dir="ltr" />
{chargeForm.formState.errors.amount_rials && (
<span className="field-error">{chargeForm.formState.errors.amount_rials.message}</span>
)}
</div>
<div style={{ display: 'flex', gap: 8 }}>
<button type="submit" className="btn primary" disabled={chargeMutation.isPending}>
{chargeMutation.isPending ? 'در حال انتقال...' : 'پرداخت'}
</button>
<button type="button" className="btn" onClick={() => setChargeOpen(false)}>انصراف</button>
</div>
</div>
</form>
</Modal>
</>
);
}
+213
View File
@@ -0,0 +1,213 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PencilIcon, EyeIcon, EyeSlashIcon, PlusIcon } 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 { ClinicStaff } from '../types';
import { formatDate } from '../lib/utils';
import DataTable, { type Column } from '../components/ui/DataTable';
import Modal from '../components/ui/Modal';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import PageHeader from '../components/ui/PageHeader';
import { ActiveBadge } from '../components/ui/StatusBadge';
const schema = z.object({
full_name: z.string().min(2, 'نام حداقل ۲ کاراکتر باید باشد'),
phone: z.string().optional(),
job_title: z.string().optional(),
address: z.string().optional(),
national_code: z.string().optional(),
});
type StaffFormData = z.infer<typeof schema>;
const EMPTY: ClinicStaff[] = [];
export default function StaffPage() {
const qc = useQueryClient();
const [createOpen, setCreateOpen] = useState(false);
const [editTarget, setEditTarget] = useState<ClinicStaff | null>(null);
const [toggleTarget, setToggleTarget] = useState<ClinicStaff | null>(null);
const { data, isLoading } = useQuery<ApiResponse<ClinicStaff[]>>({
queryKey: ['staff'],
queryFn: () => api.get('/api/v1/staff'),
});
const staff = data?.data ?? EMPTY;
const createForm = useForm<StaffFormData>({ resolver: zodResolver(schema) });
const editForm = useForm<StaffFormData>({ resolver: zodResolver(schema) });
const createMutation = useMutation({
mutationFn: (body: StaffFormData) => api.post('/api/v1/staff', body),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['staff'] });
setCreateOpen(false);
createForm.reset();
toast.success('پرسنل ایجاد شد');
},
onError: (err: any) => toast.error(err.message),
});
const editMutation = useMutation({
mutationFn: ({ uuid, body }: { uuid: string; body: StaffFormData }) =>
api.patch(`/api/v1/staff/${uuid}`, body),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['staff'] });
setEditTarget(null);
toast.success('اطلاعات پرسنل ویرایش شد');
},
onError: (err: any) => toast.error(err.message),
});
const toggleMutation = useMutation({
mutationFn: (uuid: string) => api.patch(`/api/v1/staff/${uuid}/toggle`, {}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['staff'] });
setToggleTarget(null);
toast.success('وضعیت پرسنل تغییر کرد');
},
onError: (err: any) => toast.error(err.message),
});
const openEdit = (s: ClinicStaff) => {
editForm.reset({
full_name: s.full_name,
phone: s.phone ?? '',
job_title: s.job_title ?? '',
address: s.address ?? '',
national_code: s.national_code ?? '',
});
setEditTarget(s);
};
const columns: Column<ClinicStaff>[] = [
{ key: 'full_name', header: 'نام و نام خانوادگی' },
{ key: 'job_title', header: 'سمت', render: (s) => s.job_title ?? '—' },
{ key: 'phone', header: 'تلفن', render: (s) => s.phone ?? '—' },
{ key: 'national_code', header: 'کد ملی', render: (s) => s.national_code ?? '—' },
{
key: 'active',
header: 'وضعیت',
render: (s) => <ActiveBadge active={s.active} />,
},
{
key: 'created_at',
header: 'تاریخ ثبت',
render: (s) => formatDate(s.created_at),
},
{
key: 'uuid',
header: 'عملیات',
render: (s) => (
<div style={{ display: 'flex', gap: 6 }}>
<button className="btn sm" onClick={() => openEdit(s)} title="ویرایش">
<PencilIcon style={{ width: 15 }} />
</button>
<button
className="btn sm"
onClick={() => setToggleTarget(s)}
title={s.active ? 'غیرفعال‌سازی' : 'فعال‌سازی'}
>
{s.active
? <EyeSlashIcon style={{ width: 15 }} />
: <EyeIcon style={{ width: 15 }} />
}
</button>
</div>
),
},
];
return (
<>
<PageHeader
title="مدیریت پرسنل"
description="لیست پرسنل کلینیک / مطب"
action={
<button className="btn primary sm" onClick={() => setCreateOpen(true)}>
<PlusIcon style={{ width: 16 }} /> افزودن پرسنل
</button>
}
/>
<div className="card">
<DataTable columns={columns} data={staff} loading={isLoading} />
</div>
{/* Modal ایجاد */}
<Modal open={createOpen} onClose={() => setCreateOpen(false)} title="افزودن پرسنل جدید">
<form onSubmit={createForm.handleSubmit((d) => createMutation.mutate(d))}>
<StaffFormFields form={createForm} />
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button type="submit" className="btn primary" disabled={createMutation.isPending}>
{createMutation.isPending ? 'در حال ذخیره...' : 'ذخیره'}
</button>
<button type="button" className="btn" onClick={() => setCreateOpen(false)}>انصراف</button>
</div>
</form>
</Modal>
{/* Modal ویرایش */}
<Modal open={!!editTarget} onClose={() => setEditTarget(null)} title="ویرایش پرسنل">
<form
onSubmit={editForm.handleSubmit((d) =>
editTarget && editMutation.mutate({ uuid: editTarget.uuid, body: d })
)}
>
<StaffFormFields form={editForm} />
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button type="submit" className="btn primary" disabled={editMutation.isPending}>
{editMutation.isPending ? 'در حال ذخیره...' : 'ذخیره'}
</button>
<button type="button" className="btn" onClick={() => setEditTarget(null)}>انصراف</button>
</div>
</form>
</Modal>
{/* Confirm toggle */}
<ConfirmDialog
open={!!toggleTarget}
title={toggleTarget?.active ? 'غیرفعال‌سازی پرسنل' : 'فعال‌سازی پرسنل'}
message={`آیا مطمئن هستید که می‌خواهید «${toggleTarget?.full_name}» را ${toggleTarget?.active ? 'غیرفعال' : 'فعال'} کنید؟`}
confirmLabel={toggleTarget?.active ? 'غیرفعال کن' : 'فعال کن'}
onConfirm={() => toggleTarget && toggleMutation.mutate(toggleTarget.uuid)}
onCancel={() => setToggleTarget(null)}
loading={toggleMutation.isPending}
/>
</>
);
}
function StaffFormFields({ form }: { form: ReturnType<typeof useForm<StaffFormData>> }) {
const { register, formState: { errors } } = form;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div className="field">
<label>نام و نام خانوادگی *</label>
<input {...register('full_name')} placeholder="علی رضایی" />
{errors.full_name && <span className="field-error">{errors.full_name.message}</span>}
</div>
<div className="field">
<label>سمت</label>
<input {...register('job_title')} placeholder="پرستار" />
</div>
<div className="field">
<label>تلفن</label>
<input {...register('phone')} placeholder="09121234567" dir="ltr" />
</div>
<div className="field">
<label>کد ملی</label>
<input {...register('national_code')} placeholder="0012345678" dir="ltr" />
</div>
<div className="field">
<label>آدرس</label>
<input {...register('address')} placeholder="آدرس محل سکونت" />
</div>
</div>
);
}
+238
View File
@@ -0,0 +1,238 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { CheckIcon, SparklesIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { SubscriptionPlan, MySubscription, SubscriptionPeriod } from '../types';
import { formatDate, formatRial, formatNumber } from '../lib/utils';
import Modal from '../components/ui/Modal';
import PageHeader from '../components/ui/PageHeader';
const PLAN_FEATURE_LABELS: Record<string, string> = {
patient_records: 'پرونده بیمار',
services: 'مدیریت سرویس‌ها',
sms_panel: 'پنل پیامک',
};
const PLAN_DISPLAY: Record<string, { label: string; color: string }> = {
free: { label: 'رایگان', color: '#64748b' },
basic: { label: 'پایه', color: '#3b82f6' },
professional: { label: 'حرفه‌ای', color: '#8b5cf6' },
};
const GATEWAY_LABELS: Record<string, string> = { mellat: 'ملت', sep: 'سپ' };
export default function SubscriptionPage() {
const qc = useQueryClient();
const [purchaseTarget, setPurchaseTarget] = useState<SubscriptionPeriod | null>(null);
const [selectedGateway, setSelectedGateway] = useState<'mellat' | 'sep'>('mellat');
const { data: plansData, isLoading: plansLoading } = useQuery<ApiResponse<SubscriptionPlan[]>>({
queryKey: ['subscription-plans'],
queryFn: () => api.get('/api/v1/subscription/plans'),
});
const { data: myData } = useQuery<ApiResponse<MySubscription>>({
queryKey: ['subscription-my'],
queryFn: () => api.get('/api/v1/subscription/my'),
});
const plans = plansData?.data ?? [];
const my = myData?.data;
const trialMutation = useMutation({
mutationFn: () => api.post('/api/v1/subscription/trial', {}),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['subscription-my'] });
toast.success('تریال رایگان با موفقیت فعال شد');
},
onError: (err: any) => toast.error(err.message),
});
const purchaseMutation = useMutation({
mutationFn: ({ period_uuid, gateway }: { period_uuid: string; gateway: string }) =>
api.post<{ data: { payment_url: string } }>('/api/v1/subscription-payment', { period_uuid, gateway }),
onSuccess: (res: any) => {
const url = res?.data?.payment_url;
if (url) window.location.href = url;
else toast.error('خطا در دریافت لینک پرداخت');
},
onError: (err: any) => toast.error(err.message),
});
const daysTotal = my?.expires_at && my?.starts_at
? Math.round((my.expires_at - my.starts_at) / 86400)
: null;
const daysProgress = daysTotal && my?.days_remaining != null
? Math.max(0, Math.min(100, ((daysTotal - my.days_remaining) / daysTotal) * 100))
: null;
return (
<>
<PageHeader title="پنل اشتراکی" description="مدیریت اشتراک و ارتقای پنل" />
{/* وضعیت اشتراک فعلی */}
{my && (
<div className="card" style={{ marginBottom: 20 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
<SparklesIcon style={{ width: 22, color: PLAN_DISPLAY[my.plan.name]?.color ?? '#64748b' }} />
<div>
<div style={{ fontWeight: 700, fontSize: 16 }}>
پنل {PLAN_DISPLAY[my.plan.name]?.label ?? my.plan.name}
{my.is_trial && <span className="badge amber" style={{ marginRight: 8, fontSize: 11 }}>تریال</span>}
</div>
{my.expires_at
? <div style={{ fontSize: 13, color: 'var(--text-3)' }}>
انقضا: {formatDate(my.expires_at)} {formatNumber(my.days_remaining ?? 0)} روز باقیمانده
</div>
: <div style={{ fontSize: 13, color: 'var(--text-3)' }}>بدون تاریخ انقضا</div>
}
</div>
{!my.used_trial && (
<button
className="btn primary sm"
style={{ marginRight: 'auto' }}
onClick={() => trialMutation.mutate()}
disabled={trialMutation.isPending}
>
{trialMutation.isPending ? 'در حال فعال‌سازی...' : 'فعال‌سازی تریال رایگان'}
</button>
)}
</div>
{daysProgress !== null && (
<div style={{ background: 'var(--surface-2)', borderRadius: 6, height: 6, overflow: 'hidden' }}>
<div style={{ width: `${daysProgress}%`, height: '100%', background: PLAN_DISPLAY[my.plan.name]?.color ?? '#3b82f6', transition: 'width .3s' }} />
</div>
)}
</div>
)}
{/* کارت‌های پلن */}
{plansLoading ? (
<div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری...</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 16 }}>
{plans.map((plan) => (
<PlanCard
key={plan.uuid}
plan={plan}
currentPlanLevel={my?.plan.level ?? 0}
usedTrial={my?.used_trial ?? false}
onPurchase={(period) => setPurchaseTarget(period)}
/>
))}
</div>
)}
{/* Modal پرداخت */}
<Modal
open={!!purchaseTarget}
onClose={() => setPurchaseTarget(null)}
title={`خرید ${purchaseTarget?.label ?? ''}`}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ display: 'flex', gap: 8 }}>
{(['mellat', 'sep'] as const).map((gw) => (
<button
key={gw}
className={`btn ${selectedGateway === gw ? 'primary' : ''}`}
onClick={() => setSelectedGateway(gw)}
>
{GATEWAY_LABELS[gw]}
</button>
))}
</div>
<p style={{ margin: 0, color: 'var(--text-3)', fontSize: 14 }}>
مبلغ: <b style={{ color: 'var(--text-1)' }}>{purchaseTarget ? formatRial(purchaseTarget.price_rials) : ''}</b>
</p>
<div style={{ display: 'flex', gap: 8 }}>
<button
className="btn primary"
disabled={purchaseMutation.isPending}
onClick={() =>
purchaseTarget &&
purchaseMutation.mutate({ period_uuid: purchaseTarget.uuid, gateway: selectedGateway })
}
>
{purchaseMutation.isPending ? 'در حال انتقال...' : 'پرداخت'}
</button>
<button className="btn" onClick={() => setPurchaseTarget(null)}>انصراف</button>
</div>
</div>
</Modal>
</>
);
}
function PlanCard({
plan,
currentPlanLevel,
usedTrial,
onPurchase,
}: {
plan: SubscriptionPlan;
currentPlanLevel: number;
usedTrial: boolean;
onPurchase: (period: SubscriptionPeriod) => void;
}) {
const display = PLAN_DISPLAY[plan.name] ?? { label: plan.name, color: '#64748b' };
const isCurrent = plan.level === currentPlanLevel;
const paidPeriods = plan.periods.filter((p) => !p.is_trial);
const trialPeriod = plan.periods.find((p) => p.is_trial);
return (
<div
className="card"
style={{ border: isCurrent ? `2px solid ${display.color}` : undefined, position: 'relative' }}
>
{isCurrent && (
<span className="badge green" style={{ position: 'absolute', top: 12, left: 12, fontSize: 11 }}>
پنل فعلی
</span>
)}
<div style={{ fontWeight: 700, fontSize: 18, color: display.color, marginBottom: 8 }}>
{display.label}
</div>
<div style={{ fontSize: 13, color: 'var(--text-3)', marginBottom: 12 }}>
حداکثر {plan.max_secretaries} منشی
</div>
<ul style={{ listStyle: 'none', padding: 0, margin: '0 0 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
{Object.entries(plan.features).map(([key, enabled]) => (
<li key={key} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
<CheckIcon style={{ width: 14, color: enabled ? '#22c55e' : '#94a3b8' }} />
<span style={{ color: enabled ? 'var(--text-1)' : 'var(--text-3)' }}>
{PLAN_FEATURE_LABELS[key] ?? key}
</span>
</li>
))}
</ul>
{paidPeriods.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{paidPeriods.map((period) => (
<div key={period.uuid} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span style={{ fontSize: 13 }}>{period.label}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontWeight: 600, fontSize: 13 }}>{formatRial(period.price_rials)}</span>
<button
className="btn primary sm"
onClick={() => onPurchase(period)}
>
{isCurrent ? 'تمدید' : 'خرید'}
</button>
</div>
</div>
))}
</div>
)}
{trialPeriod && !usedTrial && plan.level > 0 && (
<div style={{ marginTop: 12, fontSize: 12, color: 'var(--text-3)', borderTop: '1px solid var(--border)', paddingTop: 10 }}>
تریال {trialPeriod.duration_months} ماهه رایگان از دکمه بالای صفحه فعال کنید
</div>
)}
</div>
);
}
+98
View File
@@ -308,3 +308,101 @@ export interface Specialty {
name: string;
slug?: string;
}
export interface ClinicStaff {
uuid: string;
full_name: string;
phone: string | null;
job_title: string | null;
address: string | null;
national_code: string | null;
active: boolean;
created_at: number;
}
export interface SubscriptionPlan {
uuid: string;
name: string;
level: number;
max_secretaries: number;
features: Record<string, boolean>;
periods: SubscriptionPeriod[];
}
export interface SubscriptionPeriod {
uuid: string;
label: string;
duration_months: number;
price_rials: number;
is_trial: boolean;
}
export interface MySubscription {
plan: { name: string; level: number; features: Record<string, boolean> };
period?: { label: string; duration_months: number };
is_trial: boolean;
starts_at?: number;
expires_at?: number | null;
used_trial: boolean;
days_remaining?: number;
}
export interface ServiceSection {
uuid: string;
name: string;
active: boolean;
}
export interface ServiceItem {
uuid: string;
name: string;
price_rials: number;
staff: { uuid: string; full_name: string } | null;
active: boolean;
}
export interface SmsWalletBalance {
balance_rials: number;
sms_price_rials: number;
estimated_sms_count: number;
}
export interface SmsWalletLog {
uuid: string;
type: 'credit' | 'debit';
amount_rials: number;
description: string;
created_at: number;
}
export interface SmsSettings {
reminder_enabled: boolean;
reminder_hours_before: number;
post_visit_enabled: boolean;
post_visit_text: string | null;
}
export interface PatientRecord {
uuid: string;
entity_type: string;
entity_id: number;
user: { uuid: string; fullName: string; phone: string };
created_at: number;
}
export interface PatientSession {
uuid: string;
record_uuid: string;
appointment_uuid: string | null;
insurance_base_id: number | null;
insurance_supplementary_id: number | null;
visit_price_rials: number;
base_insurance_discount_percent: string;
supplementary_discount_percent: string;
services_total_rials: number;
final_price_rials: number;
payment_method: string;
notes: string | null;
created_at: number;
updated_at: number;
}