feat(claims): add tracking number and status history for claims
- Introduced `tracking_number` field in the `claims` table to store the insurance tracking number. - Created `claim_status_logs` table to maintain a history of status changes for claims, including who made the change and when. - Implemented `ClaimStatusLog` entity and repository for managing status log entries. - Updated `ClaimService` to log transitions and handle tracking numbers during claim submissions. - Added new API endpoint for fetching claims by patient, including detailed claim history and status logs. - Enhanced frontend with a new `ClaimPatientDetailPage` to display claims and their status history. - Added tests to ensure correct aggregation of claims and proper handling of status transitions.
This commit is contained in:
@@ -47,6 +47,7 @@ import EditSessionPage from './pages/EditSessionPage';
|
||||
import SessionPaymentPage from './pages/SessionPaymentPage';
|
||||
import InsurancePricingPage from './pages/InsurancePricingPage';
|
||||
import ClaimsPage from './pages/ClaimsPage';
|
||||
import ClaimPatientDetailPage from './pages/ClaimPatientDetailPage';
|
||||
import DoctorClaimsPage from './pages/DoctorClaimsPage';
|
||||
import MyFinancialPage from './pages/MyFinancialPage';
|
||||
import ClinicFormPage from './pages/ClinicFormPage';
|
||||
@@ -235,6 +236,7 @@ export default function App() {
|
||||
<Route path="my-patients/:recordUuid/session/:sessionUuid/edit" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']} blockClinicScope><EditSessionPage /></RoleRoute>} />
|
||||
<Route path="insurance-pricing" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><InsurancePricingPage /></RoleRoute>} />
|
||||
<Route path="claims" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClaimsPage /></RoleRoute>} />
|
||||
<Route path="claims/:patientUuid" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClaimPatientDetailPage /></RoleRoute>} />
|
||||
<Route path="my-financial" element={<RoleRoute roles={['doctor', 'secretary', 'clinic']}><MyFinancialPage /></RoleRoute>} />
|
||||
|
||||
{/* فاز ۲ — دکتر / کلینیک */}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react';
|
||||
import type { AppointmentStatus, PaymentStatus, SmsTemplateStatus, SettlementStatus } from '../../types';
|
||||
import type { AppointmentStatus, PaymentStatus, SmsTemplateStatus, SettlementStatus, ClaimStatus } from '../../types';
|
||||
|
||||
type BadgeColor = 'green' | 'amber' | 'red' | 'blue' | 'violet' | 'gray';
|
||||
|
||||
@@ -36,8 +36,17 @@ const settlementMap: Record<SettlementStatus, { color: BadgeColor; label: string
|
||||
rejected: { color: 'red', label: 'رد شده' },
|
||||
};
|
||||
|
||||
const claimMap: Record<ClaimStatus, { color: BadgeColor; label: string }> = {
|
||||
pending: { color: 'gray', label: 'در انتظار ارسال' },
|
||||
submitted: { color: 'blue', label: 'ارسال شده' },
|
||||
approved: { color: 'amber', label: 'تأیید شده' },
|
||||
rejected: { color: 'red', label: 'رد شده' },
|
||||
paid: { color: 'green', label: 'پرداخت شده' },
|
||||
mixed: { color: 'violet', label: 'وضعیتهای مختلف' },
|
||||
};
|
||||
|
||||
interface Props {
|
||||
type: 'appointment' | 'payment' | 'sms' | 'settlement' | 'active';
|
||||
type: 'appointment' | 'payment' | 'sms' | 'settlement' | 'active' | 'claim';
|
||||
value: string;
|
||||
}
|
||||
|
||||
@@ -57,6 +66,9 @@ export default function StatusBadge({ type, value }: Props) {
|
||||
} else if (type === 'settlement') {
|
||||
const m = settlementMap[value as SettlementStatus];
|
||||
if (m) { color = m.color; label = m.label; }
|
||||
} else if (type === 'claim') {
|
||||
const m = claimMap[value as ClaimStatus];
|
||||
if (m) { color = m.color; label = m.label; }
|
||||
} else if (type === 'active') {
|
||||
color = value === 'true' || value === 'active' ? 'green' : 'gray';
|
||||
label = value === 'true' || value === 'active' ? 'فعال' : 'غیرفعال';
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import { formatRial, formatNumber, formatDate, formatDateTime } from '../lib/utils';
|
||||
import type { ClaimDetailRow, ClaimStatusLogEntry } from '../types';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import DataTable, { type Column } from '../components/ui/DataTable';
|
||||
import StatusBadge from '../components/ui/StatusBadge';
|
||||
import SearchableSelect from '../components/ui/SearchableSelect';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import FeatureGate from '../components/ui/FeatureGate';
|
||||
|
||||
interface PatientHeader {
|
||||
uuid: string;
|
||||
record_uuid: string;
|
||||
full_name: string | null;
|
||||
mobile: string | null;
|
||||
national_code: string | null;
|
||||
}
|
||||
|
||||
interface DetailPayload {
|
||||
patient: PatientHeader;
|
||||
claims: ClaimDetailRow[];
|
||||
}
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: '', label: 'همه وضعیتها' },
|
||||
{ value: 'pending', label: 'در انتظار ارسال' },
|
||||
{ value: 'submitted', label: 'ارسال شده' },
|
||||
{ value: 'approved', label: 'تأیید شده' },
|
||||
{ value: 'rejected', label: 'رد شده' },
|
||||
{ value: 'paid', label: 'پرداخت شده' },
|
||||
];
|
||||
|
||||
const ACTION_LABEL: Record<string, string> = {
|
||||
submitted: 'ارسال به بیمه',
|
||||
approved: 'تأیید',
|
||||
rejected: 'رد',
|
||||
paid: 'ثبت پرداخت',
|
||||
};
|
||||
|
||||
/** نام endpoint برای هر وضعیت مقصد — وضعیتها اسم فعل ندارند. */
|
||||
const ACTION_PATH: Record<string, string> = {
|
||||
submitted: 'submit',
|
||||
approved: 'approve',
|
||||
rejected: 'reject',
|
||||
paid: 'pay',
|
||||
};
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { base: 'پایه', supplementary: 'تکمیلی' };
|
||||
|
||||
function Timeline({ logs }: { logs: ClaimStatusLogEntry[] }) {
|
||||
if (logs.length === 0) return <div style={{ fontSize: 13, color: 'var(--text-3)' }}>رویدادی ثبت نشده است.</div>;
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{logs.map((log) => (
|
||||
<div key={log.uuid} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
|
||||
<span style={{ marginTop: 6, width: 8, height: 8, borderRadius: '50%', background: 'var(--primary)', flexShrink: 0 }} />
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<div style={{ fontSize: 13, fontWeight: 600 }}>
|
||||
<StatusBadge type="claim" value={log.to_status} />
|
||||
</div>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 4 }}>
|
||||
{formatDateTime(log.at)}
|
||||
{log.by ? ` · ${log.by}` : ''}
|
||||
</div>
|
||||
{log.note && <div style={{ fontSize: 12.5, marginTop: 4 }}>{log.note}</div>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** داشبورد پروندههای بیمه — سطح دوم: همهی مطالبات یک بیمار با تاریخچهی کامل. */
|
||||
export default function ClaimPatientDetailPage() {
|
||||
const { patientUuid = '' } = useParams();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const [selected, setSelected] = useState<ClaimDetailRow | null>(null);
|
||||
const [pendingAction, setPendingAction] = useState<{ claim: ClaimDetailRow; target: string } | null>(null);
|
||||
const [reason, setReason] = useState('');
|
||||
const [trackingNumber, setTrackingNumber] = useState('');
|
||||
|
||||
const status = params.get('status') ?? '';
|
||||
|
||||
const setParam = (patch: Record<string, string>) => {
|
||||
const next = new URLSearchParams(params);
|
||||
Object.entries(patch).forEach(([k, v]) => (v ? next.set(k, v) : next.delete(k)));
|
||||
setParams(next, { replace: true });
|
||||
};
|
||||
|
||||
const queryString = status ? `?status=${status}` : '';
|
||||
|
||||
const detailQuery = useQuery<ApiResponse<DetailPayload>>({
|
||||
queryKey: ['claims-patient-detail', patientUuid, status],
|
||||
queryFn: () => api.get(`/api/v1/billing/claims/by-patient/${patientUuid}${queryString}`),
|
||||
enabled: !!patientUuid,
|
||||
});
|
||||
|
||||
const payload = detailQuery.data?.data ?? null;
|
||||
const patient = payload?.patient ?? null;
|
||||
const claims = payload?.claims ?? [];
|
||||
|
||||
const transitionMut = useMutation({
|
||||
mutationFn: ({ uuid, target, body }: { uuid: string; target: string; body: Record<string, unknown> }) =>
|
||||
api.post(`/api/v1/billing/claims/${uuid}/${ACTION_PATH[target]}`, body),
|
||||
onSuccess: () => {
|
||||
toast.success('وضعیت مطالبه بهروز شد');
|
||||
queryClient.invalidateQueries({ queryKey: ['claims-patient-detail'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['claims-by-patient'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['insurance-debt'] });
|
||||
closeAction();
|
||||
},
|
||||
onError: (e: unknown) => toast.error(e instanceof Error ? e.message : 'ثبت تغییر وضعیت ناموفق بود'),
|
||||
});
|
||||
|
||||
const closeAction = () => {
|
||||
setPendingAction(null);
|
||||
setReason('');
|
||||
setTrackingNumber('');
|
||||
};
|
||||
|
||||
const confirmAction = () => {
|
||||
if (!pendingAction) return;
|
||||
const { claim, target } = pendingAction;
|
||||
if (target === 'rejected' && reason.trim() === '') {
|
||||
toast.error('دلیل رد الزامی است');
|
||||
return;
|
||||
}
|
||||
transitionMut.mutate({
|
||||
uuid: claim.uuid,
|
||||
target,
|
||||
body: target === 'rejected' ? { reason: reason.trim() } : { tracking_number: trackingNumber.trim() || undefined },
|
||||
});
|
||||
};
|
||||
|
||||
const columns: Column<ClaimDetailRow>[] = [
|
||||
{ key: 'visit_date', header: 'تاریخ مراجعه', render: (r) => (r.visit_date ? formatDate(r.visit_date) : '—') },
|
||||
{ key: 'doctor_name', header: 'پزشک', render: (r) => r.doctor_name ?? '—' },
|
||||
{ key: 'insurance_name', header: 'بیمه', render: (r) => `${r.insurance_name ?? '—'} (${KIND_LABEL[r.insurance_kind] ?? r.insurance_kind})` },
|
||||
{ key: 'service_base_rials', header: 'مبلغ اصلی', render: (r) => formatRial(r.service_base_rials) },
|
||||
{ key: 'coverage_percent', header: 'پوشش بیمه', render: (r) => `${formatNumber(r.coverage_percent)}٪` },
|
||||
{ key: 'insurance_share_rials', header: 'سهم بیمه', render: (r) => formatRial(r.insurance_share_rials) },
|
||||
{ key: 'patient_share_rials', header: 'سهم بیمار', render: (r) => formatRial(r.patient_share_rials) },
|
||||
{ key: 'status', header: 'وضعیت', render: (r) => <StatusBadge type="claim" value={r.status} /> },
|
||||
{ key: 'submitted_at', header: 'تاریخ ارسال', render: (r) => (r.submitted_at ? formatDate(r.submitted_at) : '—') },
|
||||
{ key: 'settled_at', header: 'تاریخ تسویه', render: (r) => (r.settled_at ? formatDate(r.settled_at) : '—') },
|
||||
{ key: 'tracking_number', header: 'شماره پیگیری', render: (r) => r.tracking_number ?? '—' },
|
||||
];
|
||||
|
||||
return (
|
||||
<FeatureGate feature="insurance">
|
||||
<PageHeader
|
||||
title={patient?.full_name ?? 'پرونده بیمه بیمار'}
|
||||
description={[patient?.mobile, patient?.national_code].filter(Boolean).join(' · ') || undefined}
|
||||
breadcrumbs={[
|
||||
{ label: 'داشبورد', to: '/admin' },
|
||||
{ label: 'پروندههای بیمه', to: '/admin/claims' },
|
||||
{ label: patient?.full_name ?? '—' },
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="card" style={{ padding: 18 }}>
|
||||
<div style={{ minWidth: 180, marginBottom: 16 }}>
|
||||
<label className="field-label">وضعیت</label>
|
||||
<SearchableSelect
|
||||
options={STATUS_OPTIONS}
|
||||
value={status}
|
||||
onChange={(v) => setParam({ status: v ? String(v) : '' })}
|
||||
placeholder="همه وضعیتها"
|
||||
height={38}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={claims}
|
||||
loading={detailQuery.isLoading}
|
||||
emptyMessage="مطالبهای برای این بیمار ثبت نشده است."
|
||||
actions={(row) => (
|
||||
<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
|
||||
<button className="btn ghost sm" onClick={() => setSelected(row)}>جزئیات</button>
|
||||
{row.allowed_transitions.map((target) => (
|
||||
<button
|
||||
key={target}
|
||||
className="btn primary sm"
|
||||
onClick={() => setPendingAction({ claim: row, target })}
|
||||
disabled={transitionMut.isPending}
|
||||
>
|
||||
{ACTION_LABEL[target] ?? target}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Modal open={!!selected} title="جزئیات مطالبه" size="lg" onClose={() => setSelected(null)}>
|
||||
{selected && (
|
||||
<div dir="rtl" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12, fontSize: 13 }}>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>بیمه: </span>{selected.insurance_name ?? '—'}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>نوع: </span>{KIND_LABEL[selected.insurance_kind] ?? selected.insurance_kind}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>مبلغ اصلی: </span>{formatRial(selected.service_base_rials)}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>سهم بیمه: </span>{formatRial(selected.insurance_share_rials)}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>سهم بیمار: </span>{formatRial(selected.patient_share_rials)}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>تأییدشده: </span>{selected.total_approved_rials !== null ? formatRial(selected.total_approved_rials) : '—'}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>پرداختشده: </span>{selected.total_paid_rials !== null ? formatRial(selected.total_paid_rials) : '—'}</div>
|
||||
<div><span style={{ color: 'var(--text-3)' }}>شماره پیگیری: </span>{selected.tracking_number ?? '—'}</div>
|
||||
</div>
|
||||
|
||||
{selected.reject_reason && (
|
||||
<div style={{ fontSize: 13, color: 'var(--danger)' }}>دلیل رد: {selected.reject_reason}</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>تاریخچه تغییرات</div>
|
||||
<Timeline logs={selected.logs} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
open={!!pendingAction}
|
||||
title={pendingAction ? ACTION_LABEL[pendingAction.target] ?? 'تغییر وضعیت' : ''}
|
||||
size="sm"
|
||||
onClose={closeAction}
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost sm" onClick={closeAction}>انصراف</button>
|
||||
<button className="btn primary sm" onClick={confirmAction} disabled={transitionMut.isPending}>تأیید</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{pendingAction?.target === 'rejected' ? (
|
||||
<div>
|
||||
<label className="field-label">دلیل رد (الزامی)</label>
|
||||
<textarea
|
||||
className="input"
|
||||
rows={3}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
placeholder="دلیل رد مطالبه توسط بیمه"
|
||||
/>
|
||||
</div>
|
||||
) : pendingAction?.target === 'submitted' ? (
|
||||
<div>
|
||||
<label className="field-label">شماره پیگیری بیمه (اختیاری)</label>
|
||||
<input
|
||||
className="input"
|
||||
value={trackingNumber}
|
||||
onChange={(e) => setTrackingNumber(e.target.value)}
|
||||
placeholder="مثلاً TM-4419-88"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ fontSize: 13 }}>آیا از ثبت این تغییر وضعیت مطمئن هستید؟</div>
|
||||
)}
|
||||
</Modal>
|
||||
</FeatureGate>
|
||||
);
|
||||
}
|
||||
+166
-285
@@ -1,16 +1,37 @@
|
||||
import { useState, useMemo, useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { CheckIcon, XMarkIcon, PaperAirplaneIcon, BanknotesIcon, MagnifyingGlassIcon, ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { ArrowPathIcon } from '@heroicons/react/24/outline';
|
||||
import { api } from '../lib/api';
|
||||
import { formatRial, formatNumber, formatDate } from '../lib/utils';
|
||||
import { formatRial, formatNumber } from '../lib/utils';
|
||||
import type { ClaimPatientRow } from '../types';
|
||||
import type { ApiResponse, PaginatedResponse } from '../lib/api';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import DataTable, { type Column } from '../components/ui/DataTable';
|
||||
import StatCard from '../components/ui/StatCard';
|
||||
import StatusBadge from '../components/ui/StatusBadge';
|
||||
import SearchableSelect from '../components/ui/SearchableSelect';
|
||||
import PersianDatePicker from '../components/ui/PersianDatePicker';
|
||||
import FeatureGate from '../components/ui/FeatureGate';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
|
||||
const LIMIT = 20;
|
||||
|
||||
const STATUS_OPTIONS = [
|
||||
{ value: '', label: 'همه وضعیتها' },
|
||||
{ value: 'pending', label: 'در انتظار ارسال' },
|
||||
{ value: 'submitted', label: 'ارسال شده' },
|
||||
{ value: 'approved', label: 'تأیید شده' },
|
||||
{ value: 'rejected', label: 'رد شده' },
|
||||
{ value: 'paid', label: 'پرداخت شده' },
|
||||
];
|
||||
|
||||
const PAYMENT_OPTIONS = [
|
||||
{ value: '', label: 'همه' },
|
||||
{ value: 'paid', label: 'وصولشده' },
|
||||
{ value: 'unpaid', label: 'وصولنشده' },
|
||||
];
|
||||
|
||||
const isoNDaysAgo = (days: number): string => {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - days);
|
||||
@@ -29,34 +50,6 @@ const endOfDayUnix = (iso: string): number | null => {
|
||||
return Number.isNaN(t) ? null : Math.floor(t / 1000);
|
||||
};
|
||||
|
||||
interface ClaimItem {
|
||||
invoice_item_id: number;
|
||||
claimed_rials: number;
|
||||
approved_rials: number | null;
|
||||
title: string | null;
|
||||
is_visit: boolean;
|
||||
quantity: number;
|
||||
total_rials: number | null;
|
||||
visit_date: number | null;
|
||||
}
|
||||
|
||||
interface Claim {
|
||||
uuid: string;
|
||||
insurance_id: number;
|
||||
insurance_name: string | null;
|
||||
insurance_kind: string;
|
||||
total_claimed_rials: number;
|
||||
total_approved_rials: number | null;
|
||||
total_paid_rials: number | null;
|
||||
status: string;
|
||||
reject_reason: string | null;
|
||||
patient_name: string | null;
|
||||
patient_mobile: string | null;
|
||||
items: ClaimItem[];
|
||||
}
|
||||
|
||||
interface InsuranceOption { insurance_id: number; insurance_name: string | null }
|
||||
|
||||
interface DebtRow {
|
||||
insurance_id: number;
|
||||
insurance_name: string | null;
|
||||
@@ -66,128 +59,120 @@ interface DebtRow {
|
||||
debt: number;
|
||||
}
|
||||
|
||||
const STATUS_META: Record<string, { label: string; cls: string }> = {
|
||||
pending: { label: 'در انتظار', cls: 'gray' },
|
||||
submitted: { label: 'ارسالشده', cls: 'blue' },
|
||||
approved: { label: 'تأییدشده', cls: 'amber' },
|
||||
rejected: { label: 'ردشده', cls: 'red' },
|
||||
paid: { label: 'پرداختشده', cls: 'green' },
|
||||
};
|
||||
|
||||
const KIND_LABEL: Record<string, string> = { base: 'پایه', supplementary: 'تکمیلی' };
|
||||
const STATUS_FILTERS = ['', 'pending', 'submitted', 'approved', 'rejected', 'paid'];
|
||||
|
||||
/**
|
||||
* داشبورد پروندههای بیمه — سطح اول: یک ردیف بهازای هر بیمار.
|
||||
* فیلترها در query string زندگی میکنند تا رفرش و اشتراک لینک، نما را حفظ کند.
|
||||
*/
|
||||
export default function ClaimsPage() {
|
||||
const qc = useQueryClient();
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [insuranceFilter, setInsuranceFilter] = useState('');
|
||||
const [fromDate, setFromDate] = useState('');
|
||||
const [toDate, setToDate] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const [rejectTarget, setRejectTarget] = useState<Claim | null>(null);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const limit = 20;
|
||||
const navigate = useNavigate();
|
||||
const [params, setParams] = useSearchParams();
|
||||
|
||||
// back to page 1 whenever a filter changes
|
||||
useEffect(() => { setPage(1); }, [statusFilter, insuranceFilter, fromDate, toDate, search]);
|
||||
const search = params.get('search') ?? '';
|
||||
const status = params.get('status') ?? '';
|
||||
const insuranceId = params.get('insurance_id') ?? '';
|
||||
const paymentStatus = params.get('payment_status') ?? '';
|
||||
const from = params.get('from') ?? '';
|
||||
const to = params.get('to') ?? '';
|
||||
const page = Math.max(1, Number(params.get('page') ?? 1));
|
||||
const sort = params.get('sort') ?? 'last_activity_at';
|
||||
const dir = (params.get('dir') ?? 'desc') as 'asc' | 'desc';
|
||||
|
||||
const hasFilters = !!(search || status || insuranceId || paymentStatus || from || to);
|
||||
|
||||
/** تغییر فیلتر همیشه به صفحهی اول برمیگردد؛ ماندن روی صفحه ۵ با نتیجهی جدید بیمعناست. */
|
||||
const setParam = (patch: Record<string, string>) => {
|
||||
const next = new URLSearchParams(params);
|
||||
Object.entries(patch).forEach(([k, v]) => (v ? next.set(k, v) : next.delete(k)));
|
||||
if (!('page' in patch)) next.delete('page');
|
||||
setParams(next, { replace: true });
|
||||
};
|
||||
|
||||
const queryString = useMemo(() => {
|
||||
const p = new URLSearchParams();
|
||||
if (statusFilter) p.set('status', statusFilter);
|
||||
if (insuranceFilter) p.set('insurance_id', insuranceFilter);
|
||||
const from = toUnix(fromDate); if (from) p.set('from', String(from));
|
||||
const to = endOfDayUnix(toDate); if (to) p.set('to', String(to));
|
||||
if (search.trim()) p.set('q', search.trim());
|
||||
p.set('page', String(page));
|
||||
p.set('limit', String(limit));
|
||||
const s = p.toString();
|
||||
return s ? `?${s}` : '';
|
||||
}, [statusFilter, insuranceFilter, fromDate, toDate, search, page]);
|
||||
const qs = new URLSearchParams();
|
||||
qs.set('page', String(page));
|
||||
qs.set('limit', String(LIMIT));
|
||||
qs.set('sort', sort);
|
||||
qs.set('dir', dir);
|
||||
if (search) qs.set('search', search);
|
||||
if (status) qs.set('status', status);
|
||||
if (insuranceId) qs.set('insurance_id', insuranceId);
|
||||
if (paymentStatus) qs.set('payment_status', paymentStatus);
|
||||
const fromUnix = toUnix(from);
|
||||
const toUnixVal = endOfDayUnix(to);
|
||||
if (fromUnix) qs.set('from', String(fromUnix));
|
||||
if (toUnixVal) qs.set('to', String(toUnixVal));
|
||||
return qs.toString();
|
||||
}, [page, sort, dir, search, status, insuranceId, paymentStatus, from, to]);
|
||||
|
||||
const claimsQuery = useQuery<{ data: { data: Claim[] } }>({
|
||||
queryKey: ['claims', queryString],
|
||||
queryFn: () => api.get(`/api/v1/billing/claims${queryString}`),
|
||||
const listQuery = useQuery<PaginatedResponse<ClaimPatientRow>>({
|
||||
queryKey: ['claims-by-patient', queryString],
|
||||
queryFn: () => api.get(`/api/v1/billing/claims/by-patient?${queryString}`),
|
||||
});
|
||||
|
||||
const insuranceOptionsQuery = useQuery<{ data: { data: InsuranceOption[] } }>({
|
||||
queryKey: ['claim-insurance-options'],
|
||||
queryFn: () => api.get('/api/v1/billing/reports/insurance-debt'),
|
||||
});
|
||||
const insuranceOptions = ((insuranceOptionsQuery.data as any)?.data?.data ?? []) as InsuranceOption[];
|
||||
|
||||
const debtQuery = useQuery<{ data: { data: DebtRow[] } }>({
|
||||
// یک fetch برای هر دو مصرف: کارتهای آمار و گزینههای فیلتر بیمه.
|
||||
const debtQuery = useQuery<ApiResponse<{ data: DebtRow[] }>>({
|
||||
queryKey: ['insurance-debt'],
|
||||
queryFn: () => api.get('/api/v1/billing/reports/insurance-debt'),
|
||||
});
|
||||
|
||||
const claims = (claimsQuery.data as any)?.data?.data ?? [];
|
||||
const claimsTotal = (claimsQuery.data as any)?.data?.meta?.totalRecords ?? 0;
|
||||
const debt = (debtQuery.data as any)?.data?.data ?? [];
|
||||
const rows = listQuery.data?.data ?? [];
|
||||
const total = listQuery.data?.meta?.totalRecords ?? 0;
|
||||
const debt: DebtRow[] = debtQuery.data?.data?.data ?? [];
|
||||
|
||||
const transitionMut = useMutation({
|
||||
mutationFn: ({ uuid, action, body }: { uuid: string; action: string; body?: object }) =>
|
||||
api.post(`/api/v1/billing/claims/${uuid}/${action}`, body ?? {}),
|
||||
onSuccess: () => {
|
||||
toast.success('وضعیت مطالبه بهروزرسانی شد');
|
||||
setRejectTarget(null);
|
||||
setRejectReason('');
|
||||
qc.invalidateQueries({ queryKey: ['claims'] });
|
||||
qc.invalidateQueries({ queryKey: ['insurance-debt'] });
|
||||
},
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
const totals = useMemo(
|
||||
() => debt.reduce(
|
||||
(acc, d) => ({
|
||||
claimed: acc.claimed + d.claimed,
|
||||
paid: acc.paid + d.paid,
|
||||
debt: acc.debt + d.debt,
|
||||
}),
|
||||
{ claimed: 0, paid: 0, debt: 0 },
|
||||
),
|
||||
[debt],
|
||||
);
|
||||
|
||||
const insuranceOptions = useMemo(
|
||||
() => [
|
||||
{ value: '', label: 'همه بیمهها' },
|
||||
...debt.map((d) => ({ value: String(d.insurance_id), label: d.insurance_name ?? `بیمه #${d.insurance_id}` })),
|
||||
],
|
||||
[debt],
|
||||
);
|
||||
|
||||
const columns: Column<ClaimPatientRow>[] = [
|
||||
{ key: 'full_name', header: 'بیمار', sortable: true, render: (r) => r.full_name ?? '—' },
|
||||
{ key: 'mobile', header: 'موبایل', render: (r) => r.mobile ?? '—' },
|
||||
{ key: 'national_code', header: 'کد ملی', render: (r) => r.national_code ?? '—' },
|
||||
{ key: 'claims_count', header: 'تعداد درخواست', sortable: true, render: (r) => formatNumber(r.claims_count) },
|
||||
{ key: 'total_services_rials', header: 'مجموع خدمات', sortable: true, render: (r) => formatRial(r.total_services_rials) },
|
||||
{ key: 'total_insurance_rials', header: 'سهم بیمه', sortable: true, render: (r) => formatRial(r.total_insurance_rials) },
|
||||
{ key: 'total_patient_rials', header: 'سهم بیمار', render: (r) => formatRial(r.total_patient_rials) },
|
||||
{ key: 'overall_status', header: 'وضعیت کلی', render: (r) => <StatusBadge type="claim" value={r.overall_status} /> },
|
||||
];
|
||||
|
||||
return (
|
||||
<FeatureGate feature="insurance">
|
||||
<div className="fade-in">
|
||||
<PageHeader title="مطالبات بیمه" description="پیگیری مطالبات و بدهی بیمهها" />
|
||||
<PageHeader
|
||||
title="پروندههای بیمه"
|
||||
description="پیگیری مطالبات بیمه به تفکیک بیمار"
|
||||
breadcrumbs={[{ label: 'داشبورد', to: '/admin' }, { label: 'پروندههای بیمه' }]}
|
||||
/>
|
||||
|
||||
<div className="card" style={{ padding: 18, marginBottom: 16 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
|
||||
<BanknotesIcon style={{ width: 18, color: 'var(--text-3)' }} />
|
||||
<h2 style={{ fontSize: 14, fontWeight: 700, margin: 0 }}>بدهی بیمهها</h2>
|
||||
</div>
|
||||
{debtQuery.isLoading ? (
|
||||
<div className="muted" style={{ fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : debt.length === 0 ? (
|
||||
<div style={{ fontSize: 12.5, color: 'var(--text-3)' }}>بدهیای ثبت نشده است.</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{debt.map((d: DebtRow) => (
|
||||
<div key={d.insurance_id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 12px', borderRadius: 8, border: '1px solid var(--border)', fontSize: 13 }}>
|
||||
<span style={{ fontWeight: 600 }}>{d.insurance_name ?? `بیمه #${formatNumber(d.insurance_id)}`}</span>
|
||||
<span style={{ color: 'var(--text-3)' }}>ادعا {formatRial(d.claimed)} · پرداخت {formatRial(d.paid)}</span>
|
||||
<span style={{ fontWeight: 700, color: d.debt > 0 ? 'var(--danger)' : 'var(--success, #16a34a)' }}>بدهی {formatRial(d.debt)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 'var(--gap)', marginBottom: 'var(--gap)' }}>
|
||||
<StatCard tone="violet" label="مجموع ادعای بیمه" value={formatRial(totals.claimed)} />
|
||||
<StatCard tone="green" label="وصولشده" value={formatRial(totals.paid)} />
|
||||
<StatCard tone="pink" label="مانده وصولنشده" value={formatRial(totals.debt)} />
|
||||
<StatCard tone="amber" label="تعداد بیماران" value={formatNumber(total)} />
|
||||
</div>
|
||||
|
||||
<div className="card" style={{ padding: 18 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
|
||||
<h2 style={{ fontSize: 14, fontWeight: 700, margin: 0 }}>مطالبات</h2>
|
||||
{(statusFilter || insuranceFilter || fromDate || toDate || search) && (
|
||||
<button
|
||||
className="btn ghost sm"
|
||||
onClick={() => { setStatusFilter(''); setInsuranceFilter(''); setFromDate(''); setToDate(''); setSearch(''); setSearchInput(''); }}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 4 }}
|
||||
>
|
||||
<ArrowPathIcon style={{ width: 13 }} /> پاککردن فیلترها
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* نوار فیلتر */}
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'flex-end', marginBottom: 16 }}>
|
||||
<div style={{ minWidth: 150 }}>
|
||||
<label className="field-label">بیمه</label>
|
||||
<SearchableSelect
|
||||
options={[{ value: '', label: 'همه بیمهها' }, ...insuranceOptions.map((o) => ({ value: String(o.insurance_id), label: o.insurance_name ?? `بیمه #${o.insurance_id}` }))]}
|
||||
value={insuranceFilter}
|
||||
onChange={(v) => setInsuranceFilter(v ? String(v) : '')}
|
||||
options={insuranceOptions}
|
||||
value={insuranceId}
|
||||
onChange={(v) => setParam({ insurance_id: v ? String(v) : '' })}
|
||||
placeholder="همه بیمهها"
|
||||
height={38}
|
||||
/>
|
||||
@@ -195,172 +180,68 @@ export default function ClaimsPage() {
|
||||
<div style={{ minWidth: 150 }}>
|
||||
<label className="field-label">وضعیت</label>
|
||||
<SearchableSelect
|
||||
options={STATUS_FILTERS.map((s) => ({ value: s, label: s === '' ? 'همه وضعیتها' : STATUS_META[s]?.label ?? s }))}
|
||||
value={statusFilter}
|
||||
onChange={(v) => setStatusFilter(v ? String(v) : '')}
|
||||
options={STATUS_OPTIONS}
|
||||
value={status}
|
||||
onChange={(v) => setParam({ status: v ? String(v) : '' })}
|
||||
placeholder="همه وضعیتها"
|
||||
height={38}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ minWidth: 130 }}>
|
||||
<label className="field-label">وضعیت پرداخت</label>
|
||||
<SearchableSelect
|
||||
options={PAYMENT_OPTIONS}
|
||||
value={paymentStatus}
|
||||
onChange={(v) => setParam({ payment_status: v ? String(v) : '' })}
|
||||
placeholder="همه"
|
||||
height={38}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ minWidth: 140 }}>
|
||||
<label className="field-label">از تاریخ</label>
|
||||
<PersianDatePicker value={fromDate} onChange={setFromDate} placeholder="از تاریخ" />
|
||||
<PersianDatePicker value={from} onChange={(v) => setParam({ from: v })} height={38} />
|
||||
</div>
|
||||
<div>
|
||||
<div style={{ minWidth: 140 }}>
|
||||
<label className="field-label">تا تاریخ</label>
|
||||
<PersianDatePicker value={toDate} onChange={setToDate} placeholder="تا تاریخ" />
|
||||
<PersianDatePicker value={to} onChange={(v) => setParam({ to: v })} height={38} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', paddingBottom: 1 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn sm"
|
||||
onClick={() => { setFromDate(isoNDaysAgo(365)); setToDate(todayIso()); }}
|
||||
title="از یک سال پیش تا امروز"
|
||||
>
|
||||
یک سال اخیر
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn sm"
|
||||
onClick={() => { setFromDate(isoNDaysAgo(30)); setToDate(todayIso()); }}
|
||||
title="از یک ماه پیش تا امروز"
|
||||
>
|
||||
یک ماه اخیر
|
||||
</button>
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn ghost sm" onClick={() => setParam({ from: isoNDaysAgo(30), to: todayIso() })}>یک ماه اخیر</button>
|
||||
<button className="btn ghost sm" onClick={() => setParam({ from: isoNDaysAgo(365), to: todayIso() })}>یک سال اخیر</button>
|
||||
{hasFilters && (
|
||||
<button
|
||||
className="btn ghost sm"
|
||||
onClick={() => setParams(new URLSearchParams(), { replace: true })}
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 4 }}
|
||||
>
|
||||
<ArrowPathIcon style={{ width: 13 }} /> پاککردن فیلترها
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 200 }}>
|
||||
<label className="field-label">جستجوی بیمار (نام / موبایل / کدملی)</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<MagnifyingGlassIcon style={{ width: 15, position: 'absolute', insetInlineStart: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', pointerEvents: 'none' }} />
|
||||
<input
|
||||
className="input"
|
||||
style={{ height: 38, paddingInlineStart: 32 }}
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') setSearch(searchInput); }}
|
||||
placeholder="نام، موبایل یا کدملی بیمار"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn primary" style={{ height: 38 }} onClick={() => setSearch(searchInput)}>جستجو</button>
|
||||
</div>
|
||||
|
||||
{claimsQuery.isLoading ? (
|
||||
<div className="muted" style={{ fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : claims.length === 0 ? (
|
||||
<div style={{ fontSize: 12.5, color: 'var(--text-3)', padding: '12px 0' }}>مطالبهای یافت نشد.</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{claims.map((c: Claim) => {
|
||||
const meta = STATUS_META[c.status] ?? { label: c.status, cls: 'gray' };
|
||||
return (
|
||||
<div key={c.uuid} style={{ padding: '12px 14px', borderRadius: 10, border: '1px solid var(--border)' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, fontSize: 13.5 }}>
|
||||
{c.insurance_name ?? `بیمه #${formatNumber(c.insurance_id)}`}
|
||||
<span className="badge gray" style={{ fontSize: 10, marginInlineStart: 6 }}>{KIND_LABEL[c.insurance_kind] ?? c.insurance_kind}</span>
|
||||
<span className={`badge ${meta.cls}`} style={{ fontSize: 10, marginInlineStart: 4 }}><span className="bdot" />{meta.label}</span>
|
||||
</div>
|
||||
{c.patient_name && (
|
||||
<div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 4, fontWeight: 500 }}>
|
||||
بیمار: {c.patient_name}
|
||||
{c.patient_mobile && <span style={{ color: 'var(--text-3)', fontWeight: 400 }} dir="ltr">{' '}{c.patient_mobile}</span>}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 3 }}>
|
||||
ادعا {formatRial(c.total_claimed_rials)}
|
||||
{c.total_approved_rials != null && ` · تأیید ${formatRial(c.total_approved_rials)}`}
|
||||
{c.total_paid_rials != null && ` · پرداخت ${formatRial(c.total_paid_rials)}`}
|
||||
{c.reject_reason && ` · دلیل رد: ${c.reject_reason}`}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
|
||||
{c.status === 'pending' && (
|
||||
<button className="btn primary sm" disabled={transitionMut.isPending} onClick={() => transitionMut.mutate({ uuid: c.uuid, action: 'submit' })}>
|
||||
<PaperAirplaneIcon style={{ width: 13 }} /> ارسال
|
||||
</button>
|
||||
)}
|
||||
{c.status === 'submitted' && (
|
||||
<>
|
||||
<button className="btn primary sm" disabled={transitionMut.isPending} onClick={() => transitionMut.mutate({ uuid: c.uuid, action: 'approve' })}>
|
||||
<CheckIcon style={{ width: 13 }} /> تأیید
|
||||
</button>
|
||||
<button className="btn danger sm" onClick={() => { setRejectTarget(c); setRejectReason(''); }}>
|
||||
<XMarkIcon style={{ width: 13 }} /> رد
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{c.status === 'approved' && (
|
||||
<button className="btn primary sm" disabled={transitionMut.isPending} onClick={() => transitionMut.mutate({ uuid: c.uuid, action: 'pay' })}>
|
||||
<BanknotesIcon style={{ width: 13 }} /> پرداخت
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={rows}
|
||||
loading={listQuery.isLoading}
|
||||
searchValue={search}
|
||||
onSearchChange={(v) => setParam({ search: v })}
|
||||
searchPlaceholder="نام، موبایل یا کد ملی بیمار"
|
||||
emptyMessage="پرونده بیمهای ثبت نشده است."
|
||||
sortKey={sort}
|
||||
sortDir={dir}
|
||||
onSort={(key) => setParam({ sort: key, dir: sort === key && dir === 'desc' ? 'asc' : 'desc' })}
|
||||
actions={(row) => (
|
||||
<button className="btn primary sm" onClick={() => navigate(`/admin/claims/${row.record_uuid}`)}>
|
||||
جزئیات
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
|
||||
{c.items.length > 0 && (
|
||||
<div style={{ marginTop: 12, borderTop: '1px solid var(--border)', paddingTop: 10, overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
|
||||
<thead>
|
||||
<tr style={{ color: 'var(--text-3)', textAlign: 'right' }}>
|
||||
<th style={{ fontWeight: 600, padding: '4px 8px' }}>شرح</th>
|
||||
<th style={{ fontWeight: 600, padding: '4px 8px' }}>تاریخ مراجعه</th>
|
||||
<th style={{ fontWeight: 600, padding: '4px 8px', textAlign: 'center' }}>تعداد</th>
|
||||
<th style={{ fontWeight: 600, padding: '4px 8px', textAlign: 'left' }}>مبلغ کل</th>
|
||||
<th style={{ fontWeight: 600, padding: '4px 8px', textAlign: 'left' }}>سهم بیمه (ادعا)</th>
|
||||
<th style={{ fontWeight: 600, padding: '4px 8px', textAlign: 'left' }}>تأییدشده</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{c.items.map((it, idx) => (
|
||||
<tr key={idx} style={{ borderTop: '1px solid var(--border)' }}>
|
||||
<td style={{ padding: '7px 8px' }}>
|
||||
<span className={`badge ${it.is_visit ? 'blue' : 'gray'}`} style={{ fontSize: 9.5, marginInlineEnd: 6 }}>
|
||||
{it.is_visit ? 'ویزیت' : 'خدمت'}
|
||||
</span>
|
||||
<span style={{ fontWeight: 500 }}>{it.title ?? '—'}</span>
|
||||
</td>
|
||||
<td style={{ padding: '7px 8px', color: 'var(--text-3)' }} dir="ltr">
|
||||
{it.visit_date ? formatDate(it.visit_date) : '—'}
|
||||
</td>
|
||||
<td style={{ padding: '7px 8px', textAlign: 'center' }}>{formatNumber(it.quantity)}</td>
|
||||
<td style={{ padding: '7px 8px', textAlign: 'left' }} dir="ltr">{it.total_rials != null ? formatRial(it.total_rials) : '—'}</td>
|
||||
<td style={{ padding: '7px 8px', textAlign: 'left', fontWeight: 600 }} dir="ltr">{formatRial(it.claimed_rials)}</td>
|
||||
<td style={{ padding: '7px 8px', textAlign: 'left', color: 'var(--text-3)' }} dir="ltr">
|
||||
{it.approved_rials != null ? formatRial(it.approved_rials) : '—'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{total > LIMIT && (
|
||||
<Pagination page={page} total={total} limit={LIMIT} onPageChange={(p) => setParam({ page: String(p) })} />
|
||||
)}
|
||||
<Pagination page={page} total={claimsTotal} limit={limit} onPageChange={setPage} />
|
||||
</div>
|
||||
|
||||
<Modal open={!!rejectTarget} onClose={() => setRejectTarget(null)} title="رد مطالبه"
|
||||
footer={
|
||||
<>
|
||||
<button className="btn ghost sm" onClick={() => setRejectTarget(null)}>انصراف</button>
|
||||
<button className="btn danger sm" disabled={!rejectReason || transitionMut.isPending}
|
||||
onClick={() => rejectTarget && transitionMut.mutate({ uuid: rejectTarget.uuid, action: 'reject', body: { reason: rejectReason } })}>
|
||||
رد کردن
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="field">
|
||||
<label>دلیل رد</label>
|
||||
<textarea className="input" rows={3} dir="rtl" value={rejectReason} onChange={(e) => setRejectReason(e.target.value)} placeholder="دلیل رد را بنویسید..." />
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
</FeatureGate>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -201,6 +201,58 @@ export interface Payment {
|
||||
|
||||
export type SettlementStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
/** `mixed` فقط در نمای تجمیعی بیمار معنا دارد: مطالبات آن بیمار وضعیت یکسان ندارند. */
|
||||
export type ClaimStatus = "pending" | "submitted" | "approved" | "rejected" | "paid" | "mixed";
|
||||
|
||||
export interface ClaimPatientRow {
|
||||
patient_uuid: string;
|
||||
record_uuid: string;
|
||||
full_name: string | null;
|
||||
mobile: string | null;
|
||||
national_code: string | null;
|
||||
claims_count: number;
|
||||
total_services_rials: number;
|
||||
total_insurance_rials: number;
|
||||
total_patient_rials: number;
|
||||
total_approved_rials: number;
|
||||
total_paid_rials: number;
|
||||
overall_status: ClaimStatus;
|
||||
last_activity_at: number;
|
||||
}
|
||||
|
||||
export interface ClaimStatusLogEntry {
|
||||
uuid: string;
|
||||
from_status: string | null;
|
||||
to_status: string;
|
||||
note: string | null;
|
||||
by: string | null;
|
||||
at: number;
|
||||
}
|
||||
|
||||
export interface ClaimDetailRow {
|
||||
uuid: string;
|
||||
invoice_uuid: string | null;
|
||||
visit_date: number | null;
|
||||
doctor_name: string | null;
|
||||
insurance_id: number;
|
||||
insurance_name: string | null;
|
||||
insurance_kind: "base" | "supplementary";
|
||||
service_base_rials: number;
|
||||
coverage_percent: number;
|
||||
insurance_share_rials: number;
|
||||
patient_share_rials: number;
|
||||
total_approved_rials: number | null;
|
||||
total_paid_rials: number | null;
|
||||
status: ClaimStatus;
|
||||
tracking_number: string | null;
|
||||
reject_reason: string | null;
|
||||
submitted_at: number | null;
|
||||
settled_at: number | null;
|
||||
created_at: number;
|
||||
allowed_transitions: string[];
|
||||
logs: ClaimStatusLogEntry[];
|
||||
}
|
||||
|
||||
export interface Settlement {
|
||||
uuid: string;
|
||||
representation_name: string;
|
||||
|
||||
+110
-9
@@ -2,7 +2,9 @@
|
||||
|
||||
> **Prefix:** `/api/v1/billing`
|
||||
> دامنه: `App\Billing`. مرجع معماری: `docs/architecture/insurance-billing-system.md`.
|
||||
> tenant از `#[CurrentUser]` resolve میشود (`ROLE_DOCTOR`→doctor، `ROLE_CLINIC`→clinic، و `ROLE_SECRETARY`→ همان مطب/کلینیکِ فعال بر اساس `db_uuid` و رابطهی فعالِ منشی). یعنی منشیِ فعال هم میتواند صورتحسابهای همان tenant را ببیند/بسازد.
|
||||
> tenant از `#[CurrentUser]` با **`App\Patient\Security\PatientRecordScopeResolver`** resolve میشود — همان رزولوری که پروندههای بیمار استفاده میکنند، چون صورتحساب و مطالبه از دل مراجعه بیرون میآیند و باید در همان محیط دیده شوند. محیط فعال (`UserActiveContext`) تعیینکننده است، نه صرفاً ترتیب نقشها. منشیِ فعال هم میتواند صورتحسابهای همان tenant را ببیند/بسازد. جزئیات جدول محیطها: [patient.md](patient.md#record-access-model).
|
||||
>
|
||||
> پیش از این، این دامنه ترتیب نقشها را خودش پیاده کرده بود و اول `ROLE_DOCTOR` را میگرفت؛ در نتیجه **مالک کلینیکی که خودش پزشک هم هست** به مطب شخصیاش نگاشت میشد و صورتحساب/مطالبهی کلینیک خودش را `404` میگرفت. همین رزولور در `InsuranceController` هم استفاده میشود تا قرارداد بیمه و صورتحساب هرگز به دو محیط متفاوت نیفتند.
|
||||
|
||||
صورتحساب (`Invoice`) از یک Encounter (`PatientSession`) ساخته میشود. برای هر آیتم سهم بیمهی پایه، بیمهی مکمل و بیمار با `BillingCalculator` محاسبه میشود:
|
||||
|
||||
@@ -188,18 +190,117 @@
|
||||
|
||||
> این فیلدها با یک کوئری گروهی (`InvoiceItemRepository::detailsForIds` + `PatientSessionRepository::datesForIds`) پر میشوند تا N+1 رخ ندهد. همان enrichment روی پاسخ `POST /claims` و `POST /claims/{uuid}/{action}` هم اعمال میشود.
|
||||
|
||||
## POST /api/v1/billing/claims/{uuid}/{action}
|
||||
انتقال وضعیت. `action` ∈ `submit|approve|reject|pay`.
|
||||
## GET /api/v1/billing/claims/by-patient
|
||||
نمای سطحاول داشبورد مطالبات: **یک ردیف بهازای هر بیمار** (نه هر مطالبه)، با جمعهای تجمیعی.
|
||||
|
||||
| action | body اختیاری | اثر |
|
||||
|--------|--------------|-----|
|
||||
| submit | — | pending → submitted |
|
||||
| approve | `approved_rials` | submitted → approved (پیشفرض = کل ادعا) — باید `0 ≤ approved_rials ≤ total_claimed_rials` |
|
||||
| reject | `reason` (الزامی) | submitted → rejected |
|
||||
| pay | `paid_rials` | approved → paid (پیشفرض = approved) — باید `0 ≤ paid_rials ≤ total_approved_rials` |
|
||||
**Query params:**
|
||||
|
||||
| Param | Type | Default | توضیح |
|
||||
|-------|------|---------|-------|
|
||||
| `page` | int | 1 | شماره صفحه |
|
||||
| `limit` | int | 20 | حداکثر ۱۰۰ |
|
||||
| `sort` | string | `last_activity_at` | `full_name` \| `claims_count` \| `total_services_rials` \| `total_insurance_rials` \| `last_activity_at` |
|
||||
| `dir` | string | `desc` | `asc` \| `desc` |
|
||||
| `search` | string | — | نام، موبایل یا کد ملی بیمار |
|
||||
| `status` | string | — | `pending` \| `submitted` \| `approved` \| `rejected` \| `paid` |
|
||||
| `insurance_id` | int | — | شناسه بیمه |
|
||||
| `doctor_id` | int | — | پزشکِ نوبتِ مراجعه |
|
||||
| `payment_status` | string | — | `paid` (وصولشده) \| `unpaid` |
|
||||
| `from` / `to` | int | — | بازهی `claims.created_at` (unix ثانیه) |
|
||||
|
||||
پاسخ paginated استاندارد (`{ success, data: [], meta }`):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"patient_uuid": "45064492-...",
|
||||
"record_uuid": "ad0a3d0e-...",
|
||||
"full_name": "تست جراحی بینی",
|
||||
"mobile": "09370671756",
|
||||
"national_code": null,
|
||||
"claims_count": 2,
|
||||
"total_services_rials": 81500000,
|
||||
"total_insurance_rials": 57050000,
|
||||
"total_patient_rials": 24450000,
|
||||
"total_approved_rials": 28000000,
|
||||
"total_paid_rials": 28000000,
|
||||
"overall_status": "mixed",
|
||||
"last_activity_at": 1784404115
|
||||
}
|
||||
],
|
||||
"meta": { "totalRecords": 1, "totalPages": 1, "currentPage": 1 }
|
||||
}
|
||||
```
|
||||
|
||||
- `overall_status`: اگر همهی مطالبات بیمار یک وضعیت داشته باشند همان؛ وگرنه `mixed`.
|
||||
- ثابت: `total_services_rials = total_insurance_rials + total_patient_rials`.
|
||||
- **ضدِ double-counting:** مبالغ خدمات/سهم بیمار از **صورتحسابهای یکتا** جمع میشوند، نه از مطالبات. یک صورتحساب میتواند همزمان مطالبهی پایه و مکمل داشته باشد؛ جمعزدن از سمت مطالبه مبلغ خدمات را دوبار میشمرد.
|
||||
- مطالبه لینک مستقیم به بیمار ندارد؛ زنجیرهی `claim → claim_item → invoice_item → invoice → patient_record` است.
|
||||
|
||||
## GET /api/v1/billing/claims/by-patient/{patientUuid}
|
||||
جزئیات کامل مطالبات یک بیمار (`patientUuid` = **uuid پرونده**، همان `record_uuid` نمای سطحاول). فیلترها همان فیلترهای بالا.
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"patient": { "uuid": "...", "record_uuid": "...", "full_name": "...", "mobile": "...", "national_code": null },
|
||||
"claims": [
|
||||
{
|
||||
"uuid": "b244b506-...",
|
||||
"invoice_uuid": "15498c14-...",
|
||||
"visit_date": 1784440200,
|
||||
"doctor_name": "دکتر تست",
|
||||
"insurance_id": 176,
|
||||
"insurance_name": "تامین اجتماعی",
|
||||
"insurance_kind": "base",
|
||||
"service_base_rials": 41000000,
|
||||
"coverage_percent": 70,
|
||||
"insurance_share_rials": 28700000,
|
||||
"patient_share_rials": 12300000,
|
||||
"total_approved_rials": 28000000,
|
||||
"total_paid_rials": 28000000,
|
||||
"status": "paid",
|
||||
"tracking_number": "TM-4419-88",
|
||||
"reject_reason": null,
|
||||
"submitted_at": 1784404200,
|
||||
"settled_at": 1784404300,
|
||||
"created_at": 1784404115,
|
||||
"allowed_transitions": [],
|
||||
"logs": [
|
||||
{ "uuid": "...", "from_status": null, "to_status": "pending", "note": "ایجاد مطالبه", "by": null, "at": 1784404115 },
|
||||
{ "uuid": "...", "from_status": "pending", "to_status": "submitted", "note": null, "by": "علی بهروزی", "at": 1784404200 }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `coverage_percent` محاسبهشده است: `insurance_share_rials / service_base_rials × 100`.
|
||||
- `allowed_transitions` از `Claim::TRANSITIONS` میآید؛ پنل دکمهها را از همین میسازد و فهرست مجاز را hardcode نمیکند.
|
||||
- `logs` تاریخچهی کامل تغییر وضعیت از جدول `claim_status_logs` است (بهترتیب زمانی صعودی).
|
||||
|
||||
**Errors:** `404` پرونده بیمار یافت نشد یا متعلق به tenant دیگری است · `403` پروفایل یافت نشد.
|
||||
|
||||
## POST /api/v1/billing/claims/{uuid}/{action}
|
||||
انتقال وضعیت. `action` ∈ `submit|approve|reject|pay`. هر انتقال یک ردیف در `claim_status_logs` ثبت میکند (وضعیت مبدأ/مقصد، توضیح، کاربر، زمان).
|
||||
|
||||
| action | body | اثر |
|
||||
|--------|------|-----|
|
||||
| submit | `tracking_number` (اختیاری) | pending → submitted؛ شماره پرونده/پیگیری بیمه روی مطالبه ذخیره میشود |
|
||||
| approve | `approved_rials` (اختیاری) | submitted → approved (پیشفرض = کل ادعا) — باید `0 ≤ approved_rials ≤ total_claimed_rials` |
|
||||
| reject | `reason` (**الزامی**) | submitted → rejected |
|
||||
| pay | `paid_rials` (اختیاری) | approved → paid (پیشفرض = approved) — باید `0 ≤ paid_rials ≤ total_approved_rials` |
|
||||
|
||||
`note` (اختیاری) روی همهی اکشنها پذیرفته میشود و در تاریخچه ثبت میگردد؛ برای `reject` در نبودِ `note` خودِ `reason` ثبت میشود.
|
||||
|
||||
**Errors:** `422` انتقال نامعتبر، دلیل رد خالی، یا مبلغ `approved_rials`/`paid_rials` خارج از بازه (`field` در پاسخ) · `404` مطالبه یافت نشد.
|
||||
|
||||
> اعتبارسنجی انتقال سمت **سرور** انجام میشود (`Claim::TRANSITIONS` منبع حقیقت است)؛ مخفیکردن دکمه در UI کافی نیست.
|
||||
|
||||
## GET /api/v1/billing/reports/insurance-debt
|
||||
گزارش بدهی بیمهها برای tenant (group بر اساس بیمه).
|
||||
|
||||
|
||||
@@ -367,7 +367,9 @@ entity جاری از `#[CurrentUser]` resolve میشود: نقش `ROLE_DOCTOR
|
||||
|
||||
## TenantInsurance — قراردادهای بیمهی tenant (فاز ۱ سیستم صورتحساب)
|
||||
|
||||
قرارداد یک پزشک/کلینیک با یک بیمه: درصد پوشش، فرانشیز، سقف تعهد سالانه، نسخهبندی و وضعیت فعال. مبنای محاسبهی سهم در سیستم صورتحساب (`docs/architecture/insurance-billing-system.md`). tenant از `#[CurrentUser]` (`ROLE_DOCTOR`→doctor، `ROLE_CLINIC`→clinic). جدول `tenant_insurances`.
|
||||
قرارداد یک پزشک/کلینیک با یک بیمه: درصد پوشش، فرانشیز، سقف تعهد سالانه، نسخهبندی و وضعیت فعال. مبنای محاسبهی سهم در سیستم صورتحساب (`docs/architecture/insurance-billing-system.md`). جدول `tenant_insurances`.
|
||||
|
||||
tenant از `#[CurrentUser]` با `App\Patient\Security\PatientRecordScopeResolver` resolve میشود — همان رزولور پروندهها و صورتحسابها، تا قرارداد بیمه و صورتحسابی که از آن ساخته میشود هرگز به دو محیط متفاوت نیفتند. محیط فعال (`UserActiveContext`) تعیینکننده است، نه صرفاً ترتیب نقشها؛ مالک کلینیکی که خودش پزشک هم هست، قراردادهای **کلینیک** خود را میبیند.
|
||||
|
||||
### GET `/api/v1/billing/tenant-insurances`
|
||||
لیست قراردادهای tenant جاری — **آخرین نسخهٔ هر بیمه، فعال یا غیرفعال** (برای toggle فعال/غیرفعال در UI مدیریت بیمه). `insurance_kind` = `kind` قرارداد در صورت تعیین، وگرنه نوع بیمه از کاتالوگ.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Claim tracking number + status history, so the claims dashboard can show who moved
|
||||
* a claim, when, and under which insurer reference.
|
||||
*/
|
||||
final class Version20260718193940 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add claims.tracking_number and the claim_status_logs table';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE TABLE claim_status_logs ('
|
||||
. 'id INT AUTO_INCREMENT NOT NULL, '
|
||||
. 'uuid VARCHAR(36) NOT NULL, '
|
||||
. 'claim_id INT NOT NULL, '
|
||||
. 'from_status VARCHAR(15) DEFAULT NULL, '
|
||||
. 'to_status VARCHAR(15) NOT NULL, '
|
||||
. 'note LONGTEXT DEFAULT NULL, '
|
||||
. 'created_by_id INT DEFAULT NULL, '
|
||||
. 'created_by_name VARCHAR(120) DEFAULT NULL, '
|
||||
. 'created_at INT NOT NULL, '
|
||||
. 'UNIQUE INDEX UNIQ_A83E863D17F50A6 (uuid), '
|
||||
. 'INDEX idx_claim_status_log_claim (claim_id), '
|
||||
. 'PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
|
||||
|
||||
$this->addSql('ALTER TABLE claims ADD tracking_number VARCHAR(60) DEFAULT NULL');
|
||||
|
||||
// Backfill an approximate history for existing claims from the timestamps we
|
||||
// already store, so the timeline is not blank for pre-existing data.
|
||||
$this->addSql("INSERT INTO claim_status_logs (uuid, claim_id, from_status, to_status, note, created_at) "
|
||||
. "SELECT UUID(), id, NULL, 'pending', 'ایجاد مطالبه', created_at FROM claims");
|
||||
|
||||
$this->addSql("INSERT INTO claim_status_logs (uuid, claim_id, from_status, to_status, note, created_at) "
|
||||
. "SELECT UUID(), id, 'pending', 'submitted', NULL, submitted_at "
|
||||
. "FROM claims WHERE submitted_at IS NOT NULL");
|
||||
|
||||
$this->addSql("INSERT INTO claim_status_logs (uuid, claim_id, from_status, to_status, note, created_at) "
|
||||
. "SELECT UUID(), id, 'submitted', status, reject_reason, settled_at "
|
||||
. "FROM claims WHERE settled_at IS NOT NULL AND status IN ('rejected', 'paid')");
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP TABLE claim_status_logs');
|
||||
$this->addSql('ALTER TABLE claims DROP tracking_number');
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace App\Billing\Controller;
|
||||
use App\Auth\Entity\User;
|
||||
use App\Billing\Entity\Claim;
|
||||
use App\Billing\Repository\ClaimRepository;
|
||||
use App\Billing\Repository\ClaimStatusLogRepository;
|
||||
use App\Billing\Repository\InvoiceItemRepository;
|
||||
use App\Billing\Repository\InvoiceRepository;
|
||||
use App\Billing\Service\ClaimService;
|
||||
@@ -35,6 +36,7 @@ class BillingController extends BaseController
|
||||
private readonly PatientSessionRepository $sessionRepo,
|
||||
private readonly PatientRecordRepository $recordRepo,
|
||||
private readonly InsuranceRepository $insuranceRepo,
|
||||
private readonly ClaimStatusLogRepository $statusLogRepo,
|
||||
private readonly PatientRecordScopeResolver $scopeResolver,
|
||||
) {}
|
||||
|
||||
@@ -279,6 +281,120 @@ class BillingController extends BaseController
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* نمای سطحاول داشبورد مطالبات: یک ردیف بهازای هر بیمار با جمعهای تجمیعی.
|
||||
* فیلترها همان فیلترهای مطالبهاند و روی count هم اعمال میشوند.
|
||||
*/
|
||||
#[Route('/api/v1/billing/claims/by-patient', methods: ['GET'])]
|
||||
public function claimsByPatient(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$filters = $this->claimFilters($request);
|
||||
$page = max(1, (int) $request->query->get('page', 1));
|
||||
$limit = min(100, max(1, (int) $request->query->get('limit', 20)));
|
||||
$sort = (string) $request->query->get('sort', 'last_activity_at');
|
||||
$dir = (string) $request->query->get('dir', 'desc');
|
||||
|
||||
$rows = $this->claimRepo->aggregateByPatient($entityType, $entityId, $filters, $sort, $dir, $page, $limit);
|
||||
$total = $this->claimRepo->countPatientsWithClaims($entityType, $entityId, $filters);
|
||||
|
||||
return $this->paginated($rows, $total, $page, $limit);
|
||||
}
|
||||
|
||||
/** جزئیات کامل مطالبات یک بیمار، بههمراه تاریخچهی تغییر وضعیت هر مطالبه. */
|
||||
#[Route('/api/v1/billing/claims/by-patient/{patientUuid}', methods: ['GET'])]
|
||||
public function claimsForPatient(string $patientUuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
if ($entityId === null) {
|
||||
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'پروفایل یافت نشد', 403);
|
||||
}
|
||||
|
||||
$record = $this->recordRepo->findByUuid($patientUuid);
|
||||
if ($record === null || $record->getEntityType() !== $entityType || $record->getEntityId() !== $entityId) {
|
||||
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'پرونده بیمار یافت نشد', 404);
|
||||
}
|
||||
|
||||
$rows = $this->claimRepo->detailsForPatient($entityType, $entityId, (int) $record->getId(), $this->claimFilters($request));
|
||||
$timelines = $this->statusLogRepo->timelinesForClaims(array_map(static fn(array $r) => (int) $r['claim_id'], $rows));
|
||||
|
||||
$insuranceNames = $this->insuranceNamesFor(array_map(static fn(array $r) => (int) $r['insurance_id'], $rows));
|
||||
|
||||
$items = array_map(function (array $r) use ($timelines, $insuranceNames) {
|
||||
$claimed = (int) $r['total_claimed_rials'];
|
||||
$base = (int) $r['service_base_rials'];
|
||||
|
||||
return [
|
||||
'uuid' => $r['uuid'],
|
||||
'invoice_uuid' => $r['invoice_uuid'],
|
||||
'visit_date' => $r['visit_date'] !== null ? (int) $r['visit_date'] : null,
|
||||
'doctor_name' => $r['doctor_name'],
|
||||
'insurance_id' => (int) $r['insurance_id'],
|
||||
'insurance_name' => $insuranceNames[(int) $r['insurance_id']] ?? null,
|
||||
'insurance_kind' => $r['insurance_kind'],
|
||||
'service_base_rials' => $base,
|
||||
'coverage_percent' => $base > 0 ? round($claimed * 100 / $base, 2) : 0.0,
|
||||
'insurance_share_rials'=> $claimed,
|
||||
'patient_share_rials' => (int) $r['patient_share_rials'],
|
||||
'total_approved_rials' => $r['total_approved_rials'] !== null ? (int) $r['total_approved_rials'] : null,
|
||||
'total_paid_rials' => $r['total_paid_rials'] !== null ? (int) $r['total_paid_rials'] : null,
|
||||
'status' => $r['status'],
|
||||
'tracking_number' => $r['tracking_number'],
|
||||
'reject_reason' => $r['reject_reason'],
|
||||
'submitted_at' => $r['submitted_at'] !== null ? (int) $r['submitted_at'] : null,
|
||||
'settled_at' => $r['settled_at'] !== null ? (int) $r['settled_at'] : null,
|
||||
'created_at' => (int) $r['created_at'],
|
||||
'allowed_transitions' => Claim::transitionsFrom($r['status']),
|
||||
'logs' => $timelines[(int) $r['claim_id']] ?? [],
|
||||
];
|
||||
}, $rows);
|
||||
|
||||
return $this->success([
|
||||
'patient' => [
|
||||
'uuid' => $record->getUser()->getUuid(),
|
||||
'record_uuid' => $record->getUuid(),
|
||||
'full_name' => $record->getUser()->getRealName(),
|
||||
'mobile' => $record->getUser()->getMobileNumber(),
|
||||
'national_code' => $record->getUser()->getNationalCode(),
|
||||
],
|
||||
'claims' => $items,
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param int[] $ids @return array<int, string> */
|
||||
private function insuranceNamesFor(array $ids): array
|
||||
{
|
||||
$unique = array_values(array_unique($ids));
|
||||
if ($unique === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$names = [];
|
||||
foreach ($this->insuranceRepo->findBy(['id' => $unique]) as $insurance) {
|
||||
$names[$insurance->getId()] = $insurance->getName();
|
||||
}
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function claimFilters(Request $request): array
|
||||
{
|
||||
return [
|
||||
'status' => $request->query->get('status') ?: null,
|
||||
'insurance_id' => $request->query->get('insurance_id') ?: null,
|
||||
'doctor_id' => $request->query->get('doctor_id') ?: null,
|
||||
'payment_status' => $request->query->get('payment_status') ?: null,
|
||||
'from' => $request->query->get('from') ?: null,
|
||||
'to' => $request->query->get('to') ?: null,
|
||||
'search' => $request->query->get('search') ?: null,
|
||||
];
|
||||
}
|
||||
|
||||
#[Route('/api/v1/billing/claims/{uuid}/{action}', methods: ['POST'], requirements: ['action' => 'submit|approve|reject|pay'])]
|
||||
public function transitionClaim(string $uuid, string $action, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
@@ -296,10 +412,6 @@ class BillingController extends BaseController
|
||||
'pay' => Claim::STATUS_PAID,
|
||||
};
|
||||
|
||||
if ($action === 'reject' && trim($data['reason'] ?? '') === '') {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'دلیل رد الزامی است', 422);
|
||||
}
|
||||
|
||||
// Bound the financial figures: approved/paid cannot be negative, approved
|
||||
// cannot exceed the claimed total, and paid cannot exceed approved.
|
||||
if ($action === 'approve' && isset($data['approved_rials'])) {
|
||||
@@ -317,10 +429,12 @@ class BillingController extends BaseController
|
||||
}
|
||||
|
||||
$this->claimService->transition($claim, $target, [
|
||||
'approved_rials' => isset($data['approved_rials']) ? (int) $data['approved_rials'] : null,
|
||||
'paid_rials' => isset($data['paid_rials']) ? (int) $data['paid_rials'] : null,
|
||||
'reason' => trim($data['reason'] ?? ''),
|
||||
]);
|
||||
'approved_rials' => isset($data['approved_rials']) ? (int) $data['approved_rials'] : null,
|
||||
'paid_rials' => isset($data['paid_rials']) ? (int) $data['paid_rials'] : null,
|
||||
'reason' => trim($data['reason'] ?? ''),
|
||||
'tracking_number' => isset($data['tracking_number']) ? trim((string) $data['tracking_number']) : null,
|
||||
'note' => isset($data['note']) ? trim((string) $data['note']) : null,
|
||||
], $user);
|
||||
|
||||
return $this->success(['data' => $this->enrichClaims([$claim])[0]]);
|
||||
}
|
||||
|
||||
@@ -66,6 +66,10 @@ class Claim
|
||||
#[ORM\Column(name: 'reject_reason', type: 'text', nullable: true)]
|
||||
private ?string $rejectReason = null;
|
||||
|
||||
/** شماره پرونده/پیگیری نزد بیمهگر — هنگام ارسال وارد میشود. */
|
||||
#[ORM\Column(name: 'tracking_number', type: 'string', length: 60, nullable: true)]
|
||||
private ?string $trackingNumber = null;
|
||||
|
||||
#[ORM\Column(name: 'submitted_at', type: 'integer', nullable: true)]
|
||||
private ?int $submittedAt = null;
|
||||
|
||||
@@ -119,6 +123,41 @@ class Claim
|
||||
return in_array($status, self::TRANSITIONS[$this->status] ?? [], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* انتقالهای مجاز از وضعیت فعلی. پنل دکمهها را از همین میسازد تا فهرست
|
||||
* مجاز فقط یکجا تعریف شده باشد.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public function allowedTransitions(): array
|
||||
{
|
||||
return self::transitionsFrom($this->status);
|
||||
}
|
||||
|
||||
/**
|
||||
* همان جدول انتقال، برای مسیرهایی که ردیف خام (array hydration) دارند و
|
||||
* موجودیت را هیدریت نمیکنند.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
public static function transitionsFrom(string $status): array
|
||||
{
|
||||
return self::TRANSITIONS[$status] ?? [];
|
||||
}
|
||||
|
||||
public function getTrackingNumber(): ?string { return $this->trackingNumber; }
|
||||
public function getRejectReason(): ?string { return $this->rejectReason; }
|
||||
public function getSubmittedAt(): ?int { return $this->submittedAt; }
|
||||
public function getSettledAt(): ?int { return $this->settledAt; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
|
||||
public function setTrackingNumber(?string $v): self
|
||||
{
|
||||
$this->trackingNumber = $v !== null && trim($v) !== '' ? trim($v) : null;
|
||||
$this->updatedAt = time();
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function submit(): void
|
||||
{
|
||||
$this->status = self::STATUS_SUBMITTED;
|
||||
@@ -162,6 +201,8 @@ class Claim
|
||||
'total_paid_rials' => $this->totalPaidRials,
|
||||
'status' => $this->status,
|
||||
'reject_reason' => $this->rejectReason,
|
||||
'tracking_number' => $this->trackingNumber,
|
||||
'allowed_transitions' => $this->allowedTransitions(),
|
||||
'submitted_at' => $this->submittedAt,
|
||||
'settled_at' => $this->settledAt,
|
||||
'created_at' => $this->createdAt,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Entity;
|
||||
|
||||
use App\Billing\Repository\ClaimStatusLogRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* تاریخچهی تغییر وضعیت یک مطالبه.
|
||||
*
|
||||
* وضعیت روی خودِ Claim فقط «آخرین حالت» است؛ پیگیری پروندهی بیمه نیاز دارد بداند
|
||||
* چه کسی، کِی و با چه توضیحی آن را جابهجا کرده است.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: ClaimStatusLogRepository::class)]
|
||||
#[ORM\Table(name: 'claim_status_logs')]
|
||||
#[ORM\Index(columns: ['claim_id'], name: 'idx_claim_status_log_claim')]
|
||||
class ClaimStatusLog
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(name: 'claim_id', type: 'integer')]
|
||||
private int $claimId;
|
||||
|
||||
/** null فقط برای ردیف ساخت اولیه. */
|
||||
#[ORM\Column(name: 'from_status', type: 'string', length: 15, nullable: true)]
|
||||
private ?string $fromStatus = null;
|
||||
|
||||
#[ORM\Column(name: 'to_status', type: 'string', length: 15)]
|
||||
private string $toStatus;
|
||||
|
||||
#[ORM\Column(type: 'text', nullable: true)]
|
||||
private ?string $note = null;
|
||||
|
||||
/** null یعنی سیستمی (backfill یا اتوماسیون). */
|
||||
#[ORM\Column(name: 'created_by_id', type: 'integer', nullable: true)]
|
||||
private ?int $createdById = null;
|
||||
|
||||
#[ORM\Column(name: 'created_by_name', type: 'string', length: 120, nullable: true)]
|
||||
private ?string $createdByName = null;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
public function __construct(int $claimId, ?string $fromStatus, string $toStatus)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->claimId = $claimId;
|
||||
$this->fromStatus = $fromStatus;
|
||||
$this->toStatus = $toStatus;
|
||||
$this->createdAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getClaimId(): int { return $this->claimId; }
|
||||
public function getToStatus(): string { return $this->toStatus; }
|
||||
|
||||
public function setNote(?string $note): self
|
||||
{
|
||||
$this->note = $note !== null && trim($note) !== '' ? trim($note) : null;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setActor(?int $userId, ?string $name): self
|
||||
{
|
||||
$this->createdById = $userId;
|
||||
$this->createdByName = $name;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setCreatedAt(int $at): self
|
||||
{
|
||||
$this->createdAt = $at;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'from_status' => $this->fromStatus,
|
||||
'to_status' => $this->toStatus,
|
||||
'note' => $this->note,
|
||||
'by' => $this->createdByName,
|
||||
'at' => $this->createdAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,216 @@ class ClaimRepository extends ServiceEntityRepository
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* تجمیع مطالبات بر اساس بیمار — نمای سطحاول داشبورد.
|
||||
*
|
||||
* مبالغ خدمات/سهم بیمار از صورتحسابهای **یکتا** جمع میشوند، نه از مطالبات؛ یک
|
||||
* صورتحساب میتواند دو مطالبه (پایه و مکمل) داشته باشد و جمعزدن از سمت مطالبه
|
||||
* مبلغ خدمات را دوبار میشمرد.
|
||||
*
|
||||
* @param array<string, mixed> $filters
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function aggregateByPatient(string $entityType, int $entityId, array $filters, string $sort, string $dir, int $page, int $limit): array
|
||||
{
|
||||
[$where, $params] = $this->patientAggregateFilters($filters);
|
||||
|
||||
$orderBy = match ($sort) {
|
||||
'claims_count' => 'claims_count',
|
||||
'total_services_rials' => 'total_services_rials',
|
||||
'total_insurance_rials' => 'total_insurance_rials',
|
||||
'last_activity_at' => 'last_activity_at',
|
||||
default => 'full_name',
|
||||
};
|
||||
$direction = strtolower($dir) === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
// LIMIT/OFFSET بهصورت مقدار درج میشوند: MariaDB پارامتر رشتهای در LIMIT نمیپذیرد.
|
||||
// هر دو از قبل به int تبدیل شدهاند، پس تزریقی ممکن نیست.
|
||||
$offset = ($page - 1) * $limit;
|
||||
$sql = $this->patientAggregateSql($where)
|
||||
. " ORDER BY {$orderBy} {$direction} LIMIT {$limit} OFFSET {$offset}";
|
||||
|
||||
$params['type'] = $entityType;
|
||||
$params['id'] = $entityId;
|
||||
|
||||
$rows = $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchAllAssociative();
|
||||
|
||||
return array_map(static function (array $r): array {
|
||||
$statuses = array_filter(explode(',', (string) $r['statuses']));
|
||||
|
||||
return [
|
||||
'patient_uuid' => $r['patient_uuid'],
|
||||
'record_uuid' => $r['record_uuid'],
|
||||
'full_name' => $r['full_name'],
|
||||
'mobile' => $r['mobile'],
|
||||
'national_code' => $r['national_code'],
|
||||
'claims_count' => (int) $r['claims_count'],
|
||||
'total_services_rials' => (int) $r['total_services_rials'],
|
||||
'total_insurance_rials' => (int) $r['total_insurance_rials'],
|
||||
'total_patient_rials' => (int) $r['total_patient_rials'],
|
||||
'total_approved_rials' => (int) $r['total_approved_rials'],
|
||||
'total_paid_rials' => (int) $r['total_paid_rials'],
|
||||
'overall_status' => count($statuses) === 1 ? reset($statuses) : 'mixed',
|
||||
'last_activity_at' => (int) $r['last_activity_at'],
|
||||
];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
public function countPatientsWithClaims(string $entityType, int $entityId, array $filters): int
|
||||
{
|
||||
[$where, $params] = $this->patientAggregateFilters($filters);
|
||||
$params['type'] = $entityType;
|
||||
$params['id'] = $entityId;
|
||||
|
||||
$sql = 'SELECT COUNT(*) FROM (' . $this->patientAggregateSql($where) . ') agg';
|
||||
|
||||
return (int) $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchOne();
|
||||
}
|
||||
|
||||
private function patientAggregateSql(string $where): string
|
||||
{
|
||||
return <<<SQL
|
||||
WITH claim_map AS (
|
||||
SELECT c.id AS claim_id, MIN(inv.id) AS invoice_id, MIN(inv.patient_record_id) AS record_id
|
||||
FROM claims c
|
||||
JOIN claim_items ci ON ci.claim_id = c.id
|
||||
JOIN invoice_items ii ON ii.id = ci.invoice_item_id
|
||||
JOIN invoices inv ON inv.id = ii.invoice_id
|
||||
WHERE c.entity_type = :type AND c.entity_id = :id
|
||||
GROUP BY c.id
|
||||
)
|
||||
SELECT
|
||||
u.uuid AS patient_uuid,
|
||||
pr.uuid AS record_uuid,
|
||||
u.real_name AS full_name,
|
||||
u.mobile_number AS mobile,
|
||||
u.national_code AS national_code,
|
||||
COUNT(DISTINCT c.id) AS claims_count,
|
||||
COALESCE(SUM(c.total_claimed_rials), 0) AS total_insurance_rials,
|
||||
COALESCE(SUM(c.total_approved_rials), 0) AS total_approved_rials,
|
||||
COALESCE(SUM(c.total_paid_rials), 0) AS total_paid_rials,
|
||||
COALESCE((
|
||||
SELECT SUM(i2.total_rials) FROM invoices i2
|
||||
WHERE i2.id IN (SELECT DISTINCT cm2.invoice_id FROM claim_map cm2 WHERE cm2.record_id = pr.id)
|
||||
), 0) AS total_services_rials,
|
||||
COALESCE((
|
||||
SELECT SUM(i3.patient_rials) FROM invoices i3
|
||||
WHERE i3.id IN (SELECT DISTINCT cm3.invoice_id FROM claim_map cm3 WHERE cm3.record_id = pr.id)
|
||||
), 0) AS total_patient_rials,
|
||||
GROUP_CONCAT(DISTINCT c.status) AS statuses,
|
||||
MAX(c.updated_at) AS last_activity_at
|
||||
FROM claim_map cm
|
||||
JOIN claims c ON c.id = cm.claim_id
|
||||
JOIN invoices inv ON inv.id = cm.invoice_id
|
||||
JOIN patient_records pr ON pr.id = cm.record_id
|
||||
JOIN users u ON u.id = pr.user_id
|
||||
{$where}
|
||||
GROUP BY pr.id, u.uuid, pr.uuid, u.real_name, u.mobile_number, u.national_code
|
||||
SQL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $filters
|
||||
* @return array{0: string, 1: array<string, mixed>}
|
||||
*/
|
||||
private function patientAggregateFilters(array $filters): array
|
||||
{
|
||||
$conditions = [];
|
||||
$params = [];
|
||||
|
||||
if (!empty($filters['status'])) {
|
||||
$conditions[] = 'c.status = :status';
|
||||
$params['status'] = $filters['status'];
|
||||
}
|
||||
if (!empty($filters['insurance_id'])) {
|
||||
$conditions[] = 'c.insurance_id = :insId';
|
||||
$params['insId'] = (int) $filters['insurance_id'];
|
||||
}
|
||||
if (!empty($filters['from'])) {
|
||||
$conditions[] = 'c.created_at >= :from';
|
||||
$params['from'] = (int) $filters['from'];
|
||||
}
|
||||
if (!empty($filters['to'])) {
|
||||
$conditions[] = 'c.created_at <= :to';
|
||||
$params['to'] = (int) $filters['to'];
|
||||
}
|
||||
if (!empty($filters['doctor_id'])) {
|
||||
$conditions[] = 'EXISTS (SELECT 1 FROM patient_sessions ps '
|
||||
. 'JOIN appointments a ON a.id = ps.appointment_id '
|
||||
. 'WHERE ps.id = inv.patient_session_id AND a.doctor_id = :docId)';
|
||||
$params['docId'] = (int) $filters['doctor_id'];
|
||||
}
|
||||
if (!empty($filters['payment_status'])) {
|
||||
$conditions[] = $filters['payment_status'] === 'paid'
|
||||
? 'c.status = \'paid\''
|
||||
: 'c.status <> \'paid\'';
|
||||
}
|
||||
if (!empty($filters['search'])) {
|
||||
$conditions[] = '(u.real_name LIKE :search OR u.mobile_number LIKE :search OR u.national_code LIKE :search)';
|
||||
$params['search'] = '%' . trim((string) $filters['search']) . '%';
|
||||
}
|
||||
|
||||
return [$conditions === [] ? '' : 'WHERE ' . implode(' AND ', $conditions), $params];
|
||||
}
|
||||
|
||||
/**
|
||||
* مطالبات یک بیمار با جزئیات نمایشی (پزشک، سرویس، تاریخ مراجعه، سهمها).
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function detailsForPatient(string $entityType, int $entityId, int $recordId, array $filters): array
|
||||
{
|
||||
[$where, $params] = $this->patientAggregateFilters($filters);
|
||||
$where = $where === '' ? 'WHERE pr.id = :recordId' : $where . ' AND pr.id = :recordId';
|
||||
|
||||
$params['type'] = $entityType;
|
||||
$params['id'] = $entityId;
|
||||
$params['recordId'] = $recordId;
|
||||
|
||||
$sql = <<<SQL
|
||||
WITH claim_map AS (
|
||||
SELECT c.id AS claim_id, MIN(inv.id) AS invoice_id, MIN(inv.patient_record_id) AS record_id
|
||||
FROM claims c
|
||||
JOIN claim_items ci ON ci.claim_id = c.id
|
||||
JOIN invoice_items ii ON ii.id = ci.invoice_item_id
|
||||
JOIN invoices inv ON inv.id = ii.invoice_id
|
||||
WHERE c.entity_type = :type AND c.entity_id = :id
|
||||
GROUP BY c.id
|
||||
)
|
||||
SELECT
|
||||
c.id AS claim_id,
|
||||
c.uuid,
|
||||
c.insurance_id,
|
||||
c.insurance_kind,
|
||||
c.status,
|
||||
c.total_claimed_rials,
|
||||
c.total_approved_rials,
|
||||
c.total_paid_rials,
|
||||
c.reject_reason,
|
||||
c.tracking_number,
|
||||
c.submitted_at,
|
||||
c.settled_at,
|
||||
c.created_at,
|
||||
inv.uuid AS invoice_uuid,
|
||||
inv.total_rials AS service_base_rials,
|
||||
inv.patient_rials AS patient_share_rials,
|
||||
ps.session_at AS visit_date,
|
||||
d.name AS doctor_name
|
||||
FROM claim_map cm
|
||||
JOIN claims c ON c.id = cm.claim_id
|
||||
JOIN invoices inv ON inv.id = cm.invoice_id
|
||||
JOIN patient_records pr ON pr.id = cm.record_id
|
||||
JOIN users u ON u.id = pr.user_id
|
||||
LEFT JOIN patient_sessions ps ON ps.id = inv.patient_session_id
|
||||
LEFT JOIN appointments a ON a.id = ps.appointment_id
|
||||
LEFT JOIN doctors d ON d.id = a.doctor_id
|
||||
{$where}
|
||||
ORDER BY c.created_at DESC, c.id DESC
|
||||
SQL;
|
||||
|
||||
return $this->getEntityManager()->getConnection()->executeQuery($sql, $params)->fetchAllAssociative();
|
||||
}
|
||||
|
||||
/** آیا برای این صورتحساب از قبل مطالبهای ساخته شده؟ (از طریق آیتمهای صورتحساب) */
|
||||
public function existsForInvoice(int $invoiceId): bool
|
||||
{
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Billing\Repository;
|
||||
|
||||
use App\Billing\Entity\ClaimStatusLog;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
class ClaimStatusLogRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, ClaimStatusLog::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* تاریخچهی چند مطالبه در یک رفتوآمد، گروهبندیشده بر اساس claim_id.
|
||||
*
|
||||
* @param int[] $claimIds
|
||||
* @return array<int, array<int, array<string, mixed>>>
|
||||
*/
|
||||
public function timelinesForClaims(array $claimIds): array
|
||||
{
|
||||
if ($claimIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$logs = $this->createQueryBuilder('l')
|
||||
->where('l.claimId IN (:ids)')
|
||||
->setParameter('ids', $claimIds)
|
||||
->orderBy('l.createdAt', 'ASC')
|
||||
->addOrderBy('l.id', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$grouped = [];
|
||||
foreach ($logs as $log) {
|
||||
$grouped[$log->getClaimId()][] = $log->toArray();
|
||||
}
|
||||
|
||||
return $grouped;
|
||||
}
|
||||
|
||||
public function save(ClaimStatusLog $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
if ($flush) {
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,10 @@ use App\Billing\Contract\ClaimSubmitterInterface;
|
||||
use App\Billing\Entity\Claim;
|
||||
use App\Billing\Entity\ClaimItem;
|
||||
use App\Billing\Entity\Invoice;
|
||||
use App\Billing\Entity\ClaimStatusLog;
|
||||
use App\Billing\Repository\ClaimRepository;
|
||||
use App\Billing\Repository\ClaimStatusLogRepository;
|
||||
use App\Auth\Entity\User;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
@@ -15,6 +18,7 @@ class ClaimService
|
||||
public function __construct(
|
||||
private readonly ClaimRepository $claimRepo,
|
||||
private readonly ClaimSubmitterInterface $submitter,
|
||||
private readonly ClaimStatusLogRepository $statusLogRepo,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -59,6 +63,12 @@ class ClaimService
|
||||
}
|
||||
$this->claimRepo->getEntityManager()->flush();
|
||||
|
||||
// بعد از flush تا id مطالبه موجود باشد.
|
||||
foreach ($claims as $claim) {
|
||||
$this->logTransition($claim, null, $claim->getStatus(), 'ایجاد مطالبه', null);
|
||||
}
|
||||
$this->claimRepo->getEntityManager()->flush();
|
||||
|
||||
return $claims;
|
||||
}
|
||||
|
||||
@@ -81,7 +91,7 @@ class ClaimService
|
||||
return $hasShare ? $claim : null;
|
||||
}
|
||||
|
||||
public function transition(Claim $claim, string $target, array $opts = []): void
|
||||
public function transition(Claim $claim, string $target, array $opts = [], ?User $actor = null): void
|
||||
{
|
||||
if (!$claim->canTransitionTo($target)) {
|
||||
throw new AppException(
|
||||
@@ -91,23 +101,43 @@ class ClaimService
|
||||
);
|
||||
}
|
||||
|
||||
if ($target === Claim::STATUS_REJECTED && trim((string) ($opts['reason'] ?? '')) === '') {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'دلیل رد الزامی است', 422, 'reason');
|
||||
}
|
||||
|
||||
$from = $claim->getStatus();
|
||||
|
||||
match ($target) {
|
||||
Claim::STATUS_SUBMITTED => $this->doSubmit($claim),
|
||||
Claim::STATUS_SUBMITTED => $this->doSubmit($claim, $opts['tracking_number'] ?? null),
|
||||
Claim::STATUS_APPROVED => $claim->approve($opts['approved_rials'] ?? null),
|
||||
Claim::STATUS_REJECTED => $claim->reject($opts['reason'] ?? ''),
|
||||
Claim::STATUS_PAID => $claim->pay($opts['paid_rials'] ?? null),
|
||||
default => throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'وضعیت نامعتبر', 422),
|
||||
};
|
||||
|
||||
$this->claimRepo->save($claim);
|
||||
$this->claimRepo->save($claim, false);
|
||||
$this->logTransition($claim, $from, $target, $opts['note'] ?? $opts['reason'] ?? null, $actor);
|
||||
$this->claimRepo->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
private function doSubmit(Claim $claim): void
|
||||
private function logTransition(Claim $claim, ?string $from, string $to, ?string $note, ?User $actor): void
|
||||
{
|
||||
$log = (new ClaimStatusLog((int) $claim->getId(), $from, $to))
|
||||
->setNote($note)
|
||||
->setActor($actor?->getId(), $actor?->getRealName() ?? $actor?->getMobileNumber());
|
||||
|
||||
$this->statusLogRepo->save($log, false);
|
||||
}
|
||||
|
||||
private function doSubmit(Claim $claim, ?string $trackingNumber): void
|
||||
{
|
||||
$result = $this->submitter->submit($claim);
|
||||
if (!$result->success) {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, $result->errorMessage ?? 'ارسال مطالبه ناموفق بود', 422);
|
||||
}
|
||||
$claim->submit();
|
||||
if ($trackingNumber !== null) {
|
||||
$claim->setTrackingNumber((string) $trackingNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Billing;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Billing\Entity\Claim;
|
||||
use App\Billing\Entity\ClaimItem;
|
||||
use App\Billing\Entity\Invoice;
|
||||
use App\Billing\Entity\InvoiceItem;
|
||||
use App\Billing\ValueObject\ShareBreakdown;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* GET /api/v1/billing/claims/by-patient — the claims dashboard's first level.
|
||||
*
|
||||
* A claim reaches its patient only through claim_item → invoice_item → invoice →
|
||||
* patient_record, and one invoice can carry both a base and a supplementary claim.
|
||||
* These tests pin the aggregation against double-counting the service amount.
|
||||
*/
|
||||
class ClaimsByPatientTest extends ApiTestCase
|
||||
{
|
||||
private User $owner;
|
||||
private Doctor $doctor;
|
||||
private PatientRecord $record;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$this->doctor = new Doctor($this->owner, 'دکتر تست');
|
||||
$this->em->persist($this->doctor);
|
||||
$this->em->flush();
|
||||
|
||||
$patient = $this->createUser(['ROLE_USER']);
|
||||
$this->record = new PatientRecord('doctor', $this->doctor->getId(), $patient, 'doctor', $this->doctor->getId());
|
||||
$this->em->persist($this->record);
|
||||
$this->em->flush();
|
||||
}
|
||||
|
||||
/** Invoice of $total split into insurance/patient shares, with its claim(s). */
|
||||
private function invoiceWithClaims(int $total, int $baseShare, int $suppShare, array $statuses = ['pending']): Invoice
|
||||
{
|
||||
$patient = $total - $baseShare - $suppShare;
|
||||
|
||||
$invoice = new Invoice('doctor', $this->doctor->getId());
|
||||
$invoice->setPatientRecordId((int) $this->record->getId());
|
||||
$item = new InvoiceItem($invoice, 'جراحی', $total, 1, new ShareBreakdown($total, $baseShare, $suppShare, $patient));
|
||||
$invoice->addItem($item);
|
||||
$invoice->recalculateTotals();
|
||||
$this->em->persist($invoice);
|
||||
$this->em->persist($item);
|
||||
$this->em->flush();
|
||||
|
||||
foreach ($statuses as $i => $status) {
|
||||
$kind = $i === 0 ? Claim::KIND_BASE : Claim::KIND_SUPPLEMENTARY;
|
||||
$share = $i === 0 ? $baseShare : $suppShare;
|
||||
|
||||
$claim = new Claim('doctor', $this->doctor->getId(), 1 + $i, $kind);
|
||||
$claimItem = new ClaimItem($claim, (int) $item->getId(), $share);
|
||||
$claim->addItem($claimItem);
|
||||
if ($status !== Claim::STATUS_PENDING) {
|
||||
$claim->submit();
|
||||
}
|
||||
if ($status === Claim::STATUS_PAID) {
|
||||
$claim->approve($share);
|
||||
$claim->pay($share);
|
||||
}
|
||||
$this->em->persist($claim);
|
||||
$this->em->persist($claimItem);
|
||||
}
|
||||
$this->em->flush();
|
||||
|
||||
return $invoice;
|
||||
}
|
||||
|
||||
public function testAggregatesOneRowPerPatientWithConsistentShares(): void
|
||||
{
|
||||
$this->invoiceWithClaims(10_000_000, 7_000_000, 0);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/billing/claims/by-patient', $this->owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
self::assertCount(1, $res['data']);
|
||||
|
||||
$row = $res['data'][0];
|
||||
self::assertSame(1, $row['claims_count']);
|
||||
self::assertSame(10_000_000, $row['total_services_rials']);
|
||||
self::assertSame(7_000_000, $row['total_insurance_rials']);
|
||||
self::assertSame(3_000_000, $row['total_patient_rials']);
|
||||
self::assertSame('pending', $row['overall_status']);
|
||||
}
|
||||
|
||||
public function testServiceTotalIsNotDoubleCountedWhenAnInvoiceHasTwoClaims(): void
|
||||
{
|
||||
// پایه و مکمل روی یک صورتحساب: مبلغ خدمات باید یکبار شمرده شود.
|
||||
$this->invoiceWithClaims(10_000_000, 6_000_000, 2_000_000, ['pending', 'pending']);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/billing/claims/by-patient', $this->owner);
|
||||
$row = $res['data'][0];
|
||||
|
||||
self::assertSame(2, $row['claims_count']);
|
||||
self::assertSame(10_000_000, $row['total_services_rials']);
|
||||
self::assertSame(8_000_000, $row['total_insurance_rials']);
|
||||
self::assertSame(
|
||||
$row['total_services_rials'],
|
||||
$row['total_insurance_rials'] + $row['total_patient_rials'],
|
||||
);
|
||||
}
|
||||
|
||||
public function testOverallStatusIsMixedWhenClaimsDisagree(): void
|
||||
{
|
||||
$this->invoiceWithClaims(10_000_000, 6_000_000, 2_000_000, [Claim::STATUS_PAID, Claim::STATUS_PENDING]);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/billing/claims/by-patient', $this->owner);
|
||||
|
||||
self::assertSame('mixed', $res['data'][0]['overall_status']);
|
||||
}
|
||||
|
||||
public function testStatusFilterNarrowsTheAggregation(): void
|
||||
{
|
||||
$this->invoiceWithClaims(10_000_000, 7_000_000, 0);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/billing/claims/by-patient?status=paid', $this->owner);
|
||||
|
||||
self::assertSame(0, $res['meta']['totalRecords']);
|
||||
}
|
||||
|
||||
public function testDetailListsClaimsWithCoverageAndTimeline(): void
|
||||
{
|
||||
$this->invoiceWithClaims(10_000_000, 7_000_000, 0);
|
||||
|
||||
$res = $this->authJson('GET', '/api/v1/billing/claims/by-patient/' . $this->record->getUuid(), $this->owner);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
|
||||
$claim = $res['data']['claims'][0];
|
||||
// JSON یک float گِرد را به int تبدیل میکند؛ مقایسهی نوعمحور اینجا معنا ندارد.
|
||||
self::assertEquals(70, $claim['coverage_percent']);
|
||||
self::assertSame(7_000_000, $claim['insurance_share_rials']);
|
||||
self::assertSame(3_000_000, $claim['patient_share_rials']);
|
||||
self::assertSame(['submitted'], $claim['allowed_transitions']);
|
||||
}
|
||||
|
||||
public function testDetailRefusesARecordOfAnotherTenant(): void
|
||||
{
|
||||
$otherOwner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$otherDoctor = new Doctor($otherOwner, 'دکتر دیگر');
|
||||
$this->em->persist($otherDoctor);
|
||||
$this->em->flush();
|
||||
|
||||
$this->authJson('GET', '/api/v1/billing/claims/by-patient/' . $this->record->getUuid(), $otherOwner);
|
||||
|
||||
self::assertSame(404, $this->responseCode());
|
||||
}
|
||||
|
||||
public function testSubmitStoresTheTrackingNumberAndLogsTheTransition(): void
|
||||
{
|
||||
$this->invoiceWithClaims(10_000_000, 7_000_000, 0);
|
||||
$detail = $this->authJson('GET', '/api/v1/billing/claims/by-patient/' . $this->record->getUuid(), $this->owner);
|
||||
$uuid = $detail['data']['claims'][0]['uuid'];
|
||||
|
||||
$this->authJson('POST', '/api/v1/billing/claims/' . $uuid . '/submit', $this->owner, [
|
||||
'tracking_number' => 'TM-1',
|
||||
]);
|
||||
self::assertSame(200, $this->responseCode());
|
||||
|
||||
$after = $this->authJson('GET', '/api/v1/billing/claims/by-patient/' . $this->record->getUuid(), $this->owner);
|
||||
$claim = $after['data']['claims'][0];
|
||||
|
||||
self::assertSame('TM-1', $claim['tracking_number']);
|
||||
self::assertSame('submitted', $claim['status']);
|
||||
self::assertSame('submitted', end($claim['logs'])['to_status']);
|
||||
}
|
||||
|
||||
public function testRejectWithoutAReasonIsRefused(): void
|
||||
{
|
||||
$this->invoiceWithClaims(10_000_000, 7_000_000, 0, [Claim::STATUS_SUBMITTED]);
|
||||
$detail = $this->authJson('GET', '/api/v1/billing/claims/by-patient/' . $this->record->getUuid(), $this->owner);
|
||||
$uuid = $detail['data']['claims'][0]['uuid'];
|
||||
|
||||
$this->authJson('POST', '/api/v1/billing/claims/' . $uuid . '/reject', $this->owner, []);
|
||||
|
||||
self::assertSame(422, $this->responseCode());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user