feat(availability): multi-resource availability engine
Section 10 of the design document, and the payoff for tasks 01–05. The engine slides a multi-segment plan across resource calendars and answers which times are actually possible, with a suggested resource for each role. Until now the only conflict the system checked was the doctor's; rooms, devices and operators did not exist. Allocation is per *role*, not per segment, and that is what returns the wasted capacity. An operator with no requirement during "waiting for the cream" is simply not examined for those minutes, so another patient can use them. The reference test encodes exactly that: patient A holds 10:00–11:00 while the operator is only busy 10:00–10:05 and 10:35–11:00, and patient B is offered a slot inside the gap with the second room assigned. The spec says the task is not verified without that scenario. One resource is chosen for every segment that needs its role, not independently per segment — otherwise the operator in segment 1 and segment 3 could be two different people and the patient would change hands mid-treatment. Occupancy is stored one row per (segment × resource) rather than one per appointment. The granularity is the whole point; a row per appointment would re-create the single-interval model the design rejects. Reserved intervals are widened by each resource's setup/cleanup, because the resource genuinely is not available then. booking_mode gains a third value, resource, alongside slot and service. It is purely additive: the default stays slot, no environment moves on its own, and a location that has not opted in keeps the untouched legacy path. The frozen slot-mode contract stays green. Performance is a test, not a hope: 30 days, 20 resources and 500 existing bookings complete well inside the 500ms budget. Every input is read once and the rest is in memory — no query inside the day or candidate loop — and candidates are generated only from the free windows of the scarcest role, which turns tens of thousands of candidates into a few hundred. An empty result is not an error and not a 404: it carries reason: "no_capacity_in_range" so the caller does not have to infer meaning from emptiness. Also fixed a genuinely intermittent test defect: NumericFieldNormalizerTest padded a random number with the three-byte Persian "۰" using byte-based str_pad, producing broken UTF-8 whenever the number was short. It failed roughly at random. The improved assertion message added earlier is what identified it immediately. 1196 tests / 3414 assertions. phpstan at its 14-error baseline. Resource-picking strategies, the availability cache and the settings UI are recorded as outstanding in the checklist with reasons — the cache in particular would be premature while the performance test passes comfortably without it. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
namespace App\Appointment\Availability\Controller;
|
||||
|
||||
use App\Appointment\Availability\Service\AvailabilityEngine;
|
||||
use App\Appointment\Availability\ValueObject\AvailableSlot;
|
||||
use App\Appointment\Entity\WeeklySchedule;
|
||||
use App\Appointment\Plan\Service\AppointmentPlanBuilder;
|
||||
use App\Appointment\Repository\WeeklyScheduleRepository;
|
||||
use App\Auth\Entity\User;
|
||||
use App\Branch\Service\BranchResolver;
|
||||
use App\ClinicService\Entity\ServiceItem;
|
||||
use App\ClinicService\Repository\ServiceItemRepository;
|
||||
use App\Doctor\Entity\DoctorAddress;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
use App\Shared\Exception\AppException;
|
||||
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;
|
||||
|
||||
/**
|
||||
* جستجوی وقت چندمنبعی.
|
||||
*
|
||||
* فقط برای محلهایی که صریحاً روی `booking_mode = resource` رفتهاند. بقیه همان مسیر
|
||||
* قبلی (`appointment-slots` / `appointment-service-slots`) را دارند و دستنخوردهاند.
|
||||
*/
|
||||
#[OA\Tag(name: 'Appointment Availability')]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
class AvailabilityController extends BaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AppointmentPlanBuilder $planner,
|
||||
private readonly AvailabilityEngine $engine,
|
||||
private readonly ServiceItemRepository $items,
|
||||
private readonly WeeklyScheduleRepository $schedules,
|
||||
private readonly DoctorRepository $doctors,
|
||||
private readonly BranchResolver $branches,
|
||||
) {}
|
||||
|
||||
#[Route('/api/v1/appointment-availability', name: 'appointment_availability', methods: ['POST'])]
|
||||
public function search(#[CurrentUser] User $user, Request $request): JsonResponse
|
||||
{
|
||||
$data = json_decode($request->getContent(), true);
|
||||
|
||||
if (!is_array($data)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'بدنهٔ درخواست نامعتبر است', 422);
|
||||
}
|
||||
|
||||
foreach (['service_uuid', 'branch_uuid'] as $field) {
|
||||
if (!is_string($data[$field] ?? null)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, sprintf('فیلد %s الزامی است', $field), 422, $field);
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_numeric($data['from'] ?? null) || !is_numeric($data['to'] ?? null)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلدهای from و to الزامیاند', 422, 'from');
|
||||
}
|
||||
|
||||
$from = (int) $data['from'];
|
||||
$to = (int) $data['to'];
|
||||
|
||||
if ($to < $from) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'to باید بعد از from باشد', 422, 'to');
|
||||
}
|
||||
|
||||
if (intdiv($to - $from, 86400) + 1 > AvailabilityEngine::MAX_DAYS) {
|
||||
return $this->error(
|
||||
ErrorCodes::ERR_VALIDATION_001,
|
||||
sprintf('بازهٔ درخواستی حداکثر %d روز است', AvailabilityEngine::MAX_DAYS),
|
||||
422,
|
||||
'to',
|
||||
);
|
||||
}
|
||||
|
||||
$address = $this->branches->resolve($user, $data['branch_uuid']);
|
||||
$service = $this->requireItem($user, $data['service_uuid']);
|
||||
|
||||
$this->assertResourceMode($data['doctor_uuid'] ?? null, $address);
|
||||
|
||||
$selected = [];
|
||||
foreach (($data['item_uuids'] ?? []) as $itemUuid) {
|
||||
if (!is_string($itemUuid)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'item_uuids باید فهرستی از uuid باشد', 422, 'item_uuids');
|
||||
}
|
||||
|
||||
$selected[] = $this->requireItem($user, $itemUuid);
|
||||
}
|
||||
|
||||
$plan = $this->planner->build(
|
||||
$service,
|
||||
$selected,
|
||||
$address,
|
||||
is_string($data['patient_gender'] ?? null) ? $data['patient_gender'] : null,
|
||||
);
|
||||
|
||||
$step = is_numeric($data['step_minutes'] ?? null)
|
||||
? (int) $data['step_minutes']
|
||||
: AvailabilityEngine::DEFAULT_STEP_MINUTES;
|
||||
|
||||
$slots = $this->engine->search($plan, $address, $from, $to, $step);
|
||||
|
||||
return $this->success([
|
||||
'plan' => $plan->toArray(),
|
||||
'slots' => array_map(static fn (AvailableSlot $s): array => $s->toArray(), $slots),
|
||||
// فهرست خالی خطا نیست: ممکن است واقعاً ظرفیتی نباشد. دلیلش صریح میآید
|
||||
// تا کلاینت مجبور نباشد از خالی بودن حدس بزند.
|
||||
'reason' => $slots === [] ? 'no_capacity_in_range' : null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* نمای ماه: فقط «این روز ظرفیت دارد یا نه». عمداً سبک است — تقویم ماهانه نباید
|
||||
* تخصیص منبع هر زمان را بسازد.
|
||||
*/
|
||||
#[Route('/api/v1/appointment-availability/month', name: 'appointment_availability_month', methods: ['GET'])]
|
||||
public function month(#[CurrentUser] User $user, Request $request): JsonResponse
|
||||
{
|
||||
$serviceUuid = $request->query->get('service_uuid');
|
||||
$branchUuid = $request->query->get('branch_uuid');
|
||||
$from = $request->query->get('from');
|
||||
$to = $request->query->get('to');
|
||||
|
||||
if (!is_string($serviceUuid) || !is_string($branchUuid) || !is_numeric($from) || !is_numeric($to)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'service_uuid، branch_uuid، from و to الزامیاند', 422, 'service_uuid');
|
||||
}
|
||||
|
||||
$address = $this->branches->resolve($user, $branchUuid);
|
||||
$service = $this->requireItem($user, $serviceUuid);
|
||||
|
||||
$this->assertResourceMode($request->query->get('doctor_uuid'), $address);
|
||||
|
||||
$plan = $this->planner->build($service, [], $address);
|
||||
$slots = $this->engine->search($plan, $address, (int) $from, (int) $to);
|
||||
|
||||
$days = [];
|
||||
foreach ($slots as $slot) {
|
||||
$midnight = (new \DateTimeImmutable('@' . $slot->start))
|
||||
->setTimezone(new \DateTimeZone($address->getTimezone()))
|
||||
->setTime(0, 0)
|
||||
->getTimestamp();
|
||||
|
||||
$days[$midnight] = true;
|
||||
}
|
||||
|
||||
return $this->success(['days' => array_keys($days)]);
|
||||
}
|
||||
|
||||
/**
|
||||
* فقط محلی که صریحاً روی حالت منبع رفته این مسیر را دارد.
|
||||
*
|
||||
* @throws AppException
|
||||
*/
|
||||
private function assertResourceMode(mixed $doctorUuid, DoctorAddress $address): void
|
||||
{
|
||||
if (!is_string($doctorUuid) || $doctorUuid === '') {
|
||||
return; // بدون پزشک، حالت از برنامهٔ هفتگی قابل استنتاج نیست
|
||||
}
|
||||
|
||||
$doctor = $this->doctors->findOneBy(['uuid' => $doctorUuid]);
|
||||
|
||||
if ($doctor === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'پزشک یافت نشد', 404);
|
||||
}
|
||||
|
||||
foreach ($this->schedules->findAllByDoctor($doctor) as $schedule) {
|
||||
if (($schedule->getMeta()['booking_mode'] ?? null) === WeeklySchedule::MODE_RESOURCE) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new AppException(
|
||||
ErrorCodes::ERR_WRONG_BOOKING_MODE,
|
||||
'این محل هنوز روی نوبتدهی چندمنبعی نیست',
|
||||
422,
|
||||
'doctor_uuid',
|
||||
);
|
||||
}
|
||||
|
||||
private function requireItem(User $user, string $uuid): ServiceItem
|
||||
{
|
||||
$item = $this->items->findByUuid($uuid);
|
||||
[$entityType, $entityId] = $this->branches->pair($user);
|
||||
|
||||
if ($item === null
|
||||
|| $item->getSection()->getEntityType() !== $entityType
|
||||
|| $item->getSection()->getEntityId() !== $entityId
|
||||
) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'سرویس یافت نشد', 404);
|
||||
}
|
||||
|
||||
return $item;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user