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,302 @@
<?php
namespace App\Tests\Appointment;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Clinic\Entity\Clinic;
use App\Doctor\Entity\Doctor;
use App\Patient\Entity\PatientRecord;
use App\Patient\Entity\PatientSession;
use App\Tests\ApiTestCase;
/**
* «ثبت‌شده» → «قطعی»: POST /api/v1/appointment/{uuid}/confirm.
*
* یک عملِ اتمیک — وضعیت نوبت، پروندهٔ همان محیط با سرویس‌های نوبت، و پرداخت کامل یا
* جزئی روی همان مراجعه.
*/
class AppointmentConfirmFlowTest extends ApiTestCase
{
private function makeDoctor(string $name = 'دکتر تست'): Doctor
{
$user = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$doctor = new Doctor($user, $name);
$doctor->setMobileNumber($user->getMobileNumber());
$this->em->persist($doctor);
$this->em->flush();
return $doctor;
}
/** @return array{0: User, 1: Clinic} */
private function makeClinicWith(Doctor ...$doctors): array
{
$owner = $this->createUser(['ROLE_USER', 'ROLE_CLINIC']);
$clinic = new Clinic($owner);
$clinic->setName('کلینیک تست');
foreach ($doctors as $d) {
$clinic->getDoctors()->add($d);
}
$this->em->persist($clinic);
$this->em->flush();
return [$owner, $clinic];
}
private function makeAppointment(
Doctor $doctor,
?Clinic $clinic = null,
?User $patient = null,
int $visitPriceRials = 5_000_000,
): Appointment {
$patient ??= $this->createUser();
// اسلات یکتا به‌ازای هر نوبت: db_test بین اجراها پاک نمی‌شود.
$start = strtotime('+30 days') + random_int(0, 500_000) * 7;
$appointment = new Appointment($doctor, $patient, $start, $start + 900);
$appointment->setClinic($clinic);
$appointment->setVisitPriceRials($visitPriceRials);
$this->em->persist($appointment);
$this->em->flush();
return $appointment;
}
private function reload(Appointment $a): Appointment
{
$this->em->clear();
return $this->em->getRepository(Appointment::class)->find($a->getId());
}
// ── ساخت پنلی «ثبت‌شده» است، نه قطعی ─────────────────────────────────────
public function testPanelBookingIsCreatedPending(): void
{
$doctor = $this->makeDoctor();
$start = strtotime('+40 days') + random_int(0, 500_000) * 7;
$res = $this->authJson('POST', '/api/v1/my/appointment', $doctor->getUser(), [
'doctor_uuid' => $doctor->getUuid(),
'slot_start' => $start,
'slot_end' => $start + 1_800,
'patient_mobile' => '09' . str_pad((string) random_int(0, 999_999_999), 9, '0', STR_PAD_LEFT),
'patient_name' => 'بیمار تست',
'patient_national_code' => '00' . str_pad((string) random_int(0, 99_999_999), 8, '0', STR_PAD_LEFT),
]);
self::assertSame(201, $this->responseCode());
self::assertSame(Appointment::STATUS_PENDING, $res['data']['status']);
}
// ── قطعی‌کردن: بدون پرداخت / جزئی / کامل ─────────────────────────────────
public function testConfirmWithoutPaymentMovesToConfirmedAndOpensSession(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$res = $this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
self::assertSame(Appointment::STATUS_CONFIRMED, $res['data']['appointment']['status']);
self::assertSame(5_000_000, $res['data']['session']['final_price_rials']);
self::assertSame(0, $res['data']['session']['paid_total_rials']);
self::assertSame(5_000_000, $res['data']['session']['remaining_rials']);
self::assertFalse($res['data']['session']['is_paid']);
}
public function testConfirmWithPartialPaymentLeavesRemainder(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$res = $this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
'payments' => [['method' => 'cash', 'amount_rials' => 2_000_000]],
]);
self::assertSame(200, $this->responseCode());
self::assertSame(2_000_000, $res['data']['session']['paid_total_rials']);
self::assertSame(3_000_000, $res['data']['session']['remaining_rials']);
self::assertFalse($res['data']['session']['is_paid']);
}
public function testConfirmWithFullPaymentSettlesSession(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$res = $this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
'payments' => [['method' => 'pos', 'amount_rials' => 5_000_000]],
]);
self::assertSame(200, $this->responseCode());
self::assertSame(0, $res['data']['session']['remaining_rials']);
self::assertTrue($res['data']['session']['is_paid']);
}
public function testConfirmAcceptsSeveralPaymentRows(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$res = $this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
'payments' => [
['method' => 'cash', 'amount_rials' => 1_000_000],
['method' => 'pos', 'amount_rials' => 4_000_000],
],
]);
self::assertSame(200, $this->responseCode());
self::assertSame(5_000_000, $res['data']['session']['paid_total_rials']);
self::assertTrue($res['data']['session']['is_paid']);
}
// ── پرونده: استفادهٔ مجدد یا ساخت ────────────────────────────────────────
public function testConfirmReusesExistingRecordOfSameDoctor(): void
{
$doctor = $this->makeDoctor();
$patient = $this->createUser();
$first = $this->makeAppointment($doctor, null, $patient);
$this->authJson('POST', "/api/v1/appointment/{$first->getUuid()}/confirm", $doctor->getUser(), [
'version' => $first->getVersion(),
]);
self::assertSame(200, $this->responseCode());
$second = $this->makeAppointment($doctor, null, $patient);
$this->authJson('POST', "/api/v1/appointment/{$second->getUuid()}/confirm", $doctor->getUser(), [
'version' => $second->getVersion(),
]);
self::assertSame(200, $this->responseCode());
$records = $this->em->getRepository(PatientRecord::class)->findBy([
'entityType' => 'doctor',
'entityId' => $doctor->getId(),
'user' => $patient,
]);
self::assertCount(1, $records, 'پروندهٔ همان پزشک دوباره ساخته نمی‌شود');
$sessions = $this->em->getRepository(PatientSession::class)->findBy(['record' => $records[0]]);
self::assertCount(2, $sessions, 'هر نوبت مراجعهٔ خودش را دارد');
}
public function testConfirmInClinicFilesUnderClinicRecord(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$patient = $this->createUser();
$appointment = $this->makeAppointment($doctor, $clinic, $patient);
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $owner, [
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
$clinicRecord = $this->em->getRepository(PatientRecord::class)->findOneBy([
'entityType' => 'clinic',
'entityId' => $clinic->getId(),
'user' => $patient,
]);
$doctorRecord = $this->em->getRepository(PatientRecord::class)->findOneBy([
'entityType' => 'doctor',
'entityId' => $doctor->getId(),
'user' => $patient,
]);
self::assertNotNull($clinicRecord, 'نوبت کلینیکی در پروندهٔ کلینیک می‌نشیند');
self::assertNull($doctorRecord, 'و در مطب شخصی پزشک پروندهٔ موازی نمی‌سازد');
}
// ── خطاها ────────────────────────────────────────────────────────────────
public function testPaymentAboveTotalIsRejectedAndNothingIsCommitted(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
'payments' => [['method' => 'cash', 'amount_rials' => 9_000_000]],
]);
self::assertSame(422, $this->responseCode());
self::assertSame(Appointment::STATUS_PENDING, $this->reload($appointment)->getStatus(), 'تراکنش برگشته');
}
public function testUnknownPaymentMethodIs422(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
'payments' => [['method' => 'bitcoin', 'amount_rials' => 1_000]],
]);
self::assertSame(422, $this->responseCode());
self::assertSame(Appointment::STATUS_PENDING, $this->reload($appointment)->getStatus());
}
public function testStaleVersionIs409(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion() + 5,
]);
self::assertSame(409, $this->responseCode());
}
public function testConfirmingAnAlreadyConfirmedAppointmentIs422(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $doctor->getUser(), [
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
$fresh = $this->reload($appointment);
$this->authJson('POST', "/api/v1/appointment/{$fresh->getUuid()}/confirm", $doctor->getUser(), [
'version' => $fresh->getVersion(),
]);
self::assertSame(422, $this->responseCode(), 'confirmed → confirmed گذار مجاز نیست');
}
public function testStrangerCannotConfirm(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $this->createUser(), [
'version' => $appointment->getVersion(),
]);
self::assertSame(403, $this->responseCode());
}
public function testDetailExposesServicePricesForTheModal(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor);
$res = $this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $doctor->getUser());
self::assertSame(200, $this->responseCode());
self::assertSame(5_000_000, $res['data']['data']['visit_price_rials']);
self::assertArrayHasKey('service_items', $res['data']['data']);
}
}
@@ -28,6 +28,8 @@ class AppointmentExpiryServiceTest extends ApiTestCase
// distinct past slots — one live booking per (doctor, slot)
$slotStart = $past - $i * 1000;
$appt = new Appointment($doctor, $patient, $slotStart, $slotStart + 900);
// مثل مسیر واقعیِ رزرو آنلاین: نگه‌داشتِ موقت تا پرداخت درگاه.
$appt->markPendingWithTtl(-1);
$this->em->persist($appt);
$payment = new Payment($patient, 100_000, 'mellat', 'appointment');
@@ -53,4 +55,27 @@ class AppointmentExpiryServiceTest extends ApiTestCase
$this->assertSame(Payment::STATUS_CANCELED, $freshPay->getStatus());
}
}
/**
* نوبت «ثبت‌شده»ی پنل TTL ندارد؛ گذشتنِ ساعتِ نوبت نباید خودبه‌خود منقضی‌اش کند —
* قطعی/لغو کردنش تصمیم اپراتور است.
*/
public function testPanelRegisteredPendingSurvivesExpiry(): void
{
$owner = $this->createUser(['ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر پنل');
$this->em->persist($doctor);
$slotStart = time() - 7200;
$appt = new Appointment($doctor, $this->createUser(['ROLE_USER']), $slotStart, $slotStart + 900);
$this->em->persist($appt);
$this->em->flush();
static::getContainer()->get(AppointmentExpiryService::class)->expireStale();
$this->em->clear();
$fresh = $this->em->getRepository(Appointment::class)->find($appt->getId());
$this->assertSame(Appointment::STATUS_PENDING, $fresh->getStatus());
}
}
@@ -0,0 +1,329 @@
<?php
namespace App\Tests\Appointment;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Auth\Repository\UserActiveContextRepository;
use App\Clinic\Entity\Clinic;
use App\Clinic\Repository\ClinicDoctorPermissionRepository;
use App\Doctor\Entity\Doctor;
use App\Secretary\Entity\DoctorSecretary;
use App\Tests\ApiTestCase;
/**
* دسترسی به «یک نوبت مشخص» بر پایهٔ محیطِ خود نوبت (appointment.clinic) است، نه نقش
* کاربر. پیش از این مسیرهای تک‌نوبت فقط بیمار، پزشکِ مالک و ادمین را می‌شناختند و
* کاربر کلینیک روی نوبتی که خودش ساخته بود ۴۰۳ می‌گرفت.
*/
class ClinicAppointmentAccessTest extends ApiTestCase
{
private function makeDoctor(string $name = 'دکتر تست'): Doctor
{
$user = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$doctor = new Doctor($user, $name);
$doctor->setMobileNumber($user->getMobileNumber());
$this->em->persist($doctor);
$this->em->flush();
return $doctor;
}
/** @return array{0: User, 1: Clinic} */
private function makeClinicWith(Doctor ...$doctors): array
{
$owner = $this->createUser(['ROLE_USER', 'ROLE_CLINIC']);
$clinic = new Clinic($owner);
$clinic->setName('کلینیک تست');
foreach ($doctors as $d) {
$clinic->getDoctors()->add($d);
}
$this->em->persist($clinic);
$this->em->flush();
return [$owner, $clinic];
}
private function makeAppointment(Doctor $doctor, ?Clinic $clinic, ?User $patient = null): Appointment
{
$patient ??= $this->createUser();
$start = strtotime('+3 days 10:00');
$appointment = new Appointment($doctor, $patient, $start, $start + 900);
$appointment->setClinic($clinic);
$this->em->persist($appointment);
$this->em->flush();
return $appointment;
}
private function makeClinicSecretary(Clinic $clinic, Doctor $doctor, array $permissionPatch = []): User
{
$user = $this->createUser(['ROLE_USER', 'ROLE_SECRETARY']);
$secretary = new DoctorSecretary($doctor, $user, DoctorSecretary::OWNER_CLINIC, $clinic);
if ($permissionPatch !== []) {
$secretary->mergePermissions(['resources' => ['appointments' => $permissionPatch]]);
}
$this->em->persist($secretary);
$this->em->flush();
static::getContainer()->get(UserActiveContextRepository::class)->upsert($user, $clinic->getUuid());
return $user;
}
public function testClinicOwnerCanViewClinicAppointment(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $owner);
self::assertSame(200, $this->responseCode());
}
public function testClinicOwnerCanUpdateAndMoveClinicAppointment(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$newStart = strtotime('+4 days 11:00');
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}", $owner, [
'slot_start' => $newStart,
'slot_end' => $newStart + 900,
'note' => 'جابه‌جا شد',
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
}
public function testClinicOwnerCanChangeStatusOfClinicAppointment(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}/status", $owner, [
'status' => Appointment::STATUS_CONFIRMED,
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
}
public function testClinicOwnerCanTransferAppointmentToReserveAndBack(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$midnight = strtotime('+3 days 00:00');
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}", $owner, [
'is_reserve' => true,
'slot_start' => $midnight,
'slot_end' => $midnight,
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode(), 'انتقال به لیست رزرو');
$this->em->clear();
$reloaded = $this->em->getRepository(Appointment::class)->find($appointment->getId());
self::assertTrue($reloaded->isReserve());
$back = strtotime('+5 days 09:00');
$this->authJson('PATCH', "/api/v1/appointment/{$reloaded->getUuid()}", $owner, [
'is_reserve' => false,
'slot_start' => $back,
'slot_end' => $back + 900,
'version' => $reloaded->getVersion(),
]);
self::assertSame(200, $this->responseCode(), 'بازگشت از لیست رزرو');
}
public function testClinicOwnerCanReadAppointmentEvents(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}/events", $owner);
self::assertSame(200, $this->responseCode());
}
public function testClinicOwnerCannotTouchDoctorPersonalAppointment(): void
{
$doctor = $this->makeDoctor();
[$owner] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, null);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $owner);
self::assertSame(403, $this->responseCode(), 'مطب شخصی پزشک از دسترس کلینیک خارج است');
}
public function testForeignClinicOwnerIsDenied(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
[$otherOwner] = $this->makeClinicWith($this->makeDoctor('دکتر دیگر'));
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $otherOwner);
self::assertSame(403, $this->responseCode());
}
public function testMemberDoctorLosesAccessWhenDeactivated(): void
{
$member = $this->makeDoctor('دکتر عضو');
$colleague = $this->makeDoctor('همکار');
[, $clinic] = $this->makeClinicWith($member, $colleague);
$appointment = $this->makeAppointment($colleague, $clinic);
$permissions = static::getContainer()->get(ClinicDoctorPermissionRepository::class);
$permissions->getOrCreate($clinic, $member);
$this->em->flush();
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $member->getUser());
self::assertSame(200, $this->responseCode(), 'پزشک فعالِ کلینیک نوبت‌های همان کلینیک را می‌بیند');
$permissions->getOrCreate($clinic, $member)->setActive(false);
$this->em->flush();
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $member->getUser());
self::assertSame(403, $this->responseCode(), 'پس از پایان همکاری دسترسی قطع می‌شود');
}
public function testClinicSecretaryCanManageAssignedDoctorAppointment(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$secretary = $this->makeClinicSecretary($clinic, $doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $secretary);
self::assertSame(200, $this->responseCode());
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}/status", $secretary, [
'status' => Appointment::STATUS_CONFIRMED,
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
}
public function testClinicSecretaryCannotTouchUnassignedDoctorAppointment(): void
{
$mine = $this->makeDoctor('پزشک من');
$theirs = $this->makeDoctor('پزشک دیگر');
[, $clinic] = $this->makeClinicWith($mine, $theirs);
$secretary = $this->makeClinicSecretary($clinic, $mine);
$appointment = $this->makeAppointment($theirs, $clinic);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $secretary);
self::assertSame(403, $this->responseCode(), 'منشی فقط پزشکان تخصیص‌یافتهٔ خودش را دارد');
}
public function testSecretaryCancelRequiresCancelPermission(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$secretary = $this->makeClinicSecretary($clinic, $doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}/status", $secretary, [
'status' => Appointment::STATUS_CANCELLED_BY_DOCTOR,
'version' => $appointment->getVersion(),
]);
self::assertSame(403, $this->responseCode(), 'لغو به‌صورت پیش‌فرض برای منشی خاموش است');
}
public function testSecretaryWithCancelPermissionCanCancel(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$secretary = $this->makeClinicSecretary($clinic, $doctor, ['cancel' => true]);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}/status", $secretary, [
'status' => Appointment::STATUS_CANCELLED_BY_DOCTOR,
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
}
public function testInlineStatusCannotBypassCancelGate(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$secretary = $this->makeClinicSecretary($clinic, $doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}", $secretary, [
'status' => Appointment::STATUS_CANCELLED_BY_DOCTOR,
'version' => $appointment->getVersion(),
]);
self::assertSame(403, $this->responseCode(), 'status درون‌خطی همان گیت لغو را دارد');
}
public function testOwnerDoctorKeepsFullAccessToOwnClinicAppointment(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$appointment = $this->makeAppointment($doctor, $clinic);
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $doctor->getUser());
self::assertSame(200, $this->responseCode());
}
public function testPatientCanViewButNotRescheduleOwnAppointment(): void
{
$doctor = $this->makeDoctor();
$patient = $this->createUser();
$appointment = $this->makeAppointment($doctor, null, $patient);
$newStart = strtotime('+6 days 10:00');
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $patient);
self::assertSame(200, $this->responseCode());
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}", $patient, [
'slot_start' => $newStart,
'slot_end' => $newStart + 900,
'version' => $appointment->getVersion(),
]);
self::assertSame(403, $this->responseCode(), 'بیمار نوبت خودش را جابه‌جا نمی‌کند');
}
public function testPatientCanCancelOwnAppointment(): void
{
$doctor = $this->makeDoctor();
$patient = $this->createUser();
$appointment = $this->makeAppointment($doctor, null, $patient);
$this->authJson('PATCH', "/api/v1/appointment/{$appointment->getUuid()}/status", $patient, [
'status' => Appointment::STATUS_CANCELLED_BY_USER,
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
}
public function testStrangerIsDenied(): void
{
$doctor = $this->makeDoctor();
$appointment = $this->makeAppointment($doctor, null);
$stranger = $this->createUser();
$this->authJson('GET', "/api/v1/appointment/{$appointment->getUuid()}", $stranger);
self::assertSame(403, $this->responseCode());
}
}
+251
View File
@@ -0,0 +1,251 @@
<?php
namespace App\Tests\Patient;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Auth\Repository\UserActiveContextRepository;
use App\Clinic\Entity\Clinic;
use App\Clinic\Repository\ClinicDoctorPermissionRepository;
use App\Doctor\Entity\Doctor;
use App\Patient\Entity\PatientRecord;
use App\Secretary\Entity\DoctorSecretary;
use App\Tests\ApiTestCase;
/**
* پروندهٔ کلینیکی per-بیمار است (یکتایی clinic+user) و مدیر کلینیک همه را می‌بیند.
* پزشکِ عضو هم باید پرونده‌های بیمارانِ خودش در همان کلینیک را ببیند — رابطه از
* نوبت‌های همان پزشک در همان کلینیک می‌آید، نه از ستونی روی پرونده.
*
* با غیرفعال شدن پزشک، دسترسی‌اش قطع می‌شود ولی پرونده‌ها دست‌نخورده می‌مانند.
*/
class ClinicRecordAccessTest extends ApiTestCase
{
private function makeDoctor(string $name = 'دکتر تست'): Doctor
{
$user = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$doctor = new Doctor($user, $name);
$doctor->setMobileNumber($user->getMobileNumber());
$this->em->persist($doctor);
$this->em->flush();
return $doctor;
}
/** @return array{0: User, 1: Clinic} */
private function makeClinicWith(Doctor ...$doctors): array
{
$owner = $this->createUser(['ROLE_USER', 'ROLE_CLINIC']);
$clinic = new Clinic($owner);
$clinic->setName('کلینیک تست');
foreach ($doctors as $d) {
$clinic->getDoctors()->add($d);
}
$this->em->persist($clinic);
$this->em->flush();
return [$owner, $clinic];
}
private function activeContext(User $user, string $dbUuid): void
{
static::getContainer()->get(UserActiveContextRepository::class)->upsert($user, $dbUuid);
}
/** پروندهٔ کلینیکی بیمار + نوبتی که او را به این پزشک وصل می‌کند. */
private function makeClinicRecordFor(Clinic $clinic, Doctor $doctor, ?User $patient = null): PatientRecord
{
$patient ??= $this->createUser();
$record = new PatientRecord('clinic', $clinic->getId(), $patient, 'system', $clinic->getId());
$this->em->persist($record);
$start = strtotime('+60 days') + random_int(0, 500_000) * 7;
$appointment = new Appointment($doctor, $patient, $start, $start + 900);
$appointment->setClinic($clinic);
$this->em->persist($appointment);
$this->em->flush();
return $record;
}
private function uuidsFromList(array $response): array
{
return array_map(fn(array $row) => $row['uuid'], $response['data'] ?? []);
}
// ── پزشک عضو ─────────────────────────────────────────────────────────────
public function testMemberDoctorSeesOwnPatientsClinicRecord(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$record = $this->makeClinicRecordFor($clinic, $doctor);
$this->activeContext($doctor->getUser(), $clinic->getUuid());
$res = $this->authJson('GET', '/api/v1/patients?limit=50', $doctor->getUser());
self::assertSame(200, $this->responseCode());
self::assertContains($record->getUuid(), $this->uuidsFromList($res));
}
public function testMemberDoctorCannotSeeAnotherDoctorsClinicRecord(): void
{
$mine = $this->makeDoctor('پزشک من');
$theirs = $this->makeDoctor('پزشک دیگر');
[, $clinic] = $this->makeClinicWith($mine, $theirs);
$foreign = $this->makeClinicRecordFor($clinic, $theirs);
$this->activeContext($mine->getUser(), $clinic->getUuid());
$res = $this->authJson('GET', '/api/v1/patients?limit=50', $mine->getUser());
self::assertNotContains($foreign->getUuid(), $this->uuidsFromList($res));
$this->authJson('GET', "/api/v1/patient/{$foreign->getUuid()}", $mine->getUser());
self::assertSame(404, $this->responseCode(), 'پروندهٔ بیمارِ پزشک دیگر برای او وجود ندارد');
}
public function testMemberDoctorCanOpenAndManageOwnPatientRecord(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$record = $this->makeClinicRecordFor($clinic, $doctor);
$this->activeContext($doctor->getUser(), $clinic->getUuid());
$this->authJson('GET', "/api/v1/patient/{$record->getUuid()}", $doctor->getUser());
self::assertSame(200, $this->responseCode());
$this->authJson('POST', "/api/v1/patient/{$record->getUuid()}/note", $doctor->getUser(), [
'body' => 'یادداشت پزشک عضو',
]);
self::assertSame(201, $this->responseCode(), 'پزشک عضو فعال پرونده را مدیریت هم می‌کند');
}
public function testDoctorInPersonalContextSeesOnlyOwnOfficeRecords(): void
{
$doctor = $this->makeDoctor();
[, $clinic] = $this->makeClinicWith($doctor);
$clinicRecord = $this->makeClinicRecordFor($clinic, $doctor);
// بدون محیط فعالِ کلینیک ⇒ مطب شخصی.
$this->activeContext($doctor->getUser(), $doctor->getUuid());
$res = $this->authJson('GET', '/api/v1/patients?limit=50', $doctor->getUser());
self::assertSame(200, $this->responseCode());
self::assertNotContains($clinicRecord->getUuid(), $this->uuidsFromList($res));
}
// ── پایان همکاری ─────────────────────────────────────────────────────────
public function testDeactivatedDoctorLosesClinicRecordsButOwnerKeepsThem(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$record = $this->makeClinicRecordFor($clinic, $doctor);
$this->activeContext($doctor->getUser(), $clinic->getUuid());
$this->authJson('GET', "/api/v1/patient/{$record->getUuid()}", $doctor->getUser());
self::assertSame(200, $this->responseCode(), 'پزشک فعال دسترسی دارد');
$permissions = static::getContainer()->get(ClinicDoctorPermissionRepository::class);
$permissions->getOrCreate($clinic, $doctor)->setActive(false);
$this->em->flush();
$this->authJson('GET', "/api/v1/patient/{$record->getUuid()}", $doctor->getUser());
self::assertSame(404, $this->responseCode(), 'بعد از پایان همکاری، دسترسی قطع می‌شود');
$this->authJson('GET', "/api/v1/patient/{$record->getUuid()}", $owner);
self::assertSame(200, $this->responseCode(), 'مدیر کلینیک دسترسی کامل دارد');
$this->em->clear();
self::assertNotNull(
$this->em->getRepository(PatientRecord::class)->find($record->getId()),
'پرونده حذف یا منتقل نمی‌شود',
);
}
// ── مدیر کلینیک ──────────────────────────────────────────────────────────
public function testClinicOwnerSeesEveryDoctorsRecords(): void
{
$first = $this->makeDoctor('پزشک اول');
$second = $this->makeDoctor('پزشک دوم');
[$owner, $clinic] = $this->makeClinicWith($first, $second);
$firstRecord = $this->makeClinicRecordFor($clinic, $first);
$secondRecord = $this->makeClinicRecordFor($clinic, $second);
$res = $this->authJson('GET', '/api/v1/patients?limit=50', $owner);
$uuids = $this->uuidsFromList($res);
self::assertSame(200, $this->responseCode());
self::assertContains($firstRecord->getUuid(), $uuids);
self::assertContains($secondRecord->getUuid(), $uuids);
}
// ── منشی ─────────────────────────────────────────────────────────────────
public function testClinicSecretaryIsLimitedToAssignedDoctors(): void
{
$mine = $this->makeDoctor('پزشک من');
$theirs = $this->makeDoctor('پزشک دیگر');
[, $clinic] = $this->makeClinicWith($mine, $theirs);
$ownRecord = $this->makeClinicRecordFor($clinic, $mine);
$foreign = $this->makeClinicRecordFor($clinic, $theirs);
$secretaryUser = $this->createUser(['ROLE_USER', 'ROLE_SECRETARY']);
$relation = new DoctorSecretary($mine, $secretaryUser, DoctorSecretary::OWNER_CLINIC, $clinic);
$this->em->persist($relation);
$this->em->flush();
$this->activeContext($secretaryUser, $clinic->getUuid());
$res = $this->authJson('GET', '/api/v1/patients?limit=50', $secretaryUser);
$uuids = $this->uuidsFromList($res);
self::assertSame(200, $this->responseCode());
self::assertContains($ownRecord->getUuid(), $uuids);
self::assertNotContains($foreign->getUuid(), $uuids);
}
// ── قطعی‌کردن نوبت کلینیکی، دیده‌شده توسط هر دو نقش ───────────────────────
public function testConfirmedClinicAppointmentRecordIsVisibleToBothRoles(): void
{
$doctor = $this->makeDoctor();
[$owner, $clinic] = $this->makeClinicWith($doctor);
$patient = $this->createUser();
$start = strtotime('+70 days') + random_int(0, 500_000) * 7;
$appointment = new Appointment($doctor, $patient, $start, $start + 900);
$appointment->setClinic($clinic);
$appointment->setVisitPriceRials(3_000_000);
$this->em->persist($appointment);
$this->em->flush();
// محیط فعال را قبل از confirm ست کن: آن درخواست EntityManager را پاک می‌کند.
$this->activeContext($doctor->getUser(), $clinic->getUuid());
$this->authJson('POST', "/api/v1/appointment/{$appointment->getUuid()}/confirm", $owner, [
'version' => $appointment->getVersion(),
]);
self::assertSame(200, $this->responseCode());
$record = $this->em->getRepository(PatientRecord::class)->findOneBy([
'entityType' => 'clinic',
'entityId' => $clinic->getId(),
'user' => $patient,
]);
self::assertNotNull($record);
$this->authJson('GET', "/api/v1/patient/{$record->getUuid()}", $owner);
self::assertSame(200, $this->responseCode(), 'مدیر کلینیک');
$this->authJson('GET', "/api/v1/patient/{$record->getUuid()}", $doctor->getUser());
self::assertSame(200, $this->responseCode(), 'پزشکِ همان نوبت');
}
}