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
+68 -85
View File
@@ -3,18 +3,16 @@
namespace App\Patient\Controller;
use App\Auth\Entity\User;
use App\Auth\Repository\UserActiveContextRepository;
use App\Auth\Repository\UserRepository;
use App\Billing\Repository\InvoiceRepository;
use App\Billing\Service\ClaimService;
use App\Billing\Service\InvoiceService;
use Psr\Log\LoggerInterface;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Patient\Entity\PatientRecord;
use App\Secretary\Repository\DoctorSecretaryRepository;
use App\Patient\Repository\PatientRecordRepository;
use App\Patient\Repository\PatientSessionRepository;
use App\Patient\Security\PatientRecordScope;
use App\Patient\Security\PatientRecordScopeResolver;
use App\Patient\Service\PatientService;
use App\UserProfile\Entity\UserProfile;
use App\Shared\Constant\ErrorCodes;
@@ -38,17 +36,13 @@ class PatientController extends BaseController
private readonly PatientService $patientService,
private readonly SubscriptionService $subscriptionService,
private readonly UserRepository $userRepo,
private readonly DoctorRepository $doctorRepo,
private readonly ClinicRepository $clinicRepo,
private readonly DoctorSecretaryRepository $secretaryRepo,
private readonly UserActiveContextRepository $contextRepo,
private readonly PatientRecordScopeResolver $scopeResolver,
private readonly \App\UserProfile\Repository\UserProfileRepository $profileRepo,
private readonly \App\Insurance\Repository\InsuranceRepository $insuranceRepo,
private readonly InvoiceService $invoiceService,
private readonly ClaimService $claimService,
private readonly InvoiceRepository $invoiceRepo,
private readonly \App\Appointment\Repository\AppointmentRepository $appointmentRepo,
private readonly \App\ClinicInvitation\Repository\ClinicDoctorInvitationRepository $invitationRepo,
private readonly \App\Tag\Repository\TenantTagRepository $tenantTagRepo,
private readonly \App\Patient\Repository\PatientAttachmentRepository $attachmentRepo,
private readonly \App\Patient\Repository\PatientMedicalRecordRepository $medicalRepo,
@@ -79,7 +73,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -102,7 +96,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -123,7 +117,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -149,7 +143,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -184,7 +178,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -224,7 +218,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -243,7 +237,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -279,7 +273,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$call = $this->callRepo->findByUuid($uuid);
if ($call === null || !$this->ownsRecord($call->getRecord(), $entityType, $entityId)) {
if ($call === null || !$this->ownsRecord($call->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -295,7 +289,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -310,7 +304,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -335,7 +329,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$message = $this->messageRepo->findByUuid($uuid);
if ($message === null || !$this->ownsRecord($message->getRecord(), $entityType, $entityId)) {
if ($message === null || !$this->ownsRecord($message->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'پیام یافت نشد', 404);
}
@@ -354,7 +348,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -369,7 +363,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -391,7 +385,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$note = $this->noteRepo->findByUuid($uuid);
if ($note === null || !$this->ownsRecord($note->getRecord(), $entityType, $entityId)) {
if ($note === null || !$this->ownsRecord($note->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'یادداشت یافت نشد', 404);
}
@@ -416,7 +410,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$note = $this->noteRepo->findByUuid($uuid);
if ($note === null || !$this->ownsRecord($note->getRecord(), $entityType, $entityId)) {
if ($note === null || !$this->ownsRecord($note->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'یادداشت یافت نشد', 404);
}
@@ -432,7 +426,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -447,7 +441,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -471,7 +465,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$medical = $this->medicalRepo->findByUuid($uuid);
if ($medical === null || !$this->ownsRecord($medical->getRecord(), $entityType, $entityId)) {
if ($medical === null || !$this->ownsRecord($medical->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'رکورد پزشکی یافت نشد', 404);
}
@@ -501,7 +495,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$medical = $this->medicalRepo->findByUuid($uuid);
if ($medical === null || !$this->ownsRecord($medical->getRecord(), $entityType, $entityId)) {
if ($medical === null || !$this->ownsRecord($medical->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'رکورد پزشکی یافت نشد', 404);
}
@@ -517,7 +511,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -532,7 +526,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -554,7 +548,7 @@ class PatientController extends BaseController
{
[$entityType, $entityId] = $this->resolveEntity($user);
$attachment = $this->attachmentRepo->findByUuid($uuid);
if ($attachment === null || !$this->ownsRecord($attachment->getRecord(), $entityType, $entityId)) {
if ($attachment === null || !$this->ownsRecord($attachment->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'ضمیمه یافت نشد', 404);
}
@@ -668,8 +662,9 @@ class PatientController extends BaseController
'has_debt' => $request->query->getBoolean('has_debt'),
];
$records = $this->recordRepo->findByEntity($entityType, $entityId, $page, $limit, $search, $filters);
$total = $this->recordRepo->countByEntity($entityType, $entityId, $search, $filters);
$restrictTo = $this->scope($user)->restrictToDoctorIds;
$records = $this->recordRepo->findByEntity($entityType, $entityId, $page, $limit, $search, $filters, $restrictTo);
$total = $this->recordRepo->countByEntity($entityType, $entityId, $search, $filters, $restrictTo);
// کد ملی روی profiles ذخیره می‌شود نه users؛ اگر روی user خالی بود از پروفایل پر کن.
$userIds = array_map(fn(PatientRecord $r) => $r->getUser()->getId(), $records);
@@ -768,7 +763,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -785,7 +780,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -918,7 +913,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -944,17 +939,15 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
// نوبت‌های این بیمار فقط با پزشک(های) همین ارائه‌دهنده نمایش داده می‌شوند تا
// نوبت‌های او با کلینیک‌های دیگر نشت نکند.
$doctorIds = $entityType === 'doctor'
? [$entityId]
: $this->invitationRepo->acceptedDoctorIdsByClinic($entityId);
$appointments = $this->appointmentRepo->findByUserAndDoctorIds($record->getUser(), $doctorIds);
// محیط نوبت با appointment.clinic بیان می‌شود. تکیه بر عضویت فعلیِ پزشک
// یعنی با پایان همکاری، تاریخچهٔ نوبت‌های همان کلینیک از پرونده ناپدید شود.
$appointments = $entityType === 'doctor'
? $this->appointmentRepo->findByUserAndDoctorIds($record->getUser(), [$entityId])
: $this->appointmentRepo->findByUserAndClinic($record->getUser(), $entityId);
return $this->success(array_map(fn(\App\Appointment\Entity\Appointment $a) => [
'uuid' => $a->getUuid(),
@@ -996,7 +989,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$record = $this->recordRepo->findByUuid($uuid);
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId)) {
if ($record === null || !$this->ownsRecord($record, $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_PATIENT_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_PATIENT_NOT_FOUND), 404);
}
@@ -1039,7 +1032,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$session = $this->sessionRepo->findByUuid($uuid);
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId)) {
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_SESSION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SESSION_NOT_FOUND), 404);
}
@@ -1109,7 +1102,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$session = $this->sessionRepo->findByUuid($uuid);
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId)) {
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_SESSION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SESSION_NOT_FOUND), 404);
}
@@ -1134,7 +1127,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$session = $this->sessionRepo->findByUuid($uuid);
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId)) {
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_SESSION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SESSION_NOT_FOUND), 404);
}
$payment = $this->sessionPaymentRepo->findByUuid($paymentUuid);
@@ -1155,7 +1148,7 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$session = $this->sessionRepo->findByUuid($uuid);
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId)) {
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_SESSION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SESSION_NOT_FOUND), 404);
}
$payment = $this->sessionPaymentRepo->findByUuid($paymentUuid);
@@ -1176,46 +1169,25 @@ class PatientController extends BaseController
$this->assertPatientGate($entityType, $entityId);
$session = $this->sessionRepo->findByUuid($uuid);
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId)) {
if ($session === null || !$this->ownsRecord($session->getRecord(), $entityType, $entityId, $user)) {
return $this->error(ErrorCodes::ERR_SESSION_NOT_FOUND, ErrorCodes::message(ErrorCodes::ERR_SESSION_NOT_FOUND), 404);
}
return $this->success($this->sessionAuditRepo->findBySessionUuid($uuid));
}
/** @var array<int, PatientRecordScope> حل‌شده یک‌بار در هر درخواست، نه یک‌بار به‌ازای هر چک. */
private array $scopeCache = [];
private function scope(User $user): PatientRecordScope
{
return $this->scopeCache[$user->getId()] ??= $this->scopeResolver->resolve($user);
}
/** @return array{0: string, 1: int|null} */
private function resolveEntity(User $user): array
{
if ($user->hasRole('ROLE_DOCTOR')) {
$doctor = $this->doctorRepo->findByUser($user);
return $doctor !== null ? ['doctor', $doctor->getId()] : ['doctor', null];
}
if ($user->hasRole('ROLE_CLINIC')) {
$clinic = $this->clinicRepo->findByUser($user);
return $clinic !== null ? ['clinic', $clinic->getId()] : ['clinic', null];
}
if ($user->hasRole('ROLE_SECRETARY')) {
$dbUuid = $this->contextRepo->findByUser($user)?->getDbUuid();
if ($dbUuid !== null) {
$clinic = $this->clinicRepo->findByUuid($dbUuid);
if ($clinic !== null) {
$rel = $this->secretaryRepo->findActiveBySecretaryForClinic($user, $clinic);
if ($rel !== null) {
return ['clinic', $clinic->getId()];
}
}
$doctor = $this->doctorRepo->findByUuid($dbUuid);
if ($doctor !== null) {
$rel = $this->secretaryRepo->findActiveBySecretaryForDoctor($user, $doctor);
if ($rel !== null) {
return ['doctor', $doctor->getId()];
}
}
}
}
return ['unknown', null];
return $this->scope($user)->toLegacyTuple();
}
private function assertPatientGate(string $entityType, ?int $entityId): void
@@ -1229,10 +1201,21 @@ class PatientController extends BaseController
}
}
private function ownsRecord($record, string $entityType, ?int $entityId): bool
/**
* محیط پرونده باید همان محیط کاربر باشد، و اگر دسترسی کاربر به بیمارانِ پزشک(های)
* مشخصی محدود است، پرونده هم باید در همان محدوده بیفتد — همان قاعدهٔ لیست.
*/
private function ownsRecord($record, string $entityType, ?int $entityId, User $user): bool
{
return $entityId !== null
&& $record->getEntityType() === $entityType
&& $record->getEntityId() === $entityId;
if ($entityId === null
|| $record->getEntityType() !== $entityType
|| $record->getEntityId() !== $entityId) {
return false;
}
return $this->recordRepo->isVisibleToDoctors(
$record,
$this->scope($user)->restrictToDoctorIds,
);
}
}
@@ -34,10 +34,11 @@ class PatientRecordRepository extends ServiceEntityRepository
* (pending|completed), has_debt(bool)
* @return list<PatientRecord>
*/
public function findByEntity(string $entityType, int $entityId, int $page = 1, int $limit = 20, ?string $search = null, array $filters = []): array
public function findByEntity(string $entityType, int $entityId, int $page = 1, int $limit = 20, ?string $search = null, array $filters = [], ?array $restrictToDoctorIds = null): array
{
$qb = $this->baseQuery($entityType, $entityId);
$this->applyFilters($qb, $search, $filters);
$this->applyDoctorRestriction($qb, $entityType, $entityId, $restrictToDoctorIds);
return $qb->orderBy('r.id', 'DESC')
->setFirstResult(($page - 1) * $limit)
@@ -47,14 +48,76 @@ class PatientRecordRepository extends ServiceEntityRepository
}
/** @param array<string, mixed> $filters same shape as {@see findByEntity}. */
public function countByEntity(string $entityType, int $entityId, ?string $search = null, array $filters = []): int
public function countByEntity(string $entityType, int $entityId, ?string $search = null, array $filters = [], ?array $restrictToDoctorIds = null): int
{
$qb = $this->baseQuery($entityType, $entityId)->select('COUNT(r.id)');
$this->applyFilters($qb, $search, $filters);
$this->applyDoctorRestriction($qb, $entityType, $entityId, $restrictToDoctorIds);
return (int) $qb->getQuery()->getSingleScalarResult();
}
/**
* آیا این پرونده در دسترسِ محدودشدهٔ این پزشک(ها) هست؟ همان قاعدهٔ لیست، برای یک
* رکورد — تا detail و list هرگز از هم واگرا نشوند.
*
* @param int[]|null $restrictToDoctorIds
*/
public function isVisibleToDoctors(PatientRecord $record, ?array $restrictToDoctorIds): bool
{
if ($restrictToDoctorIds === null) {
return true;
}
if ($restrictToDoctorIds === []) {
return false;
}
$qb = $this->createQueryBuilder('r')
->select('COUNT(r.id)')
->where('r.id = :recordId')
->setParameter('recordId', $record->getId());
$this->applyDoctorRestriction($qb, $record->getEntityType(), $record->getEntityId(), $restrictToDoctorIds);
return (int) $qb->getQuery()->getSingleScalarResult() > 0;
}
/**
* پزشکِ عضو فقط بیمارانِ خودش را می‌بیند. پروندهٔ کلینیکی ستون پزشک ندارد
* (یکتایی clinic+user)، پس رابطه از نوبت‌های همان پزشک در همان کلینیک می‌آید —
* نه از session، چون مراجعهٔ دستی اصلاً پزشک ثبت‌شده ندارد.
*
* @param int[]|null $restrictToDoctorIds
*/
private function applyDoctorRestriction(
\Doctrine\ORM\QueryBuilder $qb,
string $entityType,
?int $entityId,
?array $restrictToDoctorIds,
): void {
if ($restrictToDoctorIds === null || $entityType !== 'clinic') {
return;
}
if ($restrictToDoctorIds === []) {
$qb->andWhere('1 = 0');
return;
}
$qb->andWhere(
$qb->expr()->exists(
'SELECT 1 FROM App\Appointment\Entity\Appointment ra
WHERE ra.user = r.user
AND IDENTITY(ra.clinic) = :restrictClinicId
AND IDENTITY(ra.doctor) IN (:restrictDoctorIds)'
)
)
->setParameter('restrictClinicId', $entityId)
->setParameter('restrictDoctorIds', $restrictToDoctorIds);
}
private function baseQuery(string $entityType, int $entityId): \Doctrine\ORM\QueryBuilder
{
return $this->createQueryBuilder('r')
@@ -0,0 +1,59 @@
<?php
namespace App\Patient\Security;
/**
* محیطی که پرونده‌های بیمار در آن خوانده/نوشته می‌شوند، به‌همراه محدودیت اختیاریِ
* «فقط بیمارانِ این پزشک(ها)».
*
* پروندهٔ کلینیکی per-بیمار است نه per-پزشک (یکتایی clinic+user)، پس محدودسازیِ
* پزشکِ عضو نمی‌تواند روی خودِ پرونده باشد؛ از مسیر نوبت‌های همان پزشک در همان
* کلینیک استخراج می‌شود.
*/
final class PatientRecordScope
{
/** @param int[]|null $restrictToDoctorIds null یعنی بدون محدودیت (مدیر/مالک) */
private function __construct(
public readonly string $entityType,
public readonly ?int $entityId,
public readonly ?array $restrictToDoctorIds,
) {}
public static function forDoctor(?int $doctorId): self
{
return new self('doctor', $doctorId, null);
}
/** مدیر کلینیک: همهٔ پرونده‌های کلینیک. */
public static function forClinic(?int $clinicId): self
{
return new self('clinic', $clinicId, null);
}
/**
* پزشک عضو یا منشی: پرونده‌های کلینیک، محدود به بیمارانِ این پزشک(ها).
* لیست خالی یعنی هیچ پزشکی تخصیص نیافته ⇒ هیچ پرونده‌ای.
*
* @param int[] $doctorIds
*/
public static function forClinicRestrictedToDoctors(int $clinicId, array $doctorIds): self
{
return new self('clinic', $clinicId, array_values(array_unique($doctorIds)));
}
public static function unknown(): self
{
return new self('unknown', null, null);
}
public function isRestricted(): bool
{
return $this->restrictToDoctorIds !== null;
}
/** @return array{0: string, 1: int|null} سازگار با امضای قدیمیِ resolveEntity. */
public function toLegacyTuple(): array
{
return [$this->entityType, $this->entityId];
}
}
@@ -0,0 +1,115 @@
<?php
namespace App\Patient\Security;
use App\Auth\Entity\User;
use App\Auth\Repository\UserActiveContextRepository;
use App\Clinic\Repository\ClinicRepository;
use App\Clinic\Security\ClinicDoctorPermissionChecker;
use App\Doctor\Repository\DoctorRepository;
use App\Secretary\Repository\DoctorSecretaryRepository;
/**
* «پرونده‌های کدام محیط را این کاربر می‌بیند؟»
*
* پیش از این، نگاشت تک‌مقصدی بود: نقش پزشک همیشه به پروندهٔ مطب شخصی می‌رسید، پس
* پزشکِ دعوت‌شده به کلینیک پرونده‌های بیمارانش در آن کلینیک را اصلاً نمی‌دید. محیط
* فعال (UserActiveContext) تعیین‌کننده است، دقیقاً مثل EntityContextResolver.
*
* «پایان همکاری» منبع حقیقتِ جدا ندارد: ClinicDoctorPermission/DoctorSecretary با
* active=false خودشان رد می‌کنند.
*/
class PatientRecordScopeResolver
{
private const RESOURCE = 'patients';
public function __construct(
private readonly DoctorRepository $doctorRepo,
private readonly ClinicRepository $clinicRepo,
private readonly UserActiveContextRepository $contextRepo,
private readonly DoctorSecretaryRepository $secretaryRepo,
private readonly ClinicDoctorPermissionChecker $clinicPermissions,
) {}
public function resolve(User $user): PatientRecordScope
{
if ($user->hasRole('ROLE_DOCTOR')) {
return $this->forDoctorUser($user);
}
if ($user->hasRole('ROLE_CLINIC')) {
$clinic = $this->clinicRepo->findByUser($user);
return PatientRecordScope::forClinic($clinic?->getId());
}
if ($user->hasRole('ROLE_SECRETARY')) {
return $this->forSecretary($user);
}
return PatientRecordScope::unknown();
}
/**
* پزشک در محیط کلینیکِ فعالش پرونده‌های همان کلینیک را می‌بیند — محدود به
* بیمارانِ خودش. بیرون از آن محیط، فقط پروندهٔ مطب شخصی.
*/
private function forDoctorUser(User $user): PatientRecordScope
{
$doctor = $this->doctorRepo->findByUser($user);
if ($doctor === null) {
return PatientRecordScope::forDoctor(null);
}
$dbUuid = $this->contextRepo->findByUser($user)?->getDbUuid();
$clinic = $dbUuid !== null ? $this->clinicRepo->findByUuid($dbUuid) : null;
if ($clinic === null || !$clinic->hasDoctor($doctor)) {
return PatientRecordScope::forDoctor($doctor->getId());
}
// مالک کلینیکی که خودش پزشک هم هست، محدود نمی‌شود.
if ($clinic->getUser()->getId() === $user->getId()) {
return PatientRecordScope::forClinic($clinic->getId());
}
if (!$this->clinicPermissions->can($user, $clinic, self::RESOURCE, 'view')) {
return PatientRecordScope::forDoctor($doctor->getId());
}
return PatientRecordScope::forClinicRestrictedToDoctors($clinic->getId(), [$doctor->getId()]);
}
/**
* منشی در محیط فعالش. در کلینیک، فقط بیمارانِ پزشکانِ تخصیص‌یافته به او —
* عضویت در کلینیک به‌تنهایی یعنی منشیِ یک پزشک پروندهٔ بیماران پزشک دیگر را ببیند.
*/
private function forSecretary(User $user): PatientRecordScope
{
$dbUuid = $this->contextRepo->findByUser($user)?->getDbUuid();
if ($dbUuid === null) {
return PatientRecordScope::unknown();
}
$clinic = $this->clinicRepo->findByUuid($dbUuid);
if ($clinic !== null) {
if ($this->secretaryRepo->findActiveBySecretaryForClinic($user, $clinic) === null) {
return PatientRecordScope::unknown();
}
$doctorIds = array_map(
fn($d) => $d->getId(),
$this->secretaryRepo->findDoctorsBySecretaryInClinic($user, $clinic),
);
return PatientRecordScope::forClinicRestrictedToDoctors($clinic->getId(), $doctorIds);
}
$doctor = $this->doctorRepo->findByUuid($dbUuid);
if ($doctor !== null && $this->secretaryRepo->findActiveBySecretaryForDoctor($user, $doctor) !== null) {
return PatientRecordScope::forDoctor($doctor->getId());
}
return PatientRecordScope::unknown();
}
}
+10 -6
View File
@@ -130,7 +130,7 @@ class PatientService
* محیط رزرو تعیین‌کننده است: کلینیک، یا مطب شخصی پزشک — هرگز هر دو. دو پرونده
* برای یک نوبت یعنی درآمد یک ویزیت دو بار شمرده می‌شود.
*/
public function autoCreateOnAppointmentConfirm(Appointment $appointment): void
public function autoCreateOnAppointmentConfirm(Appointment $appointment): ?PatientSession
{
$clinic = $appointment->getClinic();
@@ -138,10 +138,11 @@ class PatientService
? ['clinic', (int) $clinic->getId()]
: ['doctor', (int) $appointment->getDoctor()->getId()];
$this->autoCreateForEntity($entityType, $entityId, $appointment, $entityId);
return $this->autoCreateForEntity($entityType, $entityId, $appointment, $entityId);
}
private function autoCreateForEntity(string $entityType, int $entityId, Appointment $appointment, int $createdById): void
/** مراجعهٔ ساخته‌شده یا موجود؛ null یعنی این tenant قابلیت پرونده را ندارد. */
private function autoCreateForEntity(string $entityType, int $entityId, Appointment $appointment, int $createdById): ?PatientSession
{
if (!$this->subscriptionService->hasFeature($entityType, $entityId, 'patient_records')) {
// به‌زور پرونده نمی‌سازیم، ولی بی‌نشانه هم رد نمی‌شویم: بدون این لاگ،
@@ -152,11 +153,12 @@ class PatientService
'appointment_uuid' => $appointment->getUuid(),
]);
return;
return null;
}
if ($this->sessionRepo->findByAppointmentAndEntity($appointment, $entityType, $entityId) !== null) {
return;
$existing = $this->sessionRepo->findByAppointmentAndEntity($appointment, $entityType, $entityId);
if ($existing !== null) {
return $existing;
}
$patient = $appointment->getUser();
@@ -196,6 +198,8 @@ class PatientService
$this->sessionServiceRepo->save($line);
$session->addService($line);
}
return $session;
}
public function createSession(