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:
hamed
2026-07-30 21:21:33 +03:30
co-authored by Claude Opus 5
parent 7cca433c56
commit 24534ec483
15 changed files with 1496 additions and 82 deletions
@@ -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;
}
}
@@ -0,0 +1,113 @@
<?php
namespace App\Appointment\Availability\Entity;
use App\Appointment\Availability\Repository\ResourceOccupancyRepository;
use App\Resource\Entity\ClinicResource;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* «این منبع در این بازه گرفته است.»
*
* یک ردیف به‌ازای هر (بخشِ نوبت × منبع) — نه یکی به‌ازای کل نوبت. دقیقاً همین
* ریزدانگی است که ظرفیت آزاد می‌کند: اپراتوری که در «انتظار اثر کرم» کاری ندارد،
* ردیف اشغال هم ندارد و برای بیمار بعدی قابل استفاده است (بند ۷ مستند).
*
* بازهٔ ثبت‌شده **گسترده‌تر از بازهٔ بخش** است: زمان آماده‌سازی و تمیزکاری منبع هم
* درونش می‌آید، چون منبع واقعاً در آن دقایق در دسترس نیست.
*/
#[ORM\Entity(repositoryClass: ResourceOccupancyRepository::class)]
#[ORM\Table(name: 'resource_occupancy')]
#[ORM\Index(columns: ['resource_id', 'starts_at', 'ends_at'], name: 'idx_occupancy_resource_range')]
#[ORM\Index(columns: ['entity_type', 'entity_id'], name: 'idx_occupancy_tenant')]
#[ORM\Index(columns: ['appointment_id'], name: 'idx_occupancy_appointment')]
class ResourceOccupancy
{
use TenantOwnedTrait;
/** نوبت قطعی. */
public const STATUS_BOOKED = 'booked';
/** رزرو موقت تا پایان مهلت — تسک ۰۷ آن را مصرف می‌کند. */
public const STATUS_HOLD = 'hold';
public const STATUSES = [self::STATUS_BOOKED, self::STATUS_HOLD];
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\ManyToOne(targetEntity: ClinicResource::class)]
#[ORM\JoinColumn(name: 'resource_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
private ClinicResource $resource;
/** تهی‌پذیر چون رزرو موقت هنوز نوبتی ندارد. */
#[ORM\Column(name: 'appointment_id', type: 'integer', nullable: true)]
private ?int $appointmentId = null;
#[ORM\Column(name: 'starts_at', type: 'integer')]
private int $startsAt;
#[ORM\Column(name: 'ends_at', type: 'integer')]
private int $endsAt;
#[ORM\Column(type: 'string', length: 10, options: ['default' => self::STATUS_BOOKED])]
private string $status = self::STATUS_BOOKED;
#[ORM\Column(name: 'segment_name', type: 'string', length: 150, nullable: true)]
private ?string $segmentName = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(ClinicResource $resource, int $startsAt, int $endsAt, string $status = self::STATUS_BOOKED)
{
if ($endsAt <= $startsAt) {
throw new \InvalidArgumentException('Occupancy end must be after its start.');
}
if (!in_array($status, self::STATUSES, true)) {
throw new \InvalidArgumentException(sprintf('Unknown occupancy status "%s".', $status));
}
$this->uuid = Uuid::v4()->toRfc4122();
$this->resource = $resource;
$this->startsAt = $startsAt;
$this->endsAt = $endsAt;
$this->status = $status;
$this->createdAt = time();
$this->assignTenantPair($resource->getEntityType(), $resource->getEntityId());
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getResource(): ClinicResource { return $this->resource; }
public function getAppointmentId(): ?int { return $this->appointmentId; }
public function getStartsAt(): int { return $this->startsAt; }
public function getEndsAt(): int { return $this->endsAt; }
public function getStatus(): string { return $this->status; }
public function getSegmentName(): ?string { return $this->segmentName; }
public function setAppointmentId(?int $v): self { $this->appointmentId = $v; return $this; }
public function setSegmentName(?string $v): self { $this->segmentName = $v; return $this; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'resource_uuid' => $this->resource->getUuid(),
'resource_name' => $this->resource->getName(),
'starts_at' => $this->startsAt,
'ends_at' => $this->endsAt,
'status' => $this->status,
'segment_name' => $this->segmentName,
];
}
}
@@ -0,0 +1,60 @@
<?php
namespace App\Appointment\Availability\Repository;
use App\Appointment\Availability\Entity\ResourceOccupancy;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ResourceOccupancy>
*/
class ResourceOccupancyRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ResourceOccupancy::class);
}
/**
* اشغال‌های همهٔ منابع در یک بازه — **یک کوئری برای کل جستجو**، نه یکی per منبع
* یا per روز. موتور جستجو این را یک بار می‌گیرد و در حافظه می‌برد.
*
* @param int[] $resourceIds
* @return array<int, list<array{start: int, end: int}>> شناسهٔ منبع => بازه‌ها
*/
public function busyByResource(array $resourceIds, int $from, int $to): array
{
if ($resourceIds === []) {
return [];
}
$rows = $this->createQueryBuilder('o')
->select('IDENTITY(o.resource) AS resource_id, o.startsAt AS starts_at, o.endsAt AS ends_at')
->where('o.resource IN (:ids)')
->andWhere('o.startsAt < :to')
->andWhere('o.endsAt > :from')
->setParameter('ids', $resourceIds)
->setParameter('from', $from)
->setParameter('to', $to)
->orderBy('o.startsAt', 'ASC')
->getQuery()
->getArrayResult();
$byResource = [];
foreach ($rows as $row) {
$byResource[(int) $row['resource_id']][] = [
'start' => (int) $row['starts_at'],
'end' => (int) $row['ends_at'],
];
}
return $byResource;
}
/** @return ResourceOccupancy[] */
public function findForAppointment(int $appointmentId): array
{
return $this->findBy(['appointmentId' => $appointmentId]);
}
}
@@ -0,0 +1,300 @@
<?php
namespace App\Appointment\Availability\Service;
use App\Appointment\Availability\Repository\ResourceOccupancyRepository;
use App\Appointment\Availability\ValueObject\AvailableSlot;
use App\Appointment\Availability\ValueObject\SlotAssignment;
use App\Appointment\Plan\ValueObject\AppointmentPlan;
use App\Appointment\Plan\ValueObject\PlannedRequirement;
use App\Appointment\Plan\ValueObject\PlannedSegment;
use App\Doctor\Entity\DoctorAddress;
use App\Resource\Entity\ClinicResource;
use App\Resource\Service\ResourceAvailabilityService;
use App\Shared\Time\TimeInterval;
/**
* برنامهٔ نوبت را روی تقویم منابع می‌لغزاند و می‌گوید چه ساعت‌هایی **واقعاً** ممکن‌اند،
* با پیشنهاد اینکه کدام منبع استفاده شود (بند ۱۰ مستند).
*
* ## چرا این ظرفیت آزاد می‌کند
*
* تخصیص **per نقش** انجام می‌شود، نه per بخش: اپراتوری که در بخش «انتظار اثر کرم»
* نیازمندی ندارد، در آن دقایق اصلاً بررسی نمی‌شود و برای بیمار دیگری آزاد است.
* همین تفاوت، نیمِ هدررفتهٔ ظرفیت در مدل تک‌بازه‌ای را برمی‌گرداند.
*
* ## چرا همان منبع در بخش‌های غیرمجاور
*
* یک منبع برای **همهٔ** بخش‌هایی که آن نقش را می‌خواهند انتخاب می‌شود، نه جداگانه per
* بخش. اپراتور بخش ۱ و بخش ۳ باید یک نفر باشد؛ انتخاب مستقل، دو نفر می‌داد.
*
* ## کارایی
*
* همهٔ ورودی‌ها یک بار خوانده می‌شوند (تقویم منابع، اشغال‌ها) و بقیه در حافظه است.
* هیچ کوئری داخل حلقهٔ کاندید یا حلقهٔ روز نیست.
*/
final class AvailabilityEngine
{
/** گام پیش‌فرض تولید کاندید. */
public const DEFAULT_STEP_MINUTES = 15;
public const MAX_DAYS = 90;
/** سقف پاسخ — جستجوی یک ماهه نباید هزاران ردیف برگرداند. */
public const MAX_SLOTS = 500;
public function __construct(
private readonly ResourceAvailabilityService $calendars,
private readonly ResourceOccupancyRepository $occupancy,
) {}
/**
* @return AvailableSlot[]
*/
public function search(
AppointmentPlan $plan,
DoctorAddress $address,
int $from,
int $to,
int $stepMinutes = self::DEFAULT_STEP_MINUTES,
?int $now = null,
): array {
$now = $now ?? time();
$step = max(5, $stepMinutes) * 60;
$roles = $this->rolesOf($plan);
if ($roles === []) {
// برنامه‌ای که هیچ منبعی نمی‌خواهد فقط به ساعت کاری شعبه محدود است؛
// چنین چیزی معتبر است («انتظار در خانه») ولی وقت‌دهی ندارد.
return [];
}
$free = $this->freeWindows($roles, $address, $from, $to);
$slots = [];
foreach ($this->candidateStarts($roles, $free, $from, $to, $step, $now) as $start) {
$assignment = $this->assign($plan, $roles, $free, $start);
if ($assignment === null) {
continue;
}
$slots[] = new AvailableSlot($start, $start + $plan->totalMinutes * 60, $assignment);
if (count($slots) >= self::MAX_SLOTS) {
break;
}
}
return $slots;
}
/**
* نقش‌های موردنیاز و بازه‌های هر نقش درون نوبت.
*
* @return array<string, array{requirement: PlannedRequirement, windows: list<array{offset: int, duration: int}>}>
*/
private function rolesOf(AppointmentPlan $plan): array
{
$roles = [];
foreach ($plan->segments as $segment) {
foreach ($segment->requirements as $requirement) {
$key = $requirement->role . '#' . ($requirement->skillName ?? '') . '#' . $requirement->count;
$roles[$key]['requirement'] = $requirement;
$roles[$key]['windows'][] = [
'offset' => $segment->offsetMinutes,
'duration' => $segment->durationMinutes,
];
}
}
return $roles;
}
/**
* پنجره‌های آزاد هر منبع در کل بازه — تقویم منبع منهای اشغال‌ها.
*
* @param array<string, array{requirement: PlannedRequirement, windows: list<array{offset:int,duration:int}>}> $roles
* @return array<int, list<TimeInterval>> شناسهٔ منبع => بازه‌های آزاد
*/
private function freeWindows(array $roles, DoctorAddress $address, int $from, int $to): array
{
$resources = [];
foreach ($roles as $role) {
foreach ($role['requirement']->eligible as $resource) {
$resources[(int) $resource->getId()] = $resource;
}
}
// یک کوئری برای همهٔ اشغال‌های همهٔ منابع در کل بازه.
$busy = $this->occupancy->busyByResource(array_keys($resources), $from, $to + 86400);
$free = [];
foreach ($resources as $id => $resource) {
$open = [];
foreach ($this->calendars->rawAvailability($resource, $from, $to) as $day) {
foreach ($day->intervals as $interval) {
$open[] = $interval;
}
}
$blocks = array_map(
static fn (array $b): TimeInterval => new TimeInterval($b['start'], $b['end']),
$busy[$id] ?? [],
);
$free[$id] = $blocks === [] ? TimeInterval::mergeAll($open) : TimeInterval::subtractAll($open, $blocks);
}
return $free;
}
/**
* نقطه‌های شروع کاندید.
*
* فقط از پنجره‌های آزادِ **محدودکننده‌ترین نقش** ساخته می‌شوند، نه از کل بازهٔ
* تاریخ: هرس زودهنگام، جستجوی یک‌ماهه را از ده‌ها هزار کاندید به چند صد می‌رساند.
*
* @param array<string, array{requirement: PlannedRequirement, windows: list<array{offset:int,duration:int}>}> $roles
* @param array<int, list<TimeInterval>> $free
* @return list<int>
*/
private function candidateStarts(array $roles, array $free, int $from, int $to, int $step, int $now): array
{
$scarcest = null;
foreach ($roles as $role) {
$count = count($role['requirement']->eligible);
if ($scarcest === null || $count < count($scarcest['requirement']->eligible)) {
$scarcest = $role;
}
}
$earliestOffset = min(array_map(
static fn (array $w): int => $w['offset'],
$scarcest['windows'],
)) * 60;
$starts = [];
$limit = $to + 86400;
foreach ($scarcest['requirement']->eligible as $resource) {
foreach ($free[(int) $resource->getId()] ?? [] as $window) {
// اولین کاندیدِ ممکن، شروعی است که پنجره را از ابتدای همان بازه پوشش دهد.
$first = $this->ceilToStep($window->start - $earliestOffset, $step, $from);
for ($start = $first; $start < $limit; $start += $step) {
if ($start < $now || $start + $earliestOffset >= $window->end) {
continue;
}
$starts[$start] = true;
}
}
}
$unique = array_keys($starts);
sort($unique);
return $unique;
}
private function ceilToStep(int $value, int $step, int $origin): int
{
$delta = $value - $origin;
if ($delta <= 0) {
return $origin;
}
return $origin + (int) (ceil($delta / $step) * $step);
}
/**
* تخصیص منبع برای یک زمان شروع. `null` یعنی این زمان ممکن نیست.
*
* @param array<string, array{requirement: PlannedRequirement, windows: list<array{offset:int,duration:int}>}> $roles
* @param array<int, list<TimeInterval>> $free
*/
private function assign(AppointmentPlan $plan, array $roles, array $free, int $start): ?SlotAssignment
{
$chosen = [];
$taken = [];
foreach ($roles as $role) {
$requirement = $role['requirement'];
// بازه‌هایی که این نقش واقعاً درگیر است — نه کل نوبت.
$needed = [];
foreach ($role['windows'] as $window) {
$segmentStart = $start + $window['offset'] * 60;
$segmentEnd = $segmentStart + $window['duration'] * 60;
// آماده‌سازی و تمیزکاری منبع را هم می‌گیرد: منبع واقعاً در آن دقایق
// در دسترس نیست.
$needed[] = new TimeInterval(
$segmentStart - $requirement->setupMinutes * 60,
$segmentEnd + $requirement->cleanupMinutes * 60,
);
}
$needed = TimeInterval::mergeAll($needed);
$picked = [];
foreach ($requirement->eligible as $resource) {
$id = (int) $resource->getId();
if (isset($taken[$id])) {
continue; // یک منبع دو نقش را هم‌زمان پر نمی‌کند
}
if (!$this->fits($free[$id] ?? [], $needed)) {
continue;
}
$picked[] = $resource;
$taken[$id] = true;
if (count($picked) === $requirement->count) {
break;
}
}
if (count($picked) < $requirement->count) {
return null;
}
$chosen[$requirement->role] = $picked;
}
return new SlotAssignment($chosen);
}
/**
* @param list<TimeInterval> $free
* @param list<TimeInterval> $needed
*/
private function fits(array $free, array $needed): bool
{
foreach ($needed as $interval) {
$covered = false;
foreach ($free as $window) {
if ($window->start <= $interval->start && $window->end >= $interval->end) {
$covered = true;
break;
}
}
if (!$covered) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Appointment\Availability\ValueObject;
final readonly class AvailableSlot
{
public function __construct(
public int $start,
public int $end,
public SlotAssignment $assignment,
) {}
public function toArray(): array
{
return [
'start' => $this->start,
'end' => $this->end,
'assignment' => $this->assignment->toArray(),
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Appointment\Availability\ValueObject;
use App\Resource\Entity\ClinicResource;
/**
* کدام منبع برای کدام نقش پیشنهاد می‌شود.
*
* تخصیص per **نقش** است نه per بخش: همان اپراتور در بخش ۱ و بخش ۳ حاضر است، نه دو
* نفر — و همین باعث می‌شود بخشِ میانی که او را نمی‌خواهد، واقعاً آزادش کند.
*/
final readonly class SlotAssignment
{
/** @param array<string, list<ClinicResource>> $byRole */
public function __construct(public array $byRole) {}
public function toArray(): array
{
$out = [];
foreach ($this->byRole as $role => $resources) {
$out[$role] = array_map(
static fn (ClinicResource $r): array => [
'uuid' => $r->getUuid(),
'name' => $r->getName(),
],
$resources,
);
}
return $out;
}
}
+11 -1
View File
@@ -33,6 +33,16 @@ class WeeklySchedule
public const MODE_SLOT = 'slot'; // نوبت‌دهی اسلاتی (رفتار پیش‌فرض)
public const MODE_SERVICE = 'service'; // نوبت‌دهی بر اساس مدت سرویس
/**
* نوبت‌دهی چندمنبعی: برنامهٔ چندبخشی روی تقویم منابع (بند ۱۰ مستند).
*
* افزودنی محض است — پیش‌فرض همچنان `slot` می‌ماند و هیچ محیطی خودبه‌خود به این
* حالت نمی‌رود؛ ارتقا داوطلبانه و صریح است.
*/
public const MODE_RESOURCE = 'resource';
public const MODES = [self::MODE_SLOT, self::MODE_SERVICE, self::MODE_RESOURCE];
/** واحدهای مجاز بازهٔ رزرو آنلاین؛ همان کلیدواژه‌های strtotime. */
public const BOOKING_WINDOW_UNITS = ['day', 'week', 'month'];
@@ -131,7 +141,7 @@ class WeeklySchedule
'booking_window_unit' => in_array($meta['booking_window_unit'] ?? null, self::BOOKING_WINDOW_UNITS, true)
? $meta['booking_window_unit']
: $current['booking_window_unit'],
'booking_mode' => in_array($meta['booking_mode'] ?? null, [self::MODE_SLOT, self::MODE_SERVICE], true)
'booking_mode' => in_array($meta['booking_mode'] ?? null, self::MODES, true)
? $meta['booking_mode']
: $current['booking_mode'],
'buffer_minutes' => max(0, (int)($meta['buffer_minutes'] ?? $current['buffer_minutes'])),
+4
View File
@@ -22,6 +22,9 @@ class ErrorCodes
/** هیچ منبعی شرایط یک بخش از نوبت را ندارد — بند ۱۰ مستند. */
public const ERR_NO_ELIGIBLE_RESOURCE = 'ERR_NO_ELIGIBLE_RESOURCE';
/** این اندپوینت با روش نوبت‌دهی فعلیِ آن محل سازگار نیست. */
public const ERR_WRONG_BOOKING_MODE = 'ERR_WRONG_BOOKING_MODE';
// Conflict
public const ERR_CONFLICT_001 = 'ERR_CONFLICT_001';
@@ -134,6 +137,7 @@ class ErrorCodes
self::ERR_VALIDATION_002 => 'فیلد الزامی وارد نشده است',
self::ERR_NOT_FOUND_001 => 'منبع درخواستی یافت نشد',
self::ERR_NO_ELIGIBLE_RESOURCE => 'برای این خدمت منبع واجد شرایطی در این شعبه نیست',
self::ERR_WRONG_BOOKING_MODE => 'این عملیات با روش نوبت‌دهی این محل سازگار نیست',
self::ERR_FORBIDDEN_001 => 'دسترسی به این منبع مجاز نیست',
self::ERR_PAYMENT_001 => 'درگاه پرداخت در دسترس نیست',
self::ERR_PAYMENT_002 => 'مبلغ پرداخت نامعتبر است',