feat(resource): ad-hoc blocking, 409 recovery, and the rest of the flake

Ad-hoc resource blocking
- "The laser is being serviced this afternoon" is a specific range, not a change
  to the resource's working pattern. It stays separate from calendar exceptions
  and the modal says which is which — merging them means either an afternoon's
  closure lives in the calendar forever, or a change to working hours vanishes
  with one click
- Blocking a range that already holds an appointment is refused with 409 rather
  than silently taking capacity back; the appointment is still there and someone
  has to decide about it first
- Deleting an occupancy that belongs to an appointment is refused too, otherwise
  a patient's booking would quietly lose its resource with no record

409 on hold now recovers
Saying "someone just took it" is not enough — the operator would have to search
again by hand. The page drops the stale selection and refetches, so alternatives
are on screen immediately.

Flake, second half
The earlier fix only covered createUser's retry path. Any test that trips a
unique constraint closes the EntityManager, and the next test inherits the same
closed instance from the container. setUp now resets the registry when it finds
a closed manager, so a test's starting state no longer depends on how the
previous one failed.

Three consecutive full runs green: 1340 tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-31 20:50:43 +03:30
co-authored by Claude Opus 5
parent 3dcc7c2ec0
commit 0127b463a6
10 changed files with 639 additions and 11 deletions
@@ -41,7 +41,6 @@ class AvailabilityController extends BaseController
private readonly DoctorRepository $doctors,
private readonly BranchResolver $branches,
private readonly \App\Course\Repository\TreatmentCourseRepository $courses,
private readonly \App\Appointment\Availability\Picker\ResourcePickerRegistry $pickers,
) {}
#[Route('/api/v1/appointment-availability', name: 'appointment_availability', methods: ['POST'])]
@@ -0,0 +1,140 @@
<?php
namespace App\Appointment\Availability\Controller;
use App\Appointment\Availability\Entity\ResourceOccupancy;
use App\Appointment\Availability\Repository\ResourceOccupancyRepository;
use App\Auth\Entity\User;
use App\Branch\Service\BranchResolver;
use App\Resource\Entity\ClinicResource;
use App\Resource\Repository\ClinicResourceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
use App\Shared\Tenant\TenantOwnershipChecker;
use Doctrine\ORM\EntityManagerInterface;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
/**
* مسدودسازی **موردی** یک منبع — «این بعدازظهر دستگاه سرویس دارد».
*
* با «استثنای بلندمدت» (`resource-exception`) فرق دارد و عمداً جدا مانده:
*
* | | مسدودسازی موردی | استثنای تقویم |
* |---|---|---|
* | چیست | یک بازهٔ مشخص که منبع در دسترس نیست | تغییر الگوی تکرارشوندهٔ کاری |
* | کجا ذخیره می‌شود | `resource_occupancy` | `resource_exceptions` |
* | چقدر می‌ماند | تا وقتی حذفش کنی | بخشی از تعریف تقویم |
*
* ادغامشان یعنی یا تعطیلی یک بعدازظهر برای همیشه در تقویم بماند، یا تغییر ساعت کاری
* با یک کلیک ناپدید شود.
*/
#[OA\Tag(name: 'Resource')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class ResourceBlockController extends BaseController
{
public function __construct(
private readonly ClinicResourceRepository $resources,
private readonly ResourceOccupancyRepository $occupancy,
private readonly BranchResolver $branches,
private readonly TenantOwnershipChecker $ownership,
private readonly EntityManagerInterface $em,
) {}
#[Route('/api/v1/resource/{uuid}/blocks', name: 'resource_blocks_list', methods: ['GET'])]
public function index(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$resource = $this->requireResource($user, $uuid);
$from = $request->query->has('from') ? $request->query->getInt('from') : time();
$to = $request->query->has('to') ? $request->query->getInt('to') : $from + 30 * 86400;
return $this->success(array_map(
static fn (ResourceOccupancy $o): array => $o->toArray(),
$this->occupancy->findManualBlocks((int) $resource->getId(), $from, $to),
));
}
#[Route('/api/v1/resource/{uuid}/blocks', name: 'resource_block_create', methods: ['POST'])]
public function create(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$resource = $this->requireResource($user, $uuid);
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_numeric($data['starts_at'] ?? null) || !is_numeric($data['ends_at'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بازهٔ مسدودسازی الزامی است', 422, 'starts_at');
}
$startsAt = (int) $data['starts_at'];
$endsAt = (int) $data['ends_at'];
if ($endsAt <= $startsAt) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پایان بازه باید بعد از شروع آن باشد', 422, 'ends_at');
}
// مسدودسازی روی بازه‌ای که نوبت دارد، ظرفیت را پس نمی‌گیرد — نوبت همچنان سرجایش
// است و کاربر باید اول تکلیفش را روشن کند.
if ($this->occupancy->hasAppointmentInRange((int) $resource->getId(), $startsAt, $endsAt)) {
return $this->error(
ErrorCodes::ERR_SLOT_TAKEN,
'در این بازه نوبت ثبت‌شده وجود دارد؛ اول آن را جابه‌جا یا لغو کنید',
409,
);
}
$block = new ResourceOccupancy($resource, $startsAt, $endsAt, ResourceOccupancy::STATUS_BOOKED);
$block->setSegmentName(
is_string($data['reason'] ?? null) && trim($data['reason']) !== ''
? trim($data['reason'])
: 'مسدودسازی دستی',
);
$this->em->persist($block);
$this->em->flush();
return $this->success($block->toArray(), 201);
}
#[Route('/api/v1/resource-block/{uuid}', name: 'resource_block_delete', methods: ['DELETE'])]
public function delete(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$block = $this->occupancy->findOneBy(['uuid' => $uuid]);
[$entityType, $entityId] = $this->branches->pair($user);
if ($block === null || !$this->ownership->belongsToPair($entityType, $entityId, $block)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'مسدودسازی یافت نشد', 404);
}
// اشغالِ یک نوبت واقعی از اینجا حذف نمی‌شود؛ وگرنه نوبت بیمار بی‌صدا منبعش را
// از دست می‌دهد و هیچ‌جا هم ثبت نمی‌شود.
if ($block->getAppointmentId() !== null || $block->getHoldId() !== null) {
return $this->error(
ErrorCodes::ERR_VALIDATION_001,
'این اشغال متعلق به یک نوبت است و از اینجا حذف نمی‌شود',
422,
);
}
$this->em->remove($block);
$this->em->flush();
return $this->success(null);
}
private function requireResource(User $user, string $uuid): ClinicResource
{
$resource = $this->resources->findOneBy(['uuid' => $uuid]);
[$entityType, $entityId] = $this->branches->pair($user);
if ($resource === null || !$this->ownership->belongsToPair($entityType, $entityId, $resource)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'منبع یافت نشد', 404);
}
return $resource;
}
}
@@ -57,6 +57,55 @@ class ResourceOccupancyRepository extends ServiceEntityRepository
}
/** @return ResourceOccupancy[] */
/**
* آیا در این بازه نوبت یا رزرو موقتی روی این منبع هست؟
*
* فقط ردیف‌هایی که به نوبت یا hold وصل‌اند؛ مسدودسازی دستیِ دیگر مانع نیست —
* دو بازهٔ سرویس دستگاه می‌توانند هم‌پوشان باشند و آن مشکلی نیست.
*/
public function hasAppointmentInRange(int $resourceId, int $from, int $to): bool
{
return (int) $this->createQueryBuilder('o')
->select('COUNT(o.id)')
->where('IDENTITY(o.resource) = :resource')
->andWhere('o.appointmentId IS NOT NULL OR o.holdId IS NOT NULL')
->andWhere('o.status IN (:blocking)')
->andWhere('o.startsAt < :to')
->andWhere('o.endsAt > :from')
->setParameter('resource', $resourceId)
->setParameter('blocking', ResourceOccupancy::BLOCKING_STATUSES)
->setParameter('from', $from)
->setParameter('to', $to)
->getQuery()
->getSingleScalarResult() > 0;
}
/**
* مسدودسازی‌های دستیِ یک منبع در یک بازه.
*
* فقط ردیف‌های بدون نوبت: بقیه اشغالِ رزرو واقعی‌اند و از صفحهٔ منابع مدیریت
* نمی‌شوند — حذفشان از آنجا یعنی نوبت بیمار بی‌صدا منبعش را از دست بدهد.
*
* @return ResourceOccupancy[]
*/
public function findManualBlocks(int $resourceId, int $from, int $to): array
{
return $this->createQueryBuilder('o')
->where('IDENTITY(o.resource) = :resource')
->andWhere('o.appointmentId IS NULL')
->andWhere('o.holdId IS NULL')
->andWhere('o.status IN (:blocking)')
->andWhere('o.startsAt < :to')
->andWhere('o.endsAt > :from')
->setParameter('resource', $resourceId)
->setParameter('blocking', ResourceOccupancy::BLOCKING_STATUSES)
->setParameter('from', $from)
->setParameter('to', $to)
->orderBy('o.startsAt', 'ASC')
->getQuery()
->getResult();
}
public function findForAppointment(int $appointmentId): array
{
return $this->findBy(['appointmentId' => $appointmentId]);
@@ -261,7 +261,7 @@ final class AvailabilityEngine
// استراتژی فقط **ترتیب** را تعیین می‌کند؛ شرط جا داشتن و برداشته‌نشدن
// همچنان اینجاست، چون فقط موتور هر دو را می‌داند.
$ordered = $picker->order(
array_values($requirement->eligible),
$requirement->eligible,
new PickContext($free, $needed, $start, $preferredResourceIds),
);