feat(appointments): backend for clinic workflow (Figma نوبتها) — phase A
Extend Appointment for the clinic-facing appointments area:
- New nullable relations service_section/service_item/staff (بخش/سرویس/پرسنل)
plus deposit_required/deposit_amount_rials (بیعانه) and is_reserve.
- New statuses following_up (در حال پیگیری) and salon (سالن) with day-of
transition rules; reserve entries never occupy a slot (several reserves may
share one day), enforced in refreshActiveSlotKey.
- rescheduleTo(slotStart, slotEnd, isReserve) keeps active_slot_key consistent
for جا به جایی and reserve transfers.
- New PATCH /api/v1/appointment/{uuid}: partial update covering edit, slot
move (409 on taken slot, race backstop on the unique key), reserve toggle,
patient swap (جایگزینی) and optional status transition; optimistic lock via
version like the status endpoint.
- POST /my/appointment now accepts the workflow fields and is_reserve
(day-level entry: no past-slot rule, no atomic slot booking); GET
/my/appointments gains reserve=1 and returns the new fields per row.
Migration Version20260713195434 (+ mirrored on db_test). Docs updated.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -33,6 +33,9 @@ class AppointmentController extends BaseController
|
||||
private readonly PatientService $patientService,
|
||||
private readonly WeeklyScheduleRepository $scheduleRepo,
|
||||
private readonly \App\Representation\Service\DomainContextResolver $domainResolver,
|
||||
private readonly \App\ClinicService\Repository\ServiceSectionRepository $sectionRepo,
|
||||
private readonly \App\ClinicService\Repository\ServiceItemRepository $itemRepo,
|
||||
private readonly \App\Staff\Repository\ClinicStaffRepository $staffRepo,
|
||||
) {}
|
||||
|
||||
// ── Public: available slots ───────────────────────────────────────────────
|
||||
@@ -541,4 +544,111 @@ class AppointmentController extends BaseController
|
||||
|
||||
return $this->success(['data' => $appointment->toArray()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* General update (ویرایش / جا به جایی / انتقال به رزرو / جایگزینی).
|
||||
* All fields optional; only what is present in the body changes. Slot moves
|
||||
* go through rescheduleTo so active_slot_key stays consistent. Optimistic
|
||||
* lock via `version` like the status endpoint.
|
||||
*/
|
||||
#[Route('/api/v1/appointment/{uuid}', methods: ['PATCH'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function update(string $uuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$appointment = $this->appointmentRepo->findByUuid($uuid);
|
||||
if ($appointment === null) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'نوبت یافت نشد', 404);
|
||||
}
|
||||
|
||||
if (!$this->canManage($appointment, $user)) {
|
||||
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
|
||||
}
|
||||
|
||||
$data = json_decode($request->getContent(), true) ?? [];
|
||||
$version = (int) ($data['version'] ?? $appointment->getVersion());
|
||||
|
||||
// Slot move / reserve toggle — both times together, or neither.
|
||||
$hasStart = array_key_exists('slot_start', $data);
|
||||
$hasEnd = array_key_exists('slot_end', $data);
|
||||
if ($hasStart !== $hasEnd) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'slot_start و slot_end باید با هم ارسال شوند', 422, 'slot_start');
|
||||
}
|
||||
if ($hasStart || array_key_exists('is_reserve', $data)) {
|
||||
$newStart = $hasStart ? (int) $data['slot_start'] : $appointment->getSlotStart();
|
||||
$newEnd = $hasStart ? (int) $data['slot_end'] : $appointment->getSlotEnd();
|
||||
if ($newEnd < $newStart) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'ساعت پایان قبل از شروع است', 422, 'slot_end');
|
||||
}
|
||||
$isReserve = array_key_exists('is_reserve', $data) ? (bool) $data['is_reserve'] : null;
|
||||
$movingToLiveSlot = ($isReserve ?? $appointment->isReserve()) === false;
|
||||
if ($movingToLiveSlot && ($newStart !== $appointment->getSlotStart() || $newEnd !== $appointment->getSlotEnd())
|
||||
&& $this->appointmentRepo->isSlotTaken($appointment->getDoctor(), $newStart, $newEnd, $appointment->getId())) {
|
||||
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'این بازه زمانی قبلاً رزرو شده است', 409, 'slot_start');
|
||||
}
|
||||
$appointment->rescheduleTo($newStart, $newEnd, $isReserve);
|
||||
}
|
||||
|
||||
// Workflow relations — empty string clears, uuid assigns, unknown → 422.
|
||||
foreach ([
|
||||
'service_section_uuid' => [$this->sectionRepo, 'setServiceSection', 'بخش'],
|
||||
'service_item_uuid' => [$this->itemRepo, 'setServiceItem', 'سرویس'],
|
||||
'staff_uuid' => [$this->staffRepo, 'setStaff', 'پرسنل'],
|
||||
] as $key => [$repo, $setter, $label]) {
|
||||
if (!array_key_exists($key, $data)) {
|
||||
continue;
|
||||
}
|
||||
$value = trim((string) ($data[$key] ?? ''));
|
||||
if ($value === '') {
|
||||
$appointment->$setter(null);
|
||||
continue;
|
||||
}
|
||||
$entity = $repo->findByUuid($value);
|
||||
if ($entity === null) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, $label . ' یافت نشد', 422, $key);
|
||||
}
|
||||
$appointment->$setter($entity);
|
||||
}
|
||||
|
||||
if (array_key_exists('deposit_required', $data)) {
|
||||
$appointment->setDepositRequired((bool) $data['deposit_required']);
|
||||
}
|
||||
if (array_key_exists('deposit_amount_rials', $data)) {
|
||||
$appointment->setDepositAmountRials($data['deposit_amount_rials'] !== null ? (int) $data['deposit_amount_rials'] : null);
|
||||
}
|
||||
if (array_key_exists('note', $data)) {
|
||||
$appointment->setNote($data['note'] !== null ? trim((string) $data['note']) : null);
|
||||
}
|
||||
// جایگزینی نوبت — swap the person occupying the slot.
|
||||
if (array_key_exists('patient_name', $data)) {
|
||||
$appointment->setPatientName($data['patient_name'] !== null ? trim((string) $data['patient_name']) : null);
|
||||
}
|
||||
if (array_key_exists('patient_mobile', $data)) {
|
||||
$appointment->setPatientMobile($data['patient_mobile'] !== null ? trim((string) $data['patient_mobile']) : null);
|
||||
}
|
||||
|
||||
// Optional status transition, same rules as the dedicated endpoint.
|
||||
$newStatus = trim((string) ($data['status'] ?? ''));
|
||||
if ($newStatus !== '' && $newStatus !== $appointment->getStatus()) {
|
||||
if (!$appointment->canTransitionTo($newStatus)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_001, sprintf(
|
||||
'انتقال از "%s" به "%s" مجاز نیست', $appointment->getStatus(), $newStatus
|
||||
), 422);
|
||||
}
|
||||
$appointment->transitionTo($newStatus);
|
||||
if ($newStatus === Appointment::STATUS_CONFIRMED) {
|
||||
$this->patientService->autoCreateOnAppointmentConfirm($appointment);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$this->appointmentRepo->saveWithLock($appointment, $version);
|
||||
} catch (OptimisticLockException) {
|
||||
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'تداخل ویرایش همزمان. لطفاً دوباره تلاش کنید', 409);
|
||||
} catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException) {
|
||||
// race backstop: someone grabbed the slot between the pre-check and the flush
|
||||
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'این بازه زمانی قبلاً رزرو شده است', 409, 'slot_start');
|
||||
}
|
||||
|
||||
return $this->success(['data' => $appointment->toArray()]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,9 @@ class MyAppointmentsController extends BaseController
|
||||
private readonly DoctorSecretaryRepository $secretaryRepo,
|
||||
private readonly UserActiveContextRepository $contextRepo,
|
||||
private readonly SlotCalculatorService $slotCalculator,
|
||||
private readonly \App\ClinicService\Repository\ServiceSectionRepository $sectionRepo,
|
||||
private readonly \App\ClinicService\Repository\ServiceItemRepository $itemRepo,
|
||||
private readonly \App\Staff\Repository\ClinicStaffRepository $staffRepo,
|
||||
) {}
|
||||
|
||||
#[Route('/api/v1/my/appointment', methods: ['POST'])]
|
||||
@@ -52,12 +55,19 @@ class MyAppointmentsController extends BaseController
|
||||
$slotEnd = (int) ($data['slot_end'] ?? 0);
|
||||
$mobile = trim($data['patient_mobile'] ?? '');
|
||||
$patientName = trim($data['patient_name'] ?? '');
|
||||
$isReserve = (bool) ($data['is_reserve'] ?? false);
|
||||
|
||||
if (empty($doctorUuid) || $slotStart <= 0 || $slotEnd <= $slotStart || empty($mobile) || empty($patientName)) {
|
||||
// Reserve entries are day-level: only a date is picked in the UI, so
|
||||
// slot_end may equal slot_start and the past-slot rule does not apply.
|
||||
if ($isReserve && $slotEnd < $slotStart) {
|
||||
$slotEnd = $slotStart;
|
||||
}
|
||||
|
||||
if (empty($doctorUuid) || $slotStart <= 0 || (!$isReserve && $slotEnd <= $slotStart) || empty($mobile) || empty($patientName)) {
|
||||
return $this->error(ErrorCodes::VALIDATION, 'همه فیلدها الزامی است', 422);
|
||||
}
|
||||
|
||||
if ($slotStart < time()) {
|
||||
if (!$isReserve && $slotStart < time()) {
|
||||
return $this->error(ErrorCodes::SLOT_PAST, 'زمان این اسلات گذشته است', 422);
|
||||
}
|
||||
|
||||
@@ -81,10 +91,40 @@ class MyAppointmentsController extends BaseController
|
||||
$locationId = $this->slotCalculator->resolveSlotLocationId($doctor, $slotStart);
|
||||
if ($locationId !== null) $appointment->setAddressId($locationId);
|
||||
|
||||
try {
|
||||
$this->appointmentRepo->bookAtomically($appointment);
|
||||
} catch (SlotTakenException) {
|
||||
return $this->error(ErrorCodes::SLOT_TAKEN, 'این نوبت قبلاً رزرو شده است', 409);
|
||||
// Optional clinic-workflow fields (بخش/سرویس/پرسنل/بیعانه) — unknown uuid → 422.
|
||||
foreach ([
|
||||
'service_section_uuid' => [$this->sectionRepo, 'setServiceSection', 'بخش'],
|
||||
'service_item_uuid' => [$this->itemRepo, 'setServiceItem', 'سرویس'],
|
||||
'staff_uuid' => [$this->staffRepo, 'setStaff', 'پرسنل'],
|
||||
] as $key => [$repo, $setter, $label]) {
|
||||
$value = trim((string) ($data[$key] ?? ''));
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
$entity = $repo->findByUuid($value);
|
||||
if ($entity === null) {
|
||||
return $this->error(ErrorCodes::VALIDATION, $label . ' یافت نشد', 422);
|
||||
}
|
||||
$appointment->$setter($entity);
|
||||
}
|
||||
if (!empty($data['deposit_required'])) {
|
||||
$appointment->setDepositRequired(true);
|
||||
}
|
||||
if (isset($data['deposit_amount_rials'])) {
|
||||
$appointment->setDepositAmountRials((int) $data['deposit_amount_rials']);
|
||||
}
|
||||
$appointment->setPatientName($patientName);
|
||||
|
||||
if ($isReserve) {
|
||||
// Day-level reserve: no slot occupation, plain save (no atomic slot check).
|
||||
$appointment->rescheduleTo($slotStart, $slotEnd, true);
|
||||
$this->appointmentRepo->save($appointment);
|
||||
} else {
|
||||
try {
|
||||
$this->appointmentRepo->bookAtomically($appointment);
|
||||
} catch (SlotTakenException) {
|
||||
return $this->error(ErrorCodes::SLOT_TAKEN, 'این نوبت قبلاً رزرو شده است', 409);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->success([
|
||||
@@ -92,6 +132,7 @@ class MyAppointmentsController extends BaseController
|
||||
'slot_start' => $slotStart,
|
||||
'slot_end' => $slotEnd,
|
||||
'status' => $appointment->getStatus(),
|
||||
'is_reserve' => $appointment->isReserve(),
|
||||
], 201);
|
||||
}
|
||||
|
||||
@@ -106,15 +147,27 @@ class MyAppointmentsController extends BaseController
|
||||
$date = trim((string) $request->query->get('date', ''));
|
||||
$doctorUuid = trim((string) $request->query->get('doctor_uuid', ''));
|
||||
|
||||
// reserve=1 → only reserve-list entries; otherwise the regular slot list.
|
||||
$reserveOnly = $request->query->get('reserve') === '1';
|
||||
|
||||
$qb = $this->em->createQueryBuilder()
|
||||
->select(
|
||||
'DISTINCT a.uuid, a.slotStart, a.slotEnd, a.status, a.createdAt, a.version',
|
||||
'a.isReserve, a.depositRequired, a.depositAmountRials, a.note, a.patientName as override_name',
|
||||
'd.uuid as doctor_uuid, d.name as doctor_name',
|
||||
'u.mobileNumber as patient_mobile, u.realName as patient_name'
|
||||
'u.uuid as patient_uuid, u.mobileNumber as patient_mobile, u.realName as patient_name',
|
||||
'ss.uuid as section_uuid, ss.name as section_name',
|
||||
'si.uuid as service_uuid, si.name as service_name',
|
||||
'st.uuid as staff_uuid, st.fullName as staff_name'
|
||||
)
|
||||
->from(Appointment::class, 'a')
|
||||
->join('a.doctor', 'd')
|
||||
->join('a.user', 'u')
|
||||
->leftJoin('a.serviceSection', 'ss')
|
||||
->leftJoin('a.serviceItem', 'si')
|
||||
->leftJoin('a.staff', 'st')
|
||||
->andWhere('a.isReserve = :reserveOnly')
|
||||
->setParameter('reserveOnly', $reserveOnly)
|
||||
->orderBy('a.slotStart', 'ASC');
|
||||
|
||||
$roles = $user->getRoles();
|
||||
@@ -184,8 +237,9 @@ class MyAppointmentsController extends BaseController
|
||||
|
||||
$items = array_map(fn(array $a) => [
|
||||
'uuid' => $a['uuid'],
|
||||
'patient_name' => $a['patient_name'] ?? '',
|
||||
'patient_name' => $a['override_name'] ?: ($a['patient_name'] ?? ''),
|
||||
'patient_mobile' => $a['patient_mobile'],
|
||||
'patient_uuid' => $a['patient_uuid'],
|
||||
'doctor_uuid' => $a['doctor_uuid'],
|
||||
'doctor_name' => $a['doctor_name'],
|
||||
'slot_start' => (int) $a['slotStart'],
|
||||
@@ -196,6 +250,13 @@ class MyAppointmentsController extends BaseController
|
||||
'status' => $a['status'],
|
||||
'version' => (int) $a['version'],
|
||||
'created_at' => date('c', (int) $a['createdAt']),
|
||||
'is_reserve' => (bool) $a['isReserve'],
|
||||
'deposit_required' => (bool) $a['depositRequired'],
|
||||
'deposit_amount_rials' => $a['depositAmountRials'] !== null ? (int) $a['depositAmountRials'] : null,
|
||||
'note' => $a['note'],
|
||||
'service_section' => $a['section_uuid'] ? ['uuid' => $a['section_uuid'], 'name' => $a['section_name']] : null,
|
||||
'service_item' => $a['service_uuid'] ? ['uuid' => $a['service_uuid'], 'name' => $a['service_name']] : null,
|
||||
'staff' => $a['staff_uuid'] ? ['uuid' => $a['staff_uuid'], 'full_name' => $a['staff_name']] : null,
|
||||
], $rows);
|
||||
|
||||
return $this->paginated($items, (int) $total, $page, $limit);
|
||||
|
||||
Reference in New Issue
Block a user