Files
clinicpro/assets/admin/pages/ClinicAppointmentSettingsPage.tsx
T
hamedandClaude Opus 5 9ba4c8d948 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>
2026-08-02 15:49:01 +03:30

248 lines
9.5 KiB
TypeScript

import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
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'];
/**
* تنظیمات نوبت‌دهی کلینیک — یک تب به ازای هر پزشک، و یک تب به ازای هر منبع.
*
* منبع در مدل Resource-First واحدِ ظرفیت است و ساعت کاری و تعطیلات خودش را دارد، پس
* دقیقاً همان‌جایی مدیریت می‌شود که برنامهٔ پزشک — نه در یک صفحهٔ جدا. تب پزشک همان
* `ScheduleSection` پنل پزشک مستقل است و تب منبع همان پنل‌های صفحهٔ منبع؛ هیچ‌کدام
* نسخهٔ دومی ندارند.
*/
function ClinicAppointmentSettingsContent() {
const { dbUuid, context, availableContexts } = useAuthStore();
const { can } = usePermissions();
// منشیِ بدون مجوزِ ویرایشِ تنظیمات نوبت‌دهی، فقط مشاهده می‌کند.
const apptReadOnly = !can('appointment_settings', 'update');
// انتخاب‌ها در 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(() => {
if (context?.type === 'clinic') return dbUuid;
return availableContexts.find(c => c.type === 'clinic')?.db_uuid ?? null;
}, [context, dbUuid, availableContexts]);
const doctorsQ = useQuery({
queryKey: ['clinic-doctors', clinicUuid],
queryFn: () => api.get<ApiResponse<{ data: ClinicDoctorItem[] }>>(`/api/v1/clinic/doctor-list/${clinicUuid}`),
enabled: !!clinicUuid,
});
const doctorList: ClinicDoctorItem[] = useMemo(() => {
const raw = doctorsQ.data?.data;
return (raw as any)?.data ?? raw ?? [];
}, [doctorsQ.data]);
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 (
<div style={{ padding: 40, textAlign: 'center' }}>
<p style={{ color: 'var(--text-3)', fontSize: 14 }}>
{dbUuid ? 'کلینیکی برای این حساب کاربری یافت نشد' : 'در حال بارگذاری اطلاعات کلینیک...'}
</p>
</div>
);
}
return (
<div className="fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
<div>
<BackButton fallback="/admin/settings-menu" />
</div>
<div className="card-title-row">
<div>
<h1 className="section-title">مدیریت نوبت دهی</h1>
<div className="muted">
{scope === 'doctors'
? (selectedDoctor ? `تنظیمات نوبت‌دهی ${selectedDoctor.name}` : 'تنظیمات نوبت‌دهی پزشکان کلینیک')
: (selectedResource ? `تنظیمات نوبت‌دهی ${selectedResource.name}` : 'تنظیمات نوبت‌دهی منابع کلینیک')}
</div>
</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>
{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">
<ClinicAppointmentSettingsContent />
</SettingsLayout>
);
}