feat(resource): calendar UI, holiday admin, backfill and interval algebra
Completes task 03. The resource calendar page edits weekly shifts, records leave and
maintenance, and previews two weeks of availability with a Persian reason for every
empty day — showing the raw server key ("outside_branch_hours") to a user would have
been a meaningless message. The preview is labelled raw on the page itself, because
booked appointments are not subtracted yet and mistaking it for bookable time leads
to overbooking.
The interval algebra moved to src/Shared/Time/TimeInterval.php with twelve unit
tests: tasks 05 and 06 need the same union/intersect/subtract, and a second
implementation is how two subtly different definitions of "overlap" get born. The
half-open [start, end) contract is what makes a shift ending at 13:00 and one
starting at 13:00 not overlap.
AvailabilityQueryCountTest locks the query count flat: one day and ninety days cost
exactly the same number of queries. Without it the first refactor can put a query
inside the day loop and a 90-day response quietly becomes hundreds of queries —
something only production would reveal.
app:resource:calendar:backfill derives shifts from existing WeeklySchedule sessions,
so the resources created in task 02 are not left with empty calendars. It skips any
resource a user has already configured, which is also what makes it idempotent. The
weekly schedule itself is untouched: this is a copy, not a migration.
Also added --replace to the holiday import. upsert keys on the date, so a row written
with a *wrong* date can never correct itself — re-running just creates the right row
beside the wrong one. That is exactly what happened after fixing the Jalali
conversion bug, and it was caught while capturing real responses for the docs.
Deferred with reasons recorded in the checklist: seasonal shift validity (two
nullable columns can be added later without backfill, so "needed from day one" does
not hold), and a Jalali date picker in the exception form.
1154 tests / 3229 assertions. phpstan at its 14-error baseline, none in touched
files. tsc clean, vitest 622 tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -81,6 +81,8 @@ import ResourcesPage from './pages/ResourcesPage';
|
||||
import ResourceTypesPage from './pages/ResourceTypesPage';
|
||||
import SkillsPage from './pages/SkillsPage';
|
||||
import ResourcePoolsPage from './pages/ResourcePoolsPage';
|
||||
import ResourceCalendarPage from './pages/ResourceCalendarPage';
|
||||
import HolidaysSettingsPage from './pages/HolidaysSettingsPage';
|
||||
import PatientRecordFormPage from './pages/PatientRecordFormPage';
|
||||
import PatientDetailPage from './pages/PatientDetailPage';
|
||||
import PaymentSuccessPage from './pages/PaymentSuccessPage';
|
||||
@@ -289,6 +291,8 @@ export default function App() {
|
||||
<Route path="resources/types" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']} blockClinicScope permission={['appointment_settings', 'view']}><ResourceTypesPage /></RoleRoute>} />
|
||||
<Route path="resources/skills" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']} blockClinicScope permission={['appointment_settings', 'view']}><SkillsPage /></RoleRoute>} />
|
||||
<Route path="resources/pools" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']} blockClinicScope permission={['appointment_settings', 'view']}><ResourcePoolsPage /></RoleRoute>} />
|
||||
<Route path="resources/:resourceUuid/calendar" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']} blockClinicScope permission={['appointment_settings', 'view']}><ResourceCalendarPage /></RoleRoute>} />
|
||||
<Route path="holidays" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']} blockClinicScope permission={['appointment_settings', 'view']}><HolidaysSettingsPage /></RoleRoute>} />
|
||||
<Route path="sms-wallet" element={<RoleRoute roles={['doctor', 'clinic', 'secretary']} blockClinicScope permission={['sms', 'view']}><SmsWalletPage /></RoleRoute>} />
|
||||
<Route path="my-secretaries" element={<RoleRoute roles={['doctor', 'clinic']} blockClinicScope><MySecretariesPage /></RoleRoute>} />
|
||||
<Route path="admin-subscription" element={<RoleRoute roles={['admin']}><AdminSubscriptionPage /></RoleRoute>} />
|
||||
|
||||
@@ -31,6 +31,7 @@ export const SETTINGS_MENU: SettingsMenuItem[] = [
|
||||
{ key: 'clinic-doctors', label: 'پزشکان کلینیک', icon: BuildingOffice2Icon, to: '/admin/settings/clinic-doctors', roles: ['clinic'], perm: ['clinic_doctors', 'view'] },
|
||||
{ key: 'branches', label: 'شعبهها و اتاقها', icon: MapPinIcon, to: '/admin/branches', roles: ['doctor', 'clinic'], perm: ['appointment_settings', 'view'] },
|
||||
{ key: 'resources', label: 'منابع', icon: CubeIcon, to: '/admin/resources', roles: ['doctor', 'clinic'], perm: ['appointment_settings', 'view'] },
|
||||
{ key: 'holidays', label: 'تعطیلات رسمی', icon: CalendarDaysIcon, to: '/admin/holidays', roles: ['doctor', 'clinic'], perm: ['appointment_settings', 'view'] },
|
||||
{ key: 'payment', label: 'مدیریت پرداخت', icon: BanknotesIcon, to: '/admin/my-financial', perm: ['payments', 'view'] },
|
||||
{ key: 'secretary', label: 'مدیریت منشی', icon: UsersIcon, to: '/admin/my-secretaries' },
|
||||
{ key: 'staff', label: 'پرسنل', icon: UserPlusIcon, to: '/admin/staff', perm: ['staff', 'view'] },
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { toast } from 'sonner';
|
||||
import { api, ApiError, type ApiResponse } from '../lib/api';
|
||||
import type {
|
||||
HolidayOverride, NationalHoliday, ResourceAvailability,
|
||||
ResourceCalendarDays, ResourceException, WorkingHoursPayload,
|
||||
} from '../types';
|
||||
|
||||
function fail(e: unknown, fallback: string) {
|
||||
toast.error(e instanceof ApiError ? e.message : fallback);
|
||||
}
|
||||
|
||||
export function useResourceCalendar(resourceUuid: string | undefined) {
|
||||
const qc = useQueryClient();
|
||||
const key = ['resource-calendar', resourceUuid];
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => api.get<ApiResponse<ResourceCalendarDays>>(`/api/v1/resource/${resourceUuid}/calendar`),
|
||||
enabled: !!resourceUuid,
|
||||
});
|
||||
|
||||
/** PUT جایگزینی کامل است: روزی که نفرستید خالی میشود. */
|
||||
const save = useMutation({
|
||||
mutationFn: (days: WorkingHoursPayload) =>
|
||||
api.put<ApiResponse<ResourceCalendarDays>>(`/api/v1/resource/${resourceUuid}/calendar`, { days }),
|
||||
onSuccess: () => {
|
||||
toast.success('شیفتها ذخیره شد');
|
||||
qc.invalidateQueries({ queryKey: key });
|
||||
qc.invalidateQueries({ queryKey: ['resource-availability', resourceUuid] });
|
||||
},
|
||||
onError: (e) => fail(e, 'ذخیرهٔ شیفتها ناموفق بود'),
|
||||
});
|
||||
|
||||
return { calendar: query.data?.data, loading: query.isLoading, save };
|
||||
}
|
||||
|
||||
export function useResourceExceptions(resourceUuid: string | undefined) {
|
||||
const qc = useQueryClient();
|
||||
const key = ['resource-exceptions', resourceUuid];
|
||||
|
||||
const invalidate = () => {
|
||||
qc.invalidateQueries({ queryKey: key });
|
||||
qc.invalidateQueries({ queryKey: ['resource-availability', resourceUuid] });
|
||||
};
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => api.get<ApiResponse<ResourceException[]>>(`/api/v1/resource/${resourceUuid}/exceptions`),
|
||||
enabled: !!resourceUuid,
|
||||
});
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: (d: { type: string; starts_at: number; ends_at: number; reason?: string | null }) =>
|
||||
api.post<ApiResponse<ResourceException>>(`/api/v1/resource/${resourceUuid}/exception`, d),
|
||||
onSuccess: () => { toast.success('استثنا ثبت شد'); invalidate(); },
|
||||
onError: (e) => fail(e, 'ثبت استثنا ناموفق بود'),
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: (uuid: string) => api.delete<ApiResponse<null>>(`/api/v1/resource-exception/${uuid}`),
|
||||
onSuccess: () => { toast.success('استثنا حذف شد'); invalidate(); },
|
||||
onError: (e) => fail(e, 'حذف استثنا ناموفق بود'),
|
||||
});
|
||||
|
||||
return { exceptions: query.data?.data ?? [], loading: query.isLoading, create, remove };
|
||||
}
|
||||
|
||||
export function useResourceAvailability(resourceUuid: string | undefined, from: number, to: number) {
|
||||
const query = useQuery({
|
||||
queryKey: ['resource-availability', resourceUuid, from, to],
|
||||
queryFn: () =>
|
||||
api.get<ApiResponse<ResourceAvailability>>(`/api/v1/resource/${resourceUuid}/availability?from=${from}&to=${to}`),
|
||||
enabled: !!resourceUuid,
|
||||
});
|
||||
|
||||
return { availability: query.data?.data, loading: query.isLoading };
|
||||
}
|
||||
|
||||
export function useHolidays(year: number) {
|
||||
const qc = useQueryClient();
|
||||
const key = ['national-holidays', year];
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () =>
|
||||
api.get<ApiResponse<{ year: number; holidays: NationalHoliday[]; overrides: HolidayOverride[] }>>(
|
||||
`/api/v1/national-holidays?year=${year}`,
|
||||
),
|
||||
});
|
||||
|
||||
const setOverride = useMutation({
|
||||
mutationFn: (d: { date: number; is_working: boolean; note?: string | null }) =>
|
||||
api.post<ApiResponse<HolidayOverride>>('/api/v1/holiday-overrides', d),
|
||||
onSuccess: () => { toast.success('استثنای تعطیلی ذخیره شد'); qc.invalidateQueries({ queryKey: key }); },
|
||||
onError: (e) => fail(e, 'ذخیرهٔ استثنا ناموفق بود'),
|
||||
});
|
||||
|
||||
const removeOverride = useMutation({
|
||||
mutationFn: (uuid: string) => api.delete<ApiResponse<null>>(`/api/v1/holiday-override/${uuid}`),
|
||||
onSuccess: () => { toast.success('استثنا حذف شد'); qc.invalidateQueries({ queryKey: key }); },
|
||||
onError: (e) => fail(e, 'حذف استثنا ناموفق بود'),
|
||||
});
|
||||
|
||||
return {
|
||||
holidays: query.data?.data?.holidays ?? [],
|
||||
overrides: query.data?.data?.overrides ?? [],
|
||||
loading: query.isLoading,
|
||||
setOverride,
|
||||
removeOverride,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import React from 'react';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import DataTable, { type Column } from '../components/ui/DataTable';
|
||||
import SearchableSelect from '../components/ui/SearchableSelect';
|
||||
import { useUrlState } from '../hooks/useUrlState';
|
||||
import { usePermissions } from '../hooks/usePermissions';
|
||||
import { useHolidays } from '../hooks/useResourceCalendar';
|
||||
import { formatDate } from '../lib/utils';
|
||||
import type { NationalHoliday } from '../types';
|
||||
|
||||
/** سالِ شمسی جاری از همان فرمتکنندهٔ شمسیِ مرورگر گرفته میشود، نه با محاسبهٔ دستی. */
|
||||
function currentJalaliYear(): number {
|
||||
const formatted = new Intl.DateTimeFormat('en-u-ca-persian', { year: 'numeric' }).format(new Date());
|
||||
return Number(formatted.replace(/\D/g, '')) || 1405;
|
||||
}
|
||||
|
||||
/**
|
||||
* تعطیلات رسمی و استثناهای این محیط.
|
||||
*
|
||||
* خودِ تعطیلات کشوریاند و اینجا فقط دیده میشوند؛ آنچه محیط تغییر میدهد «باز بودن
|
||||
* یا نبودنِ» همان روز برای خودش است.
|
||||
*/
|
||||
export default function HolidaysSettingsPage() {
|
||||
const thisYear = currentJalaliYear();
|
||||
const [urlState, setUrlState] = useUrlState({ year: String(thisYear) });
|
||||
const year = Number(urlState.year) || thisYear;
|
||||
|
||||
const { holidays, overrides, loading, setOverride, removeOverride } = useHolidays(year);
|
||||
const { can } = usePermissions();
|
||||
const canUpdate = can('appointment_settings', 'update');
|
||||
|
||||
const overrideByDate = new Map(overrides.map((o) => [o.date, o]));
|
||||
|
||||
const columns: Column<NationalHoliday>[] = [
|
||||
{ key: 'jalali_date', header: 'تاریخ', render: (h) => <span style={{ fontWeight: 600 }}>{h.jalali_date}</span> },
|
||||
{ key: 'title', header: 'مناسبت', render: (h) => <span style={{ fontSize: 13 }}>{h.title}</span> },
|
||||
{
|
||||
key: 'gregorian',
|
||||
header: 'میلادی',
|
||||
render: (h) => <span style={{ fontSize: 12, color: 'var(--text-3)' }}>{formatDate(h.date * 1000)}</span>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'وضعیت این محیط',
|
||||
render: (h) =>
|
||||
overrideByDate.get(h.date)?.is_working ? (
|
||||
<span className="badge green"><span className="bdot" />باز است</span>
|
||||
) : (
|
||||
<span className="badge gray"><span className="bdot" />تعطیل</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const years = Array.from({ length: 5 }, (_, i) => thisYear - 1 + i);
|
||||
|
||||
return (
|
||||
<div className="fade-in">
|
||||
<PageHeader
|
||||
title="تعطیلات رسمی"
|
||||
description="تعطیلات کشوری برای همهٔ محیطها اعمال میشود. اگر این محیط روزی را باز است، همینجا استثنا بزنید."
|
||||
backTo="/admin/settings-menu"
|
||||
/>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={holidays}
|
||||
loading={loading}
|
||||
emptyMessage={`برای سال ${year} تعطیلی ثبت نشده است`}
|
||||
headerExtra={
|
||||
<div style={{ minWidth: 160, marginRight: 'auto' }}>
|
||||
<SearchableSelect
|
||||
options={years.map((y) => ({ value: String(y), label: String(y) }))}
|
||||
value={String(year)}
|
||||
onChange={(v) => setUrlState({ year: v ? String(v) : String(thisYear) })}
|
||||
placeholder="سال"
|
||||
height={36}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
actions={
|
||||
canUpdate
|
||||
? (h) => {
|
||||
const override = overrideByDate.get(h.date);
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
{override?.is_working ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary sm"
|
||||
disabled={removeOverride.isPending}
|
||||
onClick={() => removeOverride.mutate(override.uuid)}
|
||||
>
|
||||
تعطیل کن
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary sm"
|
||||
disabled={setOverride.isPending}
|
||||
onClick={() => setOverride.mutate({ date: h.date, is_working: true })}
|
||||
>
|
||||
این روز بازیم
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
|
||||
<ClosureCard
|
||||
overrides={overrides.filter((o) => !o.is_working)}
|
||||
canUpdate={canUpdate}
|
||||
saving={setOverride.isPending}
|
||||
onAdd={(date, note) => setOverride.mutate({ date, is_working: false, note })}
|
||||
onRemove={(uuid) => removeOverride.mutate(uuid)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* جهت دوم: روزی که تعطیل رسمی نیست ولی این محیط بسته است.
|
||||
* این با «استثنای منبع» فرق دارد — آن روی یک منبع است و این روی کل محیط.
|
||||
*/
|
||||
function ClosureCard({
|
||||
overrides, canUpdate, saving, onAdd, onRemove,
|
||||
}: {
|
||||
overrides: { uuid: string; date: number; note: string | null }[];
|
||||
canUpdate: boolean;
|
||||
saving: boolean;
|
||||
onAdd: (date: number, note: string | null) => void;
|
||||
onRemove: (uuid: string) => void;
|
||||
}) {
|
||||
const [date, setDate] = React.useState('');
|
||||
const [note, setNote] = React.useState('');
|
||||
|
||||
const timestamp = date === '' ? null : Math.floor(new Date(`${date}T00:00:00`).getTime() / 1000);
|
||||
|
||||
return (
|
||||
<div className="card" style={{ padding: 16, marginTop: 16 }}>
|
||||
<h2 className="section-title" style={{ margin: '0 0 4px' }}>تعطیلیهای این محیط</h2>
|
||||
<p style={{ fontSize: 12, color: 'var(--text-3)', margin: '0 0 12px' }}>
|
||||
روزهایی که تعطیل رسمی نیستند ولی این محیط بسته است. برای مرخصی یک نفر یا سرویس یک دستگاه،
|
||||
از تقویم همان منبع استفاده کنید.
|
||||
</p>
|
||||
|
||||
{overrides.length === 0 ? (
|
||||
<p style={{ fontSize: 13, color: 'var(--text-3)', margin: 0 }}>موردی ثبت نشده است.</p>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: 8, marginBottom: 12 }}>
|
||||
{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}` : ''}
|
||||
</span>
|
||||
{canUpdate && (
|
||||
<button type="button" className="btn secondary sm" onClick={() => onRemove(o.uuid)} aria-label="حذف تعطیلی">
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canUpdate && (
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input type="date" className="field" value={date} onChange={(e) => setDate(e.target.value)} style={{ minWidth: 170 }} />
|
||||
<input className="field" value={note} onChange={(e) => setNote(e.target.value)} placeholder="توضیح (اختیاری)" style={{ flex: 1, minWidth: 180 }} />
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary"
|
||||
disabled={saving || timestamp === null}
|
||||
onClick={() => {
|
||||
onAdd(timestamp!, note.trim() === '' ? null : note.trim());
|
||||
setDate('');
|
||||
setNote('');
|
||||
}}
|
||||
>
|
||||
افزودن
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { screen, 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() } }));
|
||||
vi.mock('../hooks/usePermissions', () => ({ usePermissions: () => ({ can: () => true }) }));
|
||||
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import { api } from '../lib/api';
|
||||
import ResourceCalendarPage from './ResourceCalendarPage';
|
||||
|
||||
const get = api.get as ReturnType<typeof vi.fn>;
|
||||
|
||||
const emptyDays = (): Record<string, unknown[]> =>
|
||||
Object.fromEntries(Array.from({ length: 7 }, (_, d) => [String(d), [] as unknown[]]));
|
||||
|
||||
function mockApi(days: Record<string, unknown[]>, availabilityDays: unknown[]) {
|
||||
get.mockImplementation((path: string) => {
|
||||
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.endsWith('/exceptions')) return Promise.resolve({ success: true, data: [] });
|
||||
if (path.startsWith('/api/v1/resources')) return Promise.resolve({ success: true, data: [] });
|
||||
return Promise.resolve({ success: true, data: [] });
|
||||
});
|
||||
}
|
||||
|
||||
function renderPage() {
|
||||
return renderWithProviders(
|
||||
<Routes>
|
||||
<Route path="/admin/resources/:resourceUuid/calendar" element={<ResourceCalendarPage />} />
|
||||
</Routes>,
|
||||
{ route: '/admin/resources/r1/calendar' },
|
||||
);
|
||||
}
|
||||
|
||||
describe('ResourceCalendarPage', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('renders seven days and marks shiftless ones', async () => {
|
||||
mockApi(emptyDays(), []);
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('شنبه')).toBeInTheDocument());
|
||||
expect(screen.getByText('جمعه')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('بدون شیفت')).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('shows stored shifts as times', 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();
|
||||
|
||||
await waitFor(() => expect(screen.getByDisplayValue('09:00')).toBeInTheDocument());
|
||||
expect(screen.getByDisplayValue('17:00')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
/**
|
||||
* دلیلِ خالی بودن روز باید فارسی نشان داده شود؛ نشان دادن کلید خام سرور
|
||||
* («outside_branch_hours») به کاربر یعنی پیام بیمعنا.
|
||||
*/
|
||||
it('translates every empty-day reason into Persian', 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: ['outside_branch_hours'] },
|
||||
{ date: 1785702600, day_of_week: 2, intervals: [], total_minutes: 0, reasons: ['exception'] },
|
||||
]);
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('تعطیل رسمی')).toBeInTheDocument());
|
||||
expect(screen.getByText('شیفت بیرون از ساعت کاری شعبه')).toBeInTheDocument();
|
||||
expect(screen.getByText('مرخصی یا سرویس')).toBeInTheDocument();
|
||||
expect(screen.queryByText('outside_branch_hours')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows free minutes for a day that has availability', async () => {
|
||||
mockApi(emptyDays(), [
|
||||
{ date: 1785529800, day_of_week: 0, intervals: [{ start: 1, end: 2 }], total_minutes: 480, reasons: [] },
|
||||
]);
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => expect(screen.getByText('480 دقیقه')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
/** پیشنمایش نباید «وقت قابل رزرو» خوانده شود — نوبتها هنوز کسر نشدهاند. */
|
||||
it('warns that the preview is raw availability', async () => {
|
||||
mockApi(emptyDays(), []);
|
||||
renderPage();
|
||||
|
||||
await waitFor(() => expect(screen.getByText(/نوبتهای ثبتشده هنوز از آن کسر نشدهاند/)).toBeInTheDocument());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,376 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { PlusIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import ConfirmDialog from '../components/ui/ConfirmDialog';
|
||||
import SearchableSelect from '../components/ui/SearchableSelect';
|
||||
import { usePermissions } from '../hooks/usePermissions';
|
||||
import { useResources } from '../hooks/useResources';
|
||||
import {
|
||||
useResourceAvailability, useResourceCalendar, useResourceExceptions,
|
||||
} from '../hooks/useResourceCalendar';
|
||||
import { formatDate } from '../lib/utils';
|
||||
import type { ResourceException } from '../types';
|
||||
|
||||
/** ۰ = شنبه — همان قرارداد بکاند و ساعت کاری شعبه. */
|
||||
const DAY_LABELS = ['شنبه', 'یکشنبه', 'دوشنبه', 'سهشنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'];
|
||||
|
||||
const MINUTES_IN_DAY = 1440;
|
||||
|
||||
/** چرا یک روز خالی است — بدون ترجمه، پاسخ خام سرور به کاربر نشان داده میشد. */
|
||||
const REASON_LABELS: Record<string, string> = {
|
||||
national_holiday: 'تعطیل رسمی',
|
||||
tenant_holiday: 'تعطیلی این محیط',
|
||||
no_shift: 'شیفتی تعریف نشده',
|
||||
branch_closed: 'شعبه این روز بسته است',
|
||||
outside_branch_hours: 'شیفت بیرون از ساعت کاری شعبه',
|
||||
exception: 'مرخصی یا سرویس',
|
||||
resource_inactive: 'منبع غیرفعال است',
|
||||
branch_inactive: 'شعبه غیرفعال است',
|
||||
};
|
||||
|
||||
const EXCEPTION_TYPES = [
|
||||
{ value: 'leave', label: 'مرخصی' },
|
||||
{ value: 'absence', label: 'غیبت' },
|
||||
{ value: 'maintenance', label: 'سرویس دورهای' },
|
||||
{ value: 'closure', label: 'تعطیلی موردی' },
|
||||
];
|
||||
|
||||
type Draft = { start: string; end: string; endOfDay: boolean };
|
||||
|
||||
function toTime(minute: number): string {
|
||||
return `${String(Math.floor(minute / 60)).padStart(2, '0')}:${String(minute % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function toMinutes(time: string): number | null {
|
||||
const m = /^(\d{1,2}):(\d{2})$/.exec(time.trim());
|
||||
if (!m) return null;
|
||||
const minutes = Number(m[1]) * 60 + Number(m[2]);
|
||||
return minutes >= 0 && minutes <= MINUTES_IN_DAY ? minutes : null;
|
||||
}
|
||||
|
||||
/** نیمهشبِ امروز بهصورت timestamp ثانیهای. */
|
||||
function todayMidnight(): number {
|
||||
const d = new Date();
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return Math.floor(d.getTime() / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* تقویم یک منبع: شیفت هفتگی، استثناها، و پیشنمایش ساعت آزاد.
|
||||
*
|
||||
* پیشنمایش عمداً «ساعت آزاد» نامیده نشده بلکه «خام» است: نوبتهای ثبتشده در آن
|
||||
* کسر نشدهاند و اشتباه گرفتنش با «وقت قابل رزرو» به بیشرزروی میانجامد.
|
||||
*/
|
||||
export default function ResourceCalendarPage() {
|
||||
const { resourceUuid } = useParams<{ resourceUuid: string }>();
|
||||
const { calendar, loading, save } = useResourceCalendar(resourceUuid);
|
||||
const { exceptions, create, remove } = useResourceExceptions(resourceUuid);
|
||||
const { resources } = useResources();
|
||||
const { can } = usePermissions();
|
||||
const canUpdate = can('appointment_settings', 'update');
|
||||
|
||||
const resource = resources.find((r) => r.uuid === resourceUuid);
|
||||
|
||||
const [draft, setDraft] = useState<Record<number, Draft[]>>({});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [toDelete, setToDelete] = useState<ResourceException | null>(null);
|
||||
|
||||
const previewFrom = todayMidnight();
|
||||
const previewTo = previewFrom + 13 * 86400;
|
||||
const { availability } = useResourceAvailability(resourceUuid, previewFrom, previewTo);
|
||||
|
||||
useEffect(() => {
|
||||
if (!calendar) return;
|
||||
const next: Record<number, Draft[]> = {};
|
||||
DAY_LABELS.forEach((_, day) => {
|
||||
next[day] = (calendar.days[String(day)] ?? []).map((r) => ({
|
||||
start: toTime(r.start_minute),
|
||||
end: r.end_minute === MINUTES_IN_DAY ? '23:59' : toTime(r.end_minute),
|
||||
endOfDay: r.end_minute === MINUTES_IN_DAY,
|
||||
}));
|
||||
});
|
||||
setDraft(next);
|
||||
}, [calendar]);
|
||||
|
||||
const totalShifts = useMemo(
|
||||
() => Object.values(draft).reduce((sum, rows) => sum + rows.length, 0),
|
||||
[draft],
|
||||
);
|
||||
|
||||
const editRange = (day: number, index: number, patch: Partial<Draft>) =>
|
||||
setDraft((d) => ({ ...d, [day]: (d[day] ?? []).map((r, i) => (i === index ? { ...r, ...patch } : r)) }));
|
||||
|
||||
const submit = () => {
|
||||
const days: Record<string, { start_minute: number; end_minute: number }[]> = {};
|
||||
|
||||
for (const [dayKey, rows] of Object.entries(draft)) {
|
||||
const parsed: { start_minute: number; end_minute: number }[] = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const start = toMinutes(row.start);
|
||||
const end = row.endOfDay ? MINUTES_IN_DAY : toMinutes(row.end);
|
||||
|
||||
if (start === null || end === null) {
|
||||
setError(`ساعت روز ${DAY_LABELS[Number(dayKey)]} را به شکل ۰۹:۰۰ وارد کنید`);
|
||||
return;
|
||||
}
|
||||
if (end <= start) {
|
||||
setError(`در روز ${DAY_LABELS[Number(dayKey)]} پایان شیفت باید بعد از شروع آن باشد`);
|
||||
return;
|
||||
}
|
||||
parsed.push({ start_minute: start, end_minute: end });
|
||||
}
|
||||
|
||||
days[dayKey] = parsed;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
save.mutate(days);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="fade-in">
|
||||
<PageHeader
|
||||
title={`تقویم ${resource?.name ?? 'منبع'}`}
|
||||
description="شیفت هفتگی منبع. ساعت واقعی از تقاطع این شیفتها با ساعت کاری شعبه بهدست میآید و تعطیلات و مرخصی از آن کسر میشود."
|
||||
backTo="/admin/resources"
|
||||
breadcrumbs={[{ label: 'منابع', to: '/admin/resources' }, { label: 'تقویم' }]}
|
||||
action={
|
||||
canUpdate ? (
|
||||
<button type="button" className="btn primary" disabled={save.isPending} onClick={submit}>
|
||||
{save.isPending ? 'در حال ذخیره...' : 'ذخیرهٔ شیفتها'}
|
||||
</button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="card"
|
||||
style={{ padding: '12px 16px', marginBottom: 16, color: 'var(--danger)', background: 'var(--danger-bg)', fontSize: 13 }}
|
||||
>
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'grid', gap: 16, gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))' }}>
|
||||
<section style={{ display: 'grid', gap: 12 }}>
|
||||
<h2 className="section-title" style={{ margin: 0 }}>
|
||||
شیفت هفتگی {totalShifts > 0 && <span style={{ fontSize: 12, color: 'var(--text-3)' }}>({totalShifts} شیفت)</span>}
|
||||
</h2>
|
||||
|
||||
{loading ? (
|
||||
<div style={{ padding: 16, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
|
||||
) : (
|
||||
DAY_LABELS.map((label, day) => {
|
||||
const rows = draft[day] ?? [];
|
||||
return (
|
||||
<div key={day} className="card" style={{ padding: 14 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: rows.length ? 10 : 0 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<span style={{ fontWeight: 700, fontSize: 14 }}>{label}</span>
|
||||
{rows.length === 0 && <span style={{ fontSize: 12, color: 'var(--text-3)' }}>بدون شیفت</span>}
|
||||
</div>
|
||||
{canUpdate && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary sm"
|
||||
onClick={() => setDraft((d) => ({ ...d, [day]: [...(d[day] ?? []), { start: '09:00', end: '17:00', endOfDay: false }] }))}
|
||||
>
|
||||
<PlusIcon style={{ width: 15 }} /> شیفت
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gap: 8 }}>
|
||||
{rows.map((row, index) => (
|
||||
<div key={index} style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input
|
||||
type="time"
|
||||
className="field"
|
||||
value={row.start}
|
||||
disabled={!canUpdate}
|
||||
onChange={(e) => editRange(day, index, { start: e.target.value })}
|
||||
style={{ width: 116 }}
|
||||
/>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>تا</span>
|
||||
{row.endOfDay ? (
|
||||
<span className="field" style={{ width: 116, color: 'var(--text-2)' }}>۲۴:۰۰</span>
|
||||
) : (
|
||||
<input
|
||||
type="time"
|
||||
className="field"
|
||||
value={row.end}
|
||||
disabled={!canUpdate}
|
||||
onChange={(e) => editRange(day, index, { end: e.target.value })}
|
||||
style={{ width: 116 }}
|
||||
/>
|
||||
)}
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 12, color: 'var(--text-3)' }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={row.endOfDay}
|
||||
disabled={!canUpdate}
|
||||
onChange={(e) => editRange(day, index, { endOfDay: e.target.checked })}
|
||||
/>
|
||||
تا پایان روز
|
||||
</label>
|
||||
{canUpdate && (
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary sm"
|
||||
onClick={() => setDraft((d) => ({ ...d, [day]: (d[day] ?? []).filter((_, i) => i !== index) }))}
|
||||
aria-label="حذف شیفت"
|
||||
>
|
||||
<TrashIcon style={{ width: 15 }} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section style={{ display: 'grid', gap: 12, alignContent: 'start' }}>
|
||||
<ExceptionsCard
|
||||
exceptions={exceptions}
|
||||
canUpdate={canUpdate}
|
||||
saving={create.isPending}
|
||||
onCreate={(payload) => create.mutate(payload)}
|
||||
onDelete={setToDelete}
|
||||
/>
|
||||
|
||||
<div className="card" style={{ padding: 14 }}>
|
||||
<h2 className="section-title" style={{ margin: '0 0 4px' }}>پیشنمایش دو هفته</h2>
|
||||
<p style={{ fontSize: 12, color: 'var(--text-3)', margin: '0 0 10px' }}>
|
||||
ساعت <strong>خام</strong> — نوبتهای ثبتشده هنوز از آن کسر نشدهاند.
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'grid', gap: 6 }}>
|
||||
{(availability?.days ?? []).map((day) => (
|
||||
<div
|
||||
key={day.date}
|
||||
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)}
|
||||
</span>
|
||||
{day.intervals.length === 0 ? (
|
||||
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>
|
||||
{day.reasons.map((r) => REASON_LABELS[r] ?? r).join('، ') || '—'}
|
||||
</span>
|
||||
) : (
|
||||
<span style={{ fontWeight: 600 }}>{day.total_minutes} دقیقه</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={!!toDelete}
|
||||
title="حذف استثنا"
|
||||
message={`آیا از حذف «${toDelete?.type_label}» مطمئن هستید؟`}
|
||||
confirmLabel="حذف"
|
||||
loading={remove.isPending}
|
||||
onConfirm={() => toDelete && remove.mutate(toDelete.uuid, { onSuccess: () => setToDelete(null) })}
|
||||
onCancel={() => setToDelete(null)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ExceptionsCard({
|
||||
exceptions, canUpdate, saving, onCreate, onDelete,
|
||||
}: {
|
||||
exceptions: ResourceException[];
|
||||
canUpdate: boolean;
|
||||
saving: boolean;
|
||||
onCreate: (payload: { type: string; starts_at: number; ends_at: number; reason?: string | null }) => void;
|
||||
onDelete: (e: ResourceException) => void;
|
||||
}) {
|
||||
const [type, setType] = useState<string>('leave');
|
||||
const [startDate, setStartDate] = useState('');
|
||||
const [endDate, setEndDate] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
|
||||
const toTimestamp = (value: string): number | null => {
|
||||
if (value === '') return null;
|
||||
const ms = new Date(`${value}T00:00:00`).getTime();
|
||||
return Number.isNaN(ms) ? null : Math.floor(ms / 1000);
|
||||
};
|
||||
|
||||
const start = toTimestamp(startDate);
|
||||
const end = toTimestamp(endDate);
|
||||
// پایان روزِ انتخابشده، نه آغازش: مرخصیِ «تا سهشنبه» شامل خودِ سهشنبه است.
|
||||
const endExclusive = end === null ? null : end + 86400;
|
||||
const invalid = start === null || endExclusive === null || endExclusive <= start;
|
||||
|
||||
return (
|
||||
<div className="card" style={{ padding: 14 }}>
|
||||
<h2 className="section-title" style={{ margin: '0 0 10px' }}>مرخصی و سرویس</h2>
|
||||
|
||||
{exceptions.length === 0 ? (
|
||||
<p style={{ fontSize: 13, color: 'var(--text-3)', margin: '0 0 10px' }}>استثنایی ثبت نشده است.</p>
|
||||
) : (
|
||||
<div style={{ display: 'grid', gap: 8, marginBottom: 12 }}>
|
||||
{exceptions.map((e) => (
|
||||
<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)}
|
||||
{e.reason ? ` · ${e.reason}` : ''}
|
||||
</span>
|
||||
{canUpdate && (
|
||||
<button type="button" className="btn secondary sm" onClick={() => onDelete(e)} aria-label="حذف استثنا">
|
||||
✕
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canUpdate && (
|
||||
<div style={{ display: 'grid', gap: 8 }}>
|
||||
<SearchableSelect
|
||||
options={EXCEPTION_TYPES}
|
||||
value={type}
|
||||
onChange={(v) => setType(v ? String(v) : 'leave')}
|
||||
placeholder="نوع استثنا"
|
||||
height={36}
|
||||
/>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input type="date" className="field" value={startDate} onChange={(e) => setStartDate(e.target.value)} style={{ flex: 1 }} />
|
||||
<input type="date" className="field" value={endDate} onChange={(e) => setEndDate(e.target.value)} style={{ flex: 1 }} />
|
||||
</div>
|
||||
<input className="field" value={reason} onChange={(e) => setReason(e.target.value)} placeholder="توضیح (اختیاری)" />
|
||||
<button
|
||||
type="button"
|
||||
className="btn secondary"
|
||||
disabled={saving || invalid}
|
||||
onClick={() => {
|
||||
onCreate({
|
||||
type,
|
||||
starts_at: start!,
|
||||
ends_at: endExclusive!,
|
||||
reason: reason.trim() === '' ? null : reason.trim(),
|
||||
});
|
||||
setStartDate('');
|
||||
setEndDate('');
|
||||
setReason('');
|
||||
}}
|
||||
>
|
||||
{saving ? 'در حال ثبت...' : 'ثبت استثنا'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { PlusIcon } from '@heroicons/react/24/outline';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import DataTable, { type Column } from '../components/ui/DataTable';
|
||||
@@ -182,6 +183,9 @@ export default function ResourcesPage() {
|
||||
<button type="button" className="btn secondary sm" onClick={() => setSkillsFor(r)}>
|
||||
مهارتها
|
||||
</button>
|
||||
<Link className="btn secondary sm" to={`/admin/resources/${r.uuid}/calendar`}>
|
||||
تقویم
|
||||
</Link>
|
||||
<button type="button" className="btn secondary sm" onClick={() => setToDelete(r)}>
|
||||
حذف
|
||||
</button>
|
||||
|
||||
@@ -1025,3 +1025,67 @@ export interface ResourcePool {
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
// ── تقویم منبع، استثنا و تعطیلات ─────────────────────────────────────────────
|
||||
|
||||
export interface ResourceCalendarDays {
|
||||
resource_uuid: string;
|
||||
timezone: string;
|
||||
defined: boolean;
|
||||
/** کلیدهای `"0"`..`"6"`؛ ۰ = شنبه */
|
||||
days: Record<string, WorkingHourRange[]>;
|
||||
}
|
||||
|
||||
export type ResourceExceptionType = 'leave' | 'absence' | 'maintenance' | 'closure';
|
||||
|
||||
export interface ResourceException {
|
||||
uuid: string;
|
||||
resource_uuid: string;
|
||||
resource_name: string;
|
||||
type: ResourceExceptionType;
|
||||
type_label: string;
|
||||
/** timestamp مطلق — استثنا میتواند چندروزه باشد */
|
||||
starts_at: number;
|
||||
ends_at: number;
|
||||
reason: string | null;
|
||||
created_at: number;
|
||||
updated_at: number;
|
||||
}
|
||||
|
||||
export interface AvailabilityInterval {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export interface AvailabilityDay {
|
||||
date: number;
|
||||
day_of_week: number;
|
||||
intervals: AvailabilityInterval[];
|
||||
total_minutes: number;
|
||||
/** چرا روز خالی است — بدون این، پاسخ خالی از باگ قابل تشخیص نیست */
|
||||
reasons: string[];
|
||||
}
|
||||
|
||||
export interface ResourceAvailability {
|
||||
resource_uuid: string;
|
||||
timezone: string;
|
||||
days: AvailabilityDay[];
|
||||
}
|
||||
|
||||
export interface NationalHoliday {
|
||||
uuid: string;
|
||||
date: number;
|
||||
jalali_date: string;
|
||||
jalali_year: number;
|
||||
title: string;
|
||||
/** `null` یعنی این محیط استثنایی ندارد */
|
||||
overridden_working?: boolean | null;
|
||||
}
|
||||
|
||||
export interface HolidayOverride {
|
||||
uuid: string;
|
||||
date: number;
|
||||
is_working: boolean;
|
||||
note: string | null;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user