feat(booking): multi-resource holds and confirmation with a database-level guarantee

Section 11 and the third closing rule of the design document: preventing a double
booking is the database's job, not the code's. Any "is it free?" check in PHP has a
race window between the read and the write — two concurrent requests both see free
and both write.

MariaDB has no range EXCLUDE constraint, so every occupied interval is broken into
fixed five-minute buckets under UNIQUE(resource_id, bucket_at, seat). The code only
INSERTs; a rejection from the database *is* the answer. `seat` carries capacity: a
three-bed room has seats 0..2, allocation walks upward on each collision, and the
fourth concurrent hold finds nowhere to sit. Counting capacity in PHP would have
rebuilt the very race this removes.

Buckets are written through DBAL rather than the ORM on purpose: a unique violation
raised inside flush() closes the EntityManager, and the next seat attempt would then
fail with "EntityManager is closed", hiding the real outcome.

Occupancy is one row per (segment × resource). The reference test asserts the payoff
directly: for a 55-minute appointment of numbing / waiting / laser, the room gets
three rows and the operator only two — the operator holds nothing during the wait and
stays bookable for someone else.

A partial hold never survives. If the second resource has no room, the first is
released and the hold itself removed; otherwise a resource stays locked for an
appointment that will never exist.

Confirming does not re-reserve anything — the seats were taken at hold time and only
the label changes. Re-reserving on confirm would reopen the race the hold closed.
Cancelling marks rows `released` instead of deleting them, because the history of
which resource was busy when is the input to the utilisation reports; the uniqueness
buckets *are* deleted, or that interval would stay locked forever.

Expired holds are released by the existing scheduler rather than a new one. That
exposed a bug in my own change: the flush guard used $count, which now includes
released holds, so reset([]) could pass false to save(). It is guarded on $expired.

The appointment itself is still built with the existing constructor, so
active_slot_key, events and the payment path behave exactly as before — the
multi-resource occupancy sits beside them, not instead of them.

12 tests. Two matter most: the second hold on the same resource and interval getting
409, and a test that writes a duplicate bucket row over a *separate connection* and
expects the unique-key violation — if that one ever passes silently, the guarantee
had moved back into the code.

1208 tests / 3495 assertions. phpstan at its 14-error baseline. Frozen slot contract
green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-31 09:28:55 +03:30
co-authored by Claude Opus 5
parent 5d93208383
commit 4395eea56e
18 changed files with 1848 additions and 77 deletions
@@ -0,0 +1,110 @@
<?php
namespace App\Appointment\Booking\Service;
use App\Appointment\Availability\Entity\ResourceOccupancy;
use App\Appointment\Booking\Entity\AppointmentHold;
use App\Appointment\Booking\Entity\AppointmentSegment;
use App\Appointment\Entity\Appointment;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Exception\AppException;
use Doctrine\ORM\EntityManagerInterface;
/**
* ثبت نهایی از یک رزرو موقت، و آزادسازی هنگام لغو.
*
* تبدیل `hold → booked` هیچ منبعی را دوباره نمی‌گیرد: صندلی‌ها از لحظهٔ رزرو موقت
* گرفته شده‌اند و اینجا فقط برچسبشان عوض می‌شود. اگر ثبت نهایی دوباره رزرو می‌کرد،
* همان پنجرهٔ مسابقه‌ای که hold حذفش کرده بود برمی‌گشت.
*/
final class BookingService
{
public function __construct(
private readonly HoldService $holds,
private readonly EntityManagerInterface $em,
) {}
/**
* @throws AppException ۴۰۹ روی رزروِ منقضی یا ثبت‌شده
*/
public function confirm(AppointmentHold $hold, Appointment $appointment, ?int $now = null): Appointment
{
$now = $now ?? time();
if ($hold->isConfirmed()) {
throw new AppException(ErrorCodes::ERR_SLOT_TAKEN, 'این رزرو قبلاً ثبت شده است', 409);
}
if ($hold->isExpired($now)) {
throw new AppException(ErrorCodes::ERR_HOLD_EXPIRED, 'مهلت رزرو موقت تمام شده است', 409);
}
$occupancies = $this->holds->occupanciesOfHold($hold);
if ($occupancies === []) {
throw new AppException(ErrorCodes::ERR_HOLD_EXPIRED, 'رزرو موقت دیگر معتبر نیست', 409);
}
foreach ($occupancies as $occupancy) {
$occupancy->markBooked()->setAppointmentId($appointment->getId());
}
$this->writeSegments($hold, $appointment);
$hold->markConfirmed($now);
$this->em->flush();
return $appointment;
}
/**
* بخش‌های نوبت از همان `payload` رزرو ساخته می‌شوند، نه از الگوی امروزِ سرویس:
* الگو ممکن است بین رزرو و ثبت عوض شده باشد و نوبت باید همان چیزی بماند که کاربر
* دیده و پذیرفته.
*/
private function writeSegments(AppointmentHold $hold, Appointment $appointment): void
{
$segments = $hold->getPayload()['plan']['segments'] ?? [];
foreach ($segments as $segment) {
$start = $hold->getStartsAt() + (int) ($segment['offset_minutes'] ?? 0) * 60;
$end = $start + (int) ($segment['duration_minutes'] ?? 0) * 60;
if ($end <= $start) {
continue;
}
$this->em->persist(new AppointmentSegment(
$appointment,
(int) ($segment['sequence'] ?? 1),
(string) ($segment['name'] ?? '—'),
$start,
$end,
(bool) ($segment['patient_present'] ?? true),
));
}
}
/**
* لغو: ردیف‌های اشغال `released` می‌شوند، **حذف فیزیکی نمی‌شوند**.
* تاریخچه ورودی گزارش بهره‌وری است.
*/
public function cancel(Appointment $appointment): int
{
$occupancies = $this->em->getRepository(ResourceOccupancy::class)
->findBy(['appointmentId' => $appointment->getId()]);
$this->holds->release($occupancies);
return count($occupancies);
}
/** رزروِ منقضی: همان آزادسازی، ولی از سمت رزرو موقت. */
public function releaseHold(AppointmentHold $hold): int
{
$occupancies = $this->holds->occupanciesOfHold($hold);
$this->holds->release($occupancies);
return count($occupancies);
}
}