Files
clinicpro/assets/admin/pages/ResourceDetailPage.test.tsx
T
hamedandClaude Opus 5 dd284ec622 refactor(branch): remove the branch domain, keep the address
Branches and rooms are not part of the resource-first product: a room is a
resource like any other, and the only thing the branch pages still managed —
opening hours — duplicated the resource's own shift.

What could not go is the address. Every appointment carries address_id (75 of
75 rows), the public booking site reads /clinic-pro/doctor-address/{id}, and a
resource derives its tenant pair from the address it belongs to. So
DoctorAddress stays as an invisible anchor with no page and no menu entry, and
GET /api/v1/addresses replaces GET /api/v1/branches for the forms that still
need to say "where".

BranchResolver was likewise not a branch feature. doctor_addresses is a global
table, so TenantFilter does not cover it and eight callers across booking,
availability, pricing and the catalog went through this resolver to avoid
leaking another clinic's address. It moved to Doctor\Service\AddressResolver
rather than dying with the domain.

The availability engine loses one layer: a resource's real hours were the
branch hours intersected with its shift, and are now the shift alone. That is
the single behavioural change, and the three tests that asserted the old
contract are replaced by one that states the new one.

Rooms already had a resource row each; the migration drops only the bridge
back to `rooms`, and drops it before the table — that foreign key is ON DELETE
CASCADE and the other order would take the resources, and their appointments,
with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 15:25:32 +03:30

149 lines
6.1 KiB
TypeScript

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
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() } }));
vi.mock('../hooks/usePermissions', () => ({ usePermissions: () => ({ can: () => true }) }));
import { Routes, Route } from 'react-router-dom';
import { api } from '../lib/api';
import ResourceDetailPage from './ResourceDetailPage';
const get = api.get as ReturnType<typeof vi.fn>;
const resource = {
uuid: 'r1',
name: 'لیزر دایود',
address_uuid: 'a1',
address_name: 'شعبهٔ مرکزی',
type_uuid: 't1',
type_code: 'device',
type_name: 'دستگاه لیزر',
capacity: 1,
setup_minutes: 5,
cleanup_minutes: 10,
attributes: {},
subject_kind: null,
subject_uuid: null,
skills: [{ skill_uuid: 's1', skill_name: 'کار با لیزر', level: 4 }],
categories: [{ uuid: 'c-hand', name: 'دست' }],
active: true,
created_at: 0,
updated_at: 0,
upcoming_appointments: 0,
};
const emptyDays = (): Record<string, unknown[]> =>
Object.fromEntries(Array.from({ length: 7 }, (_, d) => [String(d), [] as unknown[]]));
function mockApi(days: Record<string, unknown[]> = emptyDays(), availabilityDays: unknown[] = []) {
get.mockImplementation((path: string) => {
if (path === '/api/v1/resource/r1') return Promise.resolve({ success: true, data: resource });
if (path.endsWith('/calendar')) {
return Promise.resolve({
success: true,
data: { resource_uuid: 'r1', timezone: 'Asia/Tehran', defined: true, days },
});
}
if (path.includes('/availability')) {
return Promise.resolve({
success: true,
data: { resource_uuid: 'r1', timezone: 'Asia/Tehran', days: availabilityDays },
});
}
if (path.includes('/service-categories/tree')) {
return Promise.resolve({
success: true,
data: [{ uuid: 'c-hand', name: 'دست', sort_order: 0, active: true, children: [] },
{ uuid: 'c-foot', name: 'پا', sort_order: 1, active: true, children: [] }],
});
}
return Promise.resolve({ success: true, data: [] });
});
}
function renderPage(route = '/admin/resources/r1') {
return renderWithProviders(
<Routes>
<Route path="/admin/resources/:resourceUuid" element={<ResourceDetailPage />} />
</Routes>,
{ route },
);
}
describe('ResourceDetailPage', () => {
beforeEach(() => vi.clearAllMocks());
it('اطلاعات منبع را در تب پیش‌فرض نشان می‌دهد', async () => {
mockApi();
renderPage();
await waitFor(() => expect(screen.getByText('شعبهٔ مرکزی')).toBeInTheDocument());
expect(screen.getByText('ظرفیت هم‌زمان')).toBeInTheDocument();
expect(screen.getByText('کار با لیزر · 4')).toBeInTheDocument();
});
it('تب از URL خوانده می‌شود تا بازگشت و رفرش همان نما را بدهد', async () => {
mockApi();
renderPage('/admin/resources/r1?tab=hours');
await waitFor(() => expect(screen.getByText('شنبه')).toBeInTheDocument());
expect(screen.getByText('جمعه')).toBeInTheDocument();
expect(screen.getAllByText('بدون شیفت')).toHaveLength(7);
});
it('شیفت ذخیره‌شده را به‌صورت ساعت نشان می‌دهد', async () => {
const days = emptyDays();
days['0'] = [{ sequence: 0, start_minute: 540, end_minute: 1020, start_time: '09:00', end_time: '17:00', active: true }];
mockApi(days);
renderPage('/admin/resources/r1?tab=hours');
await waitFor(() => expect(screen.getByDisplayValue('09:00')).toBeInTheDocument());
expect(screen.getByDisplayValue('17:00')).toBeInTheDocument();
});
/**
* دلیلِ خالی بودن روز باید فارسی نشان داده شود؛ نشان دادن کلید خام سرور
* («outside_branch_hours») به کاربر یعنی پیام بی‌معنا.
*/
it('دلیل خالی بودن روز را فارسی می‌کند', async () => {
mockApi(emptyDays(), [
{ date: 1785529800, day_of_week: 0, intervals: [], total_minutes: 0, reasons: ['national_holiday'] },
{ date: 1785616200, day_of_week: 1, intervals: [], total_minutes: 0, reasons: ['no_shift'] },
{ date: 1785702600, day_of_week: 2, intervals: [], total_minutes: 0, reasons: ['exception'] },
]);
renderPage('/admin/resources/r1?tab=exceptions');
await waitFor(() => expect(screen.getByText('تعطیل رسمی')).toBeInTheDocument());
expect(screen.getByText('شیفتی تعریف نشده')).toBeInTheDocument();
expect(screen.getByText('مرخصی یا سرویس')).toBeInTheDocument();
expect(screen.queryByText('no_shift')).not.toBeInTheDocument();
});
/** پیش‌نمایش نباید «وقت قابل رزرو» خوانده شود — نوبت‌ها هنوز کسر نشده‌اند. */
it('پیش‌نمایش را خام معرفی می‌کند', async () => {
mockApi();
renderPage('/admin/resources/r1?tab=exceptions');
await waitFor(() => expect(screen.getByText(/نوبت‌های ثبت‌شده هنوز از آن کسر نشده‌اند/)).toBeInTheDocument());
});
it('تب دسته‌بندی فقط انتخاب می‌دهد، نه ساخت', async () => {
mockApi();
const user = userEvent.setup();
renderPage();
await waitFor(() => expect(screen.getByText('شعبهٔ مرکزی')).toBeInTheDocument());
await user.click(screen.getByRole('button', { name: 'دسته‌بندی‌ها' }));
await waitFor(() => expect(screen.getByText(/فقط انتخاب می‌شود/)).toBeInTheDocument());
expect(screen.queryByRole('button', { name: /افزودن دسته‌بندی جدید/ })).not.toBeInTheDocument();
expect(screen.getByText('تنظیمات ← دسته‌بندی‌ها')).toHaveAttribute('href', '/admin/service-categories');
});
});