feat: integrate insurance coverage management for clinic services

- Updated NewSessionPage to calculate patient share based on insurance coverage rules.
- Refactored billing calculations to utilize new patientShareOf function for service items.
- Enhanced API documentation to reflect changes in service coverage structure.
- Implemented ServiceInsuranceModal for managing insurance coverage per service.
- Added UI components for displaying and editing insurance coverage details.
- Removed obsolete toggle switch styles and adjusted CSS for new components.
- Ensured backend endpoints support both service_item_id and service_item_uuid for flexibility.
This commit is contained in:
hamed
2026-06-24 04:23:50 +03:30
parent 253414ef3e
commit 27840da78d
11 changed files with 878 additions and 258 deletions
@@ -0,0 +1,181 @@
# اتصال «بیمه‌ی سرویس» در صفحه سرویس‌های کلینیک به سامانه‌ی واقعی پوشش بیمه و مطالبات
## پروژه
`clinicpro` (backend Symfony + admin React)
## زمینه
صفحه `https://clinic-pro.ddev.site/admin/clinic-services` هنگام تعریف سرویس فقط دو فیلد ساده‌ی روی خود `ServiceItem` را ست می‌کند (این بخش قبلاً با پرامپت `service-insurance-coverage.md` اضافه شده):
- `insurance_covered` (boolean) — «این خدمت شامل بیمه می‌شود»
- `insurance_price_rials` (int, nullable) — «قیمت با بیمه»
اما سامانه‌ی واقعی بیمه و مطالبات در پروژه چیز دیگری است و **به این دو فیلد وصل نیست**:
- `App\Insurance\Entity\TenantInsurance` — قرارداد بیمه‌ی فعال هر مطب/کلینیک با یک بیمه‌گر (پایه یا تکمیلی)، دارای `coverage_percent`، `franchise_rials`، `annual_ceiling_rials`.
- `App\Insurance\Entity\TenantServiceCoverage` — قاعده‌ی پوشش **به ازای هر بیمه‌گر × هر سرویس** (`covered`, `coverage_percent`, `franchise_rials`, `ceiling_rials`). همین جدول است که محاسبه‌ی سهم را تعیین می‌کند.
- `App\Insurance\ValueObject\CoverageRule` + `App\Billing\Service\BillingCalculator` — سهم بیمه‌ی پایه/مکمل و سهم بیمار را از روی همین قاعده محاسبه می‌کنند.
- `App\Billing\Service\ClaimService::createFromInvoice()`**مطالبات بیمه** را از `Invoice` می‌سازد؛ هر `ClaimItem` فقط وقتی ساخته می‌شود که `InvoiceItem` سهم بیمه‌ی مثبت داشته باشد (`getBaseInsuranceRials()` / `getSupplementaryRials()`).
نتیجه: سرویسی که در صفحه‌ی clinic-services «شامل بیمه» علامت خورده، **هیچ ردیفی در `TenantServiceCoverage` ندارد**، پس در `BillingCalculator` سهم بیمه‌اش صفر می‌شود و در `ClaimService` هیچ `ClaimItem` نمی‌سازد ⇒ در **مطالبات بیمه ظاهر نمی‌شود**. این همان شکافی است که این پرامپت می‌بندد.
> بافت ایران: بیمه‌گرها دو دسته‌اند — **پایه** (تأمین اجتماعی، سلامت، نیروهای مسلح، …) و **تکمیلی/مکمل** (دانا، آسیا، …). هر سرویس می‌تواند با هر بیمه‌گرِ فعالِ مطب درصد پوشش، فرانشیز و سقف متفاوت داشته باشد. مدل تک‌فیلدیِ `insurance_price_rials` این تنوع را پوشش نمی‌دهد؛ منبعِ حقیقت باید `TenantServiceCoverage` باشد.
## مشکل / هدف
هنگام ویرایش یک سرویس در صفحه‌ی clinic-services، کاربر باید بتواند **پوشش بیمه‌ی آن سرویس را به ازای هر بیمه‌گرِ فعال مطب** تعریف کند (`covered` + درصد پوشش + فرانشیز + سقف). این داده باید در `TenantServiceCoverage` نوشته شود تا مستقیماً وارد چرخه‌ی `BillingCalculator → Invoice → ClaimService` (مطالبات بیمه) شود.
سه endpoint از قبل وجود دارند و باید **بازاستفاده** شوند (نه ساختن endpoint جدید):
- `GET /api/v1/billing/tenant-insurances` → لیست قراردادهای بیمه‌ی فعال مطب.
- `GET /api/v1/billing/tenant-insurances/{uuid}/service-coverage` → پوشش‌های یک قرارداد.
- `PUT /api/v1/billing/tenant-insurances/{uuid}/service-coverage` → ست‌کردن پوشش یک سرویس برای آن قرارداد.
## فایل‌های مرتبط
| فایل | نقش |
|------|-----|
| `assets/admin/pages/ClinicServicesPage.tsx` | فرم ویرایش سرویس — محل افزودن بخش پوشش بیمه |
| `assets/admin/components/ServiceTariffModal.tsx` | الگوی موجود modalِ مرتبط با سرویس (برای سبک UI ردیف‌ها) |
| `src/Insurance/Controller/InsuranceController.php` | endpointهای `tenant-insurances` و `service-coverage` (خطوط ۲۹۹–۴۳۵) |
| `src/Insurance/Service/TenantInsuranceService.php` | `setServiceCoverage(...)` که ردیف `TenantServiceCoverage` را upsert می‌کند |
| `src/Insurance/Entity/TenantServiceCoverage.php` | موجودیت قاعده‌ی پوشش به‌ازای بیمه‌گر×سرویس |
| `src/Insurance/Entity/TenantInsurance.php` | قرارداد بیمه‌ی فعال مطب |
| `src/Billing/Service/BillingCalculator.php` | محاسبه‌ی سهم از روی `CoverageRule` |
| `src/Billing/Service/ClaimService.php` | ساخت مطالبات از Invoice (مصرف‌کننده‌ی نهاییِ این داده) |
| `src/ClinicService/Entity/ServiceItem.php` | فیلدهای ساده‌ی `insurance_covered` / `insurance_price_rials` و `toArray()` (فقط `uuid` برمی‌گرداند) |
| `docs/api/insurance.md` | مستند API که باید به‌روز شود |
## وضعیت فعلی
### فرم سرویس (frontend) — فقط دو فیلد ساده
`assets/admin/pages/ClinicServicesPage.tsx` خطوط ۳۹۷–۴۱۵:
```tsx
<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13.5 }}>
<input
type="checkbox"
checked={itemForm.watch('insurance_covered') ?? false}
onChange={(e) => itemForm.setValue('insurance_covered', e.target.checked)}
/>
این خدمت شامل بیمه میشود
</label>
{itemForm.watch('insurance_covered') && (
<div className="field">
<label>قیمت با بیمه (ریال)</label>
<PriceInput
value={itemForm.watch('insurance_price_rials') ?? 0}
onChange={(v) => itemForm.setValue('insurance_price_rials', v)}
placeholder="سهم بیمار با بیمه"
min={0}
/>
</div>
)}
```
این مقادیر فقط روی `ServiceItem` ذخیره می‌شوند و در `BillingCalculator`/`ClaimService` خوانده نمی‌شوند.
### endpoint موجود ست‌کردن پوشش (backend) — payload مورد انتظار
`src/Insurance/Controller/InsuranceController.php` خط ۴۰۹:
```php
#[Route('/api/v1/billing/tenant-insurances/{uuid}/service-coverage', methods: ['PUT'])]
public function setServiceCoverage(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
{
// ... resolveEntity + بررسی مالکیت قرارداد ...
$serviceItemId = (int) ($data['service_item_id'] ?? 0); // الزامی
$this->tenantInsuranceService->setServiceCoverage(
$contract,
$serviceItemId,
(bool) ($data['covered'] ?? true),
isset($data['coverage_percent']) ? (float) $data['coverage_percent'] : null,
isset($data['franchise_rials']) ? (int) $data['franchise_rials'] : null,
isset($data['ceiling_rials']) ? (int) $data['ceiling_rials'] : null,
);
return $this->success(['message' => 'پوشش خدمت ذخیره شد']);
}
```
> توجه: endpoint با `service_item_id` (id داخلی) کار می‌کند، اما frontend فقط `uuid` سرویس دارد — `ServiceItem::toArray()` فقط `uuid` می‌دهد. وظیفه ۳ این شکاف را حل می‌کند.
### موجودیت پوشش — قاعده‌ای که محاسبه را تعیین می‌کند
`TenantServiceCoverage`: `tenant_insurance_id`، `service_item_id`، `covered`، `coverage_percent` (decimal 5,2)، `franchise_rials`، `ceiling_rials`؛ یکتا روی `(tenant_insurance_id, service_item_id)`.
## وظایف
### ۱. افزودن «پوشش بیمه به ازای بیمه‌گر» به modal سرویس (frontend)
در `ClinicServicesPage.tsx`، داخل modal سرویس (بعد از فیلد «پرسنل مسئول»)، یک بخش جدید اضافه کن:
- با `useQuery` لیست قراردادهای فعال بیمه را از `GET /api/v1/billing/tenant-insurances` بگیر (نمایش نام بیمه‌گر + برچسب نوع پایه/تکمیلی).
- این بخش فقط در حالت **ویرایش سرویس** فعال باشد (در «سرویس جدید» چون هنوز id/uuid نیست، با پیام «ابتدا سرویس را ذخیره کنید» غیرفعال شود).
- برای هر قرارداد یک ردیف با کنترل‌ها: `covered` (سوییچ)، `coverage_percent` (٪، ۰ تا ۱۰۰)، `franchise_rials` (PriceInput)، `ceiling_rials` (PriceInput).
- مقدار اولیه‌ی هر ردیف از `GET /api/v1/billing/tenant-insurances/{uuid}/service-coverage` پر شود (ردیفِ متناظر با همین سرویس).
- ذخیره‌ی هر ردیف با `PUT /api/v1/billing/tenant-insurances/{uuid}/service-coverage` و body:
```ts
{
service_item_uuid: string, // طبق وظیفه ۳ (یا service_item_id اگر id را expose کردی)
covered: boolean,
coverage_percent: number | null,
franchise_rials: number | null,
ceiling_rials: number | null,
}
```
از الگوهای موجود استفاده کن: `api.get/put` از `lib/api.ts`، `useMutation` + `qc.invalidateQueries`، `toast`، `PriceInput` برای مبالغ ریالی، `SearchableSelect` در صورت نیاز. سبک ردیف‌ها را از `ServiceTariffModal.tsx` الگو بگیر.
```tsx
type CoverageRow = {
contractUuid: string;
insuranceName: string;
type: 'basic' | 'supplementary';
covered: boolean;
coveragePercent: number | null;
franchiseRials: number | null;
ceilingRials: number | null;
};
```
### ۲. شفاف‌سازی نقش دو فیلد ساده‌ی قدیمی
`insurance_covered` / `insurance_price_rials` را حذف نکن، اما نقش‌شان را در UI روشن کن: چک‌باکس «این خدمت شامل بیمه می‌شود» به‌عنوان **پرچم نمایشی/سریع** بماند و بخش جدیدِ «پوشش به ازای بیمه‌گر» به‌عنوان **منبعِ واقعیِ محاسبه و مطالبات** معرفی شود (یک خط توضیح فارسی زیر بخش).
قبل از تصمیم، با grep بررسی کن `insurance_price_rials` و `isInsuranceCovered()` کجا مصرف می‌شوند (frontend و backend) تا چیزی نشکند.
### ۳. حل مشکل `service_item_id` در برابر `uuid` (backend)
frontend فقط `uuid` سرویس دارد ولی endpoint پوشش `service_item_id` می‌خواهد. گزینه‌ی کم‌ریسک را پیاده کن:
- **الف (ترجیح):** `setServiceCoverage` (controller + `TenantInsuranceService`) را طوری گسترش بده که اگر `service_item_id` نبود ولی `service_item_uuid` بود، id را از `ServiceItemRepository` پیدا کند و **اعتبارسنجی کند سرویس متعلق به همان مطب/کلینیکِ قرارداد است** (همان `resolveEntity`).
- خروجی `GET .../service-coverage` هم باید برای هر ردیف `service_item_uuid` بدهد (با join یا map از `service_item_id`) تا frontend ردیف درست را پیدا کند.
(اگر به‌جای آن `id` را به `ServiceItem::toArray()` افزودی، همه‌ی مصرف‌کننده‌های آن را چک کن — قرارداد API تغییر می‌کند.)
### ۴. اطمینان از جریان به مطالبات بیمه
تأیید کن (و در صورت گسست، اصلاح کن) که زنجیره کامل برقرار است:
`TenantServiceCoverage``CoverageRule``BillingCalculator::calculateItem()` → ست‌شدن `baseInsuranceRials` / `supplementaryRials` روی `InvoiceItem``ClaimService::buildClaim()` که فقط آیتم‌های دارای سهم مثبت را به `ClaimItem` تبدیل می‌کند.
اگر جایی این زنجیره به‌جای `TenantServiceCoverage` از `insurance_price_rials` می‌خواند، همان نقطه را اصلاح کن تا سرویسِ بیمه‌داری که اینجا تعریف می‌شود واقعاً در **مطالبات بیمه** ظاهر شود. این هسته‌ی خواسته‌ی کاربر است.
### ۵. مستندسازی
`docs/api/insurance.md` را به‌روز کن: payloadِ `PUT/GET .../service-coverage` (به‌خصوص افزودن `service_item_uuid`)، و توضیح اینکه پوشش سرویس از این مسیر روی محاسبه‌ی سهم و ساخت مطالبات اثر می‌گذارد.
## نکات مهم
- **معماری دوگانه را به‌هم نریز:** منبعِ حقیقتِ محاسبه `TenantServiceCoverage` است، نه `insurance_price_rials`.
- **پایه vs تکمیلی:** نوع بیمه‌گر از `Insurance` مرجع می‌آید (`InsuranceType: basic|supplementary`). در UI نوع را نشان بده؛ در `BillingCalculator` مکمل روی **باقیمانده‌ی بعد از پایه** اعمال می‌شود.
- **چندمستأجری (tenant):** endpointهای `service-coverage` با `resolveEntity($user)` مالکیت قرارداد را چک می‌کنند؛ گسترش backend باید همان مالکیت را برای سرویس هم اعمال کند.
- **حالت ساخت اولیه:** بخش پوشش فقط در حالت ویرایش (سرویس باید id داشته باشد). ساده‌ترین مسیر، یا بعد از ساختِ سرویس خودکار modal ویرایش باز شود.
- **مقادیر:** مبالغ با `PriceInput` و واحد ریال؛ `coverage_percent` عدد ۰ تا ۱۰۰.
- الگوهای پروژه: پاسخ‌ها با `$this->success()/$this->error()`؛ تاریخ‌ها Unix timestamp؛ admin با TanStack Query + RHF + Zod؛ JWT از `localStorage['clinicpro-auth']`.
- اگر `ServiceItem` تغییر کرد ⇒ migration با `doctrine:migrations:diff`.
- بعد از تغییر frontend: `ddev exec npx tsc --noEmit` و `ddev exec yarn dev`.
- پس از تغییر کد: `graphify update .`
@@ -0,0 +1,221 @@
import { useEffect, useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { ShieldCheckIcon, CheckIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import Modal from './ui/Modal';
import PriceInput from './ui/PriceInput';
import type { ServiceItem } from '../types';
interface TenantInsurance {
uuid: string;
insurance_name: string | null;
insurance_kind: 'basic' | 'supplementary' | null;
coverage_percent: number;
}
interface CoverageRow {
service_item_uuid: string | null;
covered: boolean;
coverage_percent: number | null;
franchise_rials: number | null;
ceiling_rials: number | null;
}
interface Draft {
covered: boolean;
coverage_percent: number | null;
franchise_rials: number | null;
ceiling_rials: number | null;
}
const KIND = {
basic: { label: 'پایه', cls: 'blue' },
supplementary: { label: 'تکمیلی', cls: 'violet' },
} as const;
function ContractCard({ contract, item }: { contract: TenantInsurance; item: ServiceItem }) {
const qc = useQueryClient();
const { data, isLoading } = useQuery<{ data: { data: CoverageRow[] } }>({
queryKey: ['service-coverage', contract.uuid],
queryFn: () => api.get(`/api/v1/billing/tenant-insurances/${contract.uuid}/service-coverage`),
});
const rows = (data as any)?.data?.data as CoverageRow[] | undefined;
const existing = rows?.find((r) => r.service_item_uuid === item.uuid);
const [draft, setDraft] = useState<Draft>({ covered: true, coverage_percent: null, franchise_rials: null, ceiling_rials: null });
useEffect(() => {
setDraft(existing
? {
covered: existing.covered,
coverage_percent: existing.coverage_percent,
franchise_rials: existing.franchise_rials,
ceiling_rials: existing.ceiling_rials,
}
: { covered: true, coverage_percent: null, franchise_rials: null, ceiling_rials: null });
}, [existing]);
const saveMut = useMutation({
mutationFn: () =>
api.put(`/api/v1/billing/tenant-insurances/${contract.uuid}/service-coverage`, {
service_item_uuid: item.uuid,
covered: draft.covered,
coverage_percent: draft.coverage_percent,
franchise_rials: draft.franchise_rials,
ceiling_rials: draft.ceiling_rials,
}),
onSuccess: () => {
toast.success('پوشش بیمه ذخیره شد');
qc.invalidateQueries({ queryKey: ['service-coverage', contract.uuid] });
},
onError: (e: Error) => toast.error(e.message),
});
const kind = contract.insurance_kind ? KIND[contract.insurance_kind] : null;
return (
<div style={{ border: '1px solid var(--border)', borderRadius: 'var(--r)', overflow: 'hidden' }}>
{/* سربرگ کارت */}
<div style={{
display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px',
background: 'var(--surface-2)', borderBottom: draft.covered ? '1px solid var(--border)' : 'none',
}}>
<div style={{
width: 32, height: 32, borderRadius: 9, flexShrink: 0,
display: 'grid', placeItems: 'center', background: 'var(--primary-subtle)',
}}>
<ShieldCheckIcon style={{ width: 18, color: 'var(--primary)' }} />
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<b style={{ fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{contract.insurance_name ?? 'بیمه'}
</b>
{kind && <span className={`badge ${kind.cls}`} style={{ fontSize: 10 }}>{kind.label}</span>}
{existing && (
<span className="badge green" style={{ fontSize: 10 }}>
<CheckIcon style={{ width: 10 }} /> تنظیمشده
</span>
)}
</div>
<div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 2 }}>
پوشش پیشفرض قرارداد: {contract.coverage_percent}٪
</div>
</div>
<label className="switch">
<input
type="checkbox"
checked={draft.covered}
disabled={isLoading}
onChange={(e) => setDraft((d) => ({ ...d, covered: e.target.checked }))}
/>
<span className="switch-track"><span className="switch-thumb" /></span>
</label>
</div>
{/* بدنه — فقط وقتی پوشش فعال است */}
{draft.covered && (
<div style={{ padding: 14 }}>
{isLoading ? (
<div className="muted" style={{ fontSize: 12.5 }}>در حال بارگذاری...</div>
) : (
<>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
<div style={{ minWidth: 0 }}>
<label className="field-label">درصد پوشش</label>
<input
type="number" min={0} max={100} dir="ltr" className="input"
style={{ height: 40, textAlign: 'left' }}
value={draft.coverage_percent ?? ''}
placeholder="ارث"
onChange={(e) => setDraft((d) => ({ ...d, coverage_percent: e.target.value === '' ? null : Number(e.target.value) }))}
/>
</div>
<div style={{ minWidth: 0 }}>
<label className="field-label">فرانشیز</label>
<PriceInput
className="input"
style={{ height: 40 }}
value={draft.franchise_rials ?? 0}
onChange={(v) => setDraft((d) => ({ ...d, franchise_rials: v || null }))}
placeholder="۰"
min={0}
/>
</div>
<div style={{ minWidth: 0 }}>
<label className="field-label">سقف پوشش</label>
<PriceInput
className="input"
style={{ height: 40 }}
value={draft.ceiling_rials ?? 0}
onChange={(v) => setDraft((d) => ({ ...d, ceiling_rials: v || null }))}
placeholder="بدون سقف"
min={0}
/>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginTop: 12 }}>
<span style={{ fontSize: 11, color: 'var(--text-3)' }}>مقدار خالی از قرارداد بیمه ارث میبرد</span>
<button className="btn primary sm" disabled={saveMut.isPending} onClick={() => saveMut.mutate()}>
{saveMut.isPending ? '...' : 'ذخیره'}
</button>
</div>
</>
)}
</div>
)}
{/* وقتی پوشش غیرفعال است — یک خط ذخیره */}
{!draft.covered && !isLoading && (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '12px 14px' }}>
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>این خدمت تحت این بیمه پوشش ندارد</span>
<button className="btn sm" disabled={saveMut.isPending} onClick={() => saveMut.mutate()}>
{saveMut.isPending ? '...' : 'ذخیره'}
</button>
</div>
)}
</div>
);
}
export default function ServiceInsuranceModal({ item, onClose }: { item: ServiceItem | null; onClose: () => void }) {
const { data, isLoading } = useQuery<{ data: { data: TenantInsurance[] } }>({
queryKey: ['tenant-insurances'],
queryFn: () => api.get('/api/v1/billing/tenant-insurances'),
enabled: !!item,
});
const contracts = ((data as any)?.data?.data as TenantInsurance[] | undefined) ?? [];
return (
<Modal open={!!item} onClose={onClose} title={`پوشش بیمه — ${item?.name ?? ''}`} size="md">
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{
display: 'flex', gap: 8, padding: '11px 13px', borderRadius: 'var(--r-sm)',
background: 'var(--primary-subtle)', fontSize: 12, color: 'var(--text-2)', lineHeight: 1.7,
}}>
<ShieldCheckIcon style={{ width: 16, flexShrink: 0, marginTop: 1, color: 'var(--primary)' }} />
<span>درصد پوشش، فرانشیز و سقف هر بیمهگر برای این خدمت تعیین میشود. این تنظیمات مبنای محاسبهی سهم بیمار و ساخت مطالبات بیمه است.</span>
</div>
{isLoading ? (
<div className="muted" style={{ fontSize: 13, padding: '8px 0' }}>در حال بارگذاری...</div>
) : contracts.length === 0 ? (
<div style={{
border: '2px dashed var(--border)', borderRadius: 'var(--r)',
padding: '36px 16px', textAlign: 'center',
}}>
<ShieldCheckIcon style={{ width: 34, margin: '0 auto 10px', display: 'block', opacity: 0.35 }} />
<div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-2)' }}>قرارداد بیمهی فعالی ندارید</div>
<div style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 4 }}>ابتدا از بخش بیمهها یک بیمه را فعال کنید.</div>
</div>
) : (
item && contracts.map((c) => <ContractCard key={c.uuid} contract={c} item={item} />)
)}
</div>
</Modal>
);
}
@@ -42,7 +42,7 @@ export default function SearchableSelect({
const styles: StylesConfig<SelectOption, false, GroupBase<SelectOption>> = {
control: (base, state) => ({
...base,
background: darkMode ? 'var(--surface)' : 'var(--surface)',
background: state.isFocused ? 'var(--surface)' : 'var(--surface-2)',
borderColor: state.isFocused ? 'var(--primary)' : 'var(--border)',
boxShadow: state.isFocused ? '0 0 0 4px var(--ring)' : 'none',
borderRadius: 'var(--r-sm)',
+314 -219
View File
@@ -1,6 +1,9 @@
import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { PlusIcon, PencilIcon, TrashIcon, WrenchScrewdriverIcon, BanknotesIcon } from '@heroicons/react/24/outline';
import {
PlusIcon, PencilIcon, TrashIcon, WrenchScrewdriverIcon, BanknotesIcon,
ShieldCheckIcon, MagnifyingGlassIcon, EyeIcon, EyeSlashIcon,
} from '@heroicons/react/24/outline';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
@@ -14,6 +17,7 @@ import PriceInput from '../components/ui/PriceInput';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import PageHeader from '../components/ui/PageHeader';
import ServiceTariffModal from '../components/ServiceTariffModal';
import ServiceInsuranceModal from '../components/ServiceInsuranceModal';
import SearchableSelect from '../components/ui/SearchableSelect';
import FeatureGate from '../components/ui/FeatureGate';
@@ -31,6 +35,19 @@ type ItemForm = z.infer<typeof itemSchema>;
const EMPTY_SECTIONS: ServiceSection[] = [];
const EMPTY_ITEMS: ServiceItem[] = [];
function Avatar({ name }: { name: string }) {
return (
<div style={{
width: 26, height: 26, borderRadius: '50%',
background: 'linear-gradient(145deg, oklch(0.62 0.15 162), oklch(0.48 0.16 162))',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 11, fontWeight: 700, color: '#fff', flexShrink: 0,
}}>
{name.charAt(0)}
</div>
);
}
function ClinicServicesPageInner() {
const qc = useQueryClient();
@@ -38,8 +55,11 @@ function ClinicServicesPageInner() {
const [sectionModal, setSectionModal] = useState<'create' | ServiceSection | null>(null);
const [deleteSection, setDeleteSection] = useState<ServiceSection | null>(null);
const [itemModal, setItemModal] = useState<'create' | ServiceItem | null>(null);
const [deleteItem, setDeleteItem] = useState<ServiceItem | null>(null);
const [toggleItem, setToggleItem] = useState<ServiceItem | null>(null);
const [tariffItem, setTariffItem] = useState<ServiceItem | null>(null);
const [insuranceItem, setInsuranceItem] = useState<ServiceItem | null>(null);
const [search, setSearch] = useState('');
const [showInactive, setShowInactive] = useState(true);
const { data: sectionsData, isLoading: sectionsLoading } = useQuery<ApiResponse<ServiceSection[]>>({
queryKey: ['service-sections'],
@@ -58,11 +78,23 @@ function ClinicServicesPageInner() {
});
const sections = sectionsData?.data ?? EMPTY_SECTIONS;
const items = itemsData?.data ?? EMPTY_ITEMS;
const staffOptions = (staffData?.data ?? []).filter((s) => s.active).map((s) => ({
value: s.uuid,
label: s.full_name,
}));
const allItems = itemsData?.data ?? EMPTY_ITEMS;
const allStaff = staffData?.data ?? [];
const editingStaff = itemModal && typeof itemModal === 'object' ? itemModal.staff : null;
const staffOptions = allStaff
.filter((s) => s.active || s.uuid === editingStaff?.uuid)
.map((s) => ({
value: s.uuid,
label: s.active ? s.full_name : `${s.full_name} (غیرفعال)`,
}));
const items = allItems.filter((it) => {
if (!showInactive && !it.active) return false;
if (search.trim() && !it.name.includes(search.trim())) return false;
return true;
});
const activeCount = allItems.filter((i) => i.active).length;
const sectionForm = useForm<SectionForm>({ resolver: zodResolver(sectionSchema) });
const itemForm = useForm<ItemForm>({ resolver: zodResolver(itemSchema) });
@@ -104,17 +136,15 @@ function ClinicServicesPageInner() {
onError: (e: any) => toast.error(e.message),
});
const delItem = useMutation({
mutationFn: (uuid: string) => api.delete(`/api/v1/service-item/${uuid}`),
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setDeleteItem(null); toast.success('سرویس حذف شد'); },
onError: (e: any) => {
if (e.code === 'ERR_SERVICE_ITEM_IN_USE') {
toast.error('این سرویس در پرونده بیمار استفاده شده و قابل حذف نیست');
} else {
toast.error(e.message);
}
setDeleteItem(null);
const toggleActive = useMutation({
mutationFn: ({ uuid, active }: { uuid: string; active: boolean }) =>
api.patch(`/api/v1/service-item/${uuid}`, { active }),
onSuccess: (_d, v) => {
qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] });
setToggleItem(null);
toast.success(v.active ? 'سرویس فعال شد' : 'سرویس غیرفعال شد');
},
onError: (e: any) => { toast.error(e.message); setToggleItem(null); },
});
const openEditSection = (s: ServiceSection) => {
@@ -133,13 +163,18 @@ function ClinicServicesPageInner() {
setItemModal(item);
};
const openCreateItem = () => {
itemForm.reset({ name: '', price_rials: 0, staff_uuid: '', insurance_covered: false, insurance_price_rials: 0 });
setItemModal('create');
};
return (
<>
<PageHeader title="سرویس‌های کلینیک" description="مدیریت بخش‌ها و سرویس‌های کلینیک" />
<PageHeader title="سرویس‌های کلینیک" description="بخش‌ها، سرویس‌ها، تعرفه و پوشش بیمه را مدیریت کنید" />
<div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 16, alignItems: 'start' }}>
{/* ستون بخش‌ها */}
<div className="card">
<div style={{ display: 'grid', gridTemplateColumns: '288px 1fr', gap: 18, alignItems: 'start' }}>
{/* ───────── ستون بخش‌ها ───────── */}
<div className="card" style={{ overflow: 'hidden' }}>
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '14px 16px', borderBottom: '1px solid var(--border)',
@@ -148,189 +183,194 @@ function ClinicServicesPageInner() {
<button
className="btn primary sm"
style={{ display: 'flex', alignItems: 'center', gap: 4 }}
onClick={() => { sectionForm.reset(); setSectionModal('create'); }}
onClick={() => { sectionForm.reset({ name: '' }); setSectionModal('create'); }}
>
<PlusIcon style={{ width: 14 }} /> بخش جدید
<PlusIcon style={{ width: 14 }} /> جدید
</button>
</div>
<div style={{ padding: '8px 0' }}>
<div style={{ padding: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>
{sectionsLoading ? (
<div style={{ color: 'var(--text-3)', fontSize: 13, padding: '12px 16px' }}>در حال بارگذاری...</div>
<div style={{ color: 'var(--text-3)', fontSize: 13, padding: '12px 8px' }}>در حال بارگذاری...</div>
) : sections.length === 0 ? (
<div style={{ padding: '32px 16px', textAlign: 'center', color: 'var(--text-3)' }}>
<WrenchScrewdriverIcon style={{ width: 32, margin: '0 auto 10px', display: 'block', opacity: 0.4 }} />
<WrenchScrewdriverIcon style={{ width: 30, margin: '0 auto 10px', display: 'block', opacity: 0.4 }} />
<div style={{ fontSize: 13 }}>بخشی ثبت نشده است</div>
</div>
) : (
sections.map((s) => (
<div
key={s.uuid}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '10px 14px', cursor: 'pointer',
background: selectedSection?.uuid === s.uuid ? 'var(--primary-subtle)' : 'transparent',
borderRight: selectedSection?.uuid === s.uuid ? '3px solid var(--primary)' : '3px solid transparent',
transition: 'all 0.15s',
}}
onClick={() => setSelectedSection(s)}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<WrenchScrewdriverIcon style={{
width: 16,
color: selectedSection?.uuid === s.uuid ? 'var(--primary)' : 'var(--text-3)',
transition: 'color 0.15s',
}} />
<span style={{
fontSize: 13.5, fontWeight: selectedSection?.uuid === s.uuid ? 600 : 400,
color: selectedSection?.uuid === s.uuid ? 'var(--primary)' : 'var(--text-1)',
}}>
{s.name}
</span>
sections.map((s) => {
const isActive = selectedSection?.uuid === s.uuid;
return (
<div
key={s.uuid}
className="srv-section-row"
style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '9px 10px', cursor: 'pointer', borderRadius: 9,
background: isActive ? 'var(--primary-subtle)' : 'transparent',
transition: 'background 0.15s',
}}
onClick={() => setSelectedSection(s)}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
<WrenchScrewdriverIcon style={{
width: 16, flexShrink: 0,
color: isActive ? 'var(--primary)' : 'var(--text-3)',
}} />
<span style={{
fontSize: 13.5, fontWeight: isActive ? 600 : 500,
color: isActive ? 'var(--primary)' : 'var(--text-1)',
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
}}>
{s.name}
</span>
</div>
<div className="srv-section-actions" style={{ display: 'flex', gap: 2, flexShrink: 0 }} onClick={(e) => e.stopPropagation()}>
<button className="btn sm ghost" onClick={() => openEditSection(s)} title="ویرایش">
<PencilIcon style={{ width: 13 }} />
</button>
<button className="btn sm ghost" onClick={() => setDeleteSection(s)} title="حذف">
<TrashIcon style={{ width: 13 }} />
</button>
</div>
</div>
<div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
<button
className="btn sm"
style={{ opacity: 0.7 }}
onClick={() => openEditSection(s)}
title="ویرایش"
>
<PencilIcon style={{ width: 13 }} />
</button>
<button
className="btn sm"
style={{ opacity: 0.7 }}
onClick={() => setDeleteSection(s)}
title="حذف"
>
<TrashIcon style={{ width: 13 }} />
</button>
</div>
</div>
))
);
})
)}
</div>
</div>
{/* ستون آیتم‌ها */}
<div className="card">
{/* ───────── ستون سرویس‌ها ───────── */}
<div className="card" style={{ overflow: 'hidden' }}>
{!selectedSection ? (
<div style={{
border: '2px dashed var(--border)', borderRadius: 10,
margin: 16, padding: '60px 0', textAlign: 'center', color: 'var(--text-3)',
border: '2px dashed var(--border)', borderRadius: 12,
margin: 18, padding: '64px 0', textAlign: 'center', color: 'var(--text-3)',
}}>
<WrenchScrewdriverIcon style={{ width: 40, margin: '0 auto 14px', display: 'block', opacity: 0.35 }} />
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-2)' }}>یک بخش انتخاب کنید</div>
<WrenchScrewdriverIcon style={{ width: 42, margin: '0 auto 14px', display: 'block', opacity: 0.35 }} />
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-2)' }}>یک بخش انتخاب کنید</div>
<div style={{ fontSize: 13, marginTop: 4 }}>تا سرویسهای آن را مشاهده و مدیریت کنید</div>
</div>
) : (
<>
{/* toolbar بخش انتخاب‌شده */}
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '14px 16px', borderBottom: '1px solid var(--border)',
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
padding: '14px 16px', borderBottom: '1px solid var(--border)', flexWrap: 'wrap',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<WrenchScrewdriverIcon style={{ width: 16, color: 'var(--primary)' }} />
<b style={{ fontSize: 14 }}>{selectedSection.name}</b>
{!itemsLoading && (
<span className="badge gray" style={{ fontSize: 11 }}>{items.length} سرویس</span>
<span className="badge gray" style={{ fontSize: 11 }}>
{activeCount} فعال{allItems.length > activeCount ? ` / ${allItems.length}` : ''}
</span>
)}
</div>
<button
className="btn primary sm"
style={{ display: 'flex', alignItems: 'center', gap: 4 }}
onClick={() => { itemForm.reset({ price_rials: 0, staff_uuid: '', insurance_covered: false, insurance_price_rials: 0 }); setItemModal('create'); }}
>
<PlusIcon style={{ width: 14 }} /> سرویس جدید
</button>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<div style={{ position: 'relative' }}>
<MagnifyingGlassIcon style={{ width: 15, position: 'absolute', insetInlineStart: 9, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-3)', pointerEvents: 'none' }} />
<input
className="input"
placeholder="جستجوی سرویس"
value={search}
onChange={(e) => setSearch(e.target.value)}
style={{ width: 180, paddingInlineStart: 30, height: 34 }}
/>
</div>
<button
className="btn sm ghost"
onClick={() => setShowInactive((v) => !v)}
title={showInactive ? 'پنهان‌کردن غیرفعال‌ها' : 'نمایش غیرفعال‌ها'}
>
{showInactive ? <EyeIcon style={{ width: 15 }} /> : <EyeSlashIcon style={{ width: 15 }} />}
</button>
<button className="btn primary sm" style={{ display: 'flex', alignItems: 'center', gap: 4 }} onClick={openCreateItem}>
<PlusIcon style={{ width: 14 }} /> سرویس جدید
</button>
</div>
</div>
{itemsLoading ? (
<div style={{ color: 'var(--text-3)', fontSize: 13, padding: '16px 16px' }}>در حال بارگذاری...</div>
<div style={{ color: 'var(--text-3)', fontSize: 13, padding: 16 }}>در حال بارگذاری...</div>
) : items.length === 0 ? (
<div style={{ padding: '48px 0', textAlign: 'center', color: 'var(--text-3)' }}>
<div style={{ padding: '52px 0', textAlign: 'center', color: 'var(--text-3)' }}>
<PlusIcon style={{ width: 32, margin: '0 auto 12px', display: 'block', opacity: 0.35 }} />
<div style={{ fontWeight: 500, color: 'var(--text-2)', marginBottom: 4 }}>سرویسی در این بخش وجود ندارد</div>
<button
className="btn primary sm"
style={{ marginTop: 12 }}
onClick={() => { itemForm.reset({ price_rials: 0, staff_uuid: '', insurance_covered: false, insurance_price_rials: 0 }); setItemModal('create'); }}
>
افزودن سرویس
</button>
<div style={{ fontWeight: 600, color: 'var(--text-2)', marginBottom: 4 }}>
{allItems.length === 0 ? 'سرویسی در این بخش وجود ندارد' : 'سرویسی با این فیلتر یافت نشد'}
</div>
{allItems.length === 0 && (
<button className="btn primary sm" style={{ marginTop: 12 }} onClick={openCreateItem}>
افزودن سرویس
</button>
)}
</div>
) : (
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
<thead>
<tr style={{ background: 'oklch(0.97 0.01 256)', borderBottom: '1px solid var(--border)' }}>
<th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>نام سرویس</th>
<th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>قیمت</th>
<th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>پرسنل مسئول</th>
<th style={{ textAlign: 'right', padding: '10px 16px', fontWeight: 600, color: 'var(--text-2)' }}>عملیات</th>
</tr>
</thead>
<tbody>
{items.map((item, idx) => (
<tr
key={item.uuid}
style={{
borderBottom: '1px solid var(--border)',
background: idx % 2 === 1 ? 'oklch(0.985 0.005 256)' : 'transparent',
}}
>
<td style={{ padding: '11px 16px', fontWeight: 500 }}>
{item.name}
<div style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
{items.map((item) => (
<div
key={item.uuid}
style={{
display: 'flex', alignItems: 'center', gap: 14,
padding: '12px 14px', borderRadius: 11,
border: '1px solid var(--border)',
background: item.active ? 'var(--bg)' : 'oklch(0.97 0.005 256)',
opacity: item.active ? 1 : 0.7,
transition: 'box-shadow 0.15s',
}}
>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
<span style={{ fontWeight: 600, fontSize: 13.5 }}>{item.name}</span>
{!item.active && <span className="badge gray" style={{ fontSize: 10 }}>غیرفعال</span>}
{item.insurance_covered && (
<span className="badge green" style={{ fontSize: 10, marginInlineStart: 6 }}>
<span className="bdot" />بیمه
</span>
<span className="badge green" style={{ fontSize: 10 }}><span className="bdot" />بیمه</span>
)}
</td>
<td style={{ padding: '11px 16px', color: 'var(--primary)', fontWeight: 600 }}>
{formatRial(item.price_rials)}
</td>
<td style={{ padding: '11px 16px' }}>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-3)' }}>
{item.staff ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{
width: 22, height: 22, borderRadius: '50%',
background: 'linear-gradient(145deg, oklch(0.62 0.15 162), oklch(0.48 0.16 162))',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 10, fontWeight: 700, color: '#fff', flexShrink: 0,
}}>
{item.staff.full_name.charAt(0)}
</div>
<span style={{ fontSize: 13 }}>{item.staff.full_name}</span>
</div>
<>
<Avatar name={item.staff.full_name} />
<span>{item.staff.full_name}</span>
</>
) : (
<span style={{ color: 'var(--text-3)' }}></span>
<span>بدون پرسنل مسئول</span>
)}
</td>
<td style={{ padding: '11px 16px' }}>
<div style={{ display: 'flex', gap: 4 }}>
<button className="btn sm" onClick={() => openEditItem(item)} title="ویرایش">
<PencilIcon style={{ width: 13 }} />
</button>
<button className="btn sm" onClick={() => setTariffItem(item)} title="تعرفه‌های سالانه">
<BanknotesIcon style={{ width: 13 }} />
</button>
<button className="btn sm" onClick={() => setDeleteItem(item)} title="حذف">
<TrashIcon style={{ width: 13 }} />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<div style={{ textAlign: 'end', flexShrink: 0 }}>
<div style={{ color: 'var(--primary)', fontWeight: 700, fontSize: 14 }}>{formatRial(item.price_rials)}</div>
</div>
<div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
<button className="btn sm ghost" onClick={() => openEditItem(item)} title="ویرایش">
<PencilIcon style={{ width: 14 }} />
</button>
<button className="btn sm ghost" onClick={() => setTariffItem(item)} title="تعرفه‌های سالانه">
<BanknotesIcon style={{ width: 14 }} />
</button>
<button className="btn sm ghost" onClick={() => setInsuranceItem(item)} title="پوشش بیمه">
<ShieldCheckIcon style={{ width: 14 }} />
</button>
<button
className="btn sm ghost"
onClick={() => setToggleItem(item)}
title={item.active ? 'غیرفعال‌کردن' : 'فعال‌کردن'}
style={{ color: item.active ? 'var(--text-3)' : 'var(--primary)' }}
>
{item.active ? <EyeSlashIcon style={{ width: 14 }} /> : <EyeIcon style={{ width: 14 }} />}
</button>
</div>
</div>
))}
</div>
)}
</>
)}
</div>
</div>
{/* Modal بخش */}
{/* ───────── Modal بخش ───────── */}
<Modal
open={sectionModal !== null}
onClose={() => setSectionModal(null)}
@@ -342,107 +382,162 @@ function ClinicServicesPageInner() {
})}>
<div className="field">
<label>نام بخش *</label>
<input {...sectionForm.register('name')} placeholder="مثلاً: تزریقات" />
<input {...sectionForm.register('name')} placeholder="مثلاً: تزریقات" autoFocus />
{sectionForm.formState.errors.name && (
<span className="field-error">{sectionForm.formState.errors.name.message}</span>
)}
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
<button type="submit" className="btn primary" disabled={createSection.isPending || editSection.isPending}>ذخیره</button>
<button type="button" className="btn" onClick={() => setSectionModal(null)}>انصراف</button>
</div>
</form>
</Modal>
{/* Modal آیتم */}
{/* ───────── Modal سرویس ───────── */}
<Modal
open={itemModal !== null}
onClose={() => setItemModal(null)}
title={itemModal === 'create' ? 'سرویس جدید' : 'ویرایش سرویس'}
size="md"
footer={
<>
<button type="button" className="btn" onClick={() => setItemModal(null)}>انصراف</button>
<button type="submit" form="service-item-form" className="btn primary" disabled={createItem.isPending || editItem.isPending}>
{createItem.isPending || editItem.isPending ? 'در حال ذخیره...' : 'ذخیره سرویس'}
</button>
</>
}
>
<form onSubmit={itemForm.handleSubmit((d) => {
if (itemModal === 'create' && selectedSection) {
createItem.mutate({ ...d, section_uuid: selectedSection.uuid });
} else if (itemModal !== null && typeof itemModal === 'object') {
editItem.mutate({ uuid: itemModal.uuid, body: d });
}
})}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div className="field">
<label>نام سرویس *</label>
<input {...itemForm.register('name')} placeholder="مثلاً: سرم ۵۰۰cc" />
<form
id="service-item-form"
onSubmit={itemForm.handleSubmit((d) => {
if (itemModal === 'create' && selectedSection) {
createItem.mutate({ ...d, section_uuid: selectedSection.uuid });
} else if (itemModal !== null && typeof itemModal === 'object') {
editItem.mutate({ uuid: itemModal.uuid, body: d });
}
})}
style={{ display: 'flex', flexDirection: 'column', gap: 20 }}
>
{/* اطلاعات پایه */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div>
<label className="field-label">نام سرویس *</label>
<div className="field" style={itemForm.formState.errors.name ? { borderColor: 'var(--danger)' } : undefined}>
<input {...itemForm.register('name')} placeholder="مثلاً: سرم ۵۰۰cc" autoFocus />
</div>
{itemForm.formState.errors.name && (
<span className="field-error">{itemForm.formState.errors.name.message}</span>
)}
</div>
<div className="field">
<label>قیمت (ریال) *</label>
<PriceInput
value={itemForm.watch('price_rials') ?? 0}
onChange={(v) => itemForm.setValue('price_rials', v)}
placeholder="۸۵,۰۰۰"
min={0}
/>
</div>
<div className="field">
<label>پرسنل مسئول</label>
<SearchableSelect
options={staffOptions}
value={itemForm.watch('staff_uuid') ?? ''}
onChange={(v) => itemForm.setValue('staff_uuid', v != null ? String(v) : undefined)}
placeholder="انتخاب پرسنل (اختیاری)"
isClearable
/>
</div>
<label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', fontSize: 13.5 }}>
<input
type="checkbox"
checked={itemForm.watch('insurance_covered') ?? false}
onChange={(e) => itemForm.setValue('insurance_covered', e.target.checked)}
/>
این خدمت شامل بیمه میشود
</label>
{itemForm.watch('insurance_covered') && (
<div className="field">
<label>قیمت با بیمه (ریال)</label>
<PriceInput
value={itemForm.watch('insurance_price_rials') ?? 0}
onChange={(v) => itemForm.setValue('insurance_price_rials', v)}
placeholder="سهم بیمار با بیمه"
min={0}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
<div>
<label className="field-label">قیمت پایه (ریال) *</label>
<div className="field">
<PriceInput
value={itemForm.watch('price_rials') ?? 0}
onChange={(v) => itemForm.setValue('price_rials', v)}
placeholder="۸۵,۰۰۰"
min={0}
/>
</div>
{itemForm.formState.errors.price_rials && (
<span className="field-error">{itemForm.formState.errors.price_rials.message}</span>
)}
</div>
<div>
<label className="field-label">پرسنل مسئول</label>
<SearchableSelect
options={staffOptions}
value={itemForm.watch('staff_uuid') ?? ''}
onChange={(v) => itemForm.setValue('staff_uuid', v != null ? String(v) : '')}
placeholder="انتخاب (اختیاری)"
noOptionsMessage="پرسنلی ثبت نشده"
height={42}
isClearable
/>
</div>
)}
</div>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
<button type="submit" className="btn primary" disabled={createItem.isPending || editItem.isPending}>ذخیره</button>
<button type="button" className="btn" onClick={() => setItemModal(null)}>انصراف</button>
{/* بیمه */}
<div style={{
border: '1px solid var(--border)', borderRadius: 'var(--r)',
background: 'var(--surface-2)', overflow: 'hidden',
}}>
<label style={{
display: 'flex', alignItems: 'center', gap: 11, cursor: 'pointer',
padding: '13px 16px',
}}>
<ShieldCheckIcon style={{ width: 18, color: 'var(--primary)', flexShrink: 0 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13.5, fontWeight: 600 }}>این خدمت شامل بیمه میشود</div>
<div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 2 }}>نشانهی سریع برای فهرست سرویسها</div>
</div>
<span className="switch">
<input
type="checkbox"
checked={itemForm.watch('insurance_covered') ?? false}
onChange={(e) => itemForm.setValue('insurance_covered', e.target.checked)}
/>
<span className="switch-track"><span className="switch-thumb" /></span>
</span>
</label>
{itemForm.watch('insurance_covered') && (
<div style={{ padding: '0 16px 16px', borderTop: '1px solid var(--border)', paddingTop: 14 }}>
<label className="field-label">قیمت تقریبی با بیمه (ریال)</label>
<div className="field" style={{ background: 'var(--surface)' }}>
<PriceInput
value={itemForm.watch('insurance_price_rials') ?? 0}
onChange={(v) => itemForm.setValue('insurance_price_rials', v)}
placeholder="سهم تقریبی بیمار"
min={0}
/>
</div>
<div style={{
fontSize: 11.5, color: 'var(--text-3)', lineHeight: 1.75, marginTop: 10,
display: 'flex', gap: 6,
}}>
<ShieldCheckIcon style={{ width: 14, flexShrink: 0, marginTop: 2, color: 'var(--text-3)' }} />
<span>برای محاسبهی دقیق سهم بیمار و ساخت مطالبات، پوشش هر بیمهگر را از دکمهی «پوشش بیمه» در فهرست سرویسها تنظیم کنید.</span>
</div>
</div>
)}
</div>
</form>
</Modal>
<ServiceTariffModal item={tariffItem} onClose={() => setTariffItem(null)} />
<ServiceInsuranceModal item={insuranceItem} onClose={() => setInsuranceItem(null)} />
{/* Confirm حذف بخش */}
<ConfirmDialog
open={!!deleteSection}
title="حذف بخش"
message={`آیا مطمئن هستید که می‌خواهید بخش «${deleteSection?.name}» را حذف کنید؟`}
message={`آیا مطمئن هستید که می‌خواهید بخش «${deleteSection?.name}» و همه‌ی سرویس‌های آن را حذف کنید؟`}
confirmLabel="حذف"
onConfirm={() => deleteSection && delSection.mutate(deleteSection.uuid)}
onCancel={() => setDeleteSection(null)}
loading={delSection.isPending}
/>
{/* Confirm حذف آیتم */}
{/* Confirm فعال/غیرفعال سرویس */}
<ConfirmDialog
open={!!deleteItem}
title="حذف سرویس"
message={`آیا مطمئن هستید که می‌خواهید سرویس «${deleteItem?.name}» را حذف کنید؟`}
confirmLabel="حذف"
onConfirm={() => deleteItem && delItem.mutate(deleteItem.uuid)}
onCancel={() => setDeleteItem(null)}
loading={delItem.isPending}
open={!!toggleItem}
title={toggleItem?.active ? 'غیرفعال‌کردن سرویس' : 'فعال‌کردن سرویس'}
message={
toggleItem?.active
? `سرویس «${toggleItem?.name}» غیرفعال می‌شود و در پذیرش جدید نمایش داده نمی‌شود. سوابق قبلی حفظ می‌مانند.`
: `سرویس «${toggleItem?.name}» دوباره فعال و قابل انتخاب می‌شود.`
}
confirmLabel={toggleItem?.active ? 'غیرفعال کن' : 'فعال کن'}
onConfirm={() => toggleItem && toggleActive.mutate({ uuid: toggleItem.uuid, active: !toggleItem.active })}
onCancel={() => setToggleItem(null)}
loading={toggleActive.isPending}
/>
</>
);
+67 -6
View File
@@ -23,16 +23,34 @@ const schema = z.object({
});
type FormData = z.infer<typeof schema>;
interface Contract { insurance_id: number; insurance_name: string | null; insurance_kind: string | null; coverage_percent: number }
interface Contract { uuid: string; insurance_id: number; insurance_name: string | null; insurance_kind: string | null; coverage_percent: number; franchise_rials: number; annual_ceiling_rials: number | null }
interface CoverageRow { service_item_uuid: string | null; covered: boolean; coverage_percent: number | null; franchise_rials: number | null; ceiling_rials: number | null }
const PAYMENT_LABELS: Record<string, string> = {
cash: 'نقدی', card: 'کارت', insurance: 'بیمه', online: 'آنلاین', pending: 'در انتظار',
};
function calcFinal(visit: number, base: number, supp: number, services: number) {
const afterBase = visit * (1 - base / 100);
const afterSupp = afterBase * (1 - supp / 100);
return Math.round(afterSupp) + services;
interface Rule { covered: boolean; percent: number; franchise: number; ceiling: number | null }
// (calcFinal قدیمی حذف شد — حالا سهم بیمار خدمات با patientShareOf و قاعده‌ی هر بیمه‌گر محاسبه می‌شود)
// آینه‌ی BillingCalculator سمت سرور: سهم بیمار یک خدمت با پوشش پایه/مکمل.
function patientShareOf(total: number, base: Rule | null, supp: Rule | null): number {
let baseShare = 0;
let remaining = total;
if (base && base.covered) {
baseShare = Math.round(total * (base.percent / 100));
if (base.ceiling !== null) baseShare = Math.min(baseShare, base.ceiling);
remaining = total - baseShare;
}
let suppShare = 0;
if (supp && supp.covered) {
suppShare = Math.round(remaining * (supp.percent / 100));
if (supp.ceiling !== null) suppShare = Math.min(suppShare, supp.ceiling);
remaining = remaining - suppShare;
}
const franchise = (base?.franchise ?? 0) + (supp?.franchise ?? 0);
return Math.min(remaining + franchise, total);
}
const sectionTitle: React.CSSProperties = { fontWeight: 700, fontSize: 13.5, color: 'var(--text-2)', margin: '0 0 12px' };
@@ -91,6 +109,35 @@ export default function NewSessionPage() {
const sectionOptions = (sectionsData?.data ?? []).map(s => ({ value: s.uuid, label: s.name }));
const itemOptions = (itemsData?.data ?? []).filter(i => i.active).map(i => ({ value: i.uuid, label: `${i.name}${formatRial(i.price_rials)}` }));
const baseContract = contracts.find(c => String(c.insurance_id) === baseId) ?? null;
const suppContract = contracts.find(c => String(c.insurance_id) === suppId) ?? null;
const baseCoverageQ = useQuery<{ data: { data: CoverageRow[] } }>({
queryKey: ['service-coverage', baseContract?.uuid],
queryFn: () => api.get(`/api/v1/billing/tenant-insurances/${baseContract!.uuid}/service-coverage`),
enabled: !!baseContract,
});
const suppCoverageQ = useQuery<{ data: { data: CoverageRow[] } }>({
queryKey: ['service-coverage', suppContract?.uuid],
queryFn: () => api.get(`/api/v1/billing/tenant-insurances/${suppContract!.uuid}/service-coverage`),
enabled: !!suppContract,
});
const baseCoverage = (baseCoverageQ.data as any)?.data?.data as CoverageRow[] | undefined ?? [];
const suppCoverage = (suppCoverageQ.data as any)?.data?.data as CoverageRow[] | undefined ?? [];
// قاعده‌ی پوشش یک خدمت تحت یک قرارداد: override خدمت اگر باشد، وگرنه پیش‌فرض قرارداد.
const ruleFor = (contract: Contract | null, coverage: CoverageRow[], serviceUuid: string): Rule | null => {
if (!contract) return null;
const ov = coverage.find(r => r.service_item_uuid === serviceUuid);
if (ov && !ov.covered) return { covered: false, percent: 0, franchise: 0, ceiling: null };
return {
covered: true,
percent: ov?.coverage_percent ?? contract.coverage_percent,
franchise: ov?.franchise_rials ?? contract.franchise_rials,
ceiling: ov?.ceiling_rials ?? contract.annual_ceiling_rials,
};
};
const coverageOf = (id: string): number => contracts.find(c => String(c.insurance_id) === id)?.coverage_percent ?? 0;
const applyBase = (id: string) => {
setBaseId(id);
@@ -118,9 +165,21 @@ export default function NewSessionPage() {
const base = Number(form.watch('base_insurance_discount_percent')) || 0;
const supp = Number(form.watch('supplementary_discount_percent')) || 0;
const servicesTotal = useMemo(() => selectedServices.reduce((s, x) => s + x.price * x.qty, 0), [selectedServices]);
const servicesPatient = useMemo(
() => selectedServices.reduce((sum, x) => {
const total = x.price * x.qty;
return sum + patientShareOf(
total,
ruleFor(baseContract, baseCoverage, x.uuid),
ruleFor(suppContract, suppCoverage, x.uuid),
);
}, 0),
[selectedServices, baseContract, suppContract, baseCoverage, suppCoverage],
);
const servicesInsured = servicesTotal - servicesPatient;
const afterBase = Math.round(visit * (1 - base / 100));
const afterSupp = Math.round(afterBase * (1 - supp / 100));
const finalPrice = calcFinal(visit, base, supp, servicesTotal);
const finalPrice = Math.round(afterSupp) + servicesPatient;
const createMut = useMutation({
mutationFn: (body: object) => api.post(`/api/v1/patient/${recordUuid}/session`, body),
@@ -243,6 +302,8 @@ export default function NewSessionPage() {
{base > 0 && summaryRow('پس از بیمه پایه', afterBase)}
{supp > 0 && summaryRow('پس از بیمه تکمیلی', afterSupp)}
{servicesTotal > 0 && summaryRow('جمع خدمات', servicesTotal)}
{servicesInsured > 0 && summaryRow('سهم بیمه از خدمات', servicesInsured)}
{servicesInsured > 0 && summaryRow('سهم بیمار از خدمات', servicesTotal - servicesInsured)}
<div style={{ borderTop: '1px solid var(--border)', paddingTop: 8, marginTop: 2 }}>
{summaryRow('مبلغ نهایی (سهم بیمار)', finalPrice, true)}
</div>
+8 -13
View File
@@ -568,19 +568,6 @@ table.t tbody tr:hover .row-actions { opacity: 1; }
.bar { height: 8px; border-radius: 99px; background: var(--surface-3); overflow: hidden; }
.bar > i { display: block; height: 100%; border-radius: 99px; background: linear-gradient(90deg, var(--primary), var(--primary-600)); }
/* ── Toggle switch ───────────────────────────────────────────── */
.switch {
width: 44px; height: 26px; border-radius: 99px; background: var(--border-2);
position: relative; flex-shrink: 0; transition: background .2s var(--ease); cursor: pointer; display: inline-block;
}
.switch.on { background: var(--primary); }
.switch::after {
content: ""; position: absolute; top: 3px; inset-inline-start: 3px;
width: 20px; height: 20px; border-radius: 50%; background: #fff; box-shadow: var(--shadow-sm);
transition: transform .2s var(--ease);
}
.switch.on::after { transform: translateX(-18px); }
/* ── Modal ───────────────────────────────────────────────────── */
.overlay {
position: fixed; inset: 0; z-index: 1000; display: grid; place-items: center; padding: 20px;
@@ -690,3 +677,11 @@ table.t tbody tr:hover .row-actions { opacity: 1; }
@media (max-width: 560px) {
.stat-grid { grid-template-columns: 1fr 1fr; }
}
/* صفحه سرویس‌های کلینیک */
.srv-section-row:hover { background: var(--surface-2); }
.srv-section-actions { opacity: 0; transition: opacity 0.15s; }
.srv-section-row:hover .srv-section-actions { opacity: 1; }
@media (hover: none) {
.srv-section-actions { opacity: 1; }
}
+8 -4
View File
@@ -426,6 +426,7 @@ override پوشش یک خدمت خاص تحت قرارداد یک بیمه. فی
"uuid": "…",
"tenant_insurance_id": 4,
"service_item_id": 12,
"service_item_uuid": "…",
"covered": true,
"coverage_percent": 80,
"franchise_rials": null,
@@ -442,13 +443,16 @@ override پوشش یک خدمت خاص تحت قرارداد یک بیمه. فی
**Body:**
| فیلد | نوع | توضیح |
|------|-----|-------|
| `service_item_id` | int | الزامی |
| `service_item_uuid` | string | شناسه‌ی خدمت (ترجیحی؛ پنل ادمین فقط uuid دارد) |
| `service_item_id` | int | جایگزین `service_item_uuid` (id داخلی) — یکی از این دو الزامی |
| `covered` | bool | پیش‌فرض true |
| `coverage_percent` | float \| null | null = ارث از قرارداد |
| `franchise_rials` | int \| null | null = ارث از قرارداد |
| `ceiling_rials` | int \| null | null = ارث از قرارداد |
پاسخ `200`: `{ success, data: { message } }`.
خطاها: `404 ERR_NOT_FOUND_001` قرارداد یافت نشد · `422 ERR_VALIDATION_001` service_item_id الزامی.
سرویس باید متعلق به همان مطب/کلینیکِ قرارداد باشد (`ServiceItem→section→entity_type/entity_id`).
> منطق resolve: `TenantInsuranceService::coverageRuleForService()` ابتدا override خدمت را بررسی می‌کند؛ اگر `covered=false` → `CoverageRule::notCovered()`؛ در غیر این صورت فیلدهای null از قرارداد پر می‌شوند. این `CoverageRule` در فاز ۴ ورودی `BillingCalculator` است.
پاسخ `200`: `{ success, data: { message } }`.
خطاها: `404 ERR_NOT_FOUND_001` قرارداد یافت نشد · `422 ERR_VALIDATION_001` سرویس یافت نشد · `403 ERR_FORBIDDEN_001` سرویس متعلق به شما نیست.
> منطق resolve: `TenantInsuranceService::coverageRuleForService()` ابتدا override خدمت را بررسی می‌کند؛ اگر `covered=false` → `CoverageRule::notCovered()`؛ در غیر این صورت فیلدهای null از قرارداد پر می‌شوند. این `CoverageRule` ورودی `BillingCalculator` است و سهم بیمه‌ی هر `InvoiceItem` را تعیین می‌کند؛ همان سهم‌ها در `ClaimService::createFromInvoice()` به `ClaimItem` (مطالبات بیمه) تبدیل می‌شوند. پنل ادمین این endpoint را از مودال «پوشش بیمه» در صفحه سرویس‌های کلینیک فراخوانی می‌کند.
+5 -1
View File
@@ -246,7 +246,11 @@ Creates a new visit session for a patient record.
- `payment_method`: `cash` | `card` | `insurance` | `online` | `pending`
- `services`: array of service items to attach; `price_rials` snapshot از ServiceItem؛ `quantity` (پیش‌فرض ۱) → `line_total_rials = price_rials × quantity`. هر `SessionService` در پاسخ `quantity` و `line_total_rials` دارد.
- `final_price_rials` is computed: `(visit_price × (1 - base%) × (1 - supp%)) + services_total` که `services_total = Σ(price × quantity)`
- `final_price_rials` (سهم بیمار) به این صورت محاسبه می‌شود:
- **ویزیت:** `round(visit_price × (1 - base%) × (1 - supp%))` با درصدهای انتخاب‌شده در فرم.
- **هر خدمت:** سهم بیمار با قاعده‌ی پوشش همان بیمه‌گر برای همان خدمت (`TenantServiceCoverage` از طریق `BillingCalculator`) محاسبه می‌شود؛ یعنی فقط خدمتی که بیمه‌ی انتخاب‌شده آن را پوشش می‌دهد تخفیف می‌گیرد (درصد/فرانشیز/سقف؛ مقدار نبودِ override از قرارداد ارث می‌برد). خدمتِ بدون پوشش، کامل بر عهده‌ی بیمار است.
- `final_price_rials = سهم بیمار ویزیت + Σ(سهم بیمار هر خدمت)` و `services_total_rials = Σ(price × quantity)` (قیمت کامل خدمات، بدون بیمه).
- این محاسبه دقیقاً همان منطقِ صورتحساب/مطالبات است؛ پیش‌نمایش پنل هم همین قاعده را سمت کلاینت آینه می‌کند.
**اتصال خودکار مطالبه‌ی بیمه:** اگر session دارای `insurance_base_id` یا `insurance_supplementary_id` باشد، پس از ثبت به‌صورت خودکار صورتحساب ساخته و نهایی می‌شود و مطالبه(های) بیمه در وضعیت `pending` ایجاد می‌گردد (پایه/مکمل، فقط برای سهم بیمه > ۰). این مطالبات در صفحه‌ی [مطالبات بیمه](billing.md) قابل پیگیری و ارسال‌اند. خطا در این مرحله ثبت session را خراب نمی‌کند (لاگ می‌شود). برای هر صورتحساب فقط یک‌بار مطالبه ساخته می‌شود.
+3
View File
@@ -84,6 +84,9 @@ class ServiceItem
'section_uuid' => $this->section->getUuid(),
'staff_uuid' => $this->staff?->getUuid(),
'staff_name' => $this->staff?->getFullName(),
'staff' => $this->staff !== null
? ['uuid' => $this->staff->getUuid(), 'full_name' => $this->staff->getFullName()]
: null,
'name' => $this->name,
'price_rials' => $this->priceRials,
'active' => $this->active,
@@ -3,6 +3,7 @@
namespace App\Insurance\Controller;
use App\Auth\Entity\User;
use App\ClinicService\Repository\ServiceItemRepository;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Insurance\Entity\DoctorInsurance;
@@ -39,6 +40,7 @@ class InsuranceController extends BaseController
private readonly TenantInsuranceRepository $tenantInsuranceRepo,
private readonly TenantServiceCoverageRepository $serviceCoverageRepo,
private readonly TenantInsuranceService $tenantInsuranceService,
private readonly ServiceItemRepository $serviceItemRepo,
private readonly FileValidatorService $fileValidator,
private readonly string $projectDir,
) {}
@@ -403,7 +405,14 @@ class InsuranceController extends BaseController
$rows = $this->serviceCoverageRepo->findByContract($contract->getId());
return $this->success(['data' => array_map(fn($r) => $r->toArray(), $rows)]);
$data = array_map(function ($r) {
$row = $r->toArray();
$item = $this->serviceItemRepo->find($r->getServiceItemId());
$row['service_item_uuid'] = $item?->getUuid();
return $row;
}, $rows);
return $this->success(['data' => $data]);
}
#[Route('/api/v1/billing/tenant-insurances/{uuid}/service-coverage', methods: ['PUT'])]
@@ -416,12 +425,23 @@ class InsuranceController extends BaseController
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'قرارداد یافت نشد', 404);
}
$data = json_decode($request->getContent(), true) ?? [];
$serviceItemId = isset($data['service_item_id']) ? (int) $data['service_item_id'] : 0;
if ($serviceItemId <= 0) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'service_item_id الزامی است', 422);
$data = json_decode($request->getContent(), true) ?? [];
$serviceItem = isset($data['service_item_uuid'])
? $this->serviceItemRepo->findByUuid((string) $data['service_item_uuid'])
: (isset($data['service_item_id']) ? $this->serviceItemRepo->find((int) $data['service_item_id']) : null);
if ($serviceItem === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'سرویس یافت نشد', 422);
}
$section = $serviceItem->getSection();
if ($section->getEntityType() !== $entityType || $section->getEntityId() !== $entityId) {
return $this->error(ErrorCodes::ERR_FORBIDDEN_001, 'این سرویس متعلق به شما نیست', 403);
}
$serviceItemId = $serviceItem->getId();
$this->tenantInsuranceService->setServiceCoverage(
$contract,
$serviceItemId,
+45 -9
View File
@@ -4,8 +4,11 @@ namespace App\Patient\Service;
use App\Appointment\Entity\Appointment;
use App\Auth\Repository\UserRepository;
use App\Billing\Service\BillingCalculator;
use App\Billing\ValueObject\Money;
use App\ClinicService\Repository\ServiceItemRepository;
use App\Clinic\Repository\ClinicRepository;
use App\Insurance\Service\TenantInsuranceService;
use App\Doctor\Repository\DoctorAddressRepository;
use App\Patient\Entity\PatientRecord;
use App\Patient\Entity\PatientSession;
@@ -28,17 +31,46 @@ class PatientService
private readonly SubscriptionService $subscriptionService,
private readonly DoctorAddressRepository $addressRepo,
private readonly ClinicRepository $clinicRepo,
private readonly TenantInsuranceService $tenantInsuranceService,
private readonly BillingCalculator $billingCalculator,
) {}
public function calculateFinalPrice(int $visitPrice, float $baseDiscount, float $suppDiscount, array $serviceItems): array
{
$afterBase = $visitPrice * (1 - $baseDiscount / 100);
$afterSupp = $afterBase * (1 - $suppDiscount / 100);
$servicesTotal = array_sum(array_column($serviceItems, 'price_rials'));
/**
* محاسبه‌ی سهم بیمار.
* ویزیت با درصد تخفیف انتخاب‌شده در فرم؛ هر خدمت با قاعده‌ی پوشش همان بیمه‌گر برای همان خدمت
* (TenantServiceCoverage از طریق BillingCalculator). خدمتی که آن بیمه را پوشش نمی‌دهد، کامل بر عهده‌ی بیمار است.
*
* @param array<array{item_id: int, price_rials: int}> $serviceItems قیمت کل هر ردیف (با احتساب تعداد)
*/
public function calculateFinalPrice(
int $visitPrice,
float $baseDiscount,
float $suppDiscount,
array $serviceItems,
string $entityType = 'doctor',
int $entityId = 0,
?int $baseInsuranceId = null,
?int $suppInsuranceId = null,
): array {
$afterBase = $visitPrice * (1 - $baseDiscount / 100);
$afterSupp = $afterBase * (1 - $suppDiscount / 100);
$visitShare = (int) round($afterSupp);
$servicesTotal = 0;
$servicesPatient = 0;
foreach ($serviceItems as $svc) {
$servicesTotal += $svc['price_rials'];
$baseRule = $this->tenantInsuranceService->coverageRuleForService($entityType, $entityId, $baseInsuranceId, $svc['item_id']);
$suppRule = $this->tenantInsuranceService->coverageRuleForService($entityType, $entityId, $suppInsuranceId, $svc['item_id']);
$breakdown = $this->billingCalculator->calculateItem(new Money($svc['price_rials']), $baseRule, $suppRule);
$servicesPatient += $breakdown->patientRials;
}
return [
'services_total_rials' => (int) $servicesTotal,
'final_price_rials' => (int) round($afterSupp) + (int) $servicesTotal,
'services_total_rials' => $servicesTotal,
'final_price_rials' => $visitShare + $servicesPatient,
];
}
@@ -111,7 +143,7 @@ class PatientService
$item = $this->serviceItemRepo->findByUuid($svc['service_item_uuid'] ?? '');
if ($item !== null) {
$qty = max(1, (int) ($svc['quantity'] ?? 1));
$serviceItemsData[] = ['price_rials' => $item->getPriceRials() * $qty];
$serviceItemsData[] = ['item_id' => $item->getId(), 'price_rials' => $item->getPriceRials() * $qty];
}
}
@@ -119,7 +151,11 @@ class PatientService
$session->getVisitPriceRials(),
$session->getBaseInsuranceDiscountPercent(),
$session->getSupplementaryDiscountPercent(),
$serviceItemsData
$serviceItemsData,
$entityType,
$entityId,
$session->getInsuranceBaseId(),
$session->getInsuranceSupplementaryId(),
);
$session->setServicesTotalRials($priceCalc['services_total_rials']);