feat(plan): multi-segment appointments with per-segment resource requirements

Section 7 of the design document, and the reason the whole resource layer exists.
A laser session is not one block: numbing cream (5 min, room + operator), waiting for
it to work (30 min, room only), the laser itself (20 min, room + operator + device),
aftercare (5 min, room + operator). Under the single-interval model the operator is
locked for all 60 minutes while actually working 30 — half the capacity thrown away.

AppointmentPlanBuilder turns (service, selected items, branch, patient) into a plan:
segments with offsets, durations and resource requirements. It deliberately assigns
no absolute time and no specific resource — that is the next task. This only produces
the *shape* of the appointment.

Segment duration comes from one of two sources. A fixed segment carries its own
number; an item-driven one gets its duration from task 04's DurationCalculator, so
"the laser itself" grows with two treated areas while "waiting for the cream" does
not. One number could not have expressed that.

Three contracts worth stating:

- A service with no segment templates falls back to a single continuous segment
  requiring the doctor resource — exactly today's behaviour. Without it every
  existing service would have become unplannable overnight.
- A segment with no requirements is valid: "waiting at home" consumes time but
  occupies nothing.
- same_gender_as_patient with an unknown patient gender is a 422, not a silently
  dropped requirement. Dropping it quietly would route the patient to a resource the
  clinic said must not serve them.

When no resource qualifies, the error names the role, the skill and the branch —
"no female operator with the skill «Alexandrite laser» is available at «Central»" —
rather than an empty result the caller has to interpret (section 10).

occupancy_offset carries each requirement's setup/cleanup minutes for the availability
engine. It is taken as the maximum across candidates, because the builder does not yet
know which resource will be picked and under-reserving means the next appointment
lands on top of the cleanup.

11 tests covering the document's reference example (offsets 0/5/35/55, total 60),
item-driven scaling, the no-template fallback, all three gender-constraint outcomes,
merging and both caps. 1186 tests overall. phpstan back at its 14-error baseline;
slot-mode frozen contract green.

The admin segments page is not built; the checklist records it with a target. The
backend and preview endpoint are complete and consumable without it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-30 21:07:30 +03:30
co-authored by Claude Opus 5
parent 04526542c9
commit 22c89fbae4
16 changed files with 1528 additions and 12 deletions
@@ -0,0 +1,208 @@
<?php
namespace App\Appointment\Plan\Controller;
use App\Appointment\Plan\Entity\SegmentRequirement;
use App\Appointment\Plan\Entity\SegmentTemplate;
use App\Appointment\Plan\Repository\SegmentTemplateRepository;
use App\Appointment\Plan\Service\AppointmentPlanBuilder;
use App\Auth\Entity\User;
use App\Branch\Service\BranchResolver;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Repository\ServiceItemRepository;
use App\Resource\Service\ResourceContext;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
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;
#[OA\Tag(name: 'Appointment Plan')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class AppointmentPlanController extends BaseController
{
public function __construct(
private readonly SegmentTemplateRepository $templates,
private readonly ServiceItemRepository $items,
private readonly AppointmentPlanBuilder $builder,
private readonly BranchResolver $branches,
private readonly ResourceContext $resourceContext,
private readonly EntityManagerInterface $em,
) {}
#[Route('/api/v1/service-item/{uuid}/segments', name: 'service_segments_show', methods: ['GET'])]
public function show(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$service = $this->requireItem($user, $uuid);
return $this->success(array_map(
static fn (SegmentTemplate $s): array => $s->toArray(),
$this->templates->findForService($service),
));
}
/**
* جایگزینی کامل بخش‌های یک سرویس، به‌همراه نیازمندی‌هایشان.
*
* همه‌چیز پیش از هر حذفی حل و اعتبارسنجی می‌شود — همان قرارداد بقیهٔ PUT های
* پروژه: بخش نامعتبر در انتهای فهرست نباید بخش‌های درستِ قبلی را پاک کند.
*/
#[Route('/api/v1/service-item/{uuid}/segments', name: 'service_segments_replace', methods: ['PUT'])]
public function replace(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_array($data['segments'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد segments الزامی است', 422, 'segments');
}
$service = $this->requireItem($user, $uuid);
$planned = [];
$total = 0;
foreach ($data['segments'] as $index => $row) {
if (!is_array($row) || !is_string($row['name'] ?? null) || trim($row['name']) === '') {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'نام هر بخش الزامی است', 422, 'name');
}
$source = is_string($row['duration_source'] ?? null) ? $row['duration_source'] : SegmentTemplate::DURATION_FIXED;
$minutes = is_numeric($row['duration_minutes'] ?? null) ? (int) $row['duration_minutes'] : 0;
if (!in_array($source, SegmentTemplate::DURATION_SOURCES, true)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'منبع مدت بخش نامعتبر است', 422, 'duration_source');
}
if ($source === SegmentTemplate::DURATION_FIXED && $minutes <= 0) {
return $this->error(
ErrorCodes::ERR_VALIDATION_001,
sprintf('بخش «%s» مدت مثبت لازم دارد', trim($row['name'])),
422,
'duration_minutes',
);
}
$total += $minutes;
$requirements = [];
foreach (($row['requirements'] ?? []) as $req) {
if (!is_array($req) || !is_string($req['type_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'type_uuid هر نیازمندی الزامی است', 422, 'requirements');
}
$requirements[] = [
'type' => $this->resourceContext->type($user, $req['type_uuid']),
'skill' => is_string($req['skill_uuid'] ?? null) ? $this->resourceContext->skill($user, $req['skill_uuid']) : null,
'count' => is_numeric($req['count'] ?? null) ? max(1, (int) $req['count']) : 1,
'occupancy' => is_string($req['occupancy'] ?? null) ? $req['occupancy'] : SegmentRequirement::OCCUPANCY_EXCLUSIVE,
'constraints' => is_array($req['constraints'] ?? null) ? $req['constraints'] : [],
];
}
$planned[] = [
'sequence' => is_numeric($row['sequence'] ?? null) ? (int) $row['sequence'] : $index + 1,
'name' => trim($row['name']),
'source' => $source,
'minutes' => $minutes,
'patient' => (bool) ($row['patient_present'] ?? true),
'mergeable' => (bool) ($row['mergeable'] ?? false),
'requirements' => $requirements,
];
}
if ($total > SegmentTemplate::MAX_TOTAL_MINUTES) {
return $this->error(
ErrorCodes::ERR_VALIDATION_001,
sprintf('مجموع مدت بخش‌ها از سقف %d دقیقه بیشتر است', SegmentTemplate::MAX_TOTAL_MINUTES),
422,
'segments',
);
}
$this->templates->deleteForService($service);
foreach ($planned as $row) {
$template = new SegmentTemplate($service, $row['sequence'], $row['name']);
try {
$template->setDuration($row['source'], $row['minutes']);
} catch (\InvalidArgumentException $e) {
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'مدت بخش نامعتبر است', 422, 'duration_minutes');
}
$template->setPatientPresent($row['patient'])->setMergeable($row['mergeable']);
$this->em->persist($template);
foreach ($row['requirements'] as $req) {
$requirement = new SegmentRequirement($template, $req['type'], $req['count']);
$requirement->setSkill($req['skill']);
try {
$requirement->setOccupancy($req['occupancy'])->setConstraints($req['constraints']);
} catch (\InvalidArgumentException $e) {
throw new AppException(ErrorCodes::ERR_VALIDATION_001, $e->getMessage(), 422, 'requirements');
}
$this->em->persist($requirement);
$template->getRequirements()->add($requirement);
}
}
$this->em->flush();
return $this->success(array_map(
static fn (SegmentTemplate $s): array => $s->toArray(),
$this->templates->findForService($service),
));
}
/** برنامهٔ نوبت، بدون هیچ ثبتی — پیش از رفتن به جستجوی وقت. */
#[Route('/api/v1/appointment-plan/preview', name: 'appointment_plan_preview', methods: ['POST'])]
public function preview(#[CurrentUser] User $user, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_string($data['service_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد service_uuid الزامی است', 422, 'service_uuid');
}
if (!is_string($data['branch_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد branch_uuid الزامی است', 422, 'branch_uuid');
}
$service = $this->requireItem($user, $data['service_uuid']);
$address = $this->branches->resolve($user, $data['branch_uuid']);
$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);
}
$gender = is_string($data['patient_gender'] ?? null) ? $data['patient_gender'] : null;
return $this->success($this->builder->build($service, $selected, $address, $gender)->toArray());
}
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;
}
}