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
@@ -7,6 +7,7 @@ use App\Appointment\Entity\WeeklySchedule;
use App\Appointment\Repository\AppointmentRepository;
use App\Appointment\Repository\SlotTakenException;
use App\Appointment\Repository\WeeklyScheduleRepository;
use App\Appointment\Security\AppointmentAccessChecker;
use App\Appointment\Service\AppointmentConfirmationService;
use App\Appointment\Service\SlotCalculatorService;
use App\Clinic\Entity\Clinic;
@@ -40,6 +41,7 @@ class AppointmentController extends BaseController
private readonly \App\ClinicService\Repository\ServiceItemRepository $itemRepo,
private readonly \App\Staff\Repository\ClinicStaffRepository $staffRepo,
private readonly \App\Appointment\Repository\AppointmentEventRepository $eventRepo,
private readonly \App\Appointment\Security\AppointmentAccessChecker $accessChecker,
private readonly \Psr\Log\LoggerInterface $logger,
) {}
@@ -576,7 +578,7 @@ class AppointmentController extends BaseController
}
if (!$this->canView($appointment, $user)) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
return $this->success(['data' => $appointment->toArray()]);
@@ -631,12 +633,17 @@ class AppointmentController extends BaseController
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دکتر یافت نشد', 404);
}
if ($doctor->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
$isOwner = $doctor->getUser()->getId() === $user->getId() || $user->hasRole('ROLE_ADMIN');
// مدیر کلینیک لیست پزشک عضو را می‌بیند، ولی فقط نوبت‌های همان کلینیک —
// نوبت‌های مطب شخصی پزشک به کلینیک نشت نمی‌کند.
$scopeClinic = $isOwner ? null : $this->accessChecker->viewableClinicFor($user, $doctor);
if (!$isOwner && $scopeClinic === null) {
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
$status = $request->query->get('status');
$appointments = $this->appointmentRepo->findByDoctor($doctor, $status);
$appointments = $this->appointmentRepo->findByDoctor($doctor, $status, $scopeClinic);
return $this->success(['data' => array_map(fn(Appointment $a) => $a->toArray(), $appointments)]);
}
@@ -685,16 +692,12 @@ class AppointmentController extends BaseController
private function canView(Appointment $a, User $user): bool
{
return $a->getUser()->getId() === $user->getId()
|| $a->getDoctor()->getUser()->getId() === $user->getId()
|| $user->hasRole('ROLE_ADMIN');
return $this->accessChecker->canView($a, $user);
}
private function canManage(Appointment $a, User $user): bool
{
return $a->getUser()->getId() === $user->getId()
|| $a->getDoctor()->getUser()->getId() === $user->getId()
|| $user->hasRole('ROLE_ADMIN');
return $this->accessChecker->canManage($a, $user);
}
/**
@@ -855,14 +858,20 @@ class AppointmentController extends BaseController
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'نوبت یافت نشد', 404);
}
if (!$this->canManage($appointment, $user)) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$data = json_decode($request->getContent(), true) ?? [];
$newStatus = trim($data['status'] ?? '');
$version = (int) ($data['version'] ?? $appointment->getVersion());
// لغو مجوز جداگانه دارد: منشی به‌صورت پیش‌فرض اجازهٔ لغو ندارد ولی وضعیت‌های
// دیگر را تغییر می‌دهد.
$action = in_array($newStatus, self::CANCEL_STATUSES, true)
? AppointmentAccessChecker::ACTION_CANCEL
: AppointmentAccessChecker::ACTION_UPDATE_STATUS;
if (!$this->accessChecker->can($appointment, $user, $action)) {
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
if (!$appointment->canTransitionTo($newStatus)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, sprintf(
'انتقال از "%s" به "%s" مجاز نیست', $appointment->getStatus(), $newStatus
@@ -889,6 +898,81 @@ class AppointmentController extends BaseController
return $this->success(['data' => $appointment->toArray()]);
}
/**
* قطعی‌کردن نوبت به‌همراه پرداخت — «ثبت‌شده» → «قطعی».
*
* یک عملِ اتمیک: انتقال وضعیت، ساخت/یافتنِ پروندهٔ همان محیط با سرویس‌های نوبت،
* و ثبت پرداخت‌های کامل یا جزئی روی همان مراجعه. اگر هر مرحله شکست بخورد هیچ‌کدام
* ثبت نمی‌شوند.
*/
#[OA\Post(
path: '/api/v1/appointment/{uuid}/confirm',
summary: 'Confirm an appointment and register its payments on the patient case file',
security: [['bearerAuth' => []]],
responses: [
new OA\Response(response: 200, description: 'Appointment confirmed'),
new OA\Response(response: 403, description: 'Access denied, or payments sent without the patient_records feature'),
new OA\Response(response: 404, description: 'Appointment not found'),
new OA\Response(response: 409, description: 'Version conflict'),
new OA\Response(response: 422, description: 'Invalid transition or payment'),
]
)]
#[Route('/api/v1/appointment/{uuid}/confirm', methods: ['POST'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function confirm(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
{
$appointment = $this->appointmentRepo->findByUuid($uuid);
if ($appointment === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'نوبت یافت نشد', 404);
}
if (!$this->accessChecker->can($appointment, $user, AppointmentAccessChecker::ACTION_UPDATE_STATUS)) {
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
$data = json_decode($request->getContent(), true) ?? [];
$version = (int) ($data['version'] ?? $appointment->getVersion());
if (!$appointment->canTransitionTo(Appointment::STATUS_CONFIRMED)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, sprintf(
'انتقال از "%s" به "%s" مجاز نیست', $appointment->getStatus(), Appointment::STATUS_CONFIRMED
), 422);
}
$payments = [];
foreach ((array) ($data['payments'] ?? []) as $row) {
$method = trim((string) ($row['method'] ?? ''));
$amount = (int) ($row['amount_rials'] ?? 0);
if (!in_array($method, \App\Patient\Entity\SessionPayment::METHODS, true)) {
return $this->error(ErrorCodes::ERR_SESSION_PAYMENT_INVALID, ErrorCodes::message(ErrorCodes::ERR_SESSION_PAYMENT_INVALID), 422, 'method');
}
if ($amount <= 0) {
return $this->error(ErrorCodes::ERR_SESSION_PAYMENT_INVALID, ErrorCodes::message(ErrorCodes::ERR_SESSION_PAYMENT_INVALID), 422, 'amount_rials');
}
$payments[] = ['method' => $method, 'amount_rials' => $amount];
}
try {
$session = $this->appointmentConfirmation->confirmWithPayments($appointment, $version, $payments, $user);
} catch (OptimisticLockException) {
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'تداخل ویرایش همزمان. لطفاً دوباره تلاش کنید', 409);
}
return $this->success([
'appointment' => $appointment->toArray(),
'session' => $session === null ? null : [
'uuid' => $session->getUuid(),
'visit_price_rials' => $session->getVisitPriceRials(),
'services_total_rials' => $session->getServicesTotalRials(),
'final_price_rials' => $session->getFinalPriceRials(),
'discount_rials' => $session->getDiscountRials(),
'paid_total_rials' => $session->getPaidTotalRials(),
'remaining_rials' => $session->getRemainingRials(),
'is_paid' => $session->getRemainingRials() === 0,
],
]);
}
/**
* General update (ویرایش / جا به جایی / انتقال به رزرو / جایگزینی).
* All fields optional; only what is present in the body changes. Slot moves
@@ -905,12 +989,18 @@ class AppointmentController extends BaseController
}
if (!$this->canManage($appointment, $user)) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
$data = json_decode($request->getContent(), true) ?? [];
$version = (int) ($data['version'] ?? $appointment->getVersion());
// status درون‌خطی نباید گیت لغو را دور بزند.
if (in_array(trim((string) ($data['status'] ?? '')), self::CANCEL_STATUSES, true)
&& !$this->accessChecker->canCancel($appointment, $user)) {
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
// Slot move / reserve toggle — both times together, or neither.
$hasStart = array_key_exists('slot_start', $data);
$hasEnd = array_key_exists('slot_end', $data);
@@ -1015,8 +1105,8 @@ class AppointmentController extends BaseController
if ($appointment === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'نوبت یافت نشد', 404);
}
if (!$this->canManage($appointment, $user)) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
if (!$this->canView($appointment, $user)) {
return $this->error(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ممنوع', 403);
}
return $this->success($this->eventRepo->findByAppointmentUuid($uuid));
@@ -45,7 +45,6 @@ class MyAppointmentsController extends BaseController
private readonly \App\Auth\Repository\UserRepository $userRepo,
private readonly \App\UserProfile\Repository\UserProfileRepository $profileRepo,
private readonly VisitPriceRequirementResolver $visitPriceResolver,
private readonly \App\Appointment\Service\AppointmentConfirmationService $appointmentConfirmation,
) {}
#[Route('/api/v1/my/appointment', methods: ['POST'])]
@@ -186,10 +185,10 @@ class MyAppointmentsController extends BaseController
$appointment->setPatientName($patient->getRealName() ?: $patientName);
$appointment->setPatientMobile($mobile);
// نوبتی که خودِ کلینیک/پزشک ثبت می‌کند پرداخت آنلاین ندارد و منتظر چیزی نیست؛
// قطعی است. transitionTo قبل از ذخیره می‌آید تا active_slot_key با وضعیت نهایی
// محاسبه شود.
$appointment->transitionTo(Appointment::STATUS_CONFIRMED);
// نوبت پنلی «ثبت‌شده» (pending) متولد می‌شود، نه قطعی: قطعی‌شدن یک عملِ جداست
// که هزینه‌ها را نشان می‌دهد و پرداخت می‌گیرد (POST /appointment/{uuid}/confirm).
// pending هم اسلات را اشغال می‌کند (SLOT_OCCUPYING_STATUSES)، پس جای نوبت
// محفوظ می‌ماند. expiresAt ست نمی‌شود، پس هرگز خودبه‌خود منقضی نمی‌شود.
if ($isReserve) {
// Day-level reserve: no slot occupation, plain save (no atomic slot check).
@@ -203,8 +202,6 @@ class MyAppointmentsController extends BaseController
}
}
$this->appointmentConfirmation->onConfirmed($appointment);
return $this->success([
'uuid' => $appointment->getUuid(),
'slot_start' => $slotStart,
@@ -403,30 +400,44 @@ class MyAppointmentsController extends BaseController
->groupBy('a.status');
$roles = $user->getRoles();
if (in_array('ROLE_CLINIC', $roles, true)) {
if (in_array('ROLE_ADMIN', $roles, true)) {
// Admin sees all
} elseif (in_array('ROLE_CLINIC', $roles, true)) {
$clinic = $this->clinicRepo->findByUser($user);
if ($clinic) {
$qb->join('App\Clinic\Entity\Clinic', 'c', 'WITH', 'd MEMBER OF c.doctors')
->andWhere('c = :clinic')
->setParameter('clinic', $clinic);
if ($clinic === null) {
return $this->emptyTodayStats();
}
$qb->join('App\Clinic\Entity\Clinic', 'c', 'WITH', 'd MEMBER OF c.doctors')
->andWhere('c = :clinic')
->setParameter('clinic', $clinic);
} elseif (in_array('ROLE_DOCTOR', $roles, true)) {
$doctor = $this->doctorRepo->findByUser($user);
if ($doctor) {
$qb->andWhere('a.doctor = :doctor')->setParameter('doctor', $doctor);
if ($doctor === null) {
return $this->emptyTodayStats();
}
$qb->andWhere('a.doctor = :doctor')->setParameter('doctor', $doctor);
} elseif (in_array('ROLE_SECRETARY', $roles, true)) {
$filter = $this->resolveSecretaryFilter($user);
if ($filter !== null) {
[$filterType, $filterValue] = $filter;
if ($filterType === 'clinic') {
$qb->join('App\Clinic\Entity\Clinic', 'c', 'WITH', 'd MEMBER OF c.doctors')
->andWhere('c = :clinic')
->setParameter('clinic', $filterValue);
} else {
$qb->andWhere('a.doctor = :doctor')->setParameter('doctor', $filterValue);
}
if ($filter === null) {
return $this->emptyTodayStats();
}
// در scope کلینیک، filterValue آرایه‌ی idهای پزشکانِ تخصیص‌یافته است —
// نه خود کلینیک؛ هم‌شکل با myAppointments.
[$filterType, $filterValue, $canView] = $filter;
if (!$canView) {
return $this->emptyTodayStats();
}
if ($filterType === 'clinic') {
if (empty($filterValue)) {
return $this->emptyTodayStats();
}
$qb->andWhere('a.doctor IN (:doctorIds)')->setParameter('doctorIds', $filterValue);
} else {
$qb->andWhere('a.doctor = :doctor')->setParameter('doctor', $filterValue);
}
} else {
// بیمار عادی: فقط نوبت‌های خودش — نه شمارشِ بی‌محدودهٔ کل سیستم.
$qb->andWhere('a.user = :patient')->setParameter('patient', $user);
}
$rows = $qb->getQuery()->getArrayResult();
@@ -451,6 +462,11 @@ class MyAppointmentsController extends BaseController
]);
}
private function emptyTodayStats(): JsonResponse
{
return $this->success(['total' => 0, 'completed' => 0, 'waiting' => 0, 'cancelled' => 0]);
}
/**
* Whether the acting user is allowed to book onto this doctor's calendar.
* The role gate alone is not enough: a doctor/clinic/secretary must be
+12 -1
View File
@@ -200,6 +200,11 @@ class Appointment
/**
* Recompute the unique active-slot key from the current status. Non-null
* while the appointment occupies the slot; null once it is cancelled.
*
* کلید عمداً clinic ندارد و فقط doctor+slotStart است: برنامهٔ هفتگی هر محیط
* جداست (WeeklySchedule با UNIQUE(doctor_id, clinic_key)) و می‌تواند با محیط
* دیگر هم‌پوشانی داشته باشد، ولی پزشک یک نفر است. افزودن clinic به کلید یعنی
* اجازهٔ رزرو هم‌زمان همان پزشک در مطب و کلینیک — نه رفع باگ.
*/
private function refreshActiveSlotKey(): void
{
@@ -356,8 +361,14 @@ class Appointment
'patient_reason' => $this->patientReason,
'service_section' => $this->serviceSection ? ['uuid' => $this->serviceSection->getUuid(), 'name' => $this->serviceSection->getName()] : null,
'service_item' => $this->serviceItem ? ['uuid' => $this->serviceItem->getUuid(), 'name' => $this->serviceItem->getName()] : null,
// price_rials لازم است تا مودالِ «قطعی کردن نوبت» بتواند هزینه‌ها را قبل از
// ساخته‌شدنِ مراجعه نشان دهد.
'service_items' => array_map(
fn(\App\ClinicService\Entity\ServiceItem $i) => ['uuid' => $i->getUuid(), 'name' => $i->getName()],
fn(\App\ClinicService\Entity\ServiceItem $i) => [
'uuid' => $i->getUuid(),
'name' => $i->getName(),
'price_rials' => $i->getPriceRials(),
],
$this->serviceItems->toArray()
),
'staff' => $this->staff ? ['uuid' => $this->staff->getUuid(), 'full_name' => $this->staff->getFullName()] : null,
@@ -4,6 +4,7 @@ namespace App\Appointment\Repository;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Clinic\Entity\Clinic;
use App\Doctor\Entity\Doctor;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
@@ -172,13 +173,33 @@ class AppointmentRepository extends ServiceEntityRepository
}
/** @return Appointment[] */
public function findByDoctor(Doctor $doctor, ?string $status = null): array
public function findByDoctor(Doctor $doctor, ?string $status = null, ?Clinic $clinic = null): array
{
$criteria = ['doctor' => $doctor];
if ($status !== null) $criteria['status'] = $status;
// محدودکردن به یک محیط: مدیر کلینیک نباید نوبت‌های مطب شخصی پزشک را ببیند.
if ($clinic !== null) $criteria['clinic'] = $clinic;
return $this->findBy($criteria, ['slotStart' => 'ASC']);
}
/**
* نوبت‌های یک بیمار در یک کلینیک — بر پایهٔ خودِ محیطِ ثبت‌شدهٔ نوبت، تا غیرفعال
* شدنِ بعدیِ پزشک تاریخچه را از پروندهٔ کلینیک حذف نکند.
*
* @return Appointment[]
*/
public function findByUserAndClinic(User $user, int $clinicId): array
{
return $this->createQueryBuilder('a')
->where('a.user = :user')
->andWhere('IDENTITY(a.clinic) = :clinicId')
->setParameter('user', $user)
->setParameter('clinicId', $clinicId)
->orderBy('a.slotStart', 'DESC')
->getQuery()
->getResult();
}
/** @return Appointment[] */
public function findByUser(User $user, ?string $status = null): array
{
@@ -247,11 +268,20 @@ class AppointmentRepository extends ServiceEntityRepository
->getResult();
}
/** @return Appointment[] pending appointments older than given timestamp */
/**
* رزروهای آنلاینِ پرداخت‌نشده که ساعتشان هم گذشته است.
*
* `expiresAt IS NOT NULL` یعنی فقط نگه‌داشتِ موقتِ درگاه (markPendingWithTtl).
* نوبت «ثبت‌شده»ای که کلینیک/پزشک از پنل ثبت کرده TTL ندارد و نباید سرِ ساعتِ
* نوبت خودبه‌خود منقضی شود — قطعی/لغو کردنش تصمیم اپراتور است.
*
* @return Appointment[]
*/
public function findExpiredPending(int $before): array
{
return $this->createQueryBuilder('a')
->where('a.status = :status')
->andWhere('a.expiresAt IS NOT NULL')
->andWhere('a.slotStart < :before')
->setParameter('status', Appointment::STATUS_PENDING)
->setParameter('before', $before)
@@ -0,0 +1,135 @@
<?php
namespace App\Appointment\Security;
use App\Appointment\Entity\Appointment;
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;
use App\Secretary\Security\SecretaryPermissionChecker;
/**
* تنها تصمیم‌گیرندهٔ دسترسی روی «یک نوبت مشخص».
*
* پیش از این، مسیرهای تک‌نوبت فقط بیمار، پزشکِ مالک و ادمین را می‌شناختند؛ نوبتی که
* کاربر کلینیک از مسیر /my/appointment می‌ساخت، روی مشاهده و ویرایش ۴۰۳ می‌گرفت.
* محیط نوبت با appointment.clinic بیان می‌شود (NULL یعنی مطب شخصی) و همان مبنای
* تصمیم است — نه نقش کاربر.
*
* اکشن‌ها از همان واژگان ClinicDoctorPermission/DoctorSecretary گرفته شده‌اند تا
* «پایان همکاری» فقط یک منبع حقیقت داشته باشد: active=false در همان رکوردها.
*/
class AppointmentAccessChecker
{
public const ACTION_VIEW = 'view';
public const ACTION_UPDATE_STATUS = 'update_status';
public const ACTION_CANCEL = 'cancel';
private const RESOURCE = 'appointments';
public function __construct(
private readonly ClinicDoctorPermissionChecker $clinicPermissions,
private readonly SecretaryPermissionChecker $secretaryPermissions,
private readonly DoctorSecretaryRepository $secretaryRepo,
private readonly UserActiveContextRepository $contextRepo,
private readonly ClinicRepository $clinicRepo,
private readonly DoctorRepository $doctorRepo,
) {}
public function canView(Appointment $appointment, User $user): bool
{
return $this->can($appointment, $user, self::ACTION_VIEW);
}
/** مجوز تغییر نوبت: ویرایش، جابه‌جایی، رزرو، جایگزینی و تغییر وضعیت. */
public function canManage(Appointment $appointment, User $user): bool
{
return $this->can($appointment, $user, self::ACTION_UPDATE_STATUS);
}
public function canCancel(Appointment $appointment, User $user): bool
{
return $this->can($appointment, $user, self::ACTION_CANCEL);
}
public function can(Appointment $appointment, User $user, string $action): bool
{
if ($user->hasRole('ROLE_ADMIN')) {
return true;
}
if ($appointment->getDoctor()->getUser()->getId() === $user->getId()) {
return true;
}
// بیمار نوبت خودش را می‌بیند و لغو می‌کند، ولی جابه‌جا/ویرایش نمی‌کند.
if ($appointment->getUser()->getId() === $user->getId()) {
return $action === self::ACTION_VIEW || $action === self::ACTION_CANCEL;
}
$clinic = $appointment->getClinic();
if ($clinic !== null && $this->clinicPermissions->can($user, $clinic, self::RESOURCE, $action)) {
return true;
}
return $this->secretaryCan($appointment, $user, $action);
}
/**
* کلینیکی که این کاربر در آن اجازهٔ دیدن نوبت‌های این پزشک را دارد، یا null.
* برای لیست‌هایی که باید به یک محیط محدود شوند (نه تک‌نوبت).
*/
public function viewableClinicFor(User $user, \App\Doctor\Entity\Doctor $doctor): ?\App\Clinic\Entity\Clinic
{
$dbUuid = $this->contextRepo->findByUser($user)?->getDbUuid();
$clinic = $dbUuid !== null ? $this->clinicRepo->findByUuid($dbUuid) : null;
if ($clinic === null) {
$clinic = $this->clinicRepo->findByUser($user);
}
if ($clinic === null || !$clinic->hasDoctor($doctor)) {
return null;
}
return $this->clinicPermissions->can($user, $clinic, self::RESOURCE, self::ACTION_VIEW)
? $clinic
: null;
}
/**
* منشی در محیط فعالِ خودش. در محیط کلینیک، نوبت باید هم متعلق به همان کلینیک
* باشد و هم پزشکش جزو پزشکان تخصیص‌یافته به این منشی — عضویت در کلینیک به‌تنهایی
* یعنی منشیِ یک پزشک بتواند نوبت پزشک دیگری را دست‌کاری کند.
*/
private function secretaryCan(Appointment $appointment, User $user, string $action): bool
{
$dbUuid = $this->contextRepo->findByUser($user)?->getDbUuid();
if ($dbUuid === null) {
return false;
}
$clinic = $this->clinicRepo->findByUuid($dbUuid);
if ($clinic !== null) {
if ($appointment->getClinic()?->getId() !== $clinic->getId()) {
return false;
}
$relation = $this->secretaryRepo->findActiveClinicRow($user, $clinic, $appointment->getDoctor());
return $relation !== null && $this->secretaryPermissions->can($relation, self::RESOURCE, $action);
}
$doctor = $this->doctorRepo->findByUuid($dbUuid);
if ($doctor === null || $doctor->getId() !== $appointment->getDoctor()->getId()) {
return false;
}
$relation = $this->secretaryRepo->findActiveBySecretaryForDoctor($user, $doctor);
return $relation !== null && $this->secretaryPermissions->can($relation, self::RESOURCE, $action);
}
}
@@ -3,7 +3,13 @@
namespace App\Appointment\Service;
use App\Appointment\Entity\Appointment;
use App\Appointment\Repository\AppointmentRepository;
use App\Auth\Entity\User;
use App\Patient\Entity\PatientSession;
use App\Patient\Service\PatientService;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Exception\AppException;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
/**
@@ -16,8 +22,10 @@ use Psr\Log\LoggerInterface;
class AppointmentConfirmationService
{
public function __construct(
private readonly PatientService $patientService,
private readonly LoggerInterface $logger,
private readonly PatientService $patientService,
private readonly AppointmentRepository $appointmentRepo,
private readonly EntityManagerInterface $em,
private readonly LoggerInterface $logger,
) {}
/**
@@ -27,20 +35,66 @@ class AppointmentConfirmationService
* رزرو شده و پول پرداخت شده است؛ پرونده را می‌شود با
* `app:appointment:backfill-sessions` ساخت، ولی رول‌بکِ پرداخت برگشت‌ناپذیر است.
*/
public function onConfirmed(Appointment $appointment): void
public function onConfirmed(Appointment $appointment): ?PatientSession
{
// نوبت رزروِ روز-محور اسلات و ساعت مشخص ندارد؛ مراجعهٔ زمان‌دار برایش معنا ندارد.
if ($appointment->isReserve()) {
return;
return null;
}
try {
$this->patientService->autoCreateOnAppointmentConfirm($appointment);
return $this->patientService->autoCreateOnAppointmentConfirm($appointment);
} catch (\Throwable $e) {
$this->logger->error('Auto-creating the patient record on confirm failed', [
'appointment_uuid' => $appointment->getUuid(),
'exception' => $e,
]);
return null;
}
}
/**
* قطعی‌کردنِ صریح از پنل: انتقال وضعیت، ثبت پرونده/مراجعه و ثبت پرداخت‌ها — همه
* در یک تراکنش. برخلاف onConfirmed اینجا شکست خاموش نمی‌ماند: کاربر روبه‌روی
* مودالی ایستاده که مبلغ نشان داده و منتظر تأیید است؛ «قطعی شد ولی پول ثبت نشد»
* بدترین خروجیِ ممکن است.
*
* @param array<int, array{method: string, amount_rials: int}> $payments
* @return PatientSession|null null یعنی این tenant قابلیت پرونده را ندارد
* (فقط وقتی مجاز است که پرداختی هم ارسال نشده باشد)
*/
public function confirmWithPayments(
Appointment $appointment,
int $expectedVersion,
array $payments,
User $actor,
): ?PatientSession {
return $this->em->wrapInTransaction(function () use ($appointment, $expectedVersion, $payments, $actor) {
$appointment->transitionTo(Appointment::STATUS_CONFIRMED);
$this->appointmentRepo->saveWithLock($appointment, $expectedVersion);
$session = $this->patientService->autoCreateOnAppointmentConfirm($appointment);
if ($session === null) {
if ($payments !== []) {
throw new AppException(ErrorCodes::ERR_SUBSCRIPTION_REQUIRED, null, 403);
}
return null;
}
foreach ($payments as $payment) {
$this->patientService->addSessionPayment(
$session,
$payment['method'],
$payment['amount_rials'],
null,
$actor,
);
}
return $session;
});
}
}
+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(