feat: add clinic management and financial reporting features

- Implemented ClinicFormPage for adding new clinics with validation.
- Created MyFinancialPage to display financial summaries and charts.
- Developed MyPatientsPage for managing patient data with search and pagination.
- Added PreRegistrationsPage for handling pre-registration requests with approval and rejection functionalities.
- Introduced database migration for pre_registrations table.
- Built PreRegistrationController for managing pre-registration logic, including submission, approval, and rejection.
- Created PreRegistration entity and repository for handling pre-registration data.
This commit is contained in:
hamed
2026-06-12 12:31:27 +03:30
parent 92cb834c22
commit 8ad983310c
14 changed files with 1772 additions and 469 deletions
+83
View File
@@ -0,0 +1,83 @@
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useMutation } from '@tanstack/react-query';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { ArrowRightIcon, BuildingOffice2Icon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
const schema = z.object({
owner_mobile: z.string().min(10, 'شماره موبایل معتبر نیست').max(15),
name: z.string().min(2, 'نام کلینیک حداقل ۲ کاراکتر'),
telephone: z.string().max(20).optional().or(z.literal('')),
address: z.string().max(500).optional().or(z.literal('')),
info: z.string().max(2000).optional().or(z.literal('')),
});
type FormValues = z.infer<typeof schema>;
interface ClinicCreated { uuid: string; name: string; is_active: boolean }
export default function ClinicFormPage() {
const navigate = useNavigate();
const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<FormValues>({ resolver: zodResolver(schema) });
const mutation = useMutation<ApiResponse<ClinicCreated>, Error, FormValues>({
mutationFn: (body) => api.post('/api/v1/admin/clinic', body),
onSuccess: (res) => {
toast.success(`کلینیک "${res?.data?.name}" ایجاد شد`);
navigate('/admin/clinics');
},
onError: (err) => toast.error(err.message ?? 'خطا در ایجاد کلینیک'),
});
return (
<div className="page" style={{ maxWidth: 640 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}>
<button className="btn ghost sm" onClick={() => navigate('/admin/clinics')}>
<ArrowRightIcon style={{ width: 16, height: 16 }} />بازگشت
</button>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<BuildingOffice2Icon style={{ width: 22, height: 22, color: 'var(--primary)' }} />
<h1 style={{ margin: 0, fontSize: 20, fontWeight: 700 }}>افزودن کلینیک جدید</h1>
</div>
</div>
<div className="card">
<form onSubmit={handleSubmit((v) => mutation.mutate(v))} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<label style={{ fontSize: 13, fontWeight: 600 }}>شماره موبایل صاحب کلینیک <span style={{ color: 'var(--red)' }}>*</span></label>
<input className="field" placeholder="09xxxxxxxxx" dir="ltr" {...register('owner_mobile')} />
{errors.owner_mobile && <span style={{ color: 'var(--red)', fontSize: 12 }}>{errors.owner_mobile.message}</span>}
<span style={{ fontSize: 11, color: 'var(--text-3)' }}>اگر این موبایل در سیستم نباشد، کاربر جدید ساخته میشود</span>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<label style={{ fontSize: 13, fontWeight: 600 }}>نام کلینیک <span style={{ color: 'var(--red)' }}>*</span></label>
<input className="field" placeholder="مثال: کلینیک تخصصی پارسیان" {...register('name')} />
{errors.name && <span style={{ color: 'var(--red)', fontSize: 12 }}>{errors.name.message}</span>}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<label style={{ fontSize: 13, fontWeight: 600 }}>تلفن ثابت</label>
<input className="field" placeholder="02xxxxxxxx" dir="ltr" {...register('telephone')} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<label style={{ fontSize: 13, fontWeight: 600 }}>آدرس</label>
<input className="field" placeholder="آدرس کلینیک" {...register('address')} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<label style={{ fontSize: 13, fontWeight: 600 }}>توضیحات</label>
<textarea className="field" rows={3} placeholder="درباره کلینیک..." {...register('info')} style={{ resize: 'vertical' }} />
</div>
<div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', paddingTop: 8 }}>
<button type="button" className="btn ghost" onClick={() => navigate('/admin/clinics')}>انصراف</button>
<button type="submit" className="btn primary" disabled={isSubmitting || mutation.isPending}>
{mutation.isPending ? 'در حال ذخیره...' : 'ایجاد کلینیک'}
</button>
</div>
</form>
</div>
</div>
);
}
+83
View File
@@ -0,0 +1,83 @@
import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { formatRial } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
interface MonthlyEntry {
month: string;
paid: number;
count: number;
}
interface FinancialSummary {
total_paid: number;
total_pending: number;
total_refunded: number;
count_paid: number;
monthly_chart: MonthlyEntry[];
}
function KpiCard({ label, value, color }: { label: string; value: string; color: string }) {
return (
<div className="card" style={{ flex: '1 1 200px', minWidth: 0 }}>
<div style={{ color: 'var(--text-3)', fontSize: 13, marginBottom: 6 }}>{label}</div>
<div style={{ fontSize: 22, fontWeight: 700, color }}>{value}</div>
</div>
);
}
const BAR_MAX_HEIGHT = 120;
export default function MyFinancialPage() {
const { data, isLoading } = useQuery<ApiResponse<FinancialSummary>>({
queryKey: ['my-financial-summary'],
queryFn: () => api.get('/api/v1/my/financial-summary'),
});
const summary = data?.data;
const maxPaid = summary?.monthly_chart?.reduce((m, e) => Math.max(m, e.paid), 1) ?? 1;
return (
<div className="page">
<PageHeader title="گزارش مالی" description="خلاصه پرداخت‌های بیماران" />
{isLoading ? (
<div style={{ padding: 40, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری...</div>
) : (
<>
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', marginBottom: 24 }}>
<KpiCard label="مجموع پرداخت شده" value={formatRial(summary?.total_paid ?? 0)} color="var(--green)" />
<KpiCard label="در انتظار پرداخت" value={formatRial(summary?.total_pending ?? 0)} color="var(--orange)" />
<KpiCard label="مجموع استرداد" value={formatRial(summary?.total_refunded ?? 0)} color="var(--red)" />
<KpiCard label="تعداد پرداخت موفق" value={String(summary?.count_paid ?? 0)} color="var(--primary)" />
</div>
<div className="card">
<div style={{ fontWeight: 600, marginBottom: 20 }}>نمودار ۶ ماه اخیر</div>
{summary?.monthly_chart?.length ? (
<div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, height: BAR_MAX_HEIGHT + 40 }}>
{summary.monthly_chart.map((entry) => {
const barH = Math.max(4, Math.round((entry.paid / maxPaid) * BAR_MAX_HEIGHT));
return (
<div key={entry.month} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
<div style={{ fontSize: 11, color: 'var(--text-3)' }}>{formatRial(entry.paid)}</div>
<div
style={{ width: '100%', height: barH, borderRadius: 6, background: 'linear-gradient(to top, var(--primary), oklch(0.72 0.16 256))', transition: 'height 0.3s ease' }}
title={`${entry.month}: ${formatRial(entry.paid)}${entry.count} پرداخت`}
/>
<div style={{ fontSize: 11, color: 'var(--text-2)', whiteSpace: 'nowrap' }}>{entry.month}</div>
</div>
);
})}
</div>
) : (
<div style={{ textAlign: 'center', color: 'var(--text-3)', padding: 32 }}>دادهای برای نمایش وجود ندارد</div>
)}
</div>
</>
)}
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { PhoneIcon } from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { PaginatedResponse } from '../lib/api';
import { formatDate, formatNumber } from '../lib/utils';
import DataTable, { type Column } from '../components/ui/DataTable';
import Pagination from '../components/ui/Pagination';
import PageHeader from '../components/ui/PageHeader';
interface Patient {
uuid: string;
name: string;
mobile: string;
total_appointments: number;
last_appointment: number | null;
}
const EMPTY: Patient[] = [];
export default function MyPatientsPage() {
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const limit = 20;
const { data, isLoading } = useQuery<PaginatedResponse<Patient>>({
queryKey: ['my-patients', page, search],
queryFn: () => api.get(`/api/v1/my/patients?page=${page}&limit=${limit}&search=${encodeURIComponent(search)}`),
});
const patients = data?.data ?? EMPTY;
const total = data?.meta?.totalRecords ?? 0;
const columns: Column<Patient>[] = [
{
key: 'name',
header: 'نام بیمار',
render: (p) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div className="avatar sm" style={{ background: 'linear-gradient(145deg, oklch(0.62 0.15 256), oklch(0.48 0.16 256))', flexShrink: 0 }}>
{(p.name || '؟').charAt(0)}
</div>
<span>{p.name || '—'}</span>
</div>
),
},
{
key: 'mobile',
header: 'موبایل',
render: (p) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, direction: 'ltr' }}>
<PhoneIcon style={{ width: 14, height: 14, color: 'var(--text-3)' }} />
<span>{p.mobile}</span>
</div>
),
},
{
key: 'total_appointments',
header: 'تعداد نوبت',
render: (p) => <span className="badge blue">{formatNumber(p.total_appointments)}</span>,
},
{
key: 'last_appointment',
header: 'آخرین نوبت',
render: (p) => p.last_appointment ? formatDate(String(p.last_appointment)) : '—',
},
];
return (
<div className="page">
<PageHeader title="بیماران من" description={`${formatNumber(total)} بیمار`} />
<DataTable
columns={columns}
data={patients}
loading={isLoading}
searchValue={search}
onSearchChange={(v) => { setSearch(v); setPage(1); }}
searchPlaceholder="جستجوی نام یا موبایل..."
emptyMessage="بیماری یافت نشد"
/>
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
</div>
);
}
+238
View File
@@ -0,0 +1,238 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { CheckIcon, XMarkIcon, PhoneIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { PaginatedResponse } from '../lib/api';
import { formatDate } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import Pagination from '../components/ui/Pagination';
import ConfirmDialog from '../components/ui/ConfirmDialog';
interface PreRegistration {
uuid: string;
type: 'independent_doctor' | 'doctor_with_clinic' | 'clinic_manager';
name: string;
mobile: string;
info: string | null;
status: 'pending' | 'approved' | 'rejected';
admin_note: string | null;
created_at: number;
}
const EMPTY: PreRegistration[] = [];
const TYPE_META: Record<string, { label: string; color: string }> = {
independent_doctor: { label: 'دکتر', color: 'blue' },
doctor_with_clinic: { label: 'دکتر + کلینیک', color: 'purple' },
clinic_manager: { label: 'مدیر کلینیک', color: 'orange' },
};
const STATUS_META: Record<string, { label: string; color: string }> = {
pending: { label: 'در انتظار', color: 'yellow' },
approved: { label: 'تأیید شده', color: 'green' },
rejected: { label: 'رد شده', color: 'red' },
};
const STATUS_TABS = [
{ value: 'pending', label: 'در انتظار' },
{ value: 'approved', label: 'تأیید شده' },
{ value: 'rejected', label: 'رد شده' },
{ value: 'all', label: 'همه' },
];
export default function PreRegistrationsPage() {
const qc = useQueryClient();
const [page, setPage] = useState(1);
const [statusFilter, setStatusFilter] = useState('pending');
const [approveTarget, setApproveTarget] = useState<PreRegistration | null>(null);
const [rejectTarget, setRejectTarget] = useState<PreRegistration | null>(null);
const [rejectNote, setRejectNote] = useState('');
const limit = 20;
const { data, isLoading } = useQuery<PaginatedResponse<PreRegistration>>({
queryKey: ['pre-registrations', page, statusFilter],
queryFn: () => api.get(`/api/v1/admin/pre-registrations?page=${page}&limit=${limit}&status=${statusFilter}`),
});
const items = data?.data ?? EMPTY;
const total = data?.meta?.totalRecords ?? 0;
const approveMutation = useMutation({
mutationFn: (uuid: string) => api.post(`/api/v1/admin/pre-registrations/${uuid}/approve`, {}),
onSuccess: () => {
toast.success('درخواست تأیید شد و اطلاعات ورود ارسال گردید');
setApproveTarget(null);
qc.invalidateQueries({ queryKey: ['pre-registrations'] });
},
onError: (err: Error) => toast.error(err.message),
});
const rejectMutation = useMutation({
mutationFn: ({ uuid, note }: { uuid: string; note: string }) =>
api.post(`/api/v1/admin/pre-registrations/${uuid}/reject`, { note: note || undefined }),
onSuccess: () => {
toast.success('درخواست رد شد');
setRejectTarget(null);
setRejectNote('');
qc.invalidateQueries({ queryKey: ['pre-registrations'] });
},
onError: (err: Error) => toast.error(err.message),
});
return (
<div className="page">
<PageHeader title="درخواست‌های ثبت‌نام" description={`${total} درخواست`} />
{/* Tabs */}
<div className="seg" style={{ marginBottom: 20, width: 'fit-content' }}>
{STATUS_TABS.map((tab) => (
<button
key={tab.value}
className={statusFilter === tab.value ? 'active' : ''}
onClick={() => { setStatusFilter(tab.value); setPage(1); }}
>
{tab.label}
</button>
))}
</div>
<div className="card" style={{ padding: 0, overflow: 'hidden' }}>
<table className="t">
<thead>
<tr>
<th>نام</th>
<th>موبایل</th>
<th>نوع حساب</th>
<th>توضیحات</th>
<th>وضعیت</th>
<th>تاریخ درخواست</th>
{statusFilter === 'pending' && <th />}
</tr>
</thead>
<tbody>
{isLoading
? Array.from({ length: 8 }).map((_, i) => (
<tr key={i}>
{Array.from({ length: 6 }).map((_, j) => (
<td key={j}><div className="skeleton" style={{ height: 16, borderRadius: 6 }} /></td>
))}
</tr>
))
: items.length === 0
? (
<tr>
<td colSpan={7} style={{ textAlign: 'center', padding: 48, color: 'var(--text-3)' }}>
درخواستی یافت نشد
</td>
</tr>
)
: items.map((item) => {
const typeMeta = TYPE_META[item.type] ?? { label: item.type, color: 'gray' };
const statusMeta = STATUS_META[item.status] ?? { label: item.status, color: 'gray' };
return (
<tr key={item.uuid}>
<td>
<div style={{ fontWeight: 600 }}>{item.name}</div>
</td>
<td>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, direction: 'ltr' }}>
<PhoneIcon style={{ width: 13, height: 13, color: 'var(--text-3)' }} />
<span style={{ fontSize: 13 }}>{item.mobile}</span>
</div>
</td>
<td>
<span className={`badge ${typeMeta.color}`}>
<span className="bdot" />{typeMeta.label}
</span>
</td>
<td style={{ maxWidth: 200 }}>
<span style={{ fontSize: 12, color: 'var(--text-2)', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
{item.info || '—'}
</span>
</td>
<td>
<span className={`badge ${statusMeta.color}`}>
<span className="bdot" />{statusMeta.label}
</span>
{item.admin_note && (
<div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 3 }}>{item.admin_note}</div>
)}
</td>
<td style={{ fontSize: 13 }}>{formatDate(String(item.created_at))}</td>
{statusFilter === 'pending' && (
<td>
<div className="row-actions">
<button
className="mini-btn"
title="تأیید"
style={{ color: 'var(--green)' }}
onClick={() => setApproveTarget(item)}
>
<CheckIcon style={{ width: 16, height: 16 }} />
</button>
<button
className="mini-btn"
title="رد"
style={{ color: 'var(--red)' }}
onClick={() => { setRejectTarget(item); setRejectNote(''); }}
>
<XMarkIcon style={{ width: 16, height: 16 }} />
</button>
</div>
</td>
)}
</tr>
);
})}
</tbody>
</table>
</div>
<Pagination page={page} total={total} limit={limit} onPageChange={setPage} />
{/* Approve Dialog */}
<ConfirmDialog
open={!!approveTarget}
title="تأیید درخواست"
message={`آیا درخواست "${approveTarget?.name}" را تأیید می‌کنید؟ اطلاعات ورود از طریق SMS ارسال خواهد شد.`}
confirmLabel="تأیید و ارسال SMS"
loading={approveMutation.isPending}
onConfirm={() => approveTarget && approveMutation.mutate(approveTarget.uuid)}
onCancel={() => setApproveTarget(null)}
/>
{/* Reject Dialog */}
{rejectTarget && (
<div className="overlay" onClick={() => setRejectTarget(null)}>
<div className="modal" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
<div className="modal-head">
<b>رد درخواست {rejectTarget.name}</b>
</div>
<div className="modal-body" style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<p style={{ margin: 0, fontSize: 13, color: 'var(--text-2)' }}>در صورت تمایل دلیل رد را وارد کنید (اختیاری)</p>
<textarea
className="field"
rows={3}
placeholder="دلیل رد..."
value={rejectNote}
onChange={(e) => setRejectNote(e.target.value)}
style={{ resize: 'vertical' }}
/>
</div>
<div className="modal-foot">
<button className="btn ghost sm" onClick={() => setRejectTarget(null)}>انصراف</button>
<button
className="btn danger sm"
disabled={rejectMutation.isPending}
onClick={() => rejectMutation.mutate({ uuid: rejectTarget.uuid, note: rejectNote })}
>
{rejectMutation.isPending ? 'در حال رد...' : 'رد درخواست'}
</button>
</div>
</div>
</div>
)}
</div>
);
}