Booking a device is not booking its doctor: the operator runs it and the doctor only supervises. But bookAtomically locked the doctor row and isSlotTaken checked overlap against the doctor alone, ignoring which resource was chosen, so a clinic whose devices share one supervisor could not run two of them at once. Every tenant in the database is in that position — clinic 2's six resources all point at doctor 6. Resource bookings now skip the doctor lock and carry no active_slot_key; their guarantee comes from resource_occupancy, which understands capacity and seats. Both direct paths write occupancy rows the way the hold engine already did, so ResourceBookingSlotService stops being the only thing holding two sources of truth together, and cancelling releases the seat. Occupancy is bucketed in five-minute slices, which is coarser than a booking time: a booking ending 12:35:04 spilled four seconds into the 12:35 bucket and collided with the next one starting at that same second, despite zero real overlap. This surfaced on real rows 76 and 77 during backfill. Resource bookings now snap both ends of their window down to the bucket grid — schedule-driven slots are already aligned, so only manually entered times move. The seat is claimed after persist because it needs the appointment id; losing the race removes the appointment rather than leaving a booking with no device behind it. app:appointment:backfill-resource-occupancy gives existing resource-backed appointments their missing occupancy and clears the doctor keys that no longer mean anything. It reports conflicts between two old bookings instead of picking a loser. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
124 lines
5.0 KiB
PHP
124 lines
5.0 KiB
PHP
<?php
|
|
|
|
namespace App\Appointment\Availability\Service;
|
|
|
|
use App\Appointment\Availability\Entity\ResourceOccupancy;
|
|
use App\Appointment\Booking\Entity\OccupancyBucket;
|
|
use App\Resource\Entity\ClinicResource;
|
|
use App\Shared\Constant\ErrorCodes;
|
|
use App\Shared\Exception\AppException;
|
|
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
|
|
/**
|
|
* گرفتن و آزادکردنِ زمانِ یک منبع — تنها جایی که صندلیها ادعا میشوند.
|
|
*
|
|
* پیش از این فقط مسیر رزرو موقت ردیف اشغال میساخت و مسیرهای مستقیم (پنل و سایت)
|
|
* روی `appointments.resource_id` تکیه میکردند؛ نتیجهاش دو منبعِ حقیقت بود که
|
|
* `ResourceBookingSlotService::busyIntervals` باید دستی با هم جمعشان میکرد، و
|
|
* تضمینِ دیتابیسی فقط پشت یکیشان بود.
|
|
*/
|
|
final class ResourceOccupier
|
|
{
|
|
public function __construct(private readonly EntityManagerInterface $em) {}
|
|
|
|
/**
|
|
* اولین صندلی آزادِ منبع را برای این بازه میگیرد.
|
|
*
|
|
* سطلها با DBAL خام نوشته میشوند نه با ORM: برخورد کلید یکتا در `flush()` خودِ
|
|
* EntityManager را میبندد و تلاش صندلی بعدی هم با «EntityManager is closed»
|
|
* میشکست. با DBAL، استثنا فقط یک استثناست و حلقه ادامه مییابد.
|
|
*
|
|
* @throws AppException ۴۰۹ وقتی همهٔ صندلیها گرفتهاند
|
|
*/
|
|
public function occupy(
|
|
ClinicResource $resource,
|
|
int $startsAt,
|
|
int $endsAt,
|
|
string $status = ResourceOccupancy::STATUS_BOOKED,
|
|
?int $appointmentId = null,
|
|
?int $holdId = null,
|
|
?string $segmentName = null,
|
|
): ResourceOccupancy {
|
|
$buckets = OccupancyBucket::bucketsFor($startsAt, $endsAt);
|
|
$connection = $this->em->getConnection();
|
|
|
|
for ($seat = 0; $seat < $resource->getCapacity(); $seat++) {
|
|
$occupancy = new ResourceOccupancy($resource, $startsAt, $endsAt, $status);
|
|
$occupancy->setSegmentName($segmentName);
|
|
$occupancy->setHoldId($holdId);
|
|
$occupancy->setAppointmentId($appointmentId);
|
|
|
|
$this->em->persist($occupancy);
|
|
$this->em->flush();
|
|
|
|
try {
|
|
foreach ($buckets as $bucketAt) {
|
|
$connection->insert('resource_occupancy_buckets', [
|
|
'resource_id' => $resource->getId(),
|
|
'occupancy_id' => $occupancy->getId(),
|
|
'bucket_at' => $bucketAt,
|
|
'seat' => $seat,
|
|
]);
|
|
}
|
|
|
|
return $occupancy;
|
|
} catch (UniqueConstraintViolationException) {
|
|
// این صندلی همین حالا گرفته شد. سطلهای نیمهنوشته و خودِ ردیف اشغال
|
|
// پاک میشوند تا صندلی بعدی از صفر شروع کند.
|
|
$connection->delete('resource_occupancy_buckets', ['occupancy_id' => $occupancy->getId()]);
|
|
$this->em->remove($occupancy);
|
|
$this->em->flush();
|
|
}
|
|
}
|
|
|
|
throw new AppException(
|
|
ErrorCodes::ERR_SLOT_TAKEN,
|
|
sprintf('«%s» در این زمان آزاد نیست', $resource->getName()),
|
|
409,
|
|
'resource_uuid',
|
|
);
|
|
}
|
|
|
|
/**
|
|
* آزادسازی: وضعیت `released` و پاک کردن سطلها.
|
|
*
|
|
* خودِ ردیف اشغال میماند چون تاریخچهٔ بهرهوری است؛ ولی سطلها باید بروند وگرنه
|
|
* کلید یکتا آن زمان را برای همیشه قفل نگه میدارد.
|
|
*
|
|
* @param iterable<ResourceOccupancy> $occupancies
|
|
*/
|
|
public function release(iterable $occupancies): void
|
|
{
|
|
$connection = $this->em->getConnection();
|
|
$released = false;
|
|
|
|
foreach ($occupancies as $occupancy) {
|
|
$connection->delete('resource_occupancy_buckets', ['occupancy_id' => $occupancy->getId()]);
|
|
$occupancy->markReleased();
|
|
$released = true;
|
|
}
|
|
|
|
if ($released) {
|
|
$this->em->flush();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* آزادکردنِ هرچه این نوبت گرفته بود — هنگام لغو، انقضا یا جابهجایی.
|
|
*
|
|
* @return int تعداد ردیفهای آزادشده
|
|
*/
|
|
public function releaseForAppointment(int $appointmentId): int
|
|
{
|
|
$occupancies = $this->em->getRepository(ResourceOccupancy::class)->findBy([
|
|
'appointmentId' => $appointmentId,
|
|
'status' => ResourceOccupancy::BLOCKING_STATUSES,
|
|
]);
|
|
|
|
$this->release($occupancies);
|
|
|
|
return count($occupancies);
|
|
}
|
|
}
|