feat(treatment): run a session from the staff panel, area by area

The operator opens the session, treats each body area on its own device and
records what that device was set to. Readings are validated against the resource
type's field schema, so a laser form and an RF form each enforce their own rules
without this code naming either.

Finishing is allowed with areas still open — the operator is standing in front of
a patient and must not be trapped by the software — but the count comes back so
the panel can warn. Session state mirrors onto the appointment (salon, then
completed) while its slot times are never rewritten: those are the reservation's
promise and the input to occupancy, whereas how long it actually took belongs to
the session. Overwriting them would destroy the comparison between the two.

Who performed it is recorded on the session rather than inferred from the
appointment's planned staff: when a colleague covers a sick operator, the medical
record must say who actually held the device.

Endpoints live under /api/v1/dashboard/staff because StaffRouteGuardSubscriber
closes everything else to staff-only users. Opening a second door through its
allowlist would put the access boundary in two places.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-08-06 18:17:27 +03:30
co-authored by Claude Opus 5
parent 1cdd62979f
commit 77eeefd5b4
4 changed files with 900 additions and 1 deletions
@@ -0,0 +1,221 @@
<?php
namespace App\Treatment\Controller;
use App\Auth\Entity\User;
use App\Resource\Entity\ClinicResource;
use App\Resource\Repository\ClinicResourceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Context\EntityContextResolver;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
use App\Shared\Tenant\TenantOwnershipChecker;
use App\Staff\Entity\ClinicStaff;
use App\Staff\Repository\ClinicStaffRepository;
use App\Treatment\Entity\SessionAreaRecord;
use App\Treatment\Entity\TreatmentSession;
use App\Treatment\Repository\SessionAreaRecordRepository;
use App\Treatment\Repository\TreatmentSessionRepository;
use App\Treatment\Service\SessionExecutor;
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;
/**
* پنل پرسنل: انجام جلسه.
*
* همهٔ مسیرها زیر `/api/v1/dashboard/staff` می‌نشینند چون
* {@see \App\Staff\Security\StaffRouteGuardSubscriber} کاربرِ فقط-پرسنل را بیرون از
* همان پیشوند می‌بندد. باز کردن راهِ تازه با افزودن به allowlist یعنی مرزِ دسترسی در
* دو جا تعریف شود؛ این‌طور یک جا می‌ماند.
*
* نقش به‌تنهایی کافی نیست — ردیف فعالِ پرسنل در محیط جاری هم باید باشد، چون توکن تا
* انقضا معتبر می‌ماند و غیرفعال‌شدنِ پرسنل باید همان لحظه دسترسی را ببندد. همان
* قاعده‌ای که `DashboardController::staff` دارد.
*/
#[OA\Tag(name: 'Treatment')]
#[IsGranted('ROLE_STAFF')]
class SessionExecutionController extends BaseController
{
public function __construct(
private readonly TreatmentSessionRepository $sessions,
private readonly SessionAreaRecordRepository $areaRecords,
private readonly ClinicResourceRepository $resources,
private readonly ClinicStaffRepository $staffRepo,
private readonly SessionExecutor $executor,
private readonly TenantOwnershipChecker $ownership,
private readonly EntityContextResolver $contextResolver,
) {}
/** جلسات امروزِ همین پرسنل — «جلسات امروز من». */
#[Route('/api/v1/dashboard/staff/treatment-sessions', name: 'staff_treatment_sessions', methods: ['GET'])]
public function today(#[CurrentUser] User $user): JsonResponse
{
$staff = $this->requireStaff($user);
return $this->success(array_map(
static fn (TreatmentSession $s): array => $s->toArray(withAreas: true) + [
'case_uuid' => $s->getTreatmentCase()->getUuid(),
'service_name' => $s->getTreatmentCase()->getServiceItem()->getName(),
],
$this->sessions->findTodayForStaff(
$staff,
strtotime('today midnight'),
strtotime('tomorrow midnight') - 1,
),
));
}
#[Route('/api/v1/dashboard/staff/treatment-session/{uuid}', name: 'staff_treatment_session_show', methods: ['GET'])]
public function show(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$session = $this->requireSession($user, $uuid);
return $this->success($session->toArray(withAreas: true) + [
'case' => $session->getTreatmentCase()->toArray(),
// فرمِ هر ناحیه از نوع منبعش می‌آید؛ پنل نباید فیلدها را حدس بزند.
'forms' => $this->formsFor($session),
]);
}
#[Route('/api/v1/dashboard/staff/treatment-session/{uuid}/start', name: 'staff_treatment_session_start', methods: ['POST'])]
public function start(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$staff = $this->requireStaff($user);
$session = $this->requireSession($user, $uuid);
return $this->success($this->executor->startSession($session, $staff)->toArray(withAreas: true));
}
#[Route('/api/v1/dashboard/staff/treatment-session/{uuid}/finish', name: 'staff_treatment_session_finish', methods: ['POST'])]
public function finish(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$session = $this->requireSession($user, $uuid);
$data = json_decode($request->getContent(), true) ?? [];
$note = is_string($data['note'] ?? null) ? trim($data['note']) : null;
$result = $this->executor->finishSession($session, $note !== '' ? $note : null);
return $this->success($result['session']->toArray(withAreas: true) + [
// بستن با ناحیهٔ ناتمام مجاز است؛ پنل با همین عدد هشدار می‌دهد.
'unsettled_areas' => $result['unsettled_areas'],
]);
}
#[Route('/api/v1/dashboard/staff/session-area/{uuid}/start', name: 'staff_session_area_start', methods: ['POST'])]
public function startArea(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$record = $this->requireAreaRecord($user, $uuid);
$data = json_decode($request->getContent(), true) ?? [];
return $this->success(
$this->executor->startArea($record, $this->resolveResource($user, $data))->toArray(),
);
}
#[Route('/api/v1/dashboard/staff/session-area/{uuid}/complete', name: 'staff_session_area_complete', methods: ['POST'])]
public function completeArea(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$record = $this->requireAreaRecord($user, $uuid);
$data = json_decode($request->getContent(), true) ?? [];
$note = is_string($data['note'] ?? null) ? trim($data['note']) : null;
return $this->success($this->executor->completeArea(
$record,
$this->resolveResource($user, $data),
is_array($data['parameters'] ?? null) ? $data['parameters'] : null,
$note !== '' ? $note : null,
)->toArray());
}
#[Route('/api/v1/dashboard/staff/session-area/{uuid}/skip', name: 'staff_session_area_skip', methods: ['POST'])]
public function skipArea(#[CurrentUser] User $user, string $uuid): JsonResponse
{
return $this->success($this->executor->skipArea($this->requireAreaRecord($user, $uuid))->toArray());
}
/** @return array<string, list<array<string, mixed>>> uuid منبع => تعریف فیلدها */
private function formsFor(TreatmentSession $session): array
{
$forms = [];
foreach ($session->getAreaRecords() as $record) {
$resource = $record->getResource();
if ($resource !== null) {
$forms[$resource->getUuid()] = $resource->getType()->getFieldSchema() ?? [];
}
}
return $forms;
}
private function resolveResource(User $user, array $data): ?ClinicResource
{
$uuid = is_string($data['resource_uuid'] ?? null) ? trim($data['resource_uuid']) : '';
if ($uuid === '') {
return null;
}
$resource = $this->resources->findByUuid($uuid);
[$entityType, $entityId] = $this->pair($user);
if (!$this->ownership->belongsToPair($entityType, $entityId, $resource)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'منبع یافت نشد', 404, 'resource_uuid');
}
return $resource;
}
private function requireStaff(User $user): ClinicStaff
{
[$entityType, $entityId] = $this->pair($user);
$staff = $this->staffRepo->findActiveByUserAndEntity($user, $entityType, $entityId);
if ($staff === null) {
throw new AppException(ErrorCodes::ERR_FORBIDDEN_001, 'دسترسی پرسنل تنظیم نشده', 403);
}
return $staff;
}
private function requireSession(User $user, string $uuid): TreatmentSession
{
[$entityType, $entityId] = $this->pair($user);
$session = $this->sessions->findByUuid($uuid);
if (!$this->ownership->belongsToPair($entityType, $entityId, $session)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'جلسهٔ درمان یافت نشد', 404);
}
return $session;
}
private function requireAreaRecord(User $user, string $uuid): SessionAreaRecord
{
[$entityType, $entityId] = $this->pair($user);
$record = $this->areaRecords->findByUuid($uuid);
if (!$this->ownership->belongsToPair($entityType, $entityId, $record)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'ناحیهٔ جلسه یافت نشد', 404);
}
return $record;
}
/** @return array{0: string, 1: int} */
private function pair(User $user): array
{
$context = $this->contextResolver->resolve($user);
if (!$context->isResolved()) {
throw new AppException(ErrorCodes::ERR_FORBIDDEN_001, 'محیط کاری پرسنل تنظیم نشده', 403);
}
return $context->toEntityPair();
}
}