feat(appointment): log cancellation events and show them in a Timeline

Introduce the first per-appointment event system. On cancel (via the status
or general update endpoints) an AppointmentEvent (type=cancelled, «نوبت لغو
شد») is recorded with the actor, cancel time, and an optional cancel_reason,
plus a warning-level app_log entry. New GET /appointment/{uuid}/events
returns the ordered event list. The admin appointment detail page renders a
Timeline section and the cancel dialog now collects an optional reason.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-17 11:13:23 +03:30
co-authored by Claude Fable 5
parent 36d7fe0303
commit 49b2ca60d7
8 changed files with 311 additions and 8 deletions
@@ -36,8 +36,34 @@ class AppointmentController extends BaseController
private readonly \App\ClinicService\Repository\ServiceSectionRepository $sectionRepo,
private readonly \App\ClinicService\Repository\ServiceItemRepository $itemRepo,
private readonly \App\Staff\Repository\ClinicStaffRepository $staffRepo,
private readonly \App\Appointment\Repository\AppointmentEventRepository $eventRepo,
private readonly \Psr\Log\LoggerInterface $logger,
) {}
private const CANCEL_STATUSES = [
Appointment::STATUS_CANCELLED_BY_DOCTOR,
Appointment::STATUS_CANCELLED_BY_USER,
];
/**
* ثبت رویداد لغو در Timeline نوبت + لاگ سطح warning (تا در app_log هم persist شود).
* بعد از ذخیره‌ی موفق نوبت صدا زده می‌شود.
*/
private function recordCancellation(Appointment $appointment, string $status, ?string $reason, User $user): void
{
$actorName = $user->getRealName() ?: $user->getMobileNumber();
$event = new \App\Appointment\Entity\AppointmentEvent($appointment, \App\Appointment\Entity\AppointmentEvent::TYPE_CANCELLED, 'نوبت لغو شد');
$event->setActor($user->getId(), $actorName);
$event->setReason($reason);
$this->eventRepo->save($event);
$this->logger->warning(sprintf(
'Appointment cancelled: uuid=%s status=%s by user=%d(%s) reason=%s',
$appointment->getUuid(), $status, (int) $user->getId(), $actorName, $reason ?? '-'
));
}
// ── Public: available slots ───────────────────────────────────────────────
#[OA\Get(
@@ -665,6 +691,11 @@ class AppointmentController extends BaseController
$this->patientService->autoCreateOnAppointmentConfirm($appointment);
}
if (in_array($newStatus, self::CANCEL_STATUSES, true)) {
$reason = isset($data['cancel_reason']) ? trim((string) $data['cancel_reason']) : '';
$this->recordCancellation($appointment, $newStatus, $reason !== '' ? $reason : null, $user);
}
return $this->success(['data' => $appointment->toArray()]);
}
@@ -750,7 +781,8 @@ class AppointmentController extends BaseController
}
// Optional status transition, same rules as the dedicated endpoint.
$newStatus = trim((string) ($data['status'] ?? ''));
$newStatus = trim((string) ($data['status'] ?? ''));
$cancelledTo = null;
if ($newStatus !== '' && $newStatus !== $appointment->getStatus()) {
if (!$appointment->canTransitionTo($newStatus)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, sprintf(
@@ -761,6 +793,9 @@ class AppointmentController extends BaseController
if ($newStatus === Appointment::STATUS_CONFIRMED) {
$this->patientService->autoCreateOnAppointmentConfirm($appointment);
}
if (in_array($newStatus, self::CANCEL_STATUSES, true)) {
$cancelledTo = $newStatus;
}
}
try {
@@ -772,6 +807,28 @@ class AppointmentController extends BaseController
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'این بازه زمانی قبلاً رزرو شده است', 409, 'slot_start');
}
if ($cancelledTo !== null) {
$reason = isset($data['cancel_reason']) ? trim((string) $data['cancel_reason']) : '';
$this->recordCancellation($appointment, $cancelledTo, $reason !== '' ? $reason : null, $user);
}
return $this->success(['data' => $appointment->toArray()]);
}
// ── Timeline: رویدادهای یک نوبت ───────────────────────────────────────────
#[Route('/api/v1/appointment/{uuid}/events', methods: ['GET'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function events(string $uuid, #[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);
}
return $this->success($this->eventRepo->findByAppointmentUuid($uuid));
}
}
@@ -0,0 +1,77 @@
<?php
namespace App\Appointment\Entity;
use App\Appointment\Repository\AppointmentEventRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* تاریخچه‌ی رویدادهای یک نوبت (Timeline). فعلاً فقط رویداد لغو ثبت می‌شود، اما
* ساختار عمومی است تا رویدادهای بعدی (ایجاد/تأیید/جابه‌جایی) هم قابل افزودن باشند.
*/
#[ORM\Entity(repositoryClass: AppointmentEventRepository::class)]
#[ORM\Table(name: 'appointment_events')]
#[ORM\Index(columns: ['appointment_id', 'created_at'], name: 'idx_appointment_events_appt')]
class AppointmentEvent
{
public const TYPE_CANCELLED = 'cancelled';
#[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: Appointment::class)]
#[ORM\JoinColumn(name: 'appointment_id', nullable: false, onDelete: 'CASCADE')]
private Appointment $appointment;
#[ORM\Column(type: 'string', length: 40)]
private string $type;
#[ORM\Column(type: 'string', length: 191)]
private string $title;
// کاربرِ عاملِ رویداد (مثلاً لغوکننده)؛ null برای رویدادهای سیستمی.
#[ORM\Column(name: 'actor_user_id', type: 'integer', nullable: true)]
private ?int $actorUserId = null;
// کشِ نام عامل برای نمایش بدون join اضافه.
#[ORM\Column(name: 'actor_name', type: 'string', length: 191, nullable: true)]
private ?string $actorName = null;
#[ORM\Column(type: 'text', nullable: true)]
private ?string $reason = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
public function __construct(Appointment $appointment, string $type, string $title)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->appointment = $appointment;
$this->type = $type;
$this->title = $title;
$this->createdAt = time();
}
public function setActor(?int $userId, ?string $name): self { $this->actorUserId = $userId; $this->actorName = $name; return $this; }
public function setReason(?string $reason): self { $this->reason = $reason; return $this; }
public function getUuid(): string { return $this->uuid; }
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'type' => $this->type,
'title' => $this->title,
'actor_name' => $this->actorName,
'reason' => $this->reason,
'created_at' => $this->createdAt,
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Appointment\Repository;
use App\Appointment\Entity\AppointmentEvent;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class AppointmentEventRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry) { parent::__construct($registry, AppointmentEvent::class); }
public function save(AppointmentEvent $e, bool $flush = true): void
{
$this->getEntityManager()->persist($e);
if ($flush) {
$this->getEntityManager()->flush();
}
}
/** رویدادهای یک نوبت به‌ترتیب زمان (قدیمی → جدید)، به‌صورت آرایه. */
public function findByAppointmentUuid(string $appointmentUuid): array
{
return $this->createQueryBuilder('e')
->select('e.type AS type', 'e.title AS title', 'e.actorName AS actor_name', 'e.reason AS reason', 'e.createdAt AS created_at')
->join('e.appointment', 'a')
->where('a.uuid = :uuid')->setParameter('uuid', $appointmentUuid)
->orderBy('e.createdAt', 'ASC')
->getQuery()->getArrayResult();
}
}