Files
clinicpro/tests/Appointment/BookingLocationValidityTest.php
hamedandClaude Opus 5 d53874ff50 feat(tenant): mark the booking tables with their owning environment
Phase 2 of the tenant-marking series. appointments, weekly_schedules and
date_overrides kept their environment implicit in a nullable clinic_id, so
every query that wanted "this environment's rows" had to rebuild
clinic_id IS NULL ? doctor : clinic itself. The two calendar tables also
depended on a MariaDB-only generated column, clinic_key = IFNULL(clinic_id, 0),
purely to make a unique key work across NULLs.

All three now carry the (entity_type, entity_id) pair that service_sections,
patient_records and clinic_staff already use, via a shared TenantOwnedTrait.
The pair is a deliberate denormalisation of clinic_id/doctor_id: the automatic
tenant filter and the tenant-leading indexes both need a real column, and
neither can be built on an IF() expression.

- Unique keys keep doctor_id alongside the pair. A clinic has several doctors
  and each has their own schedule, so (entity_type, entity_id) alone would
  reject the second doctor.
- clinic_key is gone from both calendar tables.
- appointments gained tenant-leading indexes; EXPLAIN on the panel's list query
  now picks idx_appointments_tenant_slot.

Deliberately unchanged, both with the reason already recorded in the code:
active_slot_key stays keyed on doctor + slot, since adding the environment
would let one doctor be booked in their own practice and a clinic at the same
moment. holidays keeps its nullable clinic_id, where NULL means "every
environment" rather than "personal practice" — a meaning the pair cannot carry.

The migration adds the columns nullable, backfills, aborts if any row is left
without an owner, and only then tightens to NOT NULL. It creates each
replacement unique index before dropping the old one, so the tables are never
left unprotected — MariaDB commits implicitly on DDL, so ordering is the only
safety net. It runs its statements through the connection rather than addSql()
because the guard has to sit between the backfill and the NOT NULL change.

Columns are NOT NULL with no default on purpose: a construction site that
forgets assignTenant() fails at flush instead of silently writing entity_id 0,
which the phase 4 filter would then hide from everyone.

Verified on the dev database: 0 rows without a tenant, 0 personal bookings
mismatched against their doctor, 0 clinic bookings mismatched against their
clinic.

Tests: 819 passing (813 + 6 new in BookingTenantTest). PHPStan clean on every
changed file.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 11:22:37 +03:30

199 lines
7.6 KiB
PHP

<?php
namespace App\Tests\Appointment;
use App\Appointment\Entity\WeeklySchedule;
use App\Clinic\Entity\Clinic;
use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorAddress;
use App\Tests\ApiTestCase;
/**
* یک «محل نوبت‌دهی» فقط وقتی وجود دارد که هم آدرس داشته باشد و هم شیفتی روی همان
* آدرس. برنامه‌ای که به آدرسِ محیط دیگر (یا هیچ آدرسی) اشاره می‌کند قابل رزرو
* نیست و نباید به بیمار پیشنهاد شود.
*
* همچنین خالی‌بودن یک روز چهار دلیل متفاوت دارد و پنل باید بتواند تفکیکشان کند.
*/
class BookingLocationValidityTest extends ApiTestCase
{
private function makeDoctor(): Doctor
{
$user = $this->createUser(['ROLE_USER', 'ROLE_DOCTOR']);
$doctor = new Doctor($user, 'دکتر محل');
$doctor->setMobileNumber($user->getMobileNumber());
$this->em->persist($doctor);
$this->em->flush();
return $doctor;
}
private function makeClinicWith(Doctor $doctor): Clinic
{
$clinic = new Clinic($this->createUser(['ROLE_USER', 'ROLE_CLINIC']));
$clinic->setName('کلینیک محل');
$clinic->getDoctors()->add($doctor);
$this->em->persist($clinic);
$this->em->flush();
return $clinic;
}
/** برنامه‌ای که همهٔ روزها یک شیفت روی $locationId دارد. */
private function scheduleFor(Doctor $doctor, ?Clinic $clinic, ?int $locationId): WeeklySchedule
{
$day = ['sessions' => [array_filter([
'active' => true,
'location_id' => $locationId,
'start_time' => '09:00',
'end_time' => '13:00',
'duration_per_patient' => 20,
], fn($v) => $v !== null)]];
$schedule = $this->newWeeklySchedule(
$doctor,
array_fill_keys(array_map('strval', range(0, 6)), $day),
$clinic
);
$this->em->persist($schedule);
$this->em->flush();
return $schedule;
}
private function locations(Doctor $doctor, string $query = ''): array
{
$body = $this->authJson(
'GET',
'/api/v1/appointment-booking-locations/' . $doctor->getUuid() . $query,
$doctor->getUser()
);
return $body['data']['booking_locations'] ?? [];
}
public function testLocationWithoutAnyAddressIsNotReturned(): void
{
$doctor = $this->makeDoctor();
$this->scheduleFor($doctor, null, null);
self::assertSame([], $this->locations($doctor), 'محلی که آدرس ندارد نباید محل به حساب بیاید');
}
public function testLocationWhoseShiftsPointOutsideItsContextIsNotReturned(): void
{
$doctor = $this->makeDoctor();
$clinic = $this->makeClinicWith($doctor);
$clinicAddress = DoctorAddress::forClinic($clinic->getId());
$personal = DoctorAddress::forDoctor($doctor);
$this->em->persist($clinicAddress);
$this->em->persist($personal);
$this->em->flush();
// برنامهٔ شخصی که شیفتش روی آدرس کلینیک نشسته — دقیقاً حالتی که در dev دیده شد.
$this->scheduleFor($doctor, null, $clinicAddress->getId());
self::assertSame([], $this->locations($doctor));
}
public function testValidLocationIsReturnedWithItsOpeningHours(): void
{
$doctor = $this->makeDoctor();
$address = DoctorAddress::forDoctor($doctor);
$this->em->persist($address);
$this->em->flush();
$this->scheduleFor($doctor, null, $address->getId());
$locations = $this->locations($doctor);
self::assertCount(1, $locations);
self::assertSame('personal', $locations[0]['type']);
self::assertSame($address->getUuid(), $locations[0]['location_uuid']);
self::assertCount(7, $locations[0]['opening_hours']);
self::assertSame($address->getId(), $locations[0]['opening_hours'][0]['location_id']);
}
public function testDateParameterReportsPerDayAvailability(): void
{
$doctor = $this->makeDoctor();
$address = DoctorAddress::forDoctor($doctor);
$this->em->persist($address);
$this->em->flush();
// فقط شنبه (اندیس 0) شیفت فعال دارد.
$active = ['sessions' => [[
'active' => true, 'location_id' => $address->getId(),
'start_time' => '09:00', 'end_time' => '13:00', 'duration_per_patient' => 20,
]]];
$setting = array_fill_keys(array_map('strval', range(0, 6)), ['sessions' => []]);
$setting['0'] = $active;
$this->em->persist($this->newWeeklySchedule($doctor, $setting));
$this->em->flush();
$saturday = $this->nextWeekday(6); // date('w'): 6 = Saturday
$sunday = $this->nextWeekday(0);
$onSaturday = $this->locations($doctor, '?date=' . $saturday);
$onSunday = $this->locations($doctor, '?date=' . $sunday);
self::assertTrue($onSaturday[0]['available_on_date'] ?? null);
self::assertFalse($onSunday[0]['available_on_date'] ?? null);
}
public function testInvalidDateIsRejected(): void
{
$doctor = $this->makeDoctor();
$this->authJson('GET', '/api/v1/appointment-booking-locations/' . $doctor->getUuid() . '?date=2026-13-99', $doctor->getUser());
self::assertSame(422, $this->responseCode());
}
public function testEmptyReasonDistinguishesTheCauses(): void
{
$doctor = $this->makeDoctor();
$today = date('Y-m-d');
// بدون هیچ برنامه‌ای
$body = $this->authJson('GET', "/api/v1/appointment-slots?doctor_uuid={$doctor->getUuid()}&date={$today}", $doctor->getUser());
self::assertSame('no_schedule', $body['data']['empty_reason'] ?? null);
// برنامه هست ولی این روز شیفت ندارد
$address = DoctorAddress::forDoctor($doctor);
$this->em->persist($address);
$this->em->flush();
$setting = array_fill_keys(array_map('strval', range(0, 6)), ['sessions' => []]);
$this->em->persist($this->newWeeklySchedule($doctor, $setting));
$this->em->flush();
$body = $this->authJson('GET', "/api/v1/appointment-slots?doctor_uuid={$doctor->getUuid()}&date={$today}", $doctor->getUser());
self::assertSame('day_off', $body['data']['empty_reason'] ?? null);
// تاریخ خارج از بازهٔ نوبت‌دهی
$farFuture = date('Y-m-d', strtotime('+2 years'));
$body = $this->authJson('GET', "/api/v1/appointment-slots?doctor_uuid={$doctor->getUuid()}&date={$farFuture}", $doctor->getUser());
self::assertSame('outside_window', $body['data']['empty_reason'] ?? null);
}
/**
* اولین وقوعِ آن روز هفته در آینده. از فردا شروع می‌شود چون شیفت‌های امروز
* ممکن است گذشته باشند و getAvailableSlots اسلات گذشته را برنمی‌گرداند —
* وگرنه تست بسته به ساعت اجرا نتیجهٔ متفاوت می‌دهد.
*
* @param int $phpDow خروجی date('w') — 0=یکشنبه ... 6=شنبه
*/
private function nextWeekday(int $phpDow): string
{
for ($i = 1; $i <= 7; $i++) {
$ts = strtotime("+{$i} day");
if ((int) date('w', $ts) === $phpDow) {
return date('Y-m-d', $ts);
}
}
return date('Y-m-d');
}
}