feat(settings): manage resource schedules beside the doctors'

A resource carries its own working hours and holidays in the resource-first
model, so it belongs on the same settings page as a doctor's schedule rather
than on a page of its own. The page now has a scope switch — doctors or
resources — with the per-item tab bar below it, and both scopes reuse the
panels that already existed: ScheduleSection for a doctor, the working-hours
and exceptions panels for a resource. The selection lives in the query
string, so back and refresh return to the same tab.

The screenshot of the finished tab caught two real defects, both fixed here:

Dates in the resource panels and the holidays page read as year 57932.
formatDate already multiplies seconds by 1000, and five call sites passed
`x * 1000` on top of it. This predates the tab — the code was inherited from
the old calendar page — but it was invisible until a two-week preview was put
on screen.

The working-hours panel still told the user their hours were intersected with
the branch's. Branches are gone; the shift is the only source now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-08-02 15:49:01 +03:30
co-authored by Claude Opus 5
parent f144401dd3
commit 9ba4c8d948
6 changed files with 286 additions and 63 deletions
@@ -26,7 +26,7 @@ export default function NationalHolidaysCard({ canUpdate, year = currentJalaliYe
return (
<div className="card" style={{ padding: 14 }}>
<h2 className="section-title" style={{ margin: '0 0 4px' }}>تعطیلات رسمی {year}</h2>
<h2 className="section-title" style={{ margin: '0 0 4px' }}>تعطیلات رسمی {year.toLocaleString('fa-IR', { useGrouping: false })}</h2>
<p style={{ fontSize: 12, color: 'var(--text-3)', margin: '0 0 10px', lineHeight: 1.9 }}>
اینها برای همهٔ پزشکان و منابع اعمال میشوند. اگر این محیط روزی را باز است،
همینجا استثنا بزنید مدیریت کاملشان در{' '}
@@ -37,7 +37,7 @@ export default function NationalHolidaysCard({ canUpdate, year = currentJalaliYe
<span style={{ fontSize: 13, color: 'var(--text-3)' }}>در حال بارگذاری...</span>
) : holidays.length === 0 ? (
<p style={{ fontSize: 13, color: 'var(--text-3)', margin: 0 }}>
برای سال {year} تعطیلی رسمی ثبت نشده است.
برای سال {year.toLocaleString('fa-IR', { useGrouping: false })} تعطیلی رسمی ثبت نشده است.
</p>
) : (
<div style={{ display: 'grid', gap: 8 }}>
@@ -51,7 +51,7 @@ export default function NationalHolidaysCard({ canUpdate, year = currentJalaliYe
{open ? 'باز' : 'تعطیل'}
</span>
<span style={{ flex: 1, color: 'var(--text-2)' }}>
{formatDate(h.date * 1000)} · {h.title}
{formatDate(h.date)} · {h.title}
</span>
{canUpdate && (
open ? (
@@ -74,7 +74,7 @@ export default function ResourceExceptionsPanel({ resourceUuid, canUpdate }: {
style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, fontSize: 13 }}
>
<span style={{ color: 'var(--text-2)' }}>
{DAY_LABELS[day.day_of_week]} · {formatDate(day.date * 1000)}
{DAY_LABELS[day.day_of_week]} · {formatDate(day.date)}
</span>
{day.intervals.length === 0 ? (
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>
@@ -139,7 +139,7 @@ function ExceptionsCard({
<div key={e.uuid} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
<span className="badge amber" style={{ fontSize: 11 }}>{e.type_label}</span>
<span style={{ flex: 1, color: 'var(--text-2)' }}>
{formatDate(e.starts_at * 1000)} تا {formatDate(e.ends_at * 1000)}
{formatDate(e.starts_at)} تا {formatDate(e.ends_at)}
{e.reason ? ` · ${e.reason}` : ''}
</span>
{canUpdate && (
@@ -2,7 +2,7 @@ import React, { useEffect, useMemo, useState } from 'react';
import { PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
import { useResourceCalendar } from '../../hooks/useResourceCalendar';
/** ۰ = شنبه — همان قرارداد بک‌اند و ساعت کاری شعبه. */
/** ۰ = شنبه — همان قرارداد بک‌اند برای روزهای هفته. */
export const DAY_LABELS = ['شنبه', 'یکشنبه', 'دوشنبه', 'سه‌شنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'];
const MINUTES_IN_DAY = 1440;
@@ -23,8 +23,8 @@ function toMinutes(time: string): number | null {
/**
* شیفت هفتگی یک منبع — روزهای کاری و ساعت هر روز.
*
* ساعت واقعی منبع تقاطع این شیفت‌ها با ساعت کاری شعبه است، نه خودشان؛ پس شیفتِ
* بیرون از ساعت شعبه ذخیره می‌شود ولی در دسترس‌پذیری اثری ندارد.
* با حذف دامنهٔ شعبه، این شیفت تنها مرجع ساعت کاری منبع است؛ فقط تعطیلات رسمی و
* استثناهای خودِ منبع از آن کسر می‌شوند.
*/
export default function ResourceWorkingHoursPanel({ resourceUuid, canUpdate }: {
resourceUuid?: string;
@@ -88,8 +88,7 @@ export default function ResourceWorkingHoursPanel({ resourceUuid, canUpdate }: {
<div style={{ display: 'grid', gap: 12 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
<p style={{ margin: 0, fontSize: 12.5, color: 'var(--text-3)' }}>
روزهای کاری و ساعت هر روز. ساعت واقعی از تقاطع این شیفتها با ساعت کاری شعبه بهدست
میآید و تعطیلات و مرخصی از آن کسر میشود.
روزهای کاری و ساعت هر روز. تعطیلات رسمی و مرخصی از همین ساعت کسر میشوند.
{totalShifts > 0 && <> · {totalShifts} شیفت</>}
</p>
{canUpdate && (
@@ -0,0 +1,103 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../test/utils';
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
vi.mock('../hooks/usePermissions', () => ({ usePermissions: () => ({ can: () => true }) }));
// ScheduleSection یک درختِ سنگین با کوئری‌های خودش است؛ اینجا فقط باید ثابت شود کدام
// scope رندر می‌شود، نه اینکه برنامهٔ پزشک درست کار می‌کند — آن تست خودش را دارد.
vi.mock('../components/schedule/ScheduleSection', () => ({
ScheduleSection: () => <div>برنامهٔ پزشک</div>,
}));
vi.mock('../components/FreeVisitPrice', () => ({ default: () => <div>قیمت ویزیت</div> }));
vi.mock('../components/resources/ResourceWorkingHoursPanel', () => ({
default: ({ resourceUuid }: { resourceUuid?: string }) => <div>ساعات کاری {resourceUuid}</div>,
DAY_LABELS: [],
}));
vi.mock('../components/resources/ResourceExceptionsPanel', () => ({
default: ({ resourceUuid }: { resourceUuid?: string }) => <div>تعطیلات {resourceUuid}</div>,
}));
let resources: Array<{ uuid: string; name: string; type_name: string }> = [];
vi.mock('../hooks/useResources', () => ({
useResources: () => ({ resources, loading: false }),
}));
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 ClinicAppointmentSettingsPage from './ClinicAppointmentSettingsPage';
const get = api.get as ReturnType<typeof vi.fn>;
const LASER = { uuid: 'r-1', name: 'لیزر دایود', type_name: 'دستگاه لیزر' };
const ROOM = { uuid: 'r-2', name: 'اتاق ۱', type_name: 'اتاق درمان' };
beforeEach(() => {
vi.clearAllMocks();
resources = [LASER, ROOM];
useAuthStore.setState({
primaryRole: 'clinic',
dbUuid: 'c-1',
context: { type: 'clinic', db_uuid: 'c-1' } as never,
availableContexts: [],
});
get.mockResolvedValue({ success: true, data: { data: [{ uuid: 'd-1', name: 'دکتر مرادی' }] } });
});
describe('ClinicAppointmentSettingsPage', () => {
it('پیش‌فرض روی پزشکان است', async () => {
renderWithProviders(<ClinicAppointmentSettingsPage />);
await waitFor(() => expect(screen.getByText('برنامهٔ پزشک')).toBeInTheDocument());
expect(screen.queryByText(/ساعات کاری r-/)).not.toBeInTheDocument();
});
/** منبع همان‌جایی مدیریت می‌شود که برنامهٔ پزشک — نه در یک صفحهٔ جدا. */
it('تب منابع، ساعت کاری و تعطیلات منبع را می‌آورد', async () => {
const user = userEvent.setup();
renderWithProviders(<ClinicAppointmentSettingsPage />);
await user.click(screen.getByRole('button', { name: 'منابع' }));
await waitFor(() => expect(screen.getByText('ساعات کاری r-1')).toBeInTheDocument());
expect(screen.getByText('تعطیلات r-1')).toBeInTheDocument();
expect(screen.queryByText('برنامهٔ پزشک')).not.toBeInTheDocument();
});
it('بین منابع جابه‌جا می‌شود', async () => {
const user = userEvent.setup();
renderWithProviders(<ClinicAppointmentSettingsPage />);
await user.click(screen.getByRole('button', { name: 'منابع' }));
await user.click(await screen.findByRole('button', { name: 'اتاق ۱' }));
await waitFor(() => expect(screen.getByText('ساعات کاری r-2')).toBeInTheDocument());
});
/** scope در URL می‌نشیند، وگرنه «بازگشت» و رفرش کاربر را به تب پزشکان می‌پراند. */
it('scope را از URL می‌خواند', async () => {
renderWithProviders(<ClinicAppointmentSettingsPage />, {
route: '/admin/settings/appointment-settings?scope=resources',
});
await waitFor(() => expect(screen.getByText('ساعات کاری r-1')).toBeInTheDocument());
});
it('کلینیک بدون منبع، حالت خالی با راه‌حل می‌دهد', async () => {
resources = [];
const user = userEvent.setup();
renderWithProviders(<ClinicAppointmentSettingsPage />);
await user.click(screen.getByRole('button', { name: 'منابع' }));
expect(await screen.findByText('هنوز منبعی تعریف نشده است')).toBeInTheDocument();
expect(screen.getByText('تنظیمات ← منابع')).toHaveAttribute('href', '/admin/resources');
});
});
@@ -1,29 +1,44 @@
import { useMemo, useState } from 'react';
import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { UserGroupIcon } from '@heroicons/react/24/outline';
import { CubeIcon, UserGroupIcon } from '@heroicons/react/24/outline';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import { usePermissions } from '../hooks/usePermissions';
import { useUrlState } from '../hooks/useUrlState';
import { useResources } from '../hooks/useResources';
import SettingsLayout from '../components/layout/SettingsLayout';
import { ScheduleSection } from '../components/schedule/ScheduleSection';
import ResourceWorkingHoursPanel from '../components/resources/ResourceWorkingHoursPanel';
import ResourceExceptionsPanel from '../components/resources/ResourceExceptionsPanel';
import FreeVisitPrice from '../components/FreeVisitPrice';
import BackButton from '../components/ui/BackButton';
import type { ClinicDoctorItem } from '../components/ClinicDoctorsManager';
const SCOPES = [
{ id: 'doctors', label: 'پزشکان' },
{ id: 'resources', label: 'منابع' },
] as const;
type Scope = typeof SCOPES[number]['id'];
/**
* تنظیمات نوبت‌دهی همه پزشکان کلینیک — یک تب به ازای هر پزشک.
* تنظیمات نوبت‌دهی کلینیک — یک تب به ازای هر پزشک، و یک تب به ازای هر منبع.
*
* هر تب دقیقاً همان ScheduleSection پنل پزشک مستقل را رندر می‌کند؛ تنها تفاوت،
* امکان جابه‌جایی بین پزشکان است.
* منبع در مدل Resource-First واحدِ ظرفیت است و ساعت کاری و تعطیلات خودش را دارد، پس
* دقیقاً همان‌جایی مدیریت می‌شود که برنامهٔ پزشک — نه در یک صفحهٔ جدا. تب پزشک همان
* `ScheduleSection` پنل پزشک مستقل است و تب منبع همان پنل‌های صفحهٔ منبع؛ هیچ‌کدام
* نسخهٔ دومی ندارند.
*/
function ClinicAppointmentSettingsContent() {
const { dbUuid, context, availableContexts } = useAuthStore();
const { can } = usePermissions();
// منشیِ بدون مجوزِ ویرایشِ تنظیمات نوبت‌دهی، فقط مشاهده می‌کند.
const apptReadOnly = !can('appointment_settings', 'update');
const [activeUuid, setActiveUuid] = useState<string | null>(null);
// انتخاب‌ها در URL می‌نشینند تا «بازگشت» و رفرش همان تب را برگردانند.
const [urlState, setUrlState] = useUrlState({ scope: 'doctors', doctor: '', resource: '' });
const scope = (SCOPES.some((s) => s.id === urlState.scope) ? urlState.scope : 'doctors') as Scope;
// کاربری که هم پزشک است هم مالک کلینیک، dbUuid‌اش ممکن است uuid پزشک باشد.
const clinicUuid = useMemo(() => {
@@ -42,8 +57,10 @@ function ClinicAppointmentSettingsContent() {
return (raw as any)?.data ?? raw ?? [];
}, [doctorsQ.data]);
const selected = activeUuid ?? doctorList[0]?.uuid ?? null;
const selectedDoctor = doctorList.find(d => d.uuid === selected) ?? null;
const { resources, loading: resourcesLoading } = useResources({ active: '1' });
const selectedDoctor = doctorList.find(d => d.uuid === urlState.doctor) ?? doctorList[0] ?? null;
const selectedResource = resources.find(r => r.uuid === urlState.resource) ?? resources[0] ?? null;
if (!clinicUuid) {
return (
@@ -64,59 +81,163 @@ function ClinicAppointmentSettingsContent() {
<div>
<h1 className="section-title">مدیریت نوبت دهی</h1>
<div className="muted">
{selectedDoctor ? `تنظیمات نوبت‌دهی ${selectedDoctor.name}` : 'تنظیمات نوبت‌دهی پزشکان کلینیک'}
{scope === 'doctors'
? (selectedDoctor ? `تنظیمات نوبت‌دهی ${selectedDoctor.name}` : 'تنظیمات نوبت‌دهی پزشکان کلینیک')
: (selectedResource ? `تنظیمات نوبت‌دهی ${selectedResource.name}` : 'تنظیمات نوبت‌دهی منابع کلینیک')}
</div>
</div>
</div>
{doctorsQ.isLoading ? (
<div className="card card-pad"><p className="muted">در حال بارگذاری پزشکان...</p></div>
) : doctorList.length === 0 ? (
<div className="card card-pad">
<div className="empty" style={{ padding: '20px 0' }}>
<UserGroupIcon style={{ width: 30, height: 30 }} />
<p className="muted">هیچ پزشکی به این کلینیک متصل نیست</p>
<Link className="btn primary sm" to="/admin/settings/clinic-doctors">مدیریت پزشکان کلینیک</Link>
</div>
</div>
) : (
<>
<div className="card card-pad" style={{ paddingBottom: 12 }}>
<div className="seg" style={{ overflowX: 'auto', flexWrap: 'nowrap' }}>
{doctorList.map(doc => (
<button
key={doc.uuid}
className={selected === doc.uuid ? 'active' : ''}
style={{ whiteSpace: 'nowrap' }}
onClick={() => setActiveUuid(doc.uuid)}
>
{doc.name}
</button>
))}
</div>
</div>
<div className="seg" style={{ alignSelf: 'flex-start' }}>
{SCOPES.map((s) => (
<button
key={s.id}
className={scope === s.id ? 'active' : ''}
onClick={() => setUrlState({ scope: s.id })}
>
{s.label}
</button>
))}
</div>
{/* 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} readOnly={apptReadOnly} />
<ScheduleSection doctorUuid={selected} clinicUuid={clinicUuid} readOnly={apptReadOnly} />
</div>
)}
</>
{scope === 'doctors' ? (
<DoctorsScope
loading={doctorsQ.isLoading}
doctors={doctorList}
selected={selectedDoctor}
clinicUuid={clinicUuid}
readOnly={apptReadOnly}
onSelect={(uuid) => setUrlState({ doctor: uuid })}
/>
) : (
<ResourcesScope
loading={resourcesLoading}
resources={resources}
selected={selectedResource}
canUpdate={!apptReadOnly}
onSelect={(uuid) => setUrlState({ resource: uuid })}
/>
)}
</div>
);
}
function TabBar<T extends { uuid: string; name: string }>({ items, selected, onSelect }: {
items: T[];
selected: T | null;
onSelect: (uuid: string) => void;
}) {
return (
<div className="card card-pad" style={{ paddingBottom: 12 }}>
<div className="seg" style={{ overflowX: 'auto', flexWrap: 'nowrap' }}>
{items.map((item) => (
<button
key={item.uuid}
className={selected?.uuid === item.uuid ? 'active' : ''}
style={{ whiteSpace: 'nowrap' }}
onClick={() => onSelect(item.uuid)}
>
{item.name}
</button>
))}
</div>
</div>
);
}
function SelectedHeader({ icon, label }: { icon: React.ReactNode; label: string }) {
return (
<div
className="card card-pad"
style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 'var(--gap)' }}
>
{icon}
<span style={{ fontWeight: 600 }}>{label}</span>
</div>
);
}
function DoctorsScope({ loading, doctors, selected, clinicUuid, readOnly, onSelect }: {
loading: boolean;
doctors: ClinicDoctorItem[];
selected: ClinicDoctorItem | null;
clinicUuid: string;
readOnly: boolean;
onSelect: (uuid: string) => void;
}) {
if (loading) return <div className="card card-pad"><p className="muted">در حال بارگذاری پزشکان...</p></div>;
if (doctors.length === 0) {
return (
<div className="card card-pad">
<div className="empty" style={{ padding: '20px 0' }}>
<UserGroupIcon style={{ width: 30, height: 30 }} />
<p className="muted">هیچ پزشکی به این کلینیک متصل نیست</p>
<Link className="btn primary sm" to="/admin/settings/clinic-doctors">مدیریت پزشکان کلینیک</Link>
</div>
</div>
);
}
return (
<>
<TabBar items={doctors} selected={selected} onSelect={onSelect} />
{/* key اجباری است: بدون آن state ویرایشِ برنامه بین پزشکان نشت می‌کند */}
{selected && (
<div key={selected.uuid}>
<SelectedHeader
icon={<UserGroupIcon style={{ width: 18, height: 18, color: 'var(--primary)' }} />}
label={selected.name}
/>
<FreeVisitPrice doctorUuid={selected.uuid} readOnly={readOnly} />
<ScheduleSection doctorUuid={selected.uuid} clinicUuid={clinicUuid} readOnly={readOnly} />
</div>
)}
</>
);
}
function ResourcesScope({ loading, resources, selected, canUpdate, onSelect }: {
loading: boolean;
resources: { uuid: string; name: string; type_name: string }[];
selected: { uuid: string; name: string; type_name: string } | null;
canUpdate: boolean;
onSelect: (uuid: string) => void;
}) {
if (loading) return <div className="card card-pad"><p className="muted">در حال بارگذاری منابع...</p></div>;
if (resources.length === 0) {
return (
<div className="card card-pad">
<div className="empty" style={{ padding: '20px 0' }}>
<CubeIcon style={{ width: 30, height: 30 }} />
<p className="muted">هنوز منبعی تعریف نشده است</p>
<Link className="btn primary sm" to="/admin/resources">تنظیمات منابع</Link>
</div>
</div>
);
}
return (
<>
<TabBar items={resources} selected={selected} onSelect={onSelect} />
{/* همان دلیل تب پزشک: بدون key، شیفتِ نیمه‌ویرایش‌شده به منبع بعدی می‌چسبد. */}
{selected && (
<div key={selected.uuid} style={{ display: 'grid', gap: 'var(--gap)' }}>
<SelectedHeader
icon={<CubeIcon style={{ width: 18, height: 18, color: 'var(--primary)' }} />}
label={`${selected.name} · ${selected.type_name}`}
/>
<ResourceWorkingHoursPanel resourceUuid={selected.uuid} canUpdate={canUpdate} />
<ResourceExceptionsPanel resourceUuid={selected.uuid} canUpdate={canUpdate} />
</div>
)}
</>
);
}
export default function ClinicAppointmentSettingsPage() {
return (
<SettingsLayout active="appointment">
+2 -2
View File
@@ -32,7 +32,7 @@ export default function HolidaysSettingsPage() {
{
key: 'gregorian',
header: 'میلادی',
render: (h) => <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{formatDate(h.date * 1000)}</span>,
render: (h) => <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{formatDate(h.date)}</span>,
},
{
key: 'status',
@@ -150,7 +150,7 @@ function ClosureCard({
{overrides.map((o) => (
<div key={o.uuid} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
<span style={{ flex: 1, color: 'var(--text-2)' }}>
{formatDate(o.date * 1000)}{o.note ? ` · ${o.note}` : ''}
{formatDate(o.date)}{o.note ? ` · ${o.note}` : ''}
</span>
{canUpdate && (
<button type="button" className="btn secondary sm" onClick={() => onRemove(o.uuid)} aria-label="حذف تعطیلی">