feat(appointments,patients): make clinic context a first-class citizen

Three related fixes, all rooted in the same flaw: authorization and scoping
decided by the caller's role instead of by the environment the data belongs to.

1. Single-appointment access (clinic operations were entirely broken)

AppointmentController::canView/canManage only knew the patient, the owning
doctor and admin -- appointment.clinic was never consulted. A clinic user could
create an appointment through /my/appointment but got 403 on detail, edit,
move, reserve transfer/replace and status change, so nearly every appointment
operation failed in clinic mode.

AppointmentAccessChecker now decides from appointment.clinic: clinic owner,
member doctor (via ClinicDoctorPermissionChecker) and assigned secretary (via
active context + DoctorSecretary) are recognised. Actions reuse the existing
permission vocabulary, so active=false remains the single source of truth for
"collaboration ended". Cancellation is gated separately and an inline status on
PATCH /appointment/{uuid} cannot bypass that gate. The patient is narrowed to
view + cancel.

Also fixed alongside: listByDoctor now serves a clinic manager but scoped to
that clinic; todayStats gained an admin branch and no longer passes an array of
doctor ids as the clinic parameter; PatientController::appointments filters on
appointment.clinic instead of current membership, so deactivating a doctor no
longer erases clinic appointment history from the case file.

The doctor-only active_slot_key was reviewed and deliberately left alone -- a
doctor is one physical person, so adding clinic to the key would permit
double-booking, not fix a bug. Reasoning recorded on the entity.

2. Appointment registration and confirmation

Panel-created appointments are born pending ("ثبت شده") instead of confirmed.
Confirming is now an explicit act: POST /appointment/{uuid}/confirm transitions
the status, files the case file for the appointment's environment (reusing an
existing record or creating one) and registers full or partial payments on the
resulting visit -- all in one transaction.

AppointmentExpiryService would have expired those pending appointments the
moment their slot time passed; findExpiredPending is now limited to online
gateway holds, which are the only pendings carrying a TTL. A pending
appointment still occupies its slot, so the time stays reserved.

The admin panel gets a "قطعی کردن نوبت" modal showing the visit fee, each
selected service, the total, and paid/remaining/status. It is wired inside
AppointmentStatusDropdown, so picking "confirmed" anywhere (timeline, detail,
reserve list, info modal) goes through it and confirmation can never silently
skip the case file and payment.

3. Clinic case-file access

PatientRecordScopeResolver replaces the single-destination role mapping: the
active context decides, so a doctor invited into a clinic finally sees their
patients' records there. A clinic record is per-patient and shared by design,
so "their own patients" is derived from appointments with that doctor in that
clinic rather than from a new column. Clinic secretaries are limited to their
assigned doctors. Read and write share one rule, and out-of-scope records
report 404 so other environments are never disclosed.

Tests: 29 new cases across the three areas (clinic appointment access, confirm
flow, clinic record access). Full suite 466 tests, 2 pre-existing failures
unchanged. API docs updated for all three.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-18 21:04:50 +03:30
co-authored by Claude Opus 4.8
parent e6422014d1
commit 7921407f33
26 changed files with 2409 additions and 188 deletions
@@ -0,0 +1,220 @@
import { useMemo, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { api } from '../../lib/api';
import type { ApiResponse } from '../../lib/api';
import { formatRial, rialToToman, tomanToRial } from '../../lib/utils';
import Modal from '../ui/Modal';
import PriceInput from '../ui/PriceInput';
import SearchableSelect from '../ui/SearchableSelect';
/** همان چهار روشِ SessionPayment::METHODS در بک‌اند. */
const METHOD_OPTIONS = [
{ value: 'cash', label: 'پرداخت نقدی' },
{ value: 'pos', label: 'پرداخت از طریق کارت خوان' },
{ value: 'card', label: 'کارت به کارت' },
{ value: 'wallet', label: 'پرداخت از طریق کیف پول' },
];
interface ServiceItem {
uuid: string;
name: string;
price_rials?: number | null;
}
interface AppointmentLike {
uuid: string;
version?: number;
visit_price_rials?: number | null;
service_items?: ServiceItem[] | null;
patient_name?: string | null;
}
interface Props {
open: boolean;
appointmentUuid: string;
/** اگر صفحه از قبل نوبت را دارد، پاس بده تا درخواست اضافه نرود. */
appointment?: AppointmentLike | null;
onClose: () => void;
/** کلید کوئریِ لیستی که بعد از قطعی‌شدن باید invalidate شود. */
queryKey?: unknown[];
}
const rowStyle: React.CSSProperties = {
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: '10px 0',
borderBottom: '1px solid var(--border)',
};
/**
* «قطعی کردن نوبت» — هزینه‌های نوبت را نشان می‌دهد، پرداخت کامل یا جزئی می‌گیرد و
* نوبت را از «ثبت شده» به «قطعی شده» می‌برد.
*
* سرور همین یک درخواست را اتمیک انجام می‌دهد: وضعیت + پرونده/مراجعه + پرداخت‌ها.
*/
export default function ConfirmAppointmentModal({
open,
appointmentUuid,
appointment,
onClose,
queryKey,
}: Props) {
const qc = useQueryClient();
const [method, setMethod] = useState('cash');
const [amountToman, setAmountToman] = useState(0);
// وقتی صفحه‌ی میزبان نوبت را ندارد (مثل ردیف لیست) خودمان جزئیات را می‌گیریم:
// مبلغ ویزیت و قیمت سرویس‌ها فقط در detail هستند.
const detailQuery = useQuery({
queryKey: ['appointment', appointmentUuid],
queryFn: () => api.get<ApiResponse<AppointmentLike>>(`/api/v1/appointment/${appointmentUuid}`),
enabled: open && !appointment,
});
const appt: AppointmentLike | null = appointment
?? ((detailQuery.data?.data as any)?.data ?? detailQuery.data?.data ?? null);
const visitPrice = Number(appt?.visit_price_rials ?? 0);
const services = appt?.service_items ?? [];
const servicesTotal = useMemo(
() => services.reduce((sum, s) => sum + Number(s.price_rials ?? 0), 0),
[services],
);
const total = visitPrice + servicesTotal;
const amountRials = tomanToRial(amountToman);
const remaining = Math.max(0, total - amountRials);
const overpaid = amountRials > total;
const paymentState = amountRials === 0
? 'بدون پرداخت'
: remaining === 0
? 'تسویه کامل'
: 'پرداخت جزئی';
const confirmMut = useMutation({
mutationFn: () =>
api.post<ApiResponse<unknown>>(`/api/v1/appointment/${appointmentUuid}/confirm`, {
version: appt?.version,
payments: amountRials > 0 ? [{ method, amount_rials: amountRials }] : [],
}),
onSuccess: () => {
toast.success('نوبت قطعی شد');
if (queryKey) qc.invalidateQueries({ queryKey });
qc.invalidateQueries({ queryKey: ['appointment', appointmentUuid] });
qc.invalidateQueries({ queryKey: ['appointment-events', appointmentUuid] });
reset();
onClose();
},
onError: (e: any) => toast.error(e?.message || 'قطعی کردن نوبت ناموفق بود'),
});
function reset() {
setAmountToman(0);
setMethod('cash');
}
function handleClose() {
reset();
onClose();
}
const loading = detailQuery.isLoading && !appointment;
return (
<Modal
open={open}
title="قطعی کردن نوبت"
size="md"
onClose={handleClose}
footer={
<>
<button type="button" className="btn" onClick={handleClose}>
انصراف
</button>
<button
type="button"
className="btn primary"
disabled={loading || overpaid || confirmMut.isPending}
onClick={() => confirmMut.mutate()}
>
{confirmMut.isPending ? 'در حال ثبت…' : 'تأیید و قطعی کردن'}
</button>
</>
}
>
{loading ? (
<p style={{ color: 'var(--text-2)' }}>در حال دریافت اطلاعات نوبت</p>
) : (
<>
{appt?.patient_name && (
<p style={{ marginBottom: 12, color: 'var(--text-2)' }}>بیمار: {appt.patient_name}</p>
)}
<div style={{ marginBottom: 18 }}>
<div style={rowStyle}>
<span>ویزیت</span>
<strong>{formatRial(visitPrice)}</strong>
</div>
{services.map((s) => (
<div key={s.uuid} style={rowStyle}>
<span>{s.name}</span>
<strong>{formatRial(Number(s.price_rials ?? 0))}</strong>
</div>
))}
<div style={{ ...rowStyle, borderBottom: 'none', fontSize: 16 }}>
<span>جمع کل</span>
<strong>{formatRial(total)}</strong>
</div>
</div>
<div className="field" style={{ marginBottom: 12 }}>
<label>روش پرداخت</label>
<SearchableSelect
value={method}
onChange={(v) => setMethod(String(v ?? 'cash'))}
options={METHOD_OPTIONS}
placeholder="روش پرداخت"
/>
</div>
<div className="field" style={{ marginBottom: 12 }}>
<label>مبلغ پرداختی (تومان)</label>
<PriceInput value={amountToman} onChange={setAmountToman} suffix="تومان" />
<button
type="button"
className="btn sm"
style={{ marginTop: 8 }}
onClick={() => setAmountToman(rialToToman(total))}
>
پرداخت کامل
</button>
</div>
{overpaid && (
<p style={{ color: 'var(--danger)', marginBottom: 12 }}>
مبلغ پرداخت از جمع کل بیشتر است.
</p>
)}
<div style={{ background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', padding: 12 }}>
<div style={rowStyle}>
<span>پرداختشده</span>
<strong>{formatRial(Math.min(amountRials, total))}</strong>
</div>
<div style={rowStyle}>
<span>باقیمانده</span>
<strong>{formatRial(remaining)}</strong>
</div>
<div style={{ ...rowStyle, borderBottom: 'none' }}>
<span>وضعیت پرداخت</span>
<strong>{paymentState}</strong>
</div>
</div>
</>
)}
</Modal>
);
}
@@ -1,8 +1,9 @@
import { useEffect, useRef } from 'react';
import { useEffect, useRef, useState } from 'react';
import { UserIcon, PhoneIcon, DocumentTextIcon, PlusIcon } from '@heroicons/react/24/outline';
import type { Appointment } from '../../types';
import AppointmentStatusDropdown from '../ui/AppointmentStatusDropdown';
import AppointmentActionsMenu from '../AppointmentActions';
import ConfirmAppointmentModal from './ConfirmAppointmentModal';
import { turnStatusConfig, EMPTY_SLOT_CONFIG } from './turnStatus';
import type { TimelineSlot } from './types';
@@ -103,6 +104,7 @@ function OccupiedCard({
appointment: Appointment; queryKey: unknown[]; onView: (a: Appointment) => void;
}) {
const cfg = turnStatusConfig(a.status);
const [confirmOpen, setConfirmOpen] = useState(false);
return (
<div
onClick={() => onView(a)}
@@ -135,6 +137,19 @@ function OccupiedCard({
{/* وضعیت + عملیات (کلیک روی این ناحیه نباید کارت را باز کند) */}
<div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', alignItems: 'center', gap: 8, alignSelf: 'flex-start', flexShrink: 0 }}>
{a.status === 'pending' && (
<>
<button type="button" className="btn primary sm" onClick={() => setConfirmOpen(true)}>
قطعی کردن نوبت
</button>
<ConfirmAppointmentModal
open={confirmOpen}
appointmentUuid={a.uuid}
onClose={() => setConfirmOpen(false)}
queryKey={queryKey}
/>
</>
)}
<AppointmentStatusDropdown uuid={a.uuid} currentStatus={a.status} version={a.version} queryKey={queryKey} />
<AppointmentActionsMenu appointment={a} queryKey={queryKey} />
</div>
@@ -4,6 +4,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ChevronDownIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../../lib/api';
import ConfirmAppointmentModal from '../appointments/ConfirmAppointmentModal';
// Labels follow the Figma نوبت‌ها design (ثبت شده / قطعی شده / ویزیت شده …).
export const STATUS_META: Record<string, { label: string; color: string }> = {
@@ -35,6 +36,7 @@ interface Props {
export default function AppointmentStatusDropdown({ uuid, currentStatus, version, queryKey }: Props) {
const [open, setOpen] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const [menuPos, setMenuPos] = useState<{ top: number; right: number } | null>(null);
const btnRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
@@ -76,7 +78,9 @@ export default function AppointmentStatusDropdown({ uuid, currentStatus, version
qc.invalidateQueries({ queryKey });
setOpen(false);
},
onError: () => toast.error('خطا در تغییر وضعیت'),
// پیام سرور را نشان بده: تداخل نسخه (۴۰۹) و نبودِ دسترسی (۴۰۳) پیام فارسی
// دقیق دارند و «خطا در تغییر وضعیت» آن را پنهان می‌کرد.
onError: (e: any) => toast.error(e?.message || 'خطا در تغییر وضعیت'),
});
const meta = STATUS_META[currentStatus] ?? { label: currentStatus, color: '#9ca3af' };
@@ -90,6 +94,19 @@ export default function AppointmentStatusDropdown({ uuid, currentStatus, version
setOpen(o => !o);
}
/**
* «قطعی شده» راه میان‌بر ندارد: قطعی‌کردن یعنی ثبت هزینه‌ها و پرداخت در پرونده،
* پس همیشه از مودال رد می‌شود. بقیهٔ وضعیت‌ها همان PATCH ساده‌اند.
*/
function handlePick(status: string) {
if (status === 'confirmed') {
setOpen(false);
setConfirmOpen(true);
return;
}
mutation.mutate(status);
}
return (
<div style={{ position: 'relative', display: 'inline-block' }}>
<button
@@ -129,7 +146,7 @@ export default function AppointmentStatusDropdown({ uuid, currentStatus, version
return (
<button
key={s}
onClick={() => mutation.mutate(s)}
onClick={() => handlePick(s)}
disabled={mutation.isPending}
style={{
display: 'flex', alignItems: 'center', gap: 8,
@@ -152,6 +169,13 @@ export default function AppointmentStatusDropdown({ uuid, currentStatus, version
</div>,
document.body
)}
<ConfirmAppointmentModal
open={confirmOpen}
appointmentUuid={uuid}
onClose={() => setConfirmOpen(false)}
queryKey={queryKey}
/>
</div>
);
}
+3 -19
View File
@@ -102,7 +102,6 @@ export default function AppointmentCreatePage() {
// ── بیعانه / وضعیت / توضیحات
const [depositRequired, setDepositRequired] = useState(false);
const [depositToman, setDepositToman] = useState(0);
const [status, setStatus] = useState('pending');
const [note, setNote] = useState('');
// ── هزینه ویزیت — الزامی بودن از تنظیمات «الزامی کردن هزینه ویزیت» (کاربر بدون
@@ -150,11 +149,9 @@ export default function AppointmentCreatePage() {
...(visitPriceToman > 0 ? { visit_price_rials: tomanToRial(visitPriceToman) } : {}),
...(note.trim() ? { note: note.trim() } : {}),
};
const res: any = await api.post(createEndpoint, payload);
if (status !== 'pending' && res?.data?.uuid) {
await api.patch(`/api/v1/appointment/${res.data.uuid}/status`, { status, version: 1 });
}
return res;
// نوبت همیشه «ثبت شده» متولد می‌شود؛ قطعی‌کردن یک عملِ جداست که هزینه‌ها را
// نشان می‌دهد و پرداخت می‌گیرد (مودال «قطعی کردن نوبت»).
return api.post(createEndpoint, payload);
},
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['appointments'] });
@@ -489,19 +486,6 @@ export default function AppointmentCreatePage() {
)}
</div>
<div style={{ maxWidth: 500 }}>
<label style={label}>انتخاب وضعیت</label>
<div style={{ margin: '6px 0 12px' }}>
<SearchableSelect
options={[{ value: 'pending', label: 'ثبت شده' }, { value: 'confirmed', label: 'قطعی شده' }]}
value={status || null}
onChange={v => setStatus(v ? String(v) : '')}
placeholder="انتخاب وضعیت"
height={44}
/>
</div>
</div>
<label style={label}>توضیحات</label>
<div className="field" style={{ height: 'auto', margin: '6px 0 16px' }}>
<textarea value={note} onChange={e => setNote(e.target.value)} rows={4} placeholder="توضیحات..."
+33 -2
View File
@@ -11,6 +11,7 @@ import PageHeader from '../components/ui/PageHeader';
import StatusBadge from '../components/ui/StatusBadge';
import ConfirmDialog from '../components/ui/ConfirmDialog';
import SearchableSelect from '../components/ui/SearchableSelect';
import ConfirmAppointmentModal from '../components/appointments/ConfirmAppointmentModal';
const ALL_STATUSES: { value: AppointmentStatus; label: string }[] = [
{ value: 'pending', label: 'رزرو شده' },
@@ -50,6 +51,7 @@ export default function AppointmentDetailPage() {
const navigate = useNavigate();
const qc = useQueryClient();
const [cancelOpen, setCancelOpen] = useState(false);
const [confirmOpen, setConfirmOpen] = useState(false);
const [cancelReason, setCancelReason] = useState('');
const [newStatus, setNewStatus] = useState('');
@@ -68,7 +70,7 @@ export default function AppointmentDetailPage() {
const statusMutation = useMutation({
mutationFn: (status: string) =>
api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, { status }),
api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, { status, version: appt?.version }),
onSuccess: () => {
toast.success('وضعیت نوبت بروزرسانی شد');
qc.invalidateQueries({ queryKey: ['appointment', uuid] });
@@ -80,6 +82,7 @@ export default function AppointmentDetailPage() {
const cancelMutation = useMutation({
mutationFn: () => api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, {
status: 'cancelled_by_doctor',
version: appt?.version,
...(cancelReason.trim() ? { cancel_reason: cancelReason.trim() } : {}),
}),
onSuccess: () => {
@@ -94,6 +97,17 @@ export default function AppointmentDetailPage() {
// پاسخ single تودرتو است: { data: { data: {...} } }
const appt: any = (data?.data as any)?.data ?? data?.data;
// قطعی‌کردن هزینه و پرداخت دارد؛ از مسیر مودال می‌رود، نه PATCH وضعیت.
function applyStatus() {
if (!newStatus) return;
if (newStatus === 'confirmed') {
setConfirmOpen(true);
return;
}
statusMutation.mutate(newStatus);
}
// بازگشت به همان روزِ نوبت (نه امروز).
const day = isoDay(appt?.slot_start);
const backTo = day ? `/admin/appointments?date=${day}` : '/admin/appointments';
@@ -144,6 +158,15 @@ export default function AppointmentDetailPage() {
<StatusBadge type="appointment" value={appt.status} />
</div>
{appt.status === 'pending' && (
<button
onClick={() => setConfirmOpen(true)}
className="btn primary w-full"
>
قطعی کردن نوبت
</button>
)}
<div className="mt-6">
<label className="cp-label mb-2">تغییر وضعیت:</label>
<div className="flex gap-2">
@@ -157,7 +180,7 @@ export default function AppointmentDetailPage() {
/>
</div>
<button
onClick={() => newStatus && statusMutation.mutate(newStatus)}
onClick={() => applyStatus()}
disabled={!newStatus || statusMutation.isPending}
className="btn primary sm"
>
@@ -233,6 +256,14 @@ export default function AppointmentDetailPage() {
/>
</div>
</ConfirmDialog>
<ConfirmAppointmentModal
open={confirmOpen}
appointmentUuid={uuid!}
appointment={appt}
onClose={() => setConfirmOpen(false)}
queryKey={['appointment', uuid]}
/>
</div>
);
}
+12 -1
View File
@@ -119,7 +119,7 @@ export default function PatientsListPage() {
if (af) qs.set('admitted_from', String(af));
if (at) qs.set('admitted_to', String(at));
const { data, isLoading } = useQuery<ApiResponse<PatientRecord[]> & { meta?: { totalRecords: number } }>({
const { data, isLoading, error } = useQuery<ApiResponse<PatientRecord[]> & { meta?: { totalRecords: number } }>({
queryKey: ['patients', qs.toString()],
queryFn: () => api.get(`/api/v1/patients?${qs.toString()}`),
});
@@ -197,6 +197,17 @@ export default function PatientsListPage() {
{isLoading ? (
<div style={{ padding: 24, color: 'var(--text-3)', fontSize: 13 }}>در حال بارگذاری...</div>
) : error ? (
/* «دسترسی ندارید» با «بیماری یافت نشد» یکی نیست — پیام سرور را نشان بده. */
<div className="card" style={{ padding: '60px 0', textAlign: 'center' }}>
<IdentificationIcon style={{ width: 52, margin: '0 auto 14px', display: 'block', opacity: 0.3, color: 'var(--danger)' }} />
<div style={{ fontSize: 14, color: 'var(--danger)' }}>
{(error as any)?.message || 'دسترسی به پرونده‌ها امکان‌پذیر نیست'}
</div>
<div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 8 }}>
اگر بهتازگی محیط کاریتان تغییر کرده، از منوی بالا محیط درست را انتخاب کنید.
</div>
</div>
) : records.length === 0 ? (
<div className="card" style={{ padding: '60px 0', textAlign: 'center', color: 'var(--text-3)' }}>
<IdentificationIcon style={{ width: 52, margin: '0 auto 14px', display: 'block', opacity: 0.3 }} />