Files
clinicpro/assets/admin/pages/BranchesPage.tsx
T
hamedandClaude Opus 5 d813843fcd feat(branch): admin UI for branch working hours and rooms, plus real API docs
Three pages, all on the existing design system: BranchesPage lists the current
environment's booking locations with their working-hours and active-room counts,
and two subpages edit the week and the rooms. The list page deliberately does not
create or rename a branch — clinic and doctor detail pages already do that, and
duplicating it would give one physical place two edit surfaces. Route permission
reuses `appointment_settings` rather than inventing a new one.

Two real bugs fell out of exercising this end to end:

`days` was serialising as a JSON *array*, not an object keyed "0".."6" — keys 0..6
are sequential so json_encode collapses them to a list. The client reads days["0"]
either way, so nothing looked broken, but the response shape was unstable: one
missing day would flip the same field to an object. The controller now casts to
stdClass and WorkingHoursTest::testDaysIsAJsonObjectNotAnArray pins it. Found by
curling the endpoint for the docs, not by any test.

`<input type="time">` caps at 23:59, so it can neither display nor produce the
legal end value 1440. An all-day range would have vanished from the form and been
corrupted by the first save. Ranges now carry an explicit end-of-day flag, with a
round-trip test proving 1440 survives.

docs/api/branch.md documents all eight endpoints with responses captured from real
curl runs against ddev, including the 422 and 404 bodies. doctor.md records that
active/timezone now appear on all nine existing address endpoints (additive), and
tenancy.md gains the two lessons this task taught: an aggregate child whose root is
itself declared global inherits no environment and needs a real pair, and
TenantFilter is not a substitute for an explicit ownership check because hard
isolation only applies to a *chosen* context.

Verified: phpunit 1067 tests / 2974 assertions green; slot-mode frozen contract
green; phpstan 14 errors before and after, none in touched files; tsc clean;
vitest 87 files / 612 tests green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 16:48:49 +03:30

178 lines
6.5 KiB
TypeScript

import React, { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { ClockIcon, Squares2X2Icon } from '@heroicons/react/24/outline';
import PageHeader from '../components/ui/PageHeader';
import DataTable, { type Column } from '../components/ui/DataTable';
import { ActiveBadge } from '../components/ui/StatusBadge';
import { useUrlState } from '../hooks/useUrlState';
import { usePermissions } from '../hooks/usePermissions';
import { useBranches } from '../hooks/useBranches';
import type { Branch } from '../types';
/**
* شعبه‌ها — همان محل‌های نوبت‌دهی محیط جاری.
*
* این صفحه شعبه نمی‌سازد و نام/آدرس را ویرایش نمی‌کند؛ آن کار از قبل در جزئیات
* کلینیک و پزشک هست و تکرارش دو منبع حقیقت می‌ساخت. اینجا فقط دروازهٔ ساعت کاری و
* اتاق‌هاست، به‌علاوهٔ دو ویژگی شعبه‌ای: فعال‌بودن و منطقهٔ زمانی.
*/
export default function BranchesPage() {
const { branches, loading, update } = useBranches();
const { can } = usePermissions();
const canUpdate = can('appointment_settings', 'update');
const [urlState, setUrlState] = useUrlState({ search: '', status: '' });
const rows = useMemo(() => {
const q = urlState.search.trim();
return branches.filter((b) => {
const haystack = `${b.name ?? ''} ${b.address ?? ''} ${b.telephone ?? ''}`;
const matchesQuery = q === '' || haystack.includes(q);
const matchesStatus =
urlState.status === '' ||
(urlState.status === 'active' ? b.active : !b.active);
return matchesQuery && matchesStatus;
});
}, [branches, urlState.search, urlState.status]);
const activeCount = branches.filter((b) => b.active).length;
const columns: Column<Branch>[] = [
{
key: 'name',
header: 'شعبه',
render: (b) => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<span style={{ fontWeight: 600 }}>{b.name || 'بدون نام'}</span>
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>
{b.type === 'clinic' ? b.clinic_name || 'کلینیک' : 'مطب شخصی'}
{b.city ? ` · ${b.city.name}` : ''}
</span>
</div>
),
},
{
key: 'address',
header: 'آدرس',
render: (b) => (
<span style={{ fontSize: 13, color: 'var(--text-2)' }}>{b.address || '—'}</span>
),
},
{
key: 'telephone',
header: 'تلفن',
render: (b) => <span style={{ fontSize: 13 }}>{b.telephone || '—'}</span>,
},
{
key: 'working_hours',
header: 'ساعت کاری',
render: (b) =>
b.working_hours_defined ? (
<span className="badge green"><span className="bdot" />تعریف‌شده</span>
) : (
<span style={{ fontSize: 12, color: 'var(--text-3)' }}>تعریف‌نشده</span>
),
},
{
key: 'rooms_count',
header: 'اتاق فعال',
render: (b) => <span style={{ fontSize: 13 }}>{b.rooms_count ?? 0}</span>,
},
{
key: 'timezone',
header: 'منطقهٔ زمانی',
render: (b) => <span style={{ fontSize: 12, color: 'var(--text-2)' }}>{b.timezone}</span>,
},
{
key: 'active',
header: 'وضعیت',
render: (b) => <ActiveBadge active={b.active} />,
},
];
return (
<div className="fade-in">
<PageHeader
title="شعبه‌ها و اتاق‌ها"
description="ساعت کاری هر محل نوبت‌دهی و اتاق‌های آن. نام و آدرس شعبه در صفحهٔ همان کلینیک یا پزشک ویرایش می‌شود."
backTo="/admin/settings-menu"
/>
<DataTable
columns={columns}
data={rows}
loading={loading}
searchValue={urlState.search}
onSearchChange={(v) => setUrlState({ search: v })}
searchPlaceholder="جستجو در شعبه‌ها..."
emptyMessage="هیچ شعبه‌ای برای این محیط ثبت نشده است"
headerExtra={
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginRight: 'auto' }}>
<StatusFilter
value={urlState.status}
onChange={(v) => setUrlState({ status: v })}
/>
</div>
}
actions={(b) => (
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Link className="btn secondary sm" to={`/admin/branches/${b.uuid}/working-hours`}>
<ClockIcon style={{ width: 15 }} /> ساعت کاری
</Link>
<Link className="btn secondary sm" to={`/admin/branches/${b.uuid}/rooms`}>
<Squares2X2Icon style={{ width: 15 }} /> اتاق‌ها
</Link>
{canUpdate && (
<button
type="button"
className="btn secondary sm"
disabled={update.isPending}
title={
b.active && activeCount === 1
? 'با غیرفعال کردن این شعبه، هیچ شعبهٔ فعالی باقی نمی‌ماند'
: undefined
}
onClick={() => {
if (
b.active &&
activeCount === 1 &&
!window.confirm('این تنها شعبهٔ فعال است. با غیرفعال کردن آن، هیچ شعبهٔ فعالی باقی نمی‌ماند. ادامه می‌دهید؟')
) {
return;
}
update.mutate({ uuid: b.uuid, d: { active: !b.active } });
}}
>
{b.active ? 'غیرفعال کردن' : 'فعال کردن'}
</button>
)}
</div>
)}
/>
</div>
);
}
function StatusFilter({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const options = [
{ value: '', label: 'همه' },
{ value: 'active', label: 'فعال' },
{ value: 'inactive', label: 'غیرفعال' },
];
return (
<div style={{ display: 'flex', gap: 4 }}>
{options.map((o) => (
<button
key={o.value}
type="button"
className={`btn sm ${value === o.value ? 'primary' : 'secondary'}`}
onClick={() => onChange(o.value)}
>
{o.label}
</button>
))}
</div>
);
}