Add tests and implementation for ServiceDetailPage and PriceInput components
- Implement PriceInput component tests to validate Persian and Arabic numeral handling, input formatting, and controlled behavior. - Create ServiceDetailPage component with detailed service information, including pricing, insurance coverage, and editing capabilities. - Add API tests for service item detail retrieval and coverage synchronization with insurance contracts. - Ensure proper error handling and user feedback for service item retrieval and coverage management.
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
# اصلاحات بخش مدیریت سرویسها (بیمه، ورودیهای عددی، صفحه جزئیات)
|
||||
|
||||
## پروژه
|
||||
|
||||
`clinicpro` — پنل ادمین React (`assets/admin/`) + یک اندپوینت جدید در backend (`src/ClinicService/`).
|
||||
cross-repo نیست؛ سایت عمومی این بخش را مصرف نمیکند.
|
||||
|
||||
## زمینه
|
||||
|
||||
بخش «مدیریت سرویسها» (`/admin/clinic-services`) الان یک صفحه واحد است: نمای بخشها → نمای کارتهای سرویس، و
|
||||
همهٔ عملیات (ویرایش، تعرفهٔ سالانه، پوشش بیمه) در مودال باز میشود. سه اشکال دارد:
|
||||
|
||||
1. **دو جای تنظیم بیمه:** در مودال ویرایش سرویس یک سوییچ «این خدمت شامل بیمه میشود» + «قیمت تقریبی با بیمه» وجود دارد،
|
||||
در حالی که تنظیمات واقعی بیمه (درصد پوشش، فرانشیز، سقف، به تفکیک هر بیمهگر) در `ServiceInsuranceModal` است.
|
||||
کاربر دو منبع حقیقت میبیند.
|
||||
2. **NaN با کیبورد فارسی:** فیلد «درصد پوشش» در `ServiceInsuranceModal` مقدار خام را `Number()` میکند؛ رقم فارسی → `NaN`.
|
||||
3. **صفحهٔ جزئیات ندارد:** کلیک روی سرویس هیچ کاری نمیکند؛ همهچیز در مودال پراکنده است.
|
||||
|
||||
## فایلهای مرتبط
|
||||
|
||||
| فایل | نقش |
|
||||
|------|-----|
|
||||
| `assets/admin/pages/ClinicServicesPage.tsx` | صفحهٔ اصلی (۶۳۴ خط): نمای بخشها + کارت سرویسها + مودال ایجاد/ویرایش سرویس |
|
||||
| `assets/admin/components/ServiceInsuranceModal.tsx` | مودال پوشش بیمه به تفکیک قرارداد بیمهگر (منشأ باگ NaN، خط ۱۳۴) |
|
||||
| `assets/admin/components/ServiceTariffModal.tsx` | مودال تعرفههای سالانه |
|
||||
| `assets/admin/components/ui/PriceInput.tsx` | ورودی مبلغ (تبدیل رقم را درست انجام میدهد ولی رفتار ویرایش ناقص است) |
|
||||
| `assets/admin/lib/forms.ts` | `numericField()` / `latinDigitsField()` — wrapper صحیح برای RHF |
|
||||
| `assets/admin/lib/utils.ts` | `toEnglishDigits`, `digitsOnly`, `rialToToman`, `tomanToRial`, `formatRial` |
|
||||
| `assets/admin/components/ui/DigitInput.tsx` | ورودی فقط-رقم برای state معمولی (غیر RHF) |
|
||||
| `assets/admin/App.tsx` | جدول route ها (خط ۲۴۸: `clinic-services`) |
|
||||
| `src/ClinicService/Controller/ClinicServiceController.php` | اندپوینتهای سرویس/بخش/تعرفه |
|
||||
| `src/ClinicService/Entity/ServiceItem.php` | Entity + `toArray()` (خط ~۱۵۰) |
|
||||
| `docs/api/clinicservice.md` (یا معادلش) | مستندات API که باید در همین session بهروز شود |
|
||||
|
||||
## وضعیت فعلی
|
||||
|
||||
### ۱) سوییچ بیمه در مودال سرویس — `ClinicServicesPage.tsx:547-591`
|
||||
|
||||
```tsx
|
||||
{/* بیمه */}
|
||||
<div style={{ border: '1px solid var(--border)', ... }}>
|
||||
<label ...>
|
||||
<ShieldCheckIcon ... />
|
||||
<div>
|
||||
<div>این خدمت شامل بیمه میشود</div>
|
||||
<div>نشانهی سریع برای فهرست سرویسها</div>
|
||||
</div>
|
||||
<span className="switch">
|
||||
<input type="checkbox" checked={itemForm.watch('insurance_covered') ?? false} ... />
|
||||
</span>
|
||||
</label>
|
||||
{itemForm.watch('insurance_covered') && (
|
||||
<PriceInput value={itemForm.watch('insurance_price_rials') ?? 0} ... /> // قیمت تقریبی با بیمه
|
||||
)}
|
||||
</div>
|
||||
```
|
||||
|
||||
### ۲) باگ NaN — `ServiceInsuranceModal.tsx:129-135`
|
||||
|
||||
```tsx
|
||||
<input
|
||||
type="text" inputMode="numeric" dir="ltr" className="input"
|
||||
value={draft.coverage_percent ?? ''}
|
||||
placeholder="ارث"
|
||||
onChange={(e) => setDraft((d) => ({
|
||||
...d,
|
||||
coverage_percent: e.target.value === '' ? null : Number(e.target.value), // ← «۲۰» ⇒ NaN
|
||||
}))}
|
||||
/>
|
||||
```
|
||||
|
||||
`placeholder="ارث"` هم غلط تایپی است (باید «ارث از قرارداد» باشد).
|
||||
|
||||
### ۳) `PriceInput` — `ui/PriceInput.tsx:31-42`
|
||||
|
||||
```tsx
|
||||
const [display, setDisplay] = useState(...);
|
||||
useEffect(() => { setDisplay(value !== '' && Number(value) > 0 ? formatDisplay(Number(value), latin) : ''); }, [value, latin]);
|
||||
|
||||
const handleChange = (e) => {
|
||||
const raw = toEnglishDigits(e.target.value).replace(/[^0-9]/g, '');
|
||||
const num = raw === '' ? 0 : Math.max(min, parseInt(raw, 10));
|
||||
onChange(num);
|
||||
setDisplay(num > 0 ? formatDisplay(num, latin) : '');
|
||||
};
|
||||
```
|
||||
|
||||
تبدیل رقم درست است، ولی: مقدار `0` همیشه به رشتهٔ خالی تبدیل میشود (کاربر نمیتواند صفر را ببیند/بنویسد)،
|
||||
`Math.max(min, …)` هنگام تایپ رقمِ اول مقدار را به `min` میپراند، و واحد (تومان) در خود فیلد دیده نمیشود
|
||||
در حالی که label میگوید «قیمت پایه (تومان)» ولی مقدار ذخیرهشده ریال است (`tomanToRial` در mutation).
|
||||
|
||||
### ۴) نبود صفحهٔ جزئیات
|
||||
|
||||
`App.tsx:248` فقط یک route دارد:
|
||||
|
||||
```tsx
|
||||
<Route path="clinic-services" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClinicServicesPage /></RoleRoute>} />
|
||||
```
|
||||
|
||||
backend هم اندپوینت «یک سرویس با uuid» ندارد؛ فقط `GET /api/v1/service-items` (همه) و
|
||||
`GET /api/v1/service-items/{sectionUuid}` (بهتفکیک بخش).
|
||||
|
||||
## وظایف
|
||||
|
||||
> ترتیب اجرا مهم است: ۲ → ۳ → ۱ → ۴ → ۵. اول ابزار عددی درست شود، بعد UI روی آن بنا شود.
|
||||
|
||||
### ۱. حذف تنظیمات بیمه از مودال ایجاد/ویرایش سرویس
|
||||
|
||||
- بلاک «بیمه» (`ClinicServicesPage.tsx:547-591`) کامل حذف شود؛ `insurance_covered` و `insurance_price_rials`
|
||||
از `itemSchema`، از `openEditItem`/`openCreateItem` و از payload های `createItem`/`editItem` حذف شوند.
|
||||
- **backend را تغییر نده:** ستونهای `insurance_covered` / `insurance_price_rials` روی `ServiceItem` باقی میمانند
|
||||
(دادهٔ قدیمی + استفاده در جای دیگر). فقط دیگر از این فرم ارسال نمیشوند. اندپوینتها `isset()`-based هستند
|
||||
(`ClinicServiceController.php:183,227`) پس نبودِ فیلد در body مشکلی ایجاد نمیکند.
|
||||
- بهجای آن، در همان محلِ حذفشده یک اشارهٔ کوتاه بگذار که کاربر را به مدیریت بیمه هدایت کند — یک باکس اطلاع
|
||||
با همان استایل باکس راهنمای موجود در `ServiceInsuranceModal.tsx:196-202` (`background: var(--primary-soft)`)
|
||||
و یک دکمهٔ `btn sm` که همان `setInsuranceItem(item)` را باز میکند. در حالت «سرویس جدید» (هنوز uuid ندارد)
|
||||
فقط متن راهنما نمایش داده شود، بدون دکمه.
|
||||
- کارت سرویس (`ClinicServicesPage.tsx:390-392`) که `item.insurance_covered` را نشان میدهد باید بهجای فیلد
|
||||
حذفشده، وضعیت واقعی بیمه را از پوششهای ثبتشده نشان دهد یا اگر داده در دسترس نیست، آن ردیف حذف شود.
|
||||
**سادهترین راه سازگار: ردیف «سهم بیمار (بیمه)» از کارت حذف شود** و اطلاعات بیمه فقط در صفحهٔ جزئیات (وظیفهٔ ۴) بیاید.
|
||||
|
||||
### ۲. رفع ریشهای NaN در ورودیهای عددی
|
||||
|
||||
هیچ فیلد عددی نباید مستقیم `Number(e.target.value)` بزند. یک ابزار مشترک در `lib/utils.ts` اضافه کن:
|
||||
|
||||
```ts
|
||||
/**
|
||||
* رشتهٔ ورودی کاربر (با ارقام فارسی/عربی، کاما، فاصله) را به عدد امن تبدیل میکند.
|
||||
* هرگز NaN برنمیگرداند؛ ورودی نامعتبر ⇒ null.
|
||||
*/
|
||||
export function parseUserNumber(raw: string | number | null | undefined): number | null {
|
||||
if (raw == null || raw === '') return null;
|
||||
const s = toEnglishDigits(String(raw)).replace(/[,\s٫٬]/g, '');
|
||||
if (!/^-?\d*\.?\d+$/.test(s)) return null;
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/** همان، با clamp اختیاری — برای درصد (۰..۱۰۰) و مقادیر غیرمنفی. */
|
||||
export function parseUserNumberClamped(raw: string | number | null | undefined, min: number, max: number): number | null {
|
||||
const n = parseUserNumber(raw);
|
||||
return n == null ? null : Math.min(max, Math.max(min, n));
|
||||
}
|
||||
```
|
||||
|
||||
سپس:
|
||||
|
||||
- **`ServiceInsuranceModal.tsx:129-135`** — فیلد «درصد پوشش» بازنویسی شود: مقدار نمایشی را در یک state رشتهای
|
||||
نگه دار (تا کاربر بتواند فیلد را خالی کند یا در حال تایپ باشد)، و مقدارِ ذخیرهشونده را با
|
||||
`parseUserNumberClamped(v, 0, 100)` بساز. `placeholder="ارث"` → `placeholder="ارث از قرارداد"`.
|
||||
فرانشیز و سقف قبلاً `PriceInput` هستند و بعد از وظیفهٔ ۳ خودبهخود درست میشوند.
|
||||
- **`ClinicServicesPage.tsx:530`** — `duration_minutes` از `numericField()` استفاده میکند (درست است)؛ اما چون
|
||||
`z.coerce.number()` روی رشتهٔ خالی `0` میدهد، schema به `z.coerce.number().min(0).optional().or(z.literal(''))`
|
||||
یا یک `preprocess` تبدیل شود تا «خالی» به `undefined` نگاشت شود، نه صفر.
|
||||
- **سراسر پنل** — این موارد بررسی و اصلاح شوند (نتیجهٔ grep روی `assets/admin`):
|
||||
- `components/ImageCropModal.tsx:59` — `Number(e.target.value)` روی `<input type="range">`؛ چون range همیشه
|
||||
مقدار لاتین میدهد بیخطر است؛ فقط تأیید کن و دست نزن.
|
||||
- `components/paymentMethods/PosFormModal.tsx:88,92` — «شماره ترمینال» و «شماره حساب» ورودی آزادند و رقم فارسی
|
||||
را همانطور ذخیره میکنند؛ باید به `DigitInput` تبدیل شوند.
|
||||
- فایلهای دارای `z.coerce.number()`: `ClinicServicesPage.tsx`, `SmsWalletPage.tsx`, `AdminSubscriptionPage.tsx`,
|
||||
`RepresentationsPage.tsx`, `MyPatientsPage.tsx` — در هرکدام مطمئن شو input متناظر با `numericField(register(...))`
|
||||
یا `PriceInput` رندر میشود، نه `register(...)` خام. هرجا خام بود اصلاح کن.
|
||||
- **تست:** برای `parseUserNumber` تست واحد بنویس (`lib/utils.test.ts` یا فایل جدید) با موارد:
|
||||
`'۲۵' → 25`، `'٢٥' → 25`، `'1,200' → 1200`، `'' → null`، `'abc' → null`، `'۱۲.۵' → 12.5`، `'-۳' → -3`.
|
||||
و یک تست کامپوننتی برای فیلد درصد پوشش که با تایپ `'۲۵'` مقدار `25` میدهد و هرگز `NaN` نمایش نمیدهد.
|
||||
|
||||
### ۳. اصلاح `PriceInput` (نمایش و ورود مبلغ)
|
||||
|
||||
`ui/PriceInput.tsx` بازنویسی شود با این رفتار:
|
||||
|
||||
- ارقام فارسی/عربی و کاما و فاصله در ورودی پذیرفته و نرمال شوند (از `parseUserNumber` استفاده کن).
|
||||
- **پیست** (paste) با متن مثل `«۸۵,۰۰۰ تومان»` باید به `85000` تبدیل شود، نه خطا.
|
||||
- مقدار `0` نباید به رشتهٔ خالی تبدیل شود مگر کاربر خودش پاک کرده باشد؛ تفکیک «خالی» از «صفر» لازم است
|
||||
(state داخلی رشتهای + `onChange(number)`).
|
||||
- `Math.max(min, …)` نباید حین تایپ اعمال شود (clamp فقط `onBlur`).
|
||||
- نمایش با جداکنندهٔ هزارگان `fa-IR` (رفتار فعلی) حفظ شود؛ `direction: ltr` و `text-align: left` بماند.
|
||||
- یک `suffix` اختیاری اضافه شود (`suffix="تومان"`) تا واحد داخل فیلد دیده شود؛ در
|
||||
`ClinicServicesPage.tsx:480` و همهٔ کاربردهای مبلغ استفاده شود.
|
||||
- مقدار ذخیرهشده همیشه عدد معتبر باشد (هرگز `NaN`/`undefined`).
|
||||
- تست موجود اگر هست بهروز شود؛ اگر نیست تست واحد بنویس (تایپ فارسی، پیست با واحد، صفر، خالی، clamp روی blur).
|
||||
|
||||
> مراقب باش: label «تومان» است ولی مقدار API ریال است (`tomanToRial` در `createItem`/`editItem`
|
||||
> و `rialToToman` در `openEditItem`). این نگاشت را تغییر نده.
|
||||
|
||||
### ۴. صفحهٔ اختصاصی جزئیات سرویس
|
||||
|
||||
**Backend — یک اندپوینت جدید (تنها موردی که واقعاً لازم است):**
|
||||
|
||||
اندپوینت «یک سرویس با uuid» وجود ندارد؛ گرفتن کل لیست و فیلتر سمت کلاینت با refresh مستقیم روی صفحهٔ جزئیات
|
||||
شکننده است. اضافه کن:
|
||||
|
||||
```php
|
||||
#[Route('/api/v1/service-item/{uuid}', methods: ['GET'])]
|
||||
public function getItem(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
// همان الگوی مالکیت/tenant که در updateItem (خط ۲۰۵) استفاده شده
|
||||
// خروجی: $this->success($item->toArray()) ← بدون nest اضافه
|
||||
}
|
||||
```
|
||||
|
||||
- `ServiceItem::toArray()` باید `section` (uuid + name)، `created_at`، `updated_at`، `staff_members`،
|
||||
`bookable`، `duration_minutes` را داشته باشد؛ اگر ندارد اضافه کن.
|
||||
- `docs/api/` مربوطه در همین session بهروز شود (قانون استاندارد پروژه).
|
||||
- migration لازم نیست (تغییر schema نداریم).
|
||||
|
||||
**Frontend:**
|
||||
|
||||
- فایل جدید `assets/admin/pages/ServiceDetailPage.tsx`.
|
||||
- route جدید در `App.tsx` کنار route فعلی، با همان `RoleRoute roles={['doctor', 'clinic']} blockClinicScope`:
|
||||
`<Route path="clinic-services/:uuid" element={...} />`.
|
||||
- در `ClinicServicesPage.tsx` کلیک روی بدنهٔ کارت سرویس → `navigate('/admin/clinic-services/' + item.uuid)`.
|
||||
منوی ⋮ و سوییچها باید `e.stopPropagation()` داشته باشند تا ناوبری اتفاق نیفتد (الگوی موجود در کارت بخشها، خط ۲۶۰).
|
||||
- محتوای صفحه:
|
||||
| بخش | منبع داده |
|
||||
|------|-----------|
|
||||
| اطلاعات پایه (نام، بخش، وضعیت فعال، نمایش در نوبتدهی، زمان متوسط، پرسنل) | `GET /api/v1/service-item/{uuid}` |
|
||||
| قیمت پایه | همان (نمایش با `formatRial`) |
|
||||
| تعرفههای سالانه | `GET /api/v1/service-items/{uuid}/tariffs` (موجود) |
|
||||
| بیمههای مرتبط و پوشش | `GET /api/v1/billing/tenant-insurances` + `.../{uuid}/service-coverage` — همان کوئریهای `ServiceInsuranceModal` |
|
||||
| تاریخ ایجاد / آخرین ویرایش | `created_at` / `updated_at` با `formatDateTime` (شمسی) |
|
||||
- **کالاهای مرتبط:** الان هیچ رابطهای بین `ServiceItem` و `src/Inventory/` وجود ندارد
|
||||
(`InventoryPackage` polymorphic است با `entity_type`/`entity_id` ولی هیچجا با `service_item` پر نمیشود).
|
||||
بنابراین در این پرامپت **این سکشن ساخته نشود**. اگر لازم شد، بهعنوان کار جدا مطرح کن و در گزارش پایانی
|
||||
بنویس چه چیزی لازم است (رابطهٔ جدید + endpoint + UI).
|
||||
- **لاگ تغییرات:** هیچ زیرساخت audit-log برای `ServiceItem` وجود ندارد. این سکشن هم ساخته نشود؛
|
||||
بهجایش فقط «تاریخ ایجاد» و «آخرین ویرایش» نمایش داده شود. در گزارش پایانی ذکر کن.
|
||||
|
||||
### ۵. UI/UX صفحهٔ جزئیات — بدون طراحی جدید
|
||||
|
||||
**اجباری:** هیچ تم/طرح/کامپوننت جدیدی ساخته نشود. صفحه دقیقاً با Layout و Design System فعلی پنل پیاده شود:
|
||||
|
||||
- از `components/ui/PageHeader` برای عنوان + breadcrumb («سرویسها ‹ {نام بخش} ‹ {نام سرویس}») + دکمهٔ اقدام.
|
||||
- از `card` / `card-pad` / `card-title-row` / `section-title` / `muted` / `badge` / `field` / `field-label`
|
||||
و توکنهای `styles.css` (`--surface`, `--border`, `--primary`, `--r`, `--gap`) استفاده شود. **هیچ hex هاردکد.**
|
||||
- تبها با همان الگوی `className="seg"` که در `pages/ClinicAppointmentSettingsPage.tsx:74-85` استفاده شده.
|
||||
- انتخابها با `SearchableSelect` (نه `<select>` بومی)، تأییدها با `ConfirmDialog`، مبالغ با `PriceInput`،
|
||||
تاریخها با `formatDate`/`formatDateTime` شمسی، اعداد با `formatNumber`.
|
||||
- ویرایش سرویس، تعرفه و پوشش بیمه از همین صفحه در دسترس باشند با **همان مودالهای موجود**
|
||||
(`ServiceTariffModal`، `ServiceInsuranceModal`) — مودال جدید ساخته نشود.
|
||||
- حالتهای loading / empty / error با همان الگوی موجود در `ClinicServicesPage.tsx` (متن `در حال بارگذاری...`،
|
||||
کارت خالی با آیکون Heroicon).
|
||||
- RTL و رشتههای فارسی؛ آیکونها فقط Heroicons v2 outline.
|
||||
|
||||
## نکات مهم
|
||||
|
||||
- **ترتیب:** ابزار عددی (وظیفهٔ ۲ و ۳) اول؛ بعد UI. اگر اول UI بسازی، باگ NaN را در صفحهٔ جدید تکرار میکنی.
|
||||
- **قانون API:** اندپوینت جدید فقط `GET /api/v1/service-item/{uuid}` است و دلیلش بالا نوشته شده. هیچ اندپوینت
|
||||
دیگری ساخته نشود — تعرفه و پوشش بیمه اندپوینت آماده دارند.
|
||||
- **پاسخها:** `$this->success($item->toArray())` — بدون `['data' => ...]` که باعث double-nest میشود.
|
||||
توجه: اندپوینتهای billing (`tenant-insurances`, `service-coverage`) **double-nested هستند** و در کد فعلی با
|
||||
`(data as any)?.data?.data` خوانده میشوند؛ همان الگو را در صفحهٔ جدید تکرار کن.
|
||||
- **مالکیت/tenant:** الگوی چک مالکیت را از `updateItem` (`ClinicServiceController.php:205`) کپی کن؛ کاربر نباید
|
||||
بتواند سرویس tenant دیگر را ببیند. یک تست خطا برای این حالت لازم است (۴۰۳/۴۰۴).
|
||||
- **تست (قانون پروژه، بدون استثنا):** هر وظیفه تست موفق + خطا + مرزی داشته باشد و تستها اجرا و سبز شوند:
|
||||
- PHPUnit برای اندپوینت جدید: سرویس موجود، uuid ناموجود، سرویس متعلق به tenant دیگر.
|
||||
- Vitest برای `parseUserNumber`, `PriceInput`, فیلد درصد پوشش، و رندر `ServiceDetailPage` (mock شدهٔ کوئریها).
|
||||
- تست موجود `pages/ClinicServicesPage.test.tsx` بعد از حذف بلاک بیمه احتمالاً میشکند — بهروز شود.
|
||||
- **بررسی نهایی:** `ddev exec php bin/phpunit`، `yarn test`، `npx tsc --noEmit --project tsconfig.json`.
|
||||
- در گزارش پایانی صریح بنویس چه چیزی ساخته نشد و چرا (کالاهای مرتبط، لاگ تغییرات).
|
||||
@@ -55,6 +55,7 @@ import StaffPage from './pages/StaffPage';
|
||||
import SubscriptionPage from './pages/SubscriptionPage';
|
||||
import DiscountsPage from './pages/DiscountsPage';
|
||||
import ClinicServicesPage from './pages/ClinicServicesPage';
|
||||
import ServiceDetailPage from './pages/ServiceDetailPage';
|
||||
import SmsWalletPage from './pages/SmsWalletPage';
|
||||
import MySecretariesPage from './pages/MySecretariesPage';
|
||||
import AdminSubscriptionPage from './pages/AdminSubscriptionPage';
|
||||
@@ -246,6 +247,7 @@ export default function App() {
|
||||
<Route path="discounts" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><DiscountsPage /></RoleRoute>} />
|
||||
<Route path="subscription/success" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><PaymentSuccessPage /></RoleRoute>} />
|
||||
<Route path="clinic-services" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ClinicServicesPage /></RoleRoute>} />
|
||||
<Route path="clinic-services/:uuid" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><ServiceDetailPage /></RoleRoute>} />
|
||||
<Route path="inventory" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><InventoryPage /></RoleRoute>} />
|
||||
<Route path="sms-wallet" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><SmsWalletPage /></RoleRoute>} />
|
||||
<Route path="my-secretaries" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><MySecretariesPage /></RoleRoute>} />
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { renderWithProviders } from '../test/utils';
|
||||
|
||||
vi.mock('../lib/api', () => ({
|
||||
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
ApiError: class extends Error {},
|
||||
}));
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
|
||||
import { api } from '../lib/api';
|
||||
import ServiceInsuranceModal from './ServiceInsuranceModal';
|
||||
import type { ServiceItem } from '../types';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
const put = api.put as ReturnType<typeof vi.fn>;
|
||||
|
||||
const item = { uuid: 'svc-1', name: 'سرم ۵۰۰cc' } as ServiceItem;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
get.mockImplementation((url: string) => {
|
||||
if (url.includes('service-coverage')) return Promise.resolve({ data: { data: [] } });
|
||||
return Promise.resolve({
|
||||
data: { data: [{ uuid: 'ins-1', insurance_name: 'بیمه ایران', insurance_kind: 'basic', coverage_percent: 70 }] },
|
||||
});
|
||||
});
|
||||
put.mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
const percentInput = async () => {
|
||||
const el = await screen.findByPlaceholderText('ارث از قرارداد');
|
||||
return el as HTMLInputElement;
|
||||
};
|
||||
|
||||
describe('ServiceInsuranceModal — فیلد درصد پوشش', () => {
|
||||
it('رقم فارسی را میپذیرد و NaN نمایش نمیدهد', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
const input = await percentInput();
|
||||
|
||||
fireEvent.change(input, { target: { value: '۲۵' } });
|
||||
|
||||
expect(input.value).toBe('25');
|
||||
expect(input.value).not.toContain('NaN');
|
||||
});
|
||||
|
||||
it('مقدار ذخیرهشده عدد معتبر است', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
fireEvent.change(await percentInput(), { target: { value: '۳۰' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
|
||||
await waitFor(() => expect(put).toHaveBeenCalled());
|
||||
expect(put.mock.calls[0][1]).toMatchObject({ service_item_uuid: 'svc-1', coverage_percent: 30 });
|
||||
});
|
||||
|
||||
it('بیش از ۱۰۰ به ۱۰۰ محدود میشود', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
fireEvent.change(await percentInput(), { target: { value: '۱۵۰' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
|
||||
await waitFor(() => expect(put).toHaveBeenCalled());
|
||||
expect(put.mock.calls[0][1]).toMatchObject({ coverage_percent: 100 });
|
||||
});
|
||||
|
||||
it('فیلد خالی → null (ارث از قرارداد)', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
const input = await percentInput();
|
||||
fireEvent.change(input, { target: { value: '۴۰' } });
|
||||
fireEvent.change(input, { target: { value: '' } });
|
||||
|
||||
expect(input.value).toBe('');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
|
||||
await waitFor(() => expect(put).toHaveBeenCalled());
|
||||
expect(put.mock.calls[0][1]).toMatchObject({ coverage_percent: null });
|
||||
});
|
||||
|
||||
it('حروف نامعتبر وارد نمیشود', async () => {
|
||||
renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
|
||||
const input = await percentInput();
|
||||
fireEvent.change(input, { target: { value: 'ابج' } });
|
||||
|
||||
expect(input.value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ 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 { digitsOnly, parseUserNumberClamped } from '../lib/utils';
|
||||
import Modal from './ui/Modal';
|
||||
import PriceInput from './ui/PriceInput';
|
||||
import type { ServiceItem } from '../types';
|
||||
@@ -46,6 +47,8 @@ function ContractCard({ contract, item }: { contract: TenantInsurance; item: Ser
|
||||
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 });
|
||||
// متن خام فیلد درصد جدا از مقدار عددی نگه داشته میشود تا کاربر بتواند فیلد را خالی کند.
|
||||
const [percentText, setPercentText] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(existing
|
||||
@@ -56,6 +59,7 @@ function ContractCard({ contract, item }: { contract: TenantInsurance; item: Ser
|
||||
ceiling_rials: existing.ceiling_rials,
|
||||
}
|
||||
: { covered: true, coverage_percent: null, franchise_rials: null, ceiling_rials: null });
|
||||
setPercentText(existing?.coverage_percent == null ? '' : String(existing.coverage_percent));
|
||||
}, [existing]);
|
||||
|
||||
const saveMut = useMutation({
|
||||
@@ -129,9 +133,14 @@ function ContractCard({ contract, item }: { contract: TenantInsurance; item: Ser
|
||||
<input
|
||||
type="text" inputMode="numeric" 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) }))}
|
||||
value={percentText}
|
||||
placeholder="ارث از قرارداد"
|
||||
onChange={(e) => {
|
||||
const digits = digitsOnly(e.target.value, 3);
|
||||
setPercentText(digits);
|
||||
setDraft((d) => ({ ...d, coverage_percent: parseUserNumberClamped(digits, 0, 100) }));
|
||||
}}
|
||||
onBlur={() => setPercentText(draft.coverage_percent == null ? '' : String(draft.coverage_percent))}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { ShieldCheckIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { z } from 'zod';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import type { ServiceItem, ClinicStaff } from '../types';
|
||||
import { rialToToman, tomanToRial } from '../lib/utils';
|
||||
import { numericField } from '../lib/forms';
|
||||
import Modal from './ui/Modal';
|
||||
import PriceInput from './ui/PriceInput';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
|
||||
const itemSchema = z.object({
|
||||
name: z.string().min(1, 'نام سرویس الزامی است'),
|
||||
price_rials: z.coerce.number().min(0, 'مبلغ نمیتواند منفی باشد'),
|
||||
staff_uuids: z.array(z.string()).optional(),
|
||||
duration_minutes: z.coerce.number().min(0).optional(),
|
||||
bookable: z.boolean().optional(),
|
||||
});
|
||||
type ItemForm = z.infer<typeof itemSchema>;
|
||||
|
||||
const EMPTY_FORM: ItemForm = { name: '', price_rials: 0, staff_uuids: [], duration_minutes: undefined, bookable: false };
|
||||
|
||||
interface Props {
|
||||
/** `'create'` برای سرویس جدید، شیء سرویس برای ویرایش، `null` یعنی بسته. */
|
||||
item: 'create' | ServiceItem | null;
|
||||
/** بخش مقصد؛ برای حالت ایجاد الزامی است. */
|
||||
sectionUuid: string | null;
|
||||
onClose: () => void;
|
||||
/** برای باز کردن مودال پوشش بیمه از داخل فرم (فقط در حالت ویرایش). */
|
||||
onManageInsurance?: (item: ServiceItem) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* فرم ایجاد/ویرایش سرویس — مشترک بین فهرست سرویسها و صفحهی جزئیات سرویس.
|
||||
*
|
||||
* تنظیمات بیمه اینجا نیست: پوشش هر بیمهگر تنها در «پوشش بیمه» مدیریت میشود و
|
||||
* پرچم `insurance_covered` سمت سرور از همانجا همگام میشود.
|
||||
*/
|
||||
export default function ServiceItemFormModal({ item, sectionUuid, onClose, onManageInsurance }: Props) {
|
||||
const qc = useQueryClient();
|
||||
const editing = item !== null && typeof item === 'object' ? item : null;
|
||||
|
||||
const { data: staffData } = useQuery<ApiResponse<ClinicStaff[]>>({
|
||||
queryKey: ['staff'],
|
||||
queryFn: () => api.get('/api/v1/staff'),
|
||||
enabled: item !== null,
|
||||
});
|
||||
const allStaff = staffData?.data ?? [];
|
||||
|
||||
const form = useForm<ItemForm>({ resolver: zodResolver(itemSchema), defaultValues: EMPTY_FORM });
|
||||
|
||||
useEffect(() => {
|
||||
if (item === null) return;
|
||||
form.reset(editing
|
||||
? {
|
||||
name: editing.name,
|
||||
price_rials: rialToToman(editing.price_rials),
|
||||
staff_uuids: (editing.staff_members ?? (editing.staff ? [editing.staff] : [])).map((s) => s.uuid),
|
||||
duration_minutes: editing.duration_minutes ?? undefined,
|
||||
bookable: editing.bookable ?? false,
|
||||
}
|
||||
: EMPTY_FORM);
|
||||
}, [item]);
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: ['service-items'] });
|
||||
qc.invalidateQueries({ queryKey: ['service-sections'] });
|
||||
if (editing) qc.invalidateQueries({ queryKey: ['service-item', editing.uuid] });
|
||||
};
|
||||
|
||||
const createItem = useMutation({
|
||||
mutationFn: (body: ItemForm) => api.post('/api/v1/service-item', {
|
||||
...body,
|
||||
section_uuid: sectionUuid,
|
||||
price_rials: tomanToRial(body.price_rials),
|
||||
}),
|
||||
onSuccess: () => { invalidate(); onClose(); toast.success('سرویس ایجاد شد'); },
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const editItem = useMutation({
|
||||
mutationFn: (body: ItemForm) => api.patch(`/api/v1/service-item/${editing!.uuid}`, {
|
||||
...body,
|
||||
price_rials: tomanToRial(body.price_rials),
|
||||
}),
|
||||
onSuccess: () => { invalidate(); onClose(); toast.success('سرویس ویرایش شد'); },
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const saving = createItem.isPending || editItem.isPending;
|
||||
|
||||
const selectedStaffUuids = form.watch('staff_uuids') ?? [];
|
||||
const editingMembers = editing ? (editing.staff_members ?? (editing.staff ? [editing.staff] : [])) : [];
|
||||
const staffOptions = allStaff
|
||||
.filter((s) => s.active || editingMembers.some((m) => m.uuid === s.uuid))
|
||||
.filter((s) => !selectedStaffUuids.includes(s.uuid))
|
||||
.map((s) => ({ value: s.uuid, label: s.active ? s.full_name : `${s.full_name} (غیرفعال)` }));
|
||||
const staffNameOf = (uuid: string) =>
|
||||
allStaff.find((s) => s.uuid === uuid)?.full_name
|
||||
?? editingMembers.find((m) => m.uuid === uuid)?.full_name
|
||||
?? uuid;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={item !== null}
|
||||
onClose={onClose}
|
||||
title={editing ? 'ویرایش سرویس' : 'سرویس جدید'}
|
||||
size="md"
|
||||
footer={
|
||||
<>
|
||||
<button type="button" className="btn" onClick={onClose}>انصراف</button>
|
||||
<button type="submit" form="service-item-form" className="btn primary" disabled={saving}>
|
||||
{saving ? 'در حال ذخیره...' : 'ذخیره سرویس'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form
|
||||
id="service-item-form"
|
||||
onSubmit={form.handleSubmit((d) => (editing ? editItem : createItem).mutate(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={form.formState.errors.name ? { borderColor: 'var(--danger)' } : undefined}>
|
||||
<input {...form.register('name')} placeholder="مثلاً: سرم ۵۰۰cc" autoFocus />
|
||||
</div>
|
||||
{form.formState.errors.name && (
|
||||
<span className="field-error">{form.formState.errors.name.message}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<div>
|
||||
<label className="field-label">قیمت پایه (تومان) *</label>
|
||||
<div className="field">
|
||||
<PriceInput
|
||||
value={form.watch('price_rials') ?? 0}
|
||||
onChange={(v) => form.setValue('price_rials', v)}
|
||||
placeholder="۸۵,۰۰۰"
|
||||
min={0}
|
||||
suffix="تومان"
|
||||
/>
|
||||
</div>
|
||||
{form.formState.errors.price_rials && (
|
||||
<span className="field-error">{form.formState.errors.price_rials.message}</span>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">پرسنل مسئول</label>
|
||||
<SearchableSelect
|
||||
options={staffOptions}
|
||||
value={''}
|
||||
onChange={(v) => { if (v != null) form.setValue('staff_uuids', [...selectedStaffUuids, String(v)]); }}
|
||||
placeholder="افزودن پرسنل (اختیاری)"
|
||||
noOptionsMessage="پرسنلی باقی نمانده"
|
||||
height={42}
|
||||
/>
|
||||
{selectedStaffUuids.length > 0 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
|
||||
{selectedStaffUuids.map((uuid) => (
|
||||
<span key={uuid} style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
fontSize: 12.5, color: 'var(--text-2)', background: 'var(--surface-2)',
|
||||
border: '1px solid var(--border)', borderRadius: 999, padding: '4px 6px 4px 10px',
|
||||
}}>
|
||||
{staffNameOf(uuid)}
|
||||
<button
|
||||
type="button" aria-label={`حذف ${staffNameOf(uuid)}`}
|
||||
onClick={() => form.setValue('staff_uuids', selectedStaffUuids.filter((u) => u !== uuid))}
|
||||
style={{ display: 'grid', placeItems: 'center', width: 16, height: 16, border: 'none', cursor: 'pointer', borderRadius: '50%', background: 'var(--surface-3)', color: 'var(--text-3)' }}
|
||||
>
|
||||
<XMarkIcon style={{ width: 11 }} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'end' }}>
|
||||
<div>
|
||||
<label className="field-label">زمان متوسط (دقیقه)</label>
|
||||
<div className="field">
|
||||
<input {...numericField(form.register('duration_minutes'))} placeholder="مثلاً: 50" />
|
||||
</div>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', padding: '9px 0' }}>
|
||||
<span className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.watch('bookable') ?? false}
|
||||
onChange={(e) => form.setValue('bookable', e.target.checked)}
|
||||
/>
|
||||
<span className="switch-track"><span className="switch-thumb" /></span>
|
||||
</span>
|
||||
<span style={{ fontSize: 13 }}>نمایش در نوبتدهی</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* بیمه — تنظیمات فقط در «پوشش بیمه» مدیریت میشود تا دادهی تکراری ساخته نشود. */}
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 10, padding: '11px 13px',
|
||||
borderRadius: 'var(--r-sm)', background: 'var(--primary-soft)',
|
||||
}}>
|
||||
<ShieldCheckIcon style={{ width: 16, flexShrink: 0, color: 'var(--primary)' }} />
|
||||
<span style={{ flex: 1, minWidth: 0, fontSize: 12, color: 'var(--text-2)', lineHeight: 1.7 }}>
|
||||
پوشش بیمهی این خدمت — درصد، فرانشیز و سقف هر بیمهگر — در بخش «پوشش بیمه» تنظیم میشود.
|
||||
</span>
|
||||
{editing && onManageInsurance && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn sm"
|
||||
style={{ flexShrink: 0 }}
|
||||
onClick={() => { const it = editing; onClose(); onManageInsurance(it); }}
|
||||
>
|
||||
پوشش بیمه
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { PencilIcon, CheckIcon, XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import { formatRial, formatNumber, rialToToman, tomanToRial } from '../lib/utils';
|
||||
import { formatRial, formatYear, rialToToman, tomanToRial } from '../lib/utils';
|
||||
import Modal from './ui/Modal';
|
||||
import PriceInput from './ui/PriceInput';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
@@ -46,7 +46,7 @@ export default function ServiceTariffModal({ item, onClose }: { item: ServiceIte
|
||||
const opts: { value: number; label: string }[] = [];
|
||||
for (let y = currentYear + 2; y >= currentYear - 5; y--) {
|
||||
if (used.has(y)) continue;
|
||||
opts.push({ value: y, label: y === currentYear ? `${formatNumber(y)} (سال جاری)` : formatNumber(y) });
|
||||
opts.push({ value: y, label: y === currentYear ? `${formatYear(y)} (سال جاری)` : formatYear(y) });
|
||||
}
|
||||
return opts;
|
||||
}, [currentYear, tariffs]);
|
||||
@@ -85,7 +85,7 @@ export default function ServiceTariffModal({ item, onClose }: { item: ServiceIte
|
||||
display: 'flex', gap: 8, padding: '11px 13px', borderRadius: 'var(--r-sm)',
|
||||
background: 'var(--primary-subtle)', fontSize: 12, color: 'var(--text-2)', lineHeight: 1.7,
|
||||
}}>
|
||||
<span>قیمت پایهی سرویس همان تعرفهی سال جاری ({currentYear ? formatNumber(currentYear) : '—'}) است و همهجا از همین استفاده میشود. تعرفهی سالهای دیگر فقط برای صورتحساب همان سال بهکار میرود.</span>
|
||||
<span>قیمت پایهی سرویس همان تعرفهی سال جاری ({currentYear ? formatYear(currentYear) : '—'}) است و همهجا از همین استفاده میشود. تعرفهی سالهای دیگر فقط برای صورتحساب همان سال بهکار میرود.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -131,7 +131,7 @@ export default function ServiceTariffModal({ item, onClose }: { item: ServiceIte
|
||||
background: isCurrent ? 'var(--primary-subtle)' : 'var(--bg)',
|
||||
}}>
|
||||
<span style={{ fontWeight: 700, fontSize: 13, minWidth: 70 }}>
|
||||
سال {formatNumber(t.year)}
|
||||
سال {formatYear(t.year)}
|
||||
{isCurrent && <span className="badge green" style={{ fontSize: 9.5, marginInlineStart: 6 }}><span className="bdot" />جاری</span>}
|
||||
</span>
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import SearchableSelect from './ui/SearchableSelect';
|
||||
import { useBankAccounts, usePosDevices } from '../hooks/usePaymentMethods';
|
||||
import { formatRial, formatNumber, tomanToRial } from '../lib/utils';
|
||||
import { formatRial, formatNumber, tomanToRial, digitsOnly } from '../lib/utils';
|
||||
|
||||
export type WalletMode = 'charge' | 'withdraw';
|
||||
|
||||
@@ -154,7 +154,7 @@ export default function WalletTransactionModal({ open, balanceRials, submitting,
|
||||
inputMode="numeric"
|
||||
value={amountToman > 0 ? formatNumber(amountToman) : ''}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value.replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06f0)).replace(/[^\d]/g, '');
|
||||
const raw = digitsOnly(e.target.value);
|
||||
setAmountToman(raw ? parseInt(raw, 10) : 0);
|
||||
}}
|
||||
placeholder="مبلغ دلخواه (تومان)"
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { TrashIcon } from '@heroicons/react/24/outline';
|
||||
import Modal from '../ui/Modal';
|
||||
import SearchableSelect from '../ui/SearchableSelect';
|
||||
import { formatRial } from '../../lib/utils';
|
||||
import { formatRial, digitsOnly } from '../../lib/utils';
|
||||
import type { InventoryItem, InventoryPackage, PackagePayload } from '../../hooks/useInventory';
|
||||
|
||||
interface Props {
|
||||
@@ -89,7 +89,7 @@ export default function AddPackageModal({ open, editing, items, saving, onClose,
|
||||
<div>
|
||||
<label className="field-label">مقدار</label>
|
||||
<div className="field">
|
||||
<input value={amount} inputMode="numeric" onChange={(e) => setAmount(e.target.value.replace(/[^0-9]/g, ''))} placeholder="1" />
|
||||
<input value={amount} inputMode="numeric" onChange={(e) => setAmount(digitsOnly(e.target.value))} placeholder="1" />
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn ghost" style={{ justifyContent: 'center', height: 46 }} onClick={addLine} disabled={items.length === 0}>
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import Modal from '../ui/Modal';
|
||||
import SearchableSelect from '../ui/SearchableSelect';
|
||||
import DigitInput from '../ui/DigitInput';
|
||||
import { BANK_OPTIONS } from './banks';
|
||||
import {
|
||||
useCreatePos,
|
||||
@@ -85,11 +86,11 @@ export default function PosFormModal({
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">شماره ترمینال</label>
|
||||
<input className="input" value={terminalNumber} onChange={(e) => setTerminalNumber(e.target.value)} placeholder="شماره ترمینال" />
|
||||
<DigitInput className="input" value={terminalNumber} onChange={setTerminalNumber} placeholder="شماره ترمینال" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="field-label">شماره حساب</label>
|
||||
<input className="input" value={accountNumber} onChange={(e) => setAccountNumber(e.target.value)} placeholder="شماره حساب" />
|
||||
<DigitInput className="input" value={accountNumber} onChange={setAccountNumber} placeholder="شماره حساب" />
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { useState } from 'react';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import PriceInput from './PriceInput';
|
||||
|
||||
/** پوشش حالت واقعی: مقدار توسط والد نگه داشته میشود (controlled). */
|
||||
function Controlled({ initial = 0, ...rest }: { initial?: number } & Record<string, unknown>) {
|
||||
const [value, setValue] = useState(initial);
|
||||
return (
|
||||
<>
|
||||
<PriceInput value={value} onChange={setValue} {...rest} />
|
||||
<span data-testid="value">{value}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const input = () => screen.getByRole('textbox') as HTMLInputElement;
|
||||
const emitted = () => screen.getByTestId('value').textContent;
|
||||
|
||||
describe('PriceInput', () => {
|
||||
it('رقم فارسی را میپذیرد و عدد لاتین میدهد', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '۸۵۰۰۰' } });
|
||||
|
||||
expect(emitted()).toBe('85000');
|
||||
expect(input().value).toBe('۸۵٬۰۰۰');
|
||||
});
|
||||
|
||||
it('رقم عربی را میپذیرد', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '٢٥٠' } });
|
||||
|
||||
expect(emitted()).toBe('250');
|
||||
});
|
||||
|
||||
it('پیست با واحد و جداکننده پاکسازی میشود', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '۸۵,۰۰۰ تومان' } });
|
||||
|
||||
expect(emitted()).toBe('85000');
|
||||
});
|
||||
|
||||
it('صفرِ تایپشده حفظ میشود و به خالی تبدیل نمیشود', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: '۰' } });
|
||||
|
||||
expect(input().value).toBe('۰');
|
||||
expect(emitted()).toBe('0');
|
||||
});
|
||||
|
||||
it('پاککردن فیلد ⇒ خالی و مقدار صفر', () => {
|
||||
render(<Controlled initial={5000} />);
|
||||
fireEvent.change(input(), { target: { value: '' } });
|
||||
|
||||
expect(input().value).toBe('');
|
||||
expect(emitted()).toBe('0');
|
||||
});
|
||||
|
||||
it('مقدار اولیه صفر ⇒ فیلد خالی (نه ۰)', () => {
|
||||
render(<Controlled initial={0} />);
|
||||
expect(input().value).toBe('');
|
||||
});
|
||||
|
||||
it('min حین تایپ اعمال نمیشود ولی روی blur اعمال میشود', () => {
|
||||
render(<Controlled min={100} />);
|
||||
fireEvent.change(input(), { target: { value: '۵' } });
|
||||
expect(emitted()).toBe('5');
|
||||
|
||||
fireEvent.blur(input());
|
||||
expect(emitted()).toBe('100');
|
||||
expect(input().value).toBe('۱۰۰');
|
||||
});
|
||||
|
||||
it('max روی blur اعمال میشود', () => {
|
||||
render(<Controlled max={1000} />);
|
||||
fireEvent.change(input(), { target: { value: '۵۰۰۰' } });
|
||||
fireEvent.blur(input());
|
||||
|
||||
expect(emitted()).toBe('1000');
|
||||
});
|
||||
|
||||
it('فیلد خالی روی blur به min پرت نمیشود', () => {
|
||||
render(<Controlled min={100} />);
|
||||
fireEvent.blur(input());
|
||||
|
||||
expect(input().value).toBe('');
|
||||
expect(emitted()).toBe('0');
|
||||
});
|
||||
|
||||
it('حروف نامعتبر حذف میشوند و هرگز NaN نمیدهد', () => {
|
||||
render(<Controlled />);
|
||||
fireEvent.change(input(), { target: { value: 'ابج' } });
|
||||
|
||||
expect(input().value).toBe('');
|
||||
expect(emitted()).toBe('0');
|
||||
expect(emitted()).not.toContain('NaN');
|
||||
});
|
||||
|
||||
it('latin ارقام لاتین با کاما نمایش میدهد', () => {
|
||||
render(<Controlled latin />);
|
||||
fireEvent.change(input(), { target: { value: '۱۲۰۰' } });
|
||||
|
||||
expect(input().value).toBe('1,200');
|
||||
});
|
||||
|
||||
it('suffix واحد را کنار فیلد نشان میدهد', () => {
|
||||
render(<Controlled suffix="تومان" />);
|
||||
expect(screen.getByText('تومان')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('تغییر مقدار از بیرون متن فیلد را همگام میکند', () => {
|
||||
const { rerender } = render(<PriceInput value={1000} onChange={vi.fn()} />);
|
||||
expect(input().value).toBe('۱٬۰۰۰');
|
||||
|
||||
rerender(<PriceInput value={0} onChange={vi.fn()} />);
|
||||
expect(input().value).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { toEnglishDigits } from '../../lib/utils';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { digitsOnly, parseUserNumber } from '../../lib/utils';
|
||||
|
||||
interface PriceInputProps {
|
||||
value: number | '';
|
||||
@@ -9,15 +9,30 @@ interface PriceInputProps {
|
||||
style?: React.CSSProperties;
|
||||
disabled?: boolean;
|
||||
min?: number;
|
||||
max?: number;
|
||||
/** نمایش ارقام لاتین با جداکنندهٔ کاما (پیشفرض: فارسی). */
|
||||
latin?: boolean;
|
||||
/** واحد نمایشی داخل فیلد، مثلاً «تومان». */
|
||||
suffix?: string;
|
||||
}
|
||||
|
||||
function formatDisplay(num: number, latin: boolean): string {
|
||||
if (num === 0) return '';
|
||||
return new Intl.NumberFormat(latin ? 'en-US' : 'fa-IR').format(num);
|
||||
}
|
||||
|
||||
/** مقدار prop را به متن نمایشی تبدیل میکند؛ صفر و خالی هر دو فیلد خالی هستند. */
|
||||
function textFromValue(value: number | '', latin: boolean): string {
|
||||
const num = value === '' ? 0 : Number(value);
|
||||
return Number.isFinite(num) && num !== 0 ? formatDisplay(num, latin) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* ورودی مبلغ: ارقام فارسی/عربی، جداکننده و واحد چسبیده به عدد را میپذیرد (پیست
|
||||
* «۸۵,۰۰۰ تومان» ⇒ 85000) و همیشه یک عدد معتبر — هرگز NaN — به بالا میدهد.
|
||||
*
|
||||
* متن فیلد state مستقل است تا «۰ تایپشده» از «خالی» تفکیک شود؛ محدودکردن به بازهٔ
|
||||
* min/max فقط روی blur اعمال میشود تا رقم اول تایپ به مرز نپرد.
|
||||
*/
|
||||
export default function PriceInput({
|
||||
value,
|
||||
onChange,
|
||||
@@ -26,31 +41,58 @@ export default function PriceInput({
|
||||
style,
|
||||
disabled,
|
||||
min = 0,
|
||||
max,
|
||||
latin = false,
|
||||
suffix,
|
||||
}: PriceInputProps) {
|
||||
const [display, setDisplay] = useState(() => (value !== '' && value > 0 ? formatDisplay(value, latin) : ''));
|
||||
const [text, setText] = useState(() => textFromValue(value, latin));
|
||||
const textRef = useRef(text);
|
||||
textRef.current = text;
|
||||
|
||||
// فقط وقتی مقدار از بیرون عوض شده باشد (reset فرم، بارگذاری داده) متن را بازنویسی کن.
|
||||
useEffect(() => {
|
||||
setDisplay(value !== '' && Number(value) > 0 ? formatDisplay(Number(value), latin) : '');
|
||||
const shown = parseUserNumber(textRef.current) ?? 0;
|
||||
const incoming = value === '' ? 0 : Number(value);
|
||||
if (shown !== incoming) setText(textFromValue(value, latin));
|
||||
}, [value, latin]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const raw = toEnglishDigits(e.target.value).replace(/[^0-9]/g, '');
|
||||
const num = raw === '' ? 0 : Math.max(min, parseInt(raw, 10));
|
||||
const raw = digitsOnly(e.target.value);
|
||||
const num = parseUserNumber(raw) ?? 0;
|
||||
setText(raw === '' ? '' : formatDisplay(num, latin));
|
||||
onChange(num);
|
||||
setDisplay(num > 0 ? formatDisplay(num, latin) : '');
|
||||
};
|
||||
|
||||
return (
|
||||
const handleBlur = () => {
|
||||
if (text === '') return;
|
||||
const num = parseUserNumber(text) ?? 0;
|
||||
const clamped = Math.min(max ?? Infinity, Math.max(min, num));
|
||||
if (clamped !== num) {
|
||||
setText(formatDisplay(clamped, latin));
|
||||
onChange(clamped);
|
||||
}
|
||||
};
|
||||
|
||||
const input = (
|
||||
<input
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
value={display}
|
||||
value={text}
|
||||
onChange={handleChange}
|
||||
onBlur={handleBlur}
|
||||
placeholder={placeholder}
|
||||
className={className}
|
||||
style={{ textAlign: 'left', direction: 'ltr', ...style }}
|
||||
style={suffix ? { textAlign: 'left', direction: 'ltr', border: 'none', background: 'transparent', outline: 'none', flex: 1, minWidth: 0, padding: 0, ...style } : { textAlign: 'left', direction: 'ltr', ...style }}
|
||||
disabled={disabled}
|
||||
/>
|
||||
);
|
||||
|
||||
if (!suffix) return input;
|
||||
|
||||
return (
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 6, width: '100%' }}>
|
||||
{input}
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)', flexShrink: 0 }}>{suffix}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ import { describe, it, expect } from 'vitest';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
digitsOnly,
|
||||
formatYear,
|
||||
parseUserNumber,
|
||||
parseUserNumberClamped,
|
||||
persianSafeNumber,
|
||||
iranNationalCodeSchema,
|
||||
iranNationalCodeOptionalSchema,
|
||||
@@ -150,6 +153,64 @@ describe('digitsOnly', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatYear', () => {
|
||||
it('سال شمسی را بدون جداکنندهی هزارگان میدهد', () => {
|
||||
expect(formatYear(1404)).toBe('۱۴۰۴');
|
||||
});
|
||||
it('برخلاف formatNumber جداکننده نمیگذارد', () => {
|
||||
expect(formatNumber(1404)).not.toBe(formatYear(1404));
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseUserNumber', () => {
|
||||
it('رقم فارسی را به عدد تبدیل میکند', () => {
|
||||
expect(parseUserNumber('۲۵')).toBe(25);
|
||||
});
|
||||
it('رقم عربی را به عدد تبدیل میکند', () => {
|
||||
expect(parseUserNumber('٢٥')).toBe(25);
|
||||
});
|
||||
it('جداکننده هزارگان و فاصله را نادیده میگیرد', () => {
|
||||
expect(parseUserNumber('1,200')).toBe(1200);
|
||||
expect(parseUserNumber('۸۵٬۰۰۰')).toBe(85000);
|
||||
expect(parseUserNumber(' ۹۰ ')).toBe(90);
|
||||
});
|
||||
it('اعشار فارسی را میپذیرد', () => {
|
||||
expect(parseUserNumber('۱۲.۵')).toBe(12.5);
|
||||
});
|
||||
it('عدد منفی را میپذیرد', () => {
|
||||
expect(parseUserNumber('-۳')).toBe(-3);
|
||||
});
|
||||
it('عدد را دستنخورده رد میکند', () => {
|
||||
expect(parseUserNumber(42)).toBe(42);
|
||||
});
|
||||
it('خالی و null → null', () => {
|
||||
expect(parseUserNumber('')).toBeNull();
|
||||
expect(parseUserNumber(null)).toBeNull();
|
||||
expect(parseUserNumber(undefined)).toBeNull();
|
||||
});
|
||||
it('ورودی نامعتبر → null و هرگز NaN', () => {
|
||||
expect(parseUserNumber('abc')).toBeNull();
|
||||
expect(parseUserNumber('۱۲ب۳')).toBeNull();
|
||||
expect(parseUserNumber('.')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseUserNumberClamped', () => {
|
||||
it('مقدار داخل بازه را دستنخورده برمیگرداند', () => {
|
||||
expect(parseUserNumberClamped('۲۵', 0, 100)).toBe(25);
|
||||
});
|
||||
it('بیشتر از سقف را به سقف میبرد', () => {
|
||||
expect(parseUserNumberClamped('۱۵۰', 0, 100)).toBe(100);
|
||||
});
|
||||
it('کمتر از کف را به کف میبرد', () => {
|
||||
expect(parseUserNumberClamped('-۵', 0, 100)).toBe(0);
|
||||
});
|
||||
it('ورودی نامعتبر → null (نه کف)', () => {
|
||||
expect(parseUserNumberClamped('abc', 0, 100)).toBeNull();
|
||||
expect(parseUserNumberClamped('', 0, 100)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('persianSafeNumber', () => {
|
||||
it('رشتهی فارسی را قبل از عدد شدن نرمال میکند', () => {
|
||||
const schema = persianSafeNumber(z.coerce.number());
|
||||
|
||||
@@ -14,6 +14,11 @@ export function formatNumber(n: number): string {
|
||||
return new Intl.NumberFormat('fa-IR').format(n);
|
||||
}
|
||||
|
||||
// سال شمسی: رقم فارسی بدون جداکنندهی هزارگان («۱۴۰۴» نه «۱٬۴۰۴»).
|
||||
export function formatYear(year: number): string {
|
||||
return new Intl.NumberFormat('fa-IR', { useGrouping: false }).format(year);
|
||||
}
|
||||
|
||||
// تایمزون رسمی سراسری برنامه = ایران. همهٔ نمایش/تبدیل تاریخ باید با این tz باشد،
|
||||
// مستقل از تایمزون مرورگرِ کاربر (اجباری).
|
||||
export const APP_TZ = 'Asia/Tehran';
|
||||
@@ -122,6 +127,28 @@ export function sanitizeMobileInput(input: string): string {
|
||||
return digitsOnly(input, 11);
|
||||
}
|
||||
|
||||
/**
|
||||
* رشتهی ورودی کاربر (ارقام فارسی/عربی، جداکنندهی هزارگان، فاصله) را به عدد امن تبدیل میکند.
|
||||
* هرگز NaN برنمیگرداند؛ ورودی نامعتبر یا خالی ⇒ null.
|
||||
*/
|
||||
export function parseUserNumber(raw: string | number | null | undefined): number | null {
|
||||
if (raw == null || raw === '') return null;
|
||||
const s = toEnglishDigits(String(raw)).replace(/[,\s٫٬]/g, '');
|
||||
if (!/^-?(\d+\.?\d*|\.\d+)$/.test(s)) return null;
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/** همان parseUserNumber با محدودکردن بازه — برای درصد (۰..۱۰۰) و مقادیر غیرمنفی. */
|
||||
export function parseUserNumberClamped(
|
||||
raw: string | number | null | undefined,
|
||||
min: number,
|
||||
max: number,
|
||||
): number | null {
|
||||
const n = parseUserNumber(raw);
|
||||
return n == null ? null : Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
// z.coerce.number() روی رشتهی فارسی NaN میدهد. فیلدهای عددی پنل در مبدأ (numericField
|
||||
// در lib/forms.ts) نرمال میشوند، پس این wrapper فقط برای مصرفکنندههای خارج از آن مسیر است.
|
||||
// روی resolverهای React Hook Form استفاده نکن — z.preprocess تایپ ورودی را unknown میکند.
|
||||
|
||||
@@ -38,6 +38,7 @@ function ClinicAppointmentSettingsContent() {
|
||||
}, [doctorsQ.data]);
|
||||
|
||||
const selected = activeUuid ?? doctorList[0]?.uuid ?? null;
|
||||
const selectedDoctor = doctorList.find(d => d.uuid === selected) ?? null;
|
||||
|
||||
if (!clinicUuid) {
|
||||
return (
|
||||
@@ -54,7 +55,9 @@ function ClinicAppointmentSettingsContent() {
|
||||
<div className="card-title-row">
|
||||
<div>
|
||||
<h1 className="section-title">مدیریت نوبت دهی</h1>
|
||||
<div className="muted">تنظیمات نوبتدهی پزشکان کلینیک</div>
|
||||
<div className="muted">
|
||||
{selectedDoctor ? `تنظیمات نوبتدهی ${selectedDoctor.name}` : 'تنظیمات نوبتدهی پزشکان کلینیک'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -88,6 +91,14 @@ function ClinicAppointmentSettingsContent() {
|
||||
{/* key اجباری است: بدون آن state ویرایشِ برنامه بین پزشکان نشت میکند */}
|
||||
{selected && (
|
||||
<div key={selected}>
|
||||
{/* نام پزشک انتخابشده، تا هنگام اسکرول هم مشخص باشد تنظیمات مربوط به کیست */}
|
||||
<div
|
||||
className="card card-pad"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 'var(--gap)' }}
|
||||
>
|
||||
<UserGroupIcon style={{ width: 18, height: 18, color: 'var(--primary)' }} />
|
||||
<span style={{ fontWeight: 600 }}>{selectedDoctor?.name}</span>
|
||||
</div>
|
||||
<FreeVisitPrice doctorUuid={selected} />
|
||||
<ScheduleSection doctorUuid={selected} />
|
||||
</div>
|
||||
|
||||
@@ -68,4 +68,54 @@ describe('ClinicServicesPage (خدمات)', () => {
|
||||
expect(screen.getByText('تعرفههای سالانه')).toBeInTheDocument();
|
||||
expect(screen.getByText('پوشش بیمه')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('فرم ویرایش سرویس دیگر سوییچ بیمه ندارد و به بخش پوشش بیمه ارجاع میدهد', async () => {
|
||||
renderWithProviders(<ClinicServicesPage />, { route: '/admin/clinic-services' });
|
||||
fireEvent.click(await screen.findByText('کندلا ۲۰۲۱'));
|
||||
fireEvent.click(await screen.findByTitle('عملیات'));
|
||||
fireEvent.click(await screen.findByText('ویرایش'));
|
||||
|
||||
expect(await screen.findByText('ویرایش سرویس')).toBeInTheDocument();
|
||||
expect(screen.queryByText('این خدمت شامل بیمه میشود')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('قیمت تقریبی با بیمه (تومان)')).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/در بخش «پوشش بیمه» تنظیم میشود/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('ذخیرهی سرویس فیلدهای بیمه را نمیفرستد', async () => {
|
||||
const patch = api.patch as ReturnType<typeof vi.fn>;
|
||||
patch.mockResolvedValue({ success: true, data: {} });
|
||||
|
||||
renderWithProviders(<ClinicServicesPage />, { route: '/admin/clinic-services' });
|
||||
fireEvent.click(await screen.findByText('کندلا ۲۰۲۱'));
|
||||
fireEvent.click(await screen.findByTitle('عملیات'));
|
||||
fireEvent.click(await screen.findByText('ویرایش'));
|
||||
fireEvent.click(await screen.findByText('ذخیره سرویس'));
|
||||
|
||||
await vi.waitFor(() => expect(patch).toHaveBeenCalled());
|
||||
const body = patch.mock.calls[0][1];
|
||||
expect(body).not.toHaveProperty('insurance_covered');
|
||||
expect(body).not.toHaveProperty('insurance_price_rials');
|
||||
});
|
||||
|
||||
it('کارت سرویسِ تحت پوشش، نشان «تحت پوشش» را نمایش میدهد', async () => {
|
||||
get.mockImplementation((url: string) => {
|
||||
if (url.includes('/subscription/my')) return Promise.resolve({ success: true, data: {
|
||||
subscription: null, used_trial: false,
|
||||
effective_plan: { name: 'professional', level: 2, max_secretaries: 10, features: { services: true } },
|
||||
} });
|
||||
if (url.includes('/payment/config')) return Promise.resolve({ success: true, data: { test_mode: true, gateways: [] } });
|
||||
if (url.includes('/service-sections')) return Promise.resolve({ success: true, data: [
|
||||
{ uuid: 'sec1', name: 'کندلا ۲۰۲۱', active: true, items_count: 1 },
|
||||
] });
|
||||
if (url.includes('/service-items/sec1')) return Promise.resolve({ success: true, data: [
|
||||
{ uuid: 'it1', name: 'فول بادی', price_rials: 35_000_000, active: true, insurance_covered: true },
|
||||
] });
|
||||
return Promise.resolve({ success: true, data: [] });
|
||||
});
|
||||
|
||||
renderWithProviders(<ClinicServicesPage />, { route: '/admin/clinic-services' });
|
||||
fireEvent.click(await screen.findByText('کندلا ۲۰۲۱'));
|
||||
|
||||
expect(await screen.findByText('تحت پوشش')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
PlusIcon, PencilIcon, TrashIcon, WrenchScrewdriverIcon, BanknotesIcon,
|
||||
@@ -12,29 +13,17 @@ import { z } from 'zod';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import type { ServiceSection, ServiceItem, ClinicStaff } from '../types';
|
||||
import { formatRial, formatNumber, rialToToman, tomanToRial } from '../lib/utils';
|
||||
import type { ServiceSection, ServiceItem } from '../types';
|
||||
import { formatRial, formatNumber } from '../lib/utils';
|
||||
import Modal from '../components/ui/Modal';
|
||||
import PriceInput from '../components/ui/PriceInput';
|
||||
import ConfirmDialog from '../components/ui/ConfirmDialog';
|
||||
import ServiceTariffModal from '../components/ServiceTariffModal';
|
||||
import ServiceInsuranceModal from '../components/ServiceInsuranceModal';
|
||||
import SearchableSelect from '../components/ui/SearchableSelect';
|
||||
import ServiceItemFormModal from '../components/ServiceItemFormModal';
|
||||
import FeatureGate from '../components/ui/FeatureGate';
|
||||
import { numericField } from '../lib/forms';
|
||||
|
||||
const sectionSchema = z.object({ name: z.string().min(1, 'نام بخش الزامی است') });
|
||||
const itemSchema = z.object({
|
||||
name: z.string().min(1, 'نام سرویس الزامی است'),
|
||||
price_rials: z.coerce.number().min(0, 'مبلغ نمیتواند منفی باشد'),
|
||||
staff_uuids: z.array(z.string()).optional(),
|
||||
insurance_covered: z.boolean().optional(),
|
||||
insurance_price_rials: z.coerce.number().min(0).optional(),
|
||||
duration_minutes: z.coerce.number().min(0).optional(),
|
||||
bookable: z.boolean().optional(),
|
||||
});
|
||||
type SectionForm = z.infer<typeof sectionSchema>;
|
||||
type ItemForm = z.infer<typeof itemSchema>;
|
||||
|
||||
const EMPTY_SECTIONS: ServiceSection[] = [];
|
||||
const EMPTY_ITEMS: ServiceItem[] = [];
|
||||
@@ -52,26 +41,9 @@ function Avatar({ name }: { name: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function SrvRow({ label, value, strong, danger }: { label: string; value: string; strong?: boolean; danger?: boolean }) {
|
||||
return (
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8, padding: '3px 0' }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)', flexShrink: 0 }}>{label}:</span>
|
||||
<span
|
||||
style={{
|
||||
fontSize: 14,
|
||||
fontWeight: strong ? 800 : 500,
|
||||
color: danger ? 'var(--danger)' : strong ? 'var(--primary)' : 'var(--text-2)',
|
||||
textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ClinicServicesPageInner() {
|
||||
const qc = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [selectedSection, setSelectedSection] = useState<ServiceSection | null>(null);
|
||||
const [sectionModal, setSectionModal] = useState<'create' | ServiceSection | null>(null);
|
||||
@@ -95,33 +67,10 @@ function ClinicServicesPageInner() {
|
||||
enabled: !!selectedSection,
|
||||
});
|
||||
|
||||
const { data: staffData } = useQuery<ApiResponse<ClinicStaff[]>>({
|
||||
queryKey: ['staff'],
|
||||
queryFn: () => api.get('/api/v1/staff'),
|
||||
});
|
||||
|
||||
const sections = sectionsData?.data ?? EMPTY_SECTIONS;
|
||||
const allItems = itemsData?.data ?? EMPTY_ITEMS;
|
||||
const allStaff = staffData?.data ?? [];
|
||||
|
||||
const sectionForm = useForm<SectionForm>({ resolver: zodResolver(sectionSchema) });
|
||||
const itemForm = useForm<ItemForm>({ resolver: zodResolver(itemSchema) });
|
||||
|
||||
const selectedStaffUuids = itemForm.watch('staff_uuids') ?? [];
|
||||
const editingMembers = itemModal && typeof itemModal === 'object'
|
||||
? (itemModal.staff_members ?? (itemModal.staff ? [itemModal.staff] : []))
|
||||
: [];
|
||||
const staffOptions = allStaff
|
||||
.filter((s) => s.active || editingMembers.some((m) => m.uuid === s.uuid))
|
||||
.filter((s) => !selectedStaffUuids.includes(s.uuid))
|
||||
.map((s) => ({
|
||||
value: s.uuid,
|
||||
label: s.active ? s.full_name : `${s.full_name} (غیرفعال)`,
|
||||
}));
|
||||
const staffNameOf = (uuid: string) =>
|
||||
allStaff.find((s) => s.uuid === uuid)?.full_name
|
||||
?? editingMembers.find((m) => m.uuid === uuid)?.full_name
|
||||
?? uuid;
|
||||
|
||||
const items = allItems.filter((it) => {
|
||||
if (!showInactive && !it.active) return false;
|
||||
@@ -164,27 +113,6 @@ function ClinicServicesPageInner() {
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const createItem = useMutation({
|
||||
mutationFn: (body: ItemForm & { section_uuid: string }) => api.post('/api/v1/service-item', {
|
||||
...body,
|
||||
price_rials: tomanToRial(body.price_rials),
|
||||
insurance_price_rials: tomanToRial(body.insurance_price_rials ?? 0),
|
||||
}),
|
||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setItemModal(null); itemForm.reset(); toast.success('سرویس ایجاد شد'); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const editItem = useMutation({
|
||||
mutationFn: ({ uuid, body }: { uuid: string; body: ItemForm }) =>
|
||||
api.patch(`/api/v1/service-item/${uuid}`, {
|
||||
...body,
|
||||
price_rials: tomanToRial(body.price_rials),
|
||||
insurance_price_rials: tomanToRial(body.insurance_price_rials ?? 0),
|
||||
}),
|
||||
onSuccess: () => { qc.invalidateQueries({ queryKey: ['service-items', selectedSection?.uuid] }); setItemModal(null); toast.success('سرویس ویرایش شد'); },
|
||||
onError: (e: any) => toast.error(e.message),
|
||||
});
|
||||
|
||||
const toggleActive = useMutation({
|
||||
mutationFn: ({ uuid, active }: { uuid: string; active: boolean }) =>
|
||||
api.patch(`/api/v1/service-item/${uuid}`, { active }),
|
||||
@@ -201,23 +129,7 @@ function ClinicServicesPageInner() {
|
||||
setSectionModal(s);
|
||||
};
|
||||
|
||||
const openEditItem = (item: ServiceItem) => {
|
||||
itemForm.reset({
|
||||
name: item.name,
|
||||
price_rials: rialToToman(item.price_rials),
|
||||
staff_uuids: (item.staff_members ?? (item.staff ? [item.staff] : [])).map((s) => s.uuid),
|
||||
insurance_covered: item.insurance_covered ?? false,
|
||||
insurance_price_rials: rialToToman(item.insurance_price_rials ?? 0),
|
||||
duration_minutes: item.duration_minutes ?? undefined,
|
||||
bookable: item.bookable ?? false,
|
||||
});
|
||||
setItemModal(item);
|
||||
};
|
||||
|
||||
const openCreateItem = () => {
|
||||
itemForm.reset({ name: '', price_rials: 0, staff_uuids: [], insurance_covered: false, insurance_price_rials: 0, duration_minutes: undefined, bookable: false });
|
||||
setItemModal('create');
|
||||
};
|
||||
const openCreateItem = () => setItemModal('create');
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -337,16 +249,20 @@ function ClinicServicesPageInner() {
|
||||
return (
|
||||
<div
|
||||
key={item.uuid}
|
||||
role="link"
|
||||
tabIndex={0}
|
||||
onClick={() => navigate(`/admin/clinic-services/${item.uuid}`)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') navigate(`/admin/clinic-services/${item.uuid}`); }}
|
||||
style={{
|
||||
position: 'relative', background: 'var(--surface)', borderRadius: 8,
|
||||
boxShadow: '0 1px 24.8px rgba(204,204,204,0.18)',
|
||||
border: '1px solid var(--border)', padding: 14,
|
||||
border: '1px solid var(--border)', padding: 14, cursor: 'pointer',
|
||||
opacity: item.active ? 1 : 0.7,
|
||||
}}
|
||||
>
|
||||
{/* نوار بالا: ⋮ (چپ) + وضعیت و نام (راست) */}
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8, marginBottom: 14 }}>
|
||||
<button className="btn sm ghost" style={{ padding: 4 }} onClick={() => setMenuOpen(menuOpen === item.uuid ? null : item.uuid)} title="عملیات">
|
||||
<button className="btn sm ghost" style={{ padding: 4 }} onClick={(e) => { e.stopPropagation(); setMenuOpen(menuOpen === item.uuid ? null : item.uuid); }} title="عملیات">
|
||||
<EllipsisHorizontalIcon style={{ width: 20 }} />
|
||||
</button>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
|
||||
@@ -358,9 +274,9 @@ function ClinicServicesPageInner() {
|
||||
</div>
|
||||
{menuOpen === item.uuid && (
|
||||
<>
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 40 }} onClick={() => setMenuOpen(null)} />
|
||||
<div style={{ position: 'absolute', top: 40, insetInlineStart: 8, zIndex: 41, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow)', padding: 6, minWidth: 176, display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<button style={menuItemStyle} onClick={() => { setMenuOpen(null); openEditItem(item); }}><PencilIcon style={{ width: 15 }} /> ویرایش</button>
|
||||
<div style={{ position: 'fixed', inset: 0, zIndex: 40 }} onClick={(e) => { e.stopPropagation(); setMenuOpen(null); }} />
|
||||
<div onClick={(e) => e.stopPropagation()} style={{ position: 'absolute', top: 40, insetInlineStart: 8, zIndex: 41, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow)', padding: 6, minWidth: 176, display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<button style={menuItemStyle} onClick={() => { setMenuOpen(null); setItemModal(item); }}><PencilIcon style={{ width: 15 }} /> ویرایش</button>
|
||||
<button style={menuItemStyle} onClick={() => { setMenuOpen(null); setTariffItem(item); }}><BanknotesIcon style={{ width: 15 }} /> تعرفههای سالانه</button>
|
||||
<button style={menuItemStyle} onClick={() => { setMenuOpen(null); setInsuranceItem(item); }}><ShieldCheckIcon style={{ width: 15 }} /> پوشش بیمه</button>
|
||||
<button style={menuItemStyle} onClick={() => { setMenuOpen(null); setToggleItem(item); }}>{item.active ? <EyeSlashIcon style={{ width: 15 }} /> : <EyeIcon style={{ width: 15 }} />}{item.active ? ' غیرفعالکردن' : ' فعالکردن'}</button>
|
||||
@@ -387,9 +303,14 @@ function ClinicServicesPageInner() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{item.insurance_covered && item.insurance_price_rials != null && (
|
||||
<SrvRow label="سهم بیمار (بیمه)" value={formatRial(item.insurance_price_rials)} />
|
||||
)}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, padding: '3px 0' }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
|
||||
<ShieldCheckIcon style={{ width: 14, color: 'var(--text-3)' }} /> بیمه:
|
||||
</span>
|
||||
{item.insurance_covered
|
||||
? <span className="badge green" style={{ fontSize: 11 }}>تحت پوشش</span>
|
||||
: <span style={{ fontSize: 12, color: 'var(--text-3)' }}>—</span>}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8, padding: '3px 0' }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)', flexShrink: 0, display: 'inline-flex', alignItems: 'center', gap: 5 }}>
|
||||
@@ -436,162 +357,12 @@ function ClinicServicesPageInner() {
|
||||
</Modal>
|
||||
|
||||
{/* ───────── Modal سرویس ───────── */}
|
||||
<Modal
|
||||
open={itemModal !== null}
|
||||
<ServiceItemFormModal
|
||||
item={itemModal}
|
||||
sectionUuid={selectedSection?.uuid ?? 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
|
||||
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 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={''}
|
||||
onChange={(v) => {
|
||||
if (v != null) itemForm.setValue('staff_uuids', [...selectedStaffUuids, String(v)]);
|
||||
}}
|
||||
placeholder="افزودن پرسنل (اختیاری)"
|
||||
noOptionsMessage="پرسنلی باقی نمانده"
|
||||
height={42}
|
||||
/>
|
||||
{selectedStaffUuids.length > 0 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
|
||||
{selectedStaffUuids.map((uuid) => (
|
||||
<span key={uuid} style={{
|
||||
display: 'inline-flex', alignItems: 'center', gap: 6,
|
||||
fontSize: 12.5, color: 'var(--text-2)', background: 'var(--surface-2)',
|
||||
border: '1px solid var(--border)', borderRadius: 999, padding: '4px 6px 4px 10px',
|
||||
}}>
|
||||
{staffNameOf(uuid)}
|
||||
<button
|
||||
type="button" aria-label={`حذف ${staffNameOf(uuid)}`}
|
||||
onClick={() => itemForm.setValue('staff_uuids', selectedStaffUuids.filter((u) => u !== uuid))}
|
||||
style={{ display: 'grid', placeItems: 'center', width: 16, height: 16, border: 'none', cursor: 'pointer', borderRadius: '50%', background: 'var(--surface-3)', color: 'var(--text-3)' }}
|
||||
>
|
||||
<XMarkIcon style={{ width: 11 }} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'end' }}>
|
||||
<div>
|
||||
<label className="field-label">زمان متوسط (دقیقه)</label>
|
||||
<div className="field">
|
||||
<input {...numericField(itemForm.register('duration_minutes'))} placeholder="مثلاً: 50" />
|
||||
</div>
|
||||
</div>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', padding: '9px 0' }}>
|
||||
<span className="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={itemForm.watch('bookable') ?? false}
|
||||
onChange={(e) => itemForm.setValue('bookable', e.target.checked)}
|
||||
/>
|
||||
<span className="switch-track"><span className="switch-thumb" /></span>
|
||||
</span>
|
||||
<span style={{ fontSize: 13 }}>نمایش در نوبتدهی</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* بیمه */}
|
||||
<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>
|
||||
|
||||
onManageInsurance={setInsuranceItem}
|
||||
/>
|
||||
<ServiceTariffModal item={tariffItem} onClose={() => setTariffItem(null)} />
|
||||
|
||||
<ServiceInsuranceModal item={insuranceItem} onClose={() => setInsuranceItem(null)} />
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, fireEvent } from '@testing-library/react';
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import { renderWithProviders } from '../test/utils';
|
||||
|
||||
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
|
||||
vi.mock('../lib/api', () => ({
|
||||
api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
|
||||
ApiError: class extends Error {},
|
||||
}));
|
||||
|
||||
import { api } from '../lib/api';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import ServiceDetailPage from './ServiceDetailPage';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
|
||||
const ITEM = {
|
||||
uuid: 'it1',
|
||||
name: 'سرم ۵۰۰cc',
|
||||
section_uuid: 'sec1',
|
||||
section_name: 'تزریقات',
|
||||
price_rials: 8_500_000,
|
||||
active: true,
|
||||
bookable: true,
|
||||
duration_minutes: 30,
|
||||
insurance_covered: true,
|
||||
staff: { uuid: 'st1', full_name: 'مریم امینی' },
|
||||
staff_members: [{ uuid: 'st1', full_name: 'مریم امینی' }],
|
||||
created_at: 1_700_000_000,
|
||||
updated_at: 1_800_000_000,
|
||||
};
|
||||
|
||||
const mockApi = (item: unknown = ITEM, notFound = false) => {
|
||||
get.mockImplementation((url: string) => {
|
||||
if (url.includes('/subscription/my')) return Promise.resolve({ success: true, data: {
|
||||
subscription: null, used_trial: false,
|
||||
effective_plan: { name: 'professional', level: 2, max_secretaries: 10, features: { services: true } },
|
||||
} });
|
||||
if (url.includes('/payment/config')) return Promise.resolve({ success: true, data: { test_mode: true, gateways: [] } });
|
||||
if (url.includes('/service-item/')) {
|
||||
return notFound ? Promise.reject(new Error('یافت نشد')) : Promise.resolve({ success: true, data: item });
|
||||
}
|
||||
if (url.includes('/tariffs')) return Promise.resolve({ success: true, data: {
|
||||
current_year: 1404, default_price_rials: 8_500_000,
|
||||
data: [
|
||||
{ uuid: 't1', year: 1404, price_rials: 8_500_000, is_active: true },
|
||||
{ uuid: 't2', year: 1403, price_rials: 7_000_000, is_active: false },
|
||||
],
|
||||
} });
|
||||
if (url.includes('/tenant-insurances')) return Promise.resolve({ data: { data: [
|
||||
{ uuid: 'ins1', insurance_name: 'بیمه ایران', insurance_kind: 'basic', coverage_percent: 70 },
|
||||
] } });
|
||||
return Promise.resolve({ success: true, data: [] });
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({ primaryRole: 'doctor' });
|
||||
get.mockReset();
|
||||
mockApi();
|
||||
});
|
||||
|
||||
// صفحه uuid را از useParams میگیرد، پس به یک Route واقعی نیاز دارد.
|
||||
const render = () =>
|
||||
renderWithProviders(
|
||||
<Routes>
|
||||
<Route path="/admin/clinic-services/:uuid" element={<ServiceDetailPage />} />
|
||||
</Routes>,
|
||||
{ route: '/admin/clinic-services/it1' },
|
||||
);
|
||||
|
||||
describe('ServiceDetailPage (جزئیات سرویس)', () => {
|
||||
it('اطلاعات پایه سرویس را با breadcrumb نمایش میدهد', async () => {
|
||||
render();
|
||||
|
||||
expect(await screen.findByRole('heading', { name: 'سرم ۵۰۰cc' })).toBeInTheDocument();
|
||||
expect(screen.getByText('سرویسها')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('تزریقات').length).toBeGreaterThan(0);
|
||||
expect(screen.getByText('مریم امینی')).toBeInTheDocument();
|
||||
expect(screen.getByText('۳۰ دقیقه')).toBeInTheDocument();
|
||||
expect(screen.getByText('تحت پوشش')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('تاریخ ایجاد و آخرین ویرایش را شمسی نشان میدهد', async () => {
|
||||
render();
|
||||
|
||||
expect(await screen.findByText('تاریخ ایجاد')).toBeInTheDocument();
|
||||
expect(screen.getByText('آخرین ویرایش')).toBeInTheDocument();
|
||||
// سال شمسی معادل ۱۷۰۰۰۰۰۰۰۰ ⇒ ۱۴۰۲
|
||||
expect(screen.getByText(/۱۴۰۲/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('تب تعرفهها فهرست سالها را با نشان «سال جاری» میآورد', async () => {
|
||||
render();
|
||||
fireEvent.click(await screen.findByText('تعرفهها'));
|
||||
|
||||
expect(await screen.findByText('سال جاری')).toBeInTheDocument();
|
||||
expect(screen.getByText('۱۴۰۴')).toBeInTheDocument();
|
||||
expect(screen.getByText('۱۴۰۳')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('تب بیمهها قراردادها و درصد پوشش را میآورد', async () => {
|
||||
render();
|
||||
fireEvent.click(await screen.findByText('بیمهها'));
|
||||
|
||||
expect(await screen.findByText('بیمه ایران')).toBeInTheDocument();
|
||||
expect(screen.getByText(/پوشش ۷۰٪/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('سرویس ناموجود → پیام خطا و دکمه بازگشت', async () => {
|
||||
mockApi(null, true);
|
||||
render();
|
||||
|
||||
expect(await screen.findByText('سرویس یافت نشد')).toBeInTheDocument();
|
||||
expect(screen.getByText('بازگشت به سرویسها')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('دکمه ویرایش، فرم مشترک سرویس را باز میکند', async () => {
|
||||
render();
|
||||
fireEvent.click(await screen.findByText('ویرایش'));
|
||||
|
||||
expect(await screen.findByText('ویرایش سرویس')).toBeInTheDocument();
|
||||
// تنظیمات بیمه نباید در فرم باشد
|
||||
expect(screen.queryByText('این خدمت شامل بیمه میشود')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('سرویس غیرفعال نشان «غیرفعال» و دکمه فعالکردن دارد', async () => {
|
||||
mockApi({ ...ITEM, active: false });
|
||||
render();
|
||||
|
||||
expect(await screen.findByText('غیرفعال')).toBeInTheDocument();
|
||||
expect(screen.getByText('فعالکردن')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
import { useState } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
BanknotesIcon, ShieldCheckIcon, ClockIcon, UsersIcon, PencilIcon,
|
||||
CalendarDaysIcon, WrenchScrewdriverIcon, CubeIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import type { ServiceItem } from '../types';
|
||||
import { formatRial, formatNumber, formatYear, formatDateTime } from '../lib/utils';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import FeatureGate from '../components/ui/FeatureGate';
|
||||
import ConfirmDialog from '../components/ui/ConfirmDialog';
|
||||
import ServiceTariffModal from '../components/ServiceTariffModal';
|
||||
import ServiceInsuranceModal from '../components/ServiceInsuranceModal';
|
||||
import ServiceItemFormModal from '../components/ServiceItemFormModal';
|
||||
|
||||
interface Tariff {
|
||||
uuid: string;
|
||||
year: number;
|
||||
price_rials: number;
|
||||
is_active: boolean;
|
||||
}
|
||||
|
||||
interface TariffList {
|
||||
current_year: number;
|
||||
default_price_rials: number;
|
||||
data: Tariff[];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const TABS = [
|
||||
{ id: 'info', label: 'اطلاعات سرویس' },
|
||||
{ id: 'tariffs', label: 'تعرفهها' },
|
||||
{ id: 'insurance', label: 'بیمهها' },
|
||||
] as const;
|
||||
type TabId = typeof TABS[number]['id'];
|
||||
|
||||
const KIND = {
|
||||
basic: { label: 'پایه', cls: 'blue' },
|
||||
supplementary: { label: 'تکمیلی', cls: 'violet' },
|
||||
} as const;
|
||||
|
||||
function Row({ icon, label, children }: { icon: React.ReactNode; label: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
|
||||
gap: 12, padding: '11px 0', borderBottom: '1px solid var(--border)',
|
||||
}}>
|
||||
<span style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
{icon} {label}
|
||||
</span>
|
||||
<span style={{ fontSize: 13.5, color: 'var(--text-2)', textAlign: 'left', minWidth: 0 }}>{children}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoTab({ item }: { item: ServiceItem }) {
|
||||
const members = item.staff_members ?? (item.staff ? [item.staff] : []);
|
||||
|
||||
return (
|
||||
<div className="card card-pad">
|
||||
<Row icon={<BanknotesIcon style={{ width: 15 }} />} label="قیمت پایه">
|
||||
<b style={{ color: 'var(--primary)', fontSize: 14 }}>{formatRial(item.price_rials)}</b>
|
||||
</Row>
|
||||
<Row icon={<WrenchScrewdriverIcon style={{ width: 15 }} />} label="بخش">
|
||||
{item.section_name ?? '—'}
|
||||
</Row>
|
||||
<Row icon={<ClockIcon style={{ width: 15 }} />} label="زمان متوسط">
|
||||
{item.duration_minutes
|
||||
? <span className="badge blue" style={{ fontSize: 11 }}>{formatNumber(Number(item.duration_minutes))} دقیقه</span>
|
||||
: '—'}
|
||||
</Row>
|
||||
<Row icon={<CalendarDaysIcon style={{ width: 15 }} />} label="نمایش در نوبتدهی">
|
||||
{item.bookable
|
||||
? <span className="badge green" style={{ fontSize: 11 }}>فعال</span>
|
||||
: <span className="badge gray" style={{ fontSize: 11 }}>غیرفعال</span>}
|
||||
</Row>
|
||||
<Row icon={<ShieldCheckIcon style={{ width: 15 }} />} label="پوشش بیمه">
|
||||
{item.insurance_covered
|
||||
? <span className="badge green" style={{ fontSize: 11 }}>تحت پوشش</span>
|
||||
: '—'}
|
||||
</Row>
|
||||
<Row icon={<UsersIcon style={{ width: 15 }} />} label="پرسنل مسئول">
|
||||
{members.length > 0 ? (
|
||||
<span style={{ display: 'flex', flexWrap: 'wrap', gap: 4, justifyContent: 'flex-end' }}>
|
||||
{members.map((m) => (
|
||||
<span key={m.uuid} style={{
|
||||
fontSize: 12, color: 'var(--text-2)', background: 'var(--surface-2)',
|
||||
border: '1px solid var(--border)', borderRadius: 999, padding: '3px 10px', whiteSpace: 'nowrap',
|
||||
}}>{m.full_name}</span>
|
||||
))}
|
||||
</span>
|
||||
) : '—'}
|
||||
</Row>
|
||||
<Row icon={<CalendarDaysIcon style={{ width: 15 }} />} label="تاریخ ایجاد">
|
||||
{item.created_at ? formatDateTime(item.created_at) : '—'}
|
||||
</Row>
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '11px 0',
|
||||
}}>
|
||||
<span style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
|
||||
<CalendarDaysIcon style={{ width: 15 }} /> آخرین ویرایش
|
||||
</span>
|
||||
<span style={{ fontSize: 13.5, color: 'var(--text-2)' }}>
|
||||
{item.updated_at ? formatDateTime(item.updated_at) : '—'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TariffsTab({ item, onManage }: { item: ServiceItem; onManage: () => void }) {
|
||||
const { data, isLoading } = useQuery<ApiResponse<TariffList>>({
|
||||
queryKey: ['service-tariffs', item.uuid],
|
||||
queryFn: () => api.get(`/api/v1/service-items/${item.uuid}/tariffs`),
|
||||
});
|
||||
|
||||
const list = data?.data;
|
||||
const tariffs = list?.data ?? [];
|
||||
|
||||
return (
|
||||
<div className="card card-pad">
|
||||
<div className="card-title-row">
|
||||
<div>
|
||||
<b style={{ fontSize: 14 }}>تعرفههای سالانه</b>
|
||||
<div className="muted" style={{ fontSize: 12 }}>
|
||||
قیمت هر سال شمسی؛ قیمت سال جاری مبنای صورتحساب است.
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn primary sm" onClick={onManage}>مدیریت تعرفهها</button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="muted" style={{ fontSize: 13, padding: '12px 0' }}>در حال بارگذاری...</div>
|
||||
) : tariffs.length === 0 ? (
|
||||
<div className="empty" style={{ padding: '28px 0' }}>
|
||||
<BanknotesIcon style={{ width: 30, height: 30 }} />
|
||||
<p className="muted">تعرفهای ثبت نشده است</p>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
|
||||
{tariffs.map((t) => (
|
||||
<div key={t.uuid} style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
|
||||
padding: '10px 12px', borderRadius: 'var(--r-sm)',
|
||||
border: '1px solid var(--border)',
|
||||
background: t.year === list?.current_year ? 'var(--primary-soft)' : 'var(--surface)',
|
||||
}}>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
|
||||
<b>{formatYear(t.year)}</b>
|
||||
{t.year === list?.current_year && <span className="badge green" style={{ fontSize: 10 }}>سال جاری</span>}
|
||||
{!t.is_active && <span className="badge gray" style={{ fontSize: 10 }}>غیرفعال</span>}
|
||||
</span>
|
||||
<b style={{ fontSize: 13.5, color: 'var(--primary)' }}>{formatRial(t.price_rials)}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InsuranceTab({ item, onManage }: { item: ServiceItem; onManage: () => void }) {
|
||||
const { data: contractsData, isLoading } = useQuery<{ data: { data: TenantInsurance[] } }>({
|
||||
queryKey: ['tenant-insurances'],
|
||||
queryFn: () => api.get('/api/v1/billing/tenant-insurances'),
|
||||
});
|
||||
|
||||
const contracts = (contractsData as any)?.data?.data as TenantInsurance[] | undefined ?? [];
|
||||
|
||||
return (
|
||||
<div className="card card-pad">
|
||||
<div className="card-title-row">
|
||||
<div>
|
||||
<b style={{ fontSize: 14 }}>بیمههای مرتبط</b>
|
||||
<div className="muted" style={{ fontSize: 12 }}>
|
||||
درصد پوشش، فرانشیز و سقف هر بیمهگر برای این خدمت.
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn primary sm" onClick={onManage}>مدیریت پوشش</button>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="muted" style={{ fontSize: 13, padding: '12px 0' }}>در حال بارگذاری...</div>
|
||||
) : contracts.length === 0 ? (
|
||||
<div className="empty" style={{ padding: '28px 0' }}>
|
||||
<ShieldCheckIcon style={{ width: 30, height: 30 }} />
|
||||
<p className="muted">قرارداد بیمهی فعالی ندارید</p>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
|
||||
{contracts.map((c) => (
|
||||
<ContractCoverageRow key={c.uuid} contract={c} itemUuid={item.uuid} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ContractCoverageRow({ contract, itemUuid }: { contract: TenantInsurance; itemUuid: string }) {
|
||||
const { data } = useQuery<{ data: { data: CoverageRow[] } }>({
|
||||
queryKey: ['service-coverage', contract.uuid],
|
||||
queryFn: () => api.get(`/api/v1/billing/tenant-insurances/${contract.uuid}/service-coverage`),
|
||||
});
|
||||
|
||||
const row = ((data as any)?.data?.data as CoverageRow[] | undefined)
|
||||
?.find((r) => r.service_item_uuid === itemUuid);
|
||||
const kind = contract.insurance_kind ? KIND[contract.insurance_kind] : null;
|
||||
const percent = row?.coverage_percent ?? contract.coverage_percent;
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
|
||||
padding: '10px 12px', borderRadius: 'var(--r-sm)', border: '1px solid var(--border)',
|
||||
}}>
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, minWidth: 0 }}>
|
||||
<ShieldCheckIcon style={{ width: 15, color: 'var(--primary)', flexShrink: 0 }} />
|
||||
<b style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{contract.insurance_name ?? 'بیمه'}
|
||||
</b>
|
||||
{kind && <span className={`badge ${kind.cls}`} style={{ fontSize: 10 }}>{kind.label}</span>}
|
||||
</span>
|
||||
{row && !row.covered ? (
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>بدون پوشش</span>
|
||||
) : (
|
||||
<span style={{ fontSize: 12.5, color: 'var(--text-2)', display: 'inline-flex', gap: 10, whiteSpace: 'nowrap' }}>
|
||||
<span>پوشش {formatNumber(percent)}٪</span>
|
||||
{row?.franchise_rials ? <span>فرانشیز {formatRial(row.franchise_rials)}</span> : null}
|
||||
{row?.ceiling_rials ? <span>سقف {formatRial(row.ceiling_rials)}</span> : null}
|
||||
{!row && <span className="muted">(ارث از قرارداد)</span>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ServiceDetailPageInner() {
|
||||
const { uuid } = useParams<{ uuid: string }>();
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
|
||||
const [tab, setTab] = useState<TabId>('info');
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [tariffOpen, setTariffOpen] = useState(false);
|
||||
const [insuranceOpen, setInsuranceOpen] = useState(false);
|
||||
const [toggleOpen, setToggleOpen] = useState(false);
|
||||
|
||||
const { data, isLoading, isError } = useQuery<ApiResponse<ServiceItem>>({
|
||||
queryKey: ['service-item', uuid],
|
||||
queryFn: () => api.get(`/api/v1/service-item/${uuid}`),
|
||||
enabled: !!uuid,
|
||||
});
|
||||
|
||||
const item = data?.data;
|
||||
|
||||
const toggleActive = useMutation({
|
||||
mutationFn: () => api.patch(`/api/v1/service-item/${uuid}`, { active: !item!.active }),
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: ['service-item', uuid] });
|
||||
qc.invalidateQueries({ queryKey: ['service-items'] });
|
||||
setToggleOpen(false);
|
||||
toast.success(item!.active ? 'سرویس غیرفعال شد' : 'سرویس فعال شد');
|
||||
},
|
||||
onError: (e: Error) => { toast.error(e.message); setToggleOpen(false); },
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return <div style={{ color: 'var(--text-3)', fontSize: 13, padding: 16 }}>در حال بارگذاری...</div>;
|
||||
}
|
||||
|
||||
if (isError || !item) {
|
||||
return (
|
||||
<div className="card" style={{ padding: '52px 0', textAlign: 'center' }}>
|
||||
<CubeIcon style={{ width: 34, margin: '0 auto 12px', display: 'block', opacity: 0.35 }} />
|
||||
<div style={{ fontWeight: 600, color: 'var(--text-2)', marginBottom: 12 }}>سرویس یافت نشد</div>
|
||||
<button className="btn primary sm" onClick={() => navigate('/admin/clinic-services')}>بازگشت به سرویسها</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fade-in">
|
||||
<PageHeader
|
||||
title={item.name}
|
||||
breadcrumbs={[
|
||||
{ label: 'سرویسها', to: '/admin/clinic-services' },
|
||||
...(item.section_name ? [{ label: item.section_name }] : []),
|
||||
{ label: item.name },
|
||||
]}
|
||||
action={
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn sm" onClick={() => setToggleOpen(true)}>
|
||||
{item.active ? 'غیرفعالکردن' : 'فعالکردن'}
|
||||
</button>
|
||||
<button className="btn primary sm" onClick={() => setEditOpen(true)}>
|
||||
<PencilIcon style={{ width: 15 }} /> ویرایش
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 'var(--gap)' }}>
|
||||
<span className={`badge ${item.active ? 'green' : 'gray'}`} style={{ fontSize: 11 }}>
|
||||
<span className="bdot" />{item.active ? 'فعال' : 'غیرفعال'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="seg" style={{ marginBottom: 'var(--gap)', overflowX: 'auto', flexWrap: 'nowrap' }}>
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
className={tab === t.id ? 'active' : ''}
|
||||
style={{ whiteSpace: 'nowrap' }}
|
||||
onClick={() => setTab(t.id)}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{tab === 'info' && <InfoTab item={item} />}
|
||||
{tab === 'tariffs' && <TariffsTab item={item} onManage={() => setTariffOpen(true)} />}
|
||||
{tab === 'insurance' && <InsuranceTab item={item} onManage={() => setInsuranceOpen(true)} />}
|
||||
|
||||
<ServiceItemFormModal
|
||||
item={editOpen ? item : null}
|
||||
sectionUuid={item.section_uuid ?? null}
|
||||
onClose={() => setEditOpen(false)}
|
||||
onManageInsurance={() => setInsuranceOpen(true)}
|
||||
/>
|
||||
<ServiceTariffModal item={tariffOpen ? item : null} onClose={() => setTariffOpen(false)} />
|
||||
<ServiceInsuranceModal item={insuranceOpen ? item : null} onClose={() => setInsuranceOpen(false)} />
|
||||
|
||||
<ConfirmDialog
|
||||
open={toggleOpen}
|
||||
title={item.active ? 'غیرفعالکردن سرویس' : 'فعالکردن سرویس'}
|
||||
message={
|
||||
item.active
|
||||
? `سرویس «${item.name}» غیرفعال میشود و در پذیرش جدید نمایش داده نمیشود. سوابق قبلی حفظ میمانند.`
|
||||
: `سرویس «${item.name}» دوباره فعال و قابل انتخاب میشود.`
|
||||
}
|
||||
confirmLabel={item.active ? 'غیرفعال کن' : 'فعال کن'}
|
||||
onConfirm={() => toggleActive.mutate()}
|
||||
onCancel={() => setToggleOpen(false)}
|
||||
loading={toggleActive.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServiceDetailPage() {
|
||||
return (
|
||||
<FeatureGate feature="services">
|
||||
<ServiceDetailPageInner />
|
||||
</FeatureGate>
|
||||
);
|
||||
}
|
||||
@@ -514,6 +514,10 @@ export interface ServiceItem {
|
||||
uuid: string;
|
||||
name: string;
|
||||
price_rials: number;
|
||||
section_uuid?: string;
|
||||
section_name?: string;
|
||||
created_at?: number;
|
||||
updated_at?: number;
|
||||
/** primary staff (first member) — kept for backward compatibility */
|
||||
staff: { uuid: string; full_name: string } | null;
|
||||
/** all personnel assigned to this service */
|
||||
|
||||
@@ -115,6 +115,46 @@
|
||||
|
||||
---
|
||||
|
||||
## GET /api/v1/service-item/{uuid}
|
||||
|
||||
یک سرویس مشخص — پشتیبان صفحهی اختصاصی «جزئیات سرویس» (`/admin/clinic-services/{uuid}`) که باید با
|
||||
refresh مستقیم هم کار کند، بنابراین فیلترکردن سمت کلاینت از فهرست کامل کافی نبود.
|
||||
|
||||
**Permission:** `IS_AUTHENTICATED_FULLY` + پنل Basic+ · فقط سرویسهای همان مطب/کلینیک
|
||||
(`ServiceItem→section→entity_type/entity_id`).
|
||||
|
||||
**Response 200:** یک ServiceItem object (ساختار یکسان با آیتمهای فهرست، شامل `section_uuid`،
|
||||
`section_name`، `staff_members`، `created_at` و `updated_at`):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"uuid": "...",
|
||||
"section_uuid": "...",
|
||||
"section_name": "تزریقات",
|
||||
"name": "سرم ۵۰۰cc",
|
||||
"price_rials": 850000,
|
||||
"active": true,
|
||||
"insurance_covered": true,
|
||||
"insurance_price_rials": null,
|
||||
"duration_minutes": 30,
|
||||
"bookable": true,
|
||||
"staff": { "uuid": "...", "full_name": "مریم امینی" },
|
||||
"staff_members": [{ "uuid": "...", "full_name": "مریم امینی" }],
|
||||
"created_at": 1718000000,
|
||||
"updated_at": 1718000000
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**خطاها:** `404 ERR_SERVICE_NOT_FOUND` — هم برای uuid ناموجود و هم برای سرویس متعلق به tenant دیگر
|
||||
(وجود سرویس نباید لو برود) · `401` بدون احراز هویت.
|
||||
|
||||
> `section_name` تازه به `ServiceItem::toArray()` اضافه شده و در **همهی** پاسخهای این فایل هست، نه فقط این endpoint.
|
||||
|
||||
---
|
||||
|
||||
## POST /api/v1/service-item
|
||||
|
||||
ایجاد سرویس جدید.
|
||||
@@ -142,8 +182,8 @@
|
||||
| price_rials | integer | ❌ (پیشفرض 0) — «قیمت پایه» |
|
||||
| staff_uuids | UUID[] | ❌ — پرسنل مسئول (چند نفر). ترجیح داده میشود |
|
||||
| staff_uuid | UUID | ❌ — legacy تکپرسنل (اگر `staff_uuids` نباشد استفاده میشود) |
|
||||
| insurance_covered | boolean | ❌ (پیشفرض false) — آیا خدمت شامل بیمه میشود |
|
||||
| insurance_price_rials | integer\|null | ❌ — سهم/قیمت بیمار با بیمه |
|
||||
| insurance_covered | boolean | ❌ (پیشفرض false) — **deprecated برای نوشتن.** پنل ادمین دیگر این فیلد را نمیفرستد؛ مقدارش بهصورت خودکار از ردیفهای پوشش بیمه همگام میشود (به [insurance.md](insurance.md#put-apiv1billingtenant-insurancesuuidservice-coverage) نگاه کن). endpoint هنوز آن را میپذیرد تا کلاینتهای قدیمی نشکنند، ولی ذخیرهی پوشش بعداً آن را بازنویسی میکند |
|
||||
| insurance_price_rials | integer\|null | ❌ — **deprecated.** سهم تقریبی بیمار؛ از فرم سرویس حذف شد. محاسبهی دقیق سهم بیمار از `TenantServiceCoverage` انجام میشود |
|
||||
| duration_minutes | integer\|null | ❌ — «زمان متوسط» انجام خدمت به دقیقه (`""`/`null` = بدون مقدار) |
|
||||
| bookable | boolean | ❌ (پیشفرض false) — «نمایش در نوبتدهی». فقط سرویسهای `bookable=true` در حالت نوبتدهی سرویسی قابلانتخاباند |
|
||||
|
||||
|
||||
@@ -477,6 +477,12 @@ override پوشش یک خدمت خاص تحت قرارداد یک بیمه. فی
|
||||
|
||||
سرویس باید متعلق به همان مطب/کلینیکِ قرارداد باشد (`ServiceItem→section→entity_type/entity_id`).
|
||||
|
||||
**اثر جانبی — همگامسازی `ServiceItem.insurance_covered`:** پس از ذخیرهی ردیف پوشش، پرچم
|
||||
`insurance_covered` همان خدمت بازمحاسبه میشود: اگر زیر **هر** قرارداد بیمهای دستکم یک ردیف با
|
||||
`covered=true` بماند ⇒ `true`، وگرنه `false`. پنل ادمین دیگر این پرچم را دستی نمیفرستد (سوییچ «این خدمت
|
||||
شامل بیمه میشود» از فرم سرویس حذف شد)، پس این endpoint تنها منبع حقیقت آن است. پیادهسازی:
|
||||
`TenantInsuranceService::syncServiceItemInsuranceFlag()` + `TenantServiceCoverageRepository::hasActiveCoverage()`.
|
||||
|
||||
پاسخ `200`: `{ success, data: { message } }`.
|
||||
خطاها: `404 ERR_NOT_FOUND_001` قرارداد یافت نشد · `422 ERR_VALIDATION_001` سرویس یافت نشد · `403 ERR_FORBIDDEN_001` سرویس متعلق به شما نیست.
|
||||
|
||||
|
||||
@@ -154,6 +154,19 @@ class ClinicServiceController extends BaseController
|
||||
return $this->success($items);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/service-item/{uuid}', methods: ['GET'])]
|
||||
public function getItem(string $uuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
[$entityType, $entityId] = $this->resolveEntity($user);
|
||||
|
||||
$item = $this->itemRepo->findByUuid($uuid);
|
||||
if ($item === null || !$this->ownsSection($item->getSection(), $entityType, $entityId)) {
|
||||
return $this->error(ErrorCodes::ERR_SERVICE_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SERVICE_NOT_FOUND), 404);
|
||||
}
|
||||
|
||||
return $this->success($item->toArray());
|
||||
}
|
||||
|
||||
#[Route('/api/v1/service-item', methods: ['POST'])]
|
||||
public function createItem(Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
|
||||
@@ -142,6 +142,7 @@ class ServiceItem
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'section_uuid' => $this->section->getUuid(),
|
||||
'section_name' => $this->section->getName(),
|
||||
'staff_uuid' => $primary?->getUuid(),
|
||||
'staff_name' => $primary?->getFullName(),
|
||||
'staff' => $primary !== null
|
||||
|
||||
@@ -27,6 +27,17 @@ class TenantServiceCoverageRepository extends ServiceEntityRepository
|
||||
return $this->findBy(['tenantInsuranceId' => $tenantInsuranceId]);
|
||||
}
|
||||
|
||||
/** آیا این خدمت زیر هر قرارداد بیمهای پوشش فعال دارد؟ */
|
||||
public function hasActiveCoverage(int $serviceItemId): bool
|
||||
{
|
||||
return (int) $this->createQueryBuilder('c')
|
||||
->select('COUNT(c.id)')
|
||||
->where('c.serviceItemId = :item AND c.covered = true')
|
||||
->setParameter('item', $serviceItemId)
|
||||
->getQuery()
|
||||
->getSingleScalarResult() > 0;
|
||||
}
|
||||
|
||||
public function save(TenantServiceCoverage $entity, bool $flush = true): void
|
||||
{
|
||||
$this->getEntityManager()->persist($entity);
|
||||
|
||||
@@ -162,5 +162,23 @@ class TenantInsuranceService
|
||||
->setCeilingRials($ceilingRials);
|
||||
|
||||
$this->coverageRepo->save($override);
|
||||
$this->syncServiceItemInsuranceFlag($serviceItemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* پرچم insurance_covered خدمت را با پوششهای واقعی همتراز میکند. پنل دیگر این
|
||||
* پرچم را دستی نمیگیرد؛ تنها منبع حقیقت، ردیفهای پوشش قراردادهای بیمه است.
|
||||
*/
|
||||
private function syncServiceItemInsuranceFlag(int $serviceItemId): void
|
||||
{
|
||||
$serviceItem = $this->serviceItemRepo->find($serviceItemId);
|
||||
if ($serviceItem === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$covered = $this->coverageRepo->hasActiveCoverage($serviceItemId);
|
||||
if ($serviceItem->isInsuranceCovered() !== $covered) {
|
||||
$this->serviceItemRepo->save($serviceItem->setInsuranceCovered($covered));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\ClinicService;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Entity\ServiceSection;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* GET /api/v1/service-item/{uuid} backs the dedicated service detail page, which
|
||||
* must survive a hard refresh — hence a single-item fetch instead of filtering
|
||||
* the full list client-side.
|
||||
*/
|
||||
class ServiceItemDetailApiTest extends ApiTestCase
|
||||
{
|
||||
/** @return array{0: User, 1: ServiceItem} */
|
||||
private function makeDoctorWithItem(string $sectionName = 'تزریقات'): array
|
||||
{
|
||||
$owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$doctor = new Doctor($owner, 'دکتر تست جزئیات');
|
||||
$this->em->persist($doctor);
|
||||
$this->em->flush();
|
||||
|
||||
$section = new ServiceSection('doctor', $doctor->getId(), $sectionName);
|
||||
$item = new ServiceItem($section, 'سرم ۵۰۰cc');
|
||||
$item->setPriceRials(850_000)->setDurationMinutes(30)->setBookable(true);
|
||||
$this->em->persist($section);
|
||||
$this->em->persist($item);
|
||||
$this->em->flush();
|
||||
|
||||
return [$owner, $item];
|
||||
}
|
||||
|
||||
public function testReturnsTheItemWithEverythingTheDetailPageNeeds(): void
|
||||
{
|
||||
[$owner, $item] = $this->makeDoctorWithItem();
|
||||
|
||||
$body = $this->authJson('GET', '/api/v1/service-item/' . $item->getUuid(), $owner);
|
||||
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$row = $body['data'];
|
||||
$this->assertSame($item->getUuid(), $row['uuid']);
|
||||
$this->assertSame('سرم ۵۰۰cc', $row['name']);
|
||||
$this->assertSame('تزریقات', $row['section_name'], 'breadcrumb به نام بخش نیاز دارد');
|
||||
$this->assertSame($item->getSection()->getUuid(), $row['section_uuid']);
|
||||
$this->assertSame(850_000, $row['price_rials']);
|
||||
$this->assertSame(30, $row['duration_minutes']);
|
||||
$this->assertTrue($row['bookable']);
|
||||
$this->assertIsInt($row['created_at']);
|
||||
$this->assertIsInt($row['updated_at']);
|
||||
$this->assertArrayHasKey('staff_members', $row);
|
||||
$this->assertArrayHasKey('insurance_covered', $row);
|
||||
}
|
||||
|
||||
public function testUnknownUuidReturns404(): void
|
||||
{
|
||||
[$owner] = $this->makeDoctorWithItem();
|
||||
|
||||
$this->authJson('GET', '/api/v1/service-item/00000000-0000-4000-8000-000000000000', $owner);
|
||||
|
||||
$this->assertSame(404, $this->responseCode());
|
||||
}
|
||||
|
||||
public function testAnotherTenantCannotReadTheItem(): void
|
||||
{
|
||||
[, $item] = $this->makeDoctorWithItem();
|
||||
|
||||
$stranger = $this->createUser(['ROLE_DOCTOR']);
|
||||
$this->em->persist(new Doctor($stranger, 'دکتر غریبه'));
|
||||
$this->em->flush();
|
||||
|
||||
$this->authJson('GET', '/api/v1/service-item/' . $item->getUuid(), $stranger);
|
||||
|
||||
$this->assertSame(404, $this->responseCode(), 'وجود سرویس نباید به tenant دیگر لو برود');
|
||||
}
|
||||
|
||||
public function testRequiresAuthentication(): void
|
||||
{
|
||||
[, $item] = $this->makeDoctorWithItem();
|
||||
|
||||
$this->client->request('GET', '/api/v1/service-item/' . $item->getUuid());
|
||||
|
||||
$this->assertSame(401, $this->responseCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tests\Insurance;
|
||||
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Entity\ServiceSection;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use App\Insurance\Entity\TenantInsurance;
|
||||
use App\Tests\ApiTestCase;
|
||||
|
||||
/**
|
||||
* The «این خدمت شامل بیمه میشود» switch was removed from the service form, so
|
||||
* ServiceItem::insuranceCovered is no longer set by hand. Saving a coverage row
|
||||
* is now the single source of truth and must keep the flag in sync — session
|
||||
* pricing (CreateStep) reads it.
|
||||
*/
|
||||
class ServiceCoverageSyncsItemFlagTest extends ApiTestCase
|
||||
{
|
||||
/** @return array{0: \App\Auth\Entity\User, 1: TenantInsurance, 2: ServiceItem} */
|
||||
private function makeDoctorContractAndItem(): array
|
||||
{
|
||||
$owner = $this->createUser(['ROLE_DOCTOR']);
|
||||
$doctor = new Doctor($owner, 'دکتر تست همگامسازی');
|
||||
$this->em->persist($doctor);
|
||||
$this->em->flush();
|
||||
|
||||
$contract = new TenantInsurance(TenantInsurance::TYPE_DOCTOR, $doctor->getId(), 1);
|
||||
$section = new ServiceSection(TenantInsurance::TYPE_DOCTOR, $doctor->getId(), 'بخش');
|
||||
$this->em->persist($contract);
|
||||
$this->em->persist($section);
|
||||
$this->em->flush();
|
||||
|
||||
$item = new ServiceItem($section, 'سرم ۵۰۰cc');
|
||||
$this->em->persist($item);
|
||||
$this->em->flush();
|
||||
|
||||
return [$owner, $contract, $item];
|
||||
}
|
||||
|
||||
/** EntityManager بین requestها clear میشود، پس پرچم باید دوباره از DB خوانده شود. */
|
||||
private function isInsured(string $uuid): bool
|
||||
{
|
||||
return $this->em->getRepository(ServiceItem::class)
|
||||
->findOneBy(['uuid' => $uuid])
|
||||
->isInsuranceCovered();
|
||||
}
|
||||
|
||||
private function putCoverage(
|
||||
\App\Auth\Entity\User $owner,
|
||||
TenantInsurance $contract,
|
||||
ServiceItem $item,
|
||||
bool $covered,
|
||||
): void {
|
||||
$this->authJson(
|
||||
'PUT',
|
||||
'/api/v1/billing/tenant-insurances/' . $contract->getUuid() . '/service-coverage',
|
||||
$owner,
|
||||
['service_item_uuid' => $item->getUuid(), 'covered' => $covered, 'coverage_percent' => 70],
|
||||
);
|
||||
}
|
||||
|
||||
public function testSavingCoveredCoverageMarksItemAsInsured(): void
|
||||
{
|
||||
[$owner, $contract, $item] = $this->makeDoctorContractAndItem();
|
||||
$this->assertFalse($item->isInsuranceCovered(), 'یک خدمت تازه نباید تحت پوشش باشد');
|
||||
|
||||
$this->putCoverage($owner, $contract, $item, true);
|
||||
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$this->assertTrue($this->isInsured($item->getUuid()));
|
||||
}
|
||||
|
||||
public function testRemovingTheOnlyCoverageClearsTheFlag(): void
|
||||
{
|
||||
[$owner, $contract, $item] = $this->makeDoctorContractAndItem();
|
||||
$uuid = $item->getUuid();
|
||||
|
||||
$this->putCoverage($owner, $contract, $item, true);
|
||||
$this->assertTrue($this->isInsured($uuid));
|
||||
|
||||
$this->putCoverage($owner, $contract, $item, false);
|
||||
|
||||
$this->assertSame(200, $this->responseCode());
|
||||
$this->assertFalse($this->isInsured($uuid));
|
||||
}
|
||||
|
||||
public function testFlagStaysSetWhileAnotherContractStillCoversTheItem(): void
|
||||
{
|
||||
[$owner, $first, $item] = $this->makeDoctorContractAndItem();
|
||||
$uuid = $item->getUuid();
|
||||
|
||||
$second = new TenantInsurance(TenantInsurance::TYPE_DOCTOR, $first->getEntityId(), 2);
|
||||
$this->em->persist($second);
|
||||
$this->em->flush();
|
||||
|
||||
$this->putCoverage($owner, $first, $item, true);
|
||||
$this->putCoverage($owner, $second, $item, true);
|
||||
|
||||
$this->putCoverage($owner, $first, $item, false);
|
||||
|
||||
$this->assertTrue($this->isInsured($uuid), 'قرارداد دوم هنوز پوشش دارد');
|
||||
}
|
||||
|
||||
public function testUnknownServiceItemIsRejected(): void
|
||||
{
|
||||
[$owner, $contract] = $this->makeDoctorContractAndItem();
|
||||
|
||||
$this->authJson(
|
||||
'PUT',
|
||||
'/api/v1/billing/tenant-insurances/' . $contract->getUuid() . '/service-coverage',
|
||||
$owner,
|
||||
['service_item_uuid' => 'no-such-uuid', 'covered' => true],
|
||||
);
|
||||
|
||||
$this->assertSame(422, $this->responseCode());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user