import { describe, it, expect, beforeEach, vi } from 'vitest'; import { screen, fireEvent, waitFor, within } from '@testing-library/react'; 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 AdminSubscriptionPage from './AdminSubscriptionPage'; const get = api.get as ReturnType; const patch = api.patch as ReturnType; const post = api.post as ReturnType; const PLANS = [ { uuid: 'p-basic', name: 'basic', level: 1, max_secretaries: 3, max_resources: 3, features: { patient_records: true, services: true, sms_panel: false }, active: true, periods: [], }, { uuid: 'p-pro', name: 'professional', level: 2, max_secretaries: 10, max_resources: -1, features: { patient_records: true, services: true, sms_panel: true }, active: true, periods: [], }, ]; /** همان پلن‌ها، با دوره — تب «اعطای اشتراک» فهرست دوره‌ها را از همین‌جا می‌سازد. */ const PLANS_WITH_PERIODS = [ { ...PLANS[0], periods: [ { uuid: 'per-basic-1', label: 'یک ماهه', duration_months: 1, price_rials: 1000000, is_trial: false }, { uuid: 'per-basic-trial', label: 'آزمایشی', duration_months: 1, price_rials: 0, is_trial: true }, ], }, { ...PLANS[1], periods: [ { uuid: 'per-pro-1', label: 'یک ماهه', duration_months: 1, price_rials: 3000000, is_trial: false }, ], }, ]; function mockApi() { get.mockImplementation((url: string) => { if (url.includes('/admin/subscription/plans')) return Promise.resolve({ success: true, data: PLANS }); return Promise.resolve({ success: true, data: [], meta: { totalRecords: 0 } }); }); patch.mockResolvedValue({ success: true, data: PLANS[0] }); } /** مودالِ ویرایشِ پلنِ داده‌شده را باز می‌کند. هر کارت یک دکمهٔ مداد دارد. */ async function openEdit(planLabel: string) { const card = (await screen.findByText(planLabel)).closest('.card') as HTMLElement; const buttons = within(card).getAllByRole('button'); fireEvent.click(buttons[buttons.length - 1]); } describe('AdminSubscriptionPage — سقف منابع پلن', () => { beforeEach(() => { get.mockReset(); patch.mockReset(); mockApi(); }); it('سقف منابع هر پلن را روی کارتش نشان می‌دهد', async () => { renderWithProviders(, { route: '/admin/admin-subscription' }); expect(await screen.findByText('حداکثر ۳ منبع')).toBeInTheDocument(); expect(screen.getByText('حداکثر نامحدود منبع')).toBeInTheDocument(); }); it('فرم ویرایش با مقدار فعلی پر می‌شود و همان را می‌فرستد', async () => { renderWithProviders(, { route: '/admin/admin-subscription' }); await openEdit('پایه'); const input = await screen.findByLabelText('حداکثر منبع *'); expect(input).toHaveValue('3'); fireEvent.change(input, { target: { value: '5' } }); fireEvent.click(screen.getByText('ذخیره')); await waitFor(() => expect(patch).toHaveBeenCalled()); expect(patch.mock.calls[0][0]).toBe('/api/v1/admin/subscription/plan/p-basic'); expect(patch.mock.calls[0][1]).toMatchObject({ max_resources: 5 }); }); /** ادمین «۱-» تایپ نمی‌کند؛ سوییچ همان قرارداد را می‌سازد. */ it('سوییچ «منابع نامحدود» مقدار ۱- می‌فرستد', async () => { renderWithProviders(, { route: '/admin/admin-subscription' }); await openEdit('پایه'); await screen.findByLabelText('حداکثر منبع *'); fireEvent.click(screen.getByText('منابع نامحدود')); fireEvent.click(screen.getByText('ذخیره')); await waitFor(() => expect(patch).toHaveBeenCalled()); expect(patch.mock.calls[0][1]).toMatchObject({ max_resources: -1 }); }); it('پلن نامحدود با سوییچِ روشن باز می‌شود و فیلد عددی‌اش قفل است', async () => { renderWithProviders(, { route: '/admin/admin-subscription' }); await openEdit('حرفه‌ای'); expect(await screen.findByLabelText('حداکثر منبع *')).toBeDisabled(); }); }); // ── اعطای اشتراک ────────────────────────────────────────────────────────── const DOCTORS = [{ uuid: 'doc-1', name: 'دکتر رضایی', mobile: '09120000001' }]; /** پاسخ `admin/subscription/active` — `null` یعنی مقصد اشتراک فعالی ندارد. */ function mockGrantApi(activeSubscription: unknown = null) { get.mockImplementation((url: string) => { if (url.includes('/admin/subscription/plans')) return Promise.resolve({ success: true, data: PLANS_WITH_PERIODS }); if (url.includes('/admin/subscription/active')) return Promise.resolve({ success: true, data: { subscription: activeSubscription } }); if (url.includes('/admin/doctors')) return Promise.resolve({ success: true, data: DOCTORS, meta: { totalRecords: 1 } }); if (url.includes('/admin/clinics')) return Promise.resolve({ success: true, data: [], meta: { totalRecords: 0 } }); return Promise.resolve({ success: true, data: [], meta: { totalRecords: 0 } }); }); post.mockResolvedValue({ success: true, data: {} }); } /** انتخاب گزینه از SearchableSelect با inputId */ async function pickOption(inputId: string, option: string) { const input = document.getElementById(inputId) as HTMLInputElement; fireEvent.focus(input); fireEvent.keyDown(input, { key: 'ArrowDown' }); fireEvent.click(await screen.findByText(option)); } async function openGrantTab() { renderWithProviders(, { route: '/admin/admin-subscription' }); // تبِ «اعطای اشتراک» و دکمهٔ ثبتِ فرم هم‌نام‌اند؛ تب همیشه اولی است. fireEvent.click((await screen.findAllByText('اعطای اشتراک'))[0]); } /** دکمهٔ ثبتِ فرم اعطا — با نقش تنها قابل تفکیک نیست، چون تب هم‌نام است. */ function submitGrantForm() { fireEvent.click(document.querySelector('button[type="submit"]') as HTMLButtonElement); } describe('AdminSubscriptionPage — اعطای اشتراک', () => { beforeEach(() => { get.mockReset(); post.mockReset(); }); it('برای مقصد بدون اشتراک، دوره را می‌فرستد و پرداختی در کار نیست', async () => { mockGrantApi(null); await openGrantTab(); await pickOption('grant-entity', 'دکتر رضایی — 09120000001'); expect(await screen.findByText('این مقصد اشتراک فعالی ندارد.')).toBeInTheDocument(); await pickOption('grant-period', 'حرفه‌ای — یک ماهه (۳۰۰٬۰۰۰ تومان)'); submitGrantForm(); await waitFor(() => expect(post).toHaveBeenCalled()); expect(post.mock.calls[0][0]).toBe('/api/v1/admin/subscription/grant'); expect(post.mock.calls[0][1]).toEqual({ entity_type: 'doctor', entity_uuid: 'doc-1', period_uuid: 'per-pro-1' }); }); /** دورهٔ تریال، تریالِ نگرفتهٔ کاربر را می‌سوزاند؛ نباید در فهرست باشد. */ it('دوره‌های تریال در فهرست اعطا نمی‌آیند', async () => { mockGrantApi(null); await openGrantTab(); const input = document.getElementById('grant-period') as HTMLInputElement; fireEvent.focus(input); fireEvent.keyDown(input, { key: 'ArrowDown' }); expect(await screen.findByText('پایه — یک ماهه (۱۰۰٬۰۰۰ تومان)')).toBeInTheDocument(); expect(screen.queryByText(/آزمایشی/)).not.toBeInTheDocument(); }); it('اشتراک فعالِ مقصد را قبل از اعطا نشان می‌دهد', async () => { mockGrantApi({ plan: { name: 'professional', level: 2 }, expires_at: 1800000000, is_trial: false, is_granted: true }); await openGrantTab(); await pickOption('grant-entity', 'دکتر رضایی — 09120000001'); expect(await screen.findByText('حرفه‌ای')).toBeInTheDocument(); expect(screen.getByText('اعطایی')).toBeInTheDocument(); }); it('پلن پایین‌تر از پلن فعال، اول تأیید می‌خواهد', async () => { mockGrantApi({ plan: { name: 'professional', level: 2 }, expires_at: 1800000000, is_trial: false, is_granted: false }); await openGrantTab(); await pickOption('grant-entity', 'دکتر رضایی — 09120000001'); await screen.findByText(/اشتراک فعلی/); await pickOption('grant-period', 'پایه — یک ماهه (۱۰۰٬۰۰۰ تومان)'); submitGrantForm(); expect(await screen.findByText('کاهش سطح پلن')).toBeInTheDocument(); expect(post).not.toHaveBeenCalled(); fireEvent.click(screen.getByText('اعطا کن')); await waitFor(() => expect(post).toHaveBeenCalled()); expect(post.mock.calls[0][1]).toMatchObject({ period_uuid: 'per-basic-1' }); }); it('ارتقا به پلن بالاتر بدون تأیید اضافه ثبت می‌شود', async () => { mockGrantApi({ plan: { name: 'basic', level: 1 }, expires_at: 1800000000, is_trial: false, is_granted: false }); await openGrantTab(); await pickOption('grant-entity', 'دکتر رضایی — 09120000001'); await screen.findByText(/اشتراک فعلی/); await pickOption('grant-period', 'حرفه‌ای — یک ماهه (۳۰۰٬۰۰۰ تومان)'); submitGrantForm(); await waitFor(() => expect(post).toHaveBeenCalled()); expect(screen.queryByText('کاهش سطح پلن')).not.toBeInTheDocument(); }); }); describe('AdminSubscriptionPage — گزارش', () => { beforeEach(() => { get.mockReset(); post.mockReset(); }); it('اشتراک اعطایی را «اعطایی» نشان می‌دهد، نه «پولی»', async () => { get.mockImplementation((url: string) => { if (url.includes('/admin/subscription/plans')) return Promise.resolve({ success: true, data: PLANS }); if (url.includes('/admin/subscription/report')) { return Promise.resolve({ success: true, meta: { totalRecords: 1 }, data: [{ uuid: 's-1', entityType: 'doctor', entityId: 4, entityName: 'دکتر رضایی', isTrial: false, isGranted: true, grantedBy: 'ادمین', startsAt: 1700000000, expiresAt: 1800000000, createdAt: 1700000000, plan_name: 'professional', plan_level: 2, }], }); } return Promise.resolve({ success: true, data: [], meta: { totalRecords: 0 } }); }); renderWithProviders(, { route: '/admin/admin-subscription' }); fireEvent.click(await screen.findByText('گزارش فروش')); expect(await screen.findByText('اعطایی')).toBeInTheDocument(); expect(screen.getByText('دکتر رضایی')).toBeInTheDocument(); expect(screen.getByText('ادمین')).toBeInTheDocument(); expect(screen.queryByText('پولی')).not.toBeInTheDocument(); }); });