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:
hamed
2026-07-13 23:37:32 +03:30
co-authored by Claude Fable 5
parent 8287a48af1
commit 4678739d15
8 changed files with 671 additions and 11 deletions
+44
View File
@@ -475,3 +475,47 @@ Role-aware paginated list of appointments. Returns only what the authenticated u
"currentPage": 1
}
}
---
## Clinic workflow extensions (نوبتها Figma)
New optional fields on `Appointment` (all backward-compatible): `service_section` (بخش), `service_item` (سرویس), `staff` (پرسنل), `deposit_required` / `deposit_amount_rials` (بیعانه), `is_reserve` (نوبت رزرو day-level, never occupies a slot).
New statuses: `following_up` (در حال پیگیری), `salon` (سالن). Transitions:
`pending confirmed|following_up|cancelled_*|expired` · `confirmed completed|following_up|salon|cancelled_*|no_show` · `following_up confirmed|salon|completed|cancelled_*|no_show` · `salon completed|following_up|cancelled_*|no_show`
### PATCH `/api/v1/appointment/{uuid}`
General update (ویرایش / جا به جایی / انتقال به رزرو / جایگزینی). All body fields optional; only present keys change. **Permission:** appointment's patient, owning doctor, or admin.
```json
{
"slot_start": 1731000000, "slot_end": 1731001800,
"is_reserve": false,
"service_section_uuid": "…", "service_item_uuid": "…", "staff_uuid": "…",
"deposit_required": true, "deposit_amount_rials": 5000000,
"note": "…", "patient_name": "…", "patient_mobile": "…",
"status": "confirmed", "version": 3
}
```
- `slot_start`/`slot_end` must be sent together; moving to an occupied slot → `409`.
- Relation uuids: empty string clears; unknown uuid → `422`.
- `status` follows the same transition rules as `PATCH /appointment/{uuid}/status`.
- Optimistic lock via `version``409` on concurrent edit.
Response `200`: `{ success, data: { data: <appointment.toArray()> } }`
| HTTP | Description |
|------|-------------|
| 404 | نوبت یافت نشد |
| 403 | not patient/doctor/admin |
| 422 | half slot pair, end < start, unknown relation uuid, invalid transition |
| 409 | slot taken or version conflict |
### POST `/api/v1/my/appointment` (extended)
Extra optional body fields: `service_section_uuid`, `service_item_uuid`, `staff_uuid`, `deposit_required`, `deposit_amount_rials`, `is_reserve`.
`is_reserve: true` → day-level reserve entry: `slot_end` may equal `slot_start`, the past-slot rule is skipped, and the entry never occupies a slot (several reserves may share a day). Response `201` now also returns `is_reserve`.
### GET `/api/v1/my/appointments` (extended)
New query param `reserve=1` → returns only reserve-list entries; without it only regular slot bookings are returned. Each row now also includes: `patient_uuid`, `is_reserve`, `deposit_required`, `deposit_amount_rials`, `note`, `service_section`, `service_item`, `staff` (each `{uuid, name|full_name}` or null).
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260713195434 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE appointments ADD deposit_required TINYINT DEFAULT 0 NOT NULL, ADD deposit_amount_rials INT DEFAULT NULL, ADD is_reserve TINYINT DEFAULT 0 NOT NULL, ADD service_section_id INT DEFAULT NULL, ADD service_item_id INT DEFAULT NULL, ADD staff_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE appointments ADD CONSTRAINT FK_6A41727A4E72DACE FOREIGN KEY (service_section_id) REFERENCES service_sections (id) ON DELETE SET NULL');
$this->addSql('ALTER TABLE appointments ADD CONSTRAINT FK_6A41727ADDEB00C2 FOREIGN KEY (service_item_id) REFERENCES service_items (id) ON DELETE SET NULL');
$this->addSql('ALTER TABLE appointments ADD CONSTRAINT FK_6A41727AD4D57CD FOREIGN KEY (staff_id) REFERENCES clinic_staff (id) ON DELETE SET NULL');
$this->addSql('CREATE INDEX IDX_6A41727A4E72DACE ON appointments (service_section_id)');
$this->addSql('CREATE INDEX IDX_6A41727ADDEB00C2 ON appointments (service_item_id)');
$this->addSql('CREATE INDEX IDX_6A41727AD4D57CD ON appointments (staff_id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE appointments DROP FOREIGN KEY FK_6A41727A4E72DACE');
$this->addSql('ALTER TABLE appointments DROP FOREIGN KEY FK_6A41727ADDEB00C2');
$this->addSql('ALTER TABLE appointments DROP FOREIGN KEY FK_6A41727AD4D57CD');
$this->addSql('DROP INDEX IDX_6A41727A4E72DACE ON appointments');
$this->addSql('DROP INDEX IDX_6A41727ADDEB00C2 ON appointments');
$this->addSql('DROP INDEX IDX_6A41727AD4D57CD ON appointments');
$this->addSql('ALTER TABLE appointments DROP deposit_required, DROP deposit_amount_rials, DROP is_reserve, DROP service_section_id, DROP service_item_id, DROP staff_id');
}
}
@@ -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);
+77 -3
View File
@@ -19,6 +19,7 @@ class Appointment
// ↘ cancelled_by_doctor / cancelled_by_user
// pending → expired (cron)
// confirmed → no_show
// Day-of clinic workflow (Figma نوبت‌ها): confirmed → following_up → salon → completed
public const STATUS_PENDING = 'pending';
public const STATUS_CONFIRMED = 'confirmed';
public const STATUS_COMPLETED = 'completed';
@@ -26,12 +27,16 @@ class Appointment
public const STATUS_CANCELLED_BY_USER = 'cancelled_by_user';
public const STATUS_EXPIRED = 'expired';
public const STATUS_NO_SHOW = 'no_show';
public const STATUS_FOLLOWING_UP = 'following_up'; // در حال پیگیری
public const STATUS_SALON = 'salon'; // سالن (در اتاق انتظار)
public const PAYMENT_TTL = 900; // 15 minutes to pay before a pending booking expires
public const ALLOWED_TRANSITIONS = [
self::STATUS_PENDING => [self::STATUS_CONFIRMED, self::STATUS_CANCELLED_BY_DOCTOR, self::STATUS_CANCELLED_BY_USER, self::STATUS_EXPIRED],
self::STATUS_CONFIRMED => [self::STATUS_COMPLETED, self::STATUS_CANCELLED_BY_DOCTOR, self::STATUS_CANCELLED_BY_USER, self::STATUS_NO_SHOW],
self::STATUS_PENDING => [self::STATUS_CONFIRMED, self::STATUS_FOLLOWING_UP, self::STATUS_CANCELLED_BY_DOCTOR, self::STATUS_CANCELLED_BY_USER, self::STATUS_EXPIRED],
self::STATUS_CONFIRMED => [self::STATUS_COMPLETED, self::STATUS_FOLLOWING_UP, self::STATUS_SALON, self::STATUS_CANCELLED_BY_DOCTOR, self::STATUS_CANCELLED_BY_USER, self::STATUS_NO_SHOW],
self::STATUS_FOLLOWING_UP => [self::STATUS_CONFIRMED, self::STATUS_SALON, self::STATUS_COMPLETED, self::STATUS_CANCELLED_BY_DOCTOR, self::STATUS_CANCELLED_BY_USER, self::STATUS_NO_SHOW],
self::STATUS_SALON => [self::STATUS_COMPLETED, self::STATUS_FOLLOWING_UP, self::STATUS_CANCELLED_BY_DOCTOR, self::STATUS_CANCELLED_BY_USER, self::STATUS_NO_SHOW],
];
/**
@@ -107,6 +112,37 @@ class Appointment
#[ORM\Column(name: 'booking_representation_id', type: 'integer', nullable: true)]
private ?int $bookingRepresentationId = null;
// ── Clinic-workflow fields (Figma نوبت‌ها) ────────────────────────────────
/** بخش — clinic service section this appointment belongs to. */
#[ORM\ManyToOne(targetEntity: \App\ClinicService\Entity\ServiceSection::class)]
#[ORM\JoinColumn(name: 'service_section_id', nullable: true, onDelete: 'SET NULL')]
private ?\App\ClinicService\Entity\ServiceSection $serviceSection = null;
/** سرویس — concrete service item to perform. */
#[ORM\ManyToOne(targetEntity: \App\ClinicService\Entity\ServiceItem::class)]
#[ORM\JoinColumn(name: 'service_item_id', nullable: true, onDelete: 'SET NULL')]
private ?\App\ClinicService\Entity\ServiceItem $serviceItem = null;
/** پرسنل — staff member assigned to the appointment. */
#[ORM\ManyToOne(targetEntity: \App\Staff\Entity\ClinicStaff::class)]
#[ORM\JoinColumn(name: 'staff_id', nullable: true, onDelete: 'SET NULL')]
private ?\App\Staff\Entity\ClinicStaff $staff = null;
/** بیعانه مورد نیاز است. */
#[ORM\Column(name: 'deposit_required', type: 'boolean', options: ['default' => false])]
private bool $depositRequired = false;
#[ORM\Column(name: 'deposit_amount_rials', type: 'integer', nullable: true)]
private ?int $depositAmountRials = null;
/**
* Reserve-list entry (نوبت رزرو): booked for a day, not a time slot.
* slotStart/slotEnd hold that day's midnight so date queries keep working.
*/
#[ORM\Column(name: 'is_reserve', type: 'boolean', options: ['default' => false])]
private bool $isReserve = false;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
@@ -131,7 +167,9 @@ class Appointment
*/
private function refreshActiveSlotKey(): void
{
$this->activeSlotKey = in_array($this->status, self::SLOT_OCCUPYING_STATUSES, true)
// Reserve-list entries are day-level wishes, not slot bookings — they
// never occupy a slot, so several reserves may share the same day.
$this->activeSlotKey = !$this->isReserve && in_array($this->status, self::SLOT_OCCUPYING_STATUSES, true)
? sprintf('%d:%d', $this->doctor->getId(), $this->slotStart)
: null;
}
@@ -163,6 +201,36 @@ class Appointment
public function setPatientGender(?string $v): self { $this->patientGender = $v; return $this; }
public function setPatientReason(?string $v): self { $this->patientReason = $v; return $this; }
public function getServiceSection(): ?\App\ClinicService\Entity\ServiceSection { return $this->serviceSection; }
public function getServiceItem(): ?\App\ClinicService\Entity\ServiceItem { return $this->serviceItem; }
public function getStaff(): ?\App\Staff\Entity\ClinicStaff { return $this->staff; }
public function isDepositRequired(): bool { return $this->depositRequired; }
public function getDepositAmountRials(): ?int { return $this->depositAmountRials; }
public function isReserve(): bool { return $this->isReserve; }
public function setServiceSection(?\App\ClinicService\Entity\ServiceSection $v): self { $this->serviceSection = $v; return $this; }
public function setServiceItem(?\App\ClinicService\Entity\ServiceItem $v): self { $this->serviceItem = $v; return $this; }
public function setStaff(?\App\Staff\Entity\ClinicStaff $v): self { $this->staff = $v; return $this; }
public function setDepositRequired(bool $v): self { $this->depositRequired = $v; return $this; }
public function setDepositAmountRials(?int $v): self { $this->depositAmountRials = $v; return $this; }
/**
* Move the appointment to a new slot (جا به جایی نوبت) and/or flip its
* reserve flag (انتقال به لیست رزرو و بالعکس). Goes through here — not raw
* setters — so active_slot_key stays consistent with the new slot.
*/
public function rescheduleTo(int $slotStart, int $slotEnd, ?bool $isReserve = null): self
{
$this->slotStart = $slotStart;
$this->slotEnd = $slotEnd;
if ($isReserve !== null) {
$this->isReserve = $isReserve;
}
$this->updatedAt = time();
$this->refreshActiveSlotKey();
return $this;
}
public function markPendingWithTtl(int $ttl): self
{
$this->expiresAt = time() + $ttl;
@@ -231,6 +299,12 @@ class Appointment
'patient_national_code' => $this->patientNationalCode,
'patient_gender' => $this->patientGender,
'patient_reason' => $this->patientReason,
'service_section' => $this->serviceSection ? ['uuid' => $this->serviceSection->getUuid(), 'name' => $this->serviceSection->getName()] : null,
'service_item' => $this->serviceItem ? ['uuid' => $this->serviceItem->getUuid(), 'name' => $this->serviceItem->getName()] : null,
'staff' => $this->staff ? ['uuid' => $this->staff->getUuid(), 'full_name' => $this->staff->getFullName()] : null,
'deposit_required' => $this->depositRequired,
'deposit_amount_rials' => $this->depositAmountRials,
'is_reserve' => $this->isReserve,
'version' => $this->version,
'created_at' => $this->createdAt,
'updated_at' => $this->updatedAt,
@@ -0,0 +1,105 @@
<?php
namespace App\Tests\Appointment;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceSection;
use App\Doctor\Entity\Doctor;
use App\Staff\Entity\ClinicStaff;
use App\Tests\ApiTestCase;
/**
* POST /api/v1/my/appointment extensions (workflow fields + reserve entries)
* and the GET /api/v1/my/appointments ?reserve list split.
*/
class AppointmentCreateReserveTest extends ApiTestCase
{
/** @return array{0: \App\Auth\Entity\User, 1: Doctor} */
private function doctor(): array
{
$owner = $this->createUser(['ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر');
$this->em->persist($doctor);
$this->em->flush();
return [$owner, $doctor];
}
public function testCreateWithWorkflowFields(): void
{
[$owner, $doctor] = $this->doctor();
$section = new ServiceSection('doctor', $doctor->getId(), 'زیبایی');
$item = new ServiceItem($section, 'لیزر فول بادی');
$staff = new ClinicStaff('doctor', $doctor->getId(), 'سحر ایمانی');
$this->em->persist($section);
$this->em->persist($item);
$this->em->persist($staff);
$this->em->flush();
$start = time() + 86_400;
$res = $this->authJson('POST', '/api/v1/my/appointment', $owner, [
'doctor_uuid' => $doctor->getUuid(),
'slot_start' => $start,
'slot_end' => $start + 2_400,
'patient_mobile' => '09' . random_int(100000000, 999999999),
'patient_name' => 'مریم اسکندری',
'service_section_uuid' => $section->getUuid(),
'service_item_uuid' => $item->getUuid(),
'staff_uuid' => $staff->getUuid(),
'deposit_required' => true,
'deposit_amount_rials' => 5_000_000,
]);
self::assertSame(201, $this->responseCode());
self::assertFalse($res['data']['is_reserve']);
$list = $this->authJson('GET', '/api/v1/my/appointments?limit=50', $owner);
$row = $list['data'][0];
self::assertSame('لیزر فول بادی', $row['service_item']['name']);
self::assertSame('سحر ایمانی', $row['staff']['full_name']);
self::assertTrue($row['deposit_required']);
}
public function testReserveEntriesSkipSlotRulesAndAreListedSeparately(): void
{
[$owner, $doctor] = $this->doctor();
$day = strtotime('today midnight'); // past for a slot booking — fine for a reserve
// two reserves on the same day must both succeed (no slot occupation)
foreach (['ساغر صابری', 'پریسا همتی'] as $name) {
$this->authJson('POST', '/api/v1/my/appointment', $owner, [
'doctor_uuid' => $doctor->getUuid(),
'slot_start' => $day,
'slot_end' => $day,
'patient_mobile' => '09' . random_int(100000000, 999999999),
'patient_name' => $name,
'is_reserve' => true,
]);
self::assertSame(201, $this->responseCode());
}
$reserves = $this->authJson('GET', '/api/v1/my/appointments?reserve=1&limit=50', $owner);
self::assertCount(2, $reserves['data']);
self::assertTrue($reserves['data'][0]['is_reserve']);
// the regular list must not contain reserve entries
$regular = $this->authJson('GET', '/api/v1/my/appointments?limit=50', $owner);
self::assertCount(0, $regular['data']);
}
public function testUnknownServiceUuidIs422(): void
{
[$owner, $doctor] = $this->doctor();
$start = time() + 86_400;
$this->authJson('POST', '/api/v1/my/appointment', $owner, [
'doctor_uuid' => $doctor->getUuid(),
'slot_start' => $start,
'slot_end' => $start + 1_800,
'patient_mobile' => '09' . random_int(100000000, 999999999),
'patient_name' => 'x',
'service_item_uuid' => 'missing-uuid',
]);
self::assertSame(422, $this->responseCode());
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
namespace App\Tests\Appointment;
use App\Appointment\Entity\Appointment;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceSection;
use App\Doctor\Entity\Doctor;
use App\Staff\Entity\ClinicStaff;
use App\Tests\ApiTestCase;
/**
* PATCH /api/v1/appointment/{uuid} — general update used by ویرایش,
* جا به جایی, انتقال به رزرو and جایگزینی نوبت.
*/
class AppointmentUpdateTest extends ApiTestCase
{
/** @return array{0: \App\Auth\Entity\User, 1: Doctor, 2: Appointment} */
private function booking(): array
{
$owner = $this->createUser(['ROLE_DOCTOR']);
$doctor = new Doctor($owner, 'دکتر');
$this->em->persist($doctor);
$this->em->flush();
$appointment = new Appointment($doctor, $this->createUser(), time() + 86_400, time() + 86_400 + 1_800);
$this->em->persist($appointment);
$this->em->flush();
return [$owner, $doctor, $appointment];
}
public function testUpdatesWorkflowFields(): void
{
[$owner, $doctor, $appointment] = $this->booking();
$section = new ServiceSection('doctor', $doctor->getId(), 'زیبایی');
$item = new ServiceItem($section, 'لیزر توتال');
$staff = new ClinicStaff('doctor', $doctor->getId(), 'سحر ایمانی');
$this->em->persist($section);
$this->em->persist($item);
$this->em->persist($staff);
$this->em->flush();
$res = $this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'service_section_uuid' => $section->getUuid(),
'service_item_uuid' => $item->getUuid(),
'staff_uuid' => $staff->getUuid(),
'deposit_required' => true,
'deposit_amount_rials' => 5_000_000,
'note' => 'یادداشت',
'patient_name' => 'مریم خلیلی',
]);
self::assertSame(200, $this->responseCode());
$d = $res['data']['data'];
self::assertSame('زیبایی', $d['service_section']['name']);
self::assertSame('لیزر توتال', $d['service_item']['name']);
self::assertSame('سحر ایمانی', $d['staff']['full_name']);
self::assertTrue($d['deposit_required']);
self::assertSame('مریم خلیلی', $d['patient_name']);
}
public function testRescheduleMovesSlot(): void
{
[$owner, , $appointment] = $this->booking();
$newStart = time() + 2 * 86_400;
$res = $this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'slot_start' => $newStart, 'slot_end' => $newStart + 1_800,
]);
self::assertSame(200, $this->responseCode());
self::assertSame($newStart, $res['data']['data']['slot_start']);
}
public function testRescheduleRejectsTakenSlot(): void
{
[$owner, $doctor, $appointment] = $this->booking();
$otherStart = time() + 3 * 86_400;
$this->em->persist(new Appointment($doctor, $this->createUser(), $otherStart, $otherStart + 1_800));
$this->em->flush();
$this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'slot_start' => $otherStart, 'slot_end' => $otherStart + 1_800,
]);
self::assertSame(409, $this->responseCode());
}
public function testTransferToReserveAndBack(): void
{
[$owner, , $appointment] = $this->booking();
$day = strtotime('tomorrow midnight');
$res = $this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'is_reserve' => true, 'slot_start' => $day, 'slot_end' => $day,
]);
self::assertSame(200, $this->responseCode());
self::assertTrue($res['data']['data']['is_reserve']);
$back = time() + 4 * 86_400;
$version = $res['data']['data']['version'];
$res2 = $this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'is_reserve' => false, 'slot_start' => $back, 'slot_end' => $back + 1_800, 'version' => $version,
]);
self::assertSame(200, $this->responseCode());
self::assertFalse($res2['data']['data']['is_reserve']);
}
public function testRejectsHalfSlotPair(): void
{
[$owner, , $appointment] = $this->booking();
$this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'slot_start' => time() + 86_400,
]);
self::assertSame(422, $this->responseCode());
}
public function testForbiddenForStranger(): void
{
[, , $appointment] = $this->booking();
$stranger = $this->createUser(['ROLE_DOCTOR']);
$this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $stranger, ['note' => 'x']);
self::assertSame(403, $this->responseCode());
}
public function testUnknownStaffUuidIs422(): void
{
[$owner, , $appointment] = $this->booking();
$this->authJson('PATCH', '/api/v1/appointment/' . $appointment->getUuid(), $owner, [
'staff_uuid' => 'no-such-uuid',
]);
self::assertSame(422, $this->responseCode());
}
}
@@ -0,0 +1,88 @@
<?php
namespace App\Tests\Appointment;
use App\Appointment\Entity\Appointment;
use App\Doctor\Entity\Doctor;
use App\Tests\ApiTestCase;
/**
* Clinic-workflow additions on Appointment: following_up/salon statuses,
* service section/item + staff relations, deposit fields, reserve flag,
* and rescheduleTo keeping active_slot_key consistent.
*/
class AppointmentWorkflowFieldsTest extends ApiTestCase
{
private function makeDoctor(): Doctor
{
$doctor = new Doctor($this->createUser(['ROLE_DOCTOR']), 'دکتر تست');
$this->em->persist($doctor);
$this->em->flush();
return $doctor;
}
private function newBooking(Doctor $doctor, int $start): Appointment
{
$a = new Appointment($doctor, $this->createUser(), $start, $start + 1_800);
$this->em->persist($a);
$this->em->flush();
return $a;
}
public function testDayOfWorkflowTransitions(): void
{
$a = $this->newBooking($this->makeDoctor(), time() + 86_400);
$a->transitionTo(Appointment::STATUS_CONFIRMED);
$a->transitionTo(Appointment::STATUS_FOLLOWING_UP);
$a->transitionTo(Appointment::STATUS_SALON);
$a->transitionTo(Appointment::STATUS_COMPLETED);
$this->em->flush();
self::assertSame(Appointment::STATUS_COMPLETED, $a->getStatus());
}
public function testPendingCannotJumpToSalon(): void
{
$a = $this->newBooking($this->makeDoctor(), time() + 86_400);
$this->expectException(\LogicException::class);
$a->transitionTo(Appointment::STATUS_SALON);
}
public function testWorkflowFieldsPersistAndSerialize(): void
{
$a = $this->newBooking($this->makeDoctor(), time() + 86_400);
$a->setDepositRequired(true)
->setDepositAmountRials(5_000_000);
$a->rescheduleTo($a->getSlotStart(), $a->getSlotEnd(), true);
$this->em->flush();
$this->em->clear();
$reloaded = $this->em->getRepository(Appointment::class)->findOneBy(['uuid' => $a->getUuid()]);
$arr = $reloaded->toArray();
self::assertTrue($arr['deposit_required']);
self::assertSame(5_000_000, $arr['deposit_amount_rials']);
self::assertTrue($arr['is_reserve']);
self::assertNull($arr['service_section']);
self::assertNull($arr['staff']);
}
public function testRescheduleFreesTheOldSlot(): void
{
$doctor = $this->makeDoctor();
$start = time() + 86_400;
$first = $this->newBooking($doctor, $start);
$first->rescheduleTo($start + 3_600, $start + 5_400);
$this->em->flush();
// old slot must be free again — a new live booking on it succeeds
$second = $this->newBooking($doctor, $start);
self::assertNotNull($second->getId());
}
}