diff --git a/assets/admin/components/ui/ConfirmDialog.tsx b/assets/admin/components/ui/ConfirmDialog.tsx
index f031428b..1b9d298e 100644
--- a/assets/admin/components/ui/ConfirmDialog.tsx
+++ b/assets/admin/components/ui/ConfirmDialog.tsx
@@ -12,6 +12,8 @@ interface Props {
loading?: boolean;
onConfirm: () => void;
onCancel: () => void;
+ /** محتوای اضافه زیر پیام (مثلاً فیلد دلیل). */
+ children?: React.ReactNode;
}
export default function ConfirmDialog({
@@ -24,6 +26,7 @@ export default function ConfirmDialog({
loading = false,
onConfirm,
onCancel,
+ children,
}: Props) {
if (!open) return null;
@@ -48,6 +51,7 @@ export default function ConfirmDialog({
+
+
+
تاریخچه رویدادها
+ {eventsQuery.isLoading ? (
+
+ ) : events.length === 0 ? (
+
رویدادی برای این نوبت ثبت نشده است.
+ ) : (
+
+ {events.map((ev, i) => (
+ -
+
+
+
+ {ev.title}
+ {formatDateTime(ev.created_at)}
+
+ {ev.actor_name && (
+
توسط: {ev.actor_name}
+ )}
+ {ev.reason && (
+
دلیل: {ev.reason}
+ )}
+
+
+ ))}
+
+ )}
+
) : (
@@ -176,8 +219,20 @@ export default function AppointmentDetailPage() {
danger
loading={cancelMutation.isPending}
onConfirm={() => cancelMutation.mutate()}
- onCancel={() => setCancelOpen(false)}
- />
+ onCancel={() => { setCancelOpen(false); setCancelReason(''); }}
+ >
+
+
+
+
);
}
diff --git a/assets/admin/types/index.ts b/assets/admin/types/index.ts
index bcec24e5..2a0a2b41 100644
--- a/assets/admin/types/index.ts
+++ b/assets/admin/types/index.ts
@@ -116,6 +116,14 @@ export interface Appointment {
staff?: { uuid: string; full_name: string } | null;
}
+export interface AppointmentEvent {
+ type: string;
+ title: string;
+ actor_name: string | null;
+ reason: string | null;
+ created_at: number;
+}
+
export type PaymentStatus =
| "pending"
| "success"
diff --git a/docs/api/appointment.md b/docs/api/appointment.md
index fd9016e6..24d82ded 100644
--- a/docs/api/appointment.md
+++ b/docs/api/appointment.md
@@ -417,8 +417,9 @@ Change appointment status.
### Request Body
```json
{
- "status": "cancelled",
- "version": 3
+ "status": "cancelled_by_doctor",
+ "version": 3,
+ "cancel_reason": "بیمار درخواست لغو داد"
}
```
@@ -426,6 +427,7 @@ Change appointment status.
|-------|------|----------|-------------|
| `status` | string | ✅ | New status value |
| `version` | integer | ❌ | Optimistic lock version (prevents double-submit) |
+| `cancel_reason` | string | ❌ | Only when transitioning to `cancelled_by_doctor` / `cancelled_by_user`. Stored on the recorded cancellation event (Timeline). Ignored for other statuses. |
**Allowed Transitions by Role:**
| Actor | Allowed transitions |
@@ -434,6 +436,8 @@ Change appointment status.
| Doctor / Secretary | `pending → confirmed`, `confirmed → completed`, `confirmed → no_show` |
| Admin | Any transition |
+> **Cancellation is logged.** When the status becomes `cancelled_by_doctor` or `cancelled_by_user`, an `AppointmentEvent` (type `cancelled`, title «نوبت لغو شد») is recorded with the actor (user id + name), the optional `cancel_reason`, and the cancel time — surfaced via `GET /api/v1/appointment/{uuid}/events`. A `warning`-level entry is also written to `app_log`.
+
### Response `200`
Updated appointment object.
@@ -448,6 +452,42 @@ Updated appointment object.
---
+## GET `/api/v1/appointment/{uuid}/events`
+
+Appointment Timeline — chronological event history for one appointment. Currently records cancellation events; the structure is generic for future event types.
+
+**Permission:** `IS_AUTHENTICATED_FULLY` — caller must be able to manage the appointment (`canManage`).
+
+### Path Parameters
+| Param | Type | Description |
+|-------|------|-------------|
+| `uuid` | string (UUID) | Appointment UUID |
+
+### Response `200`
+```json
+{
+ "success": true,
+ "data": [
+ {
+ "type": "cancelled",
+ "title": "نوبت لغو شد",
+ "actor_name": "دکتر حامد حسینی",
+ "reason": "بیمار درخواست لغو داد",
+ "created_at": 1784273931
+ }
+ ]
+}
+```
+Events are ordered oldest → newest. `data` is a flat array (single nesting). `actor_name` and `reason` may be `null`. `created_at` is a Unix timestamp.
+
+### Errors
+| Code | HTTP | Description |
+|------|------|-------------|
+| `ERR_AUTH_006` | 403 | Not allowed to manage this appointment |
+| `ERR_VALIDATION_002` | 404 | Appointment not found |
+
+---
+
## POST `/api/v1/my/appointment`
Create a new appointment for a patient. Used by doctor/clinic/secretary to book appointments on behalf of patients. If no user exists with the given mobile, a new user account is created automatically.
@@ -619,7 +659,7 @@ General update (ویرایش / جا به جایی / انتقال به رزرو /
- `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`.
+- `status` follows the same transition rules as `PATCH /appointment/{uuid}/status`. A transition to `cancelled_by_doctor`/`cancelled_by_user` records a cancellation event (Timeline) + `app_log` warning; an optional `cancel_reason` body field is stored on the event.
- Optimistic lock via `version` → `409` on concurrent edit.
Response `200`: `{ success, data: { data: } }`
diff --git a/migrations/Version20260717073617.php b/migrations/Version20260717073617.php
new file mode 100644
index 00000000..b3bccfa2
--- /dev/null
+++ b/migrations/Version20260717073617.php
@@ -0,0 +1,31 @@
+addSql('CREATE TABLE appointment_events (id INT AUTO_INCREMENT NOT NULL, uuid VARCHAR(36) NOT NULL, type VARCHAR(40) NOT NULL, title VARCHAR(191) NOT NULL, actor_user_id INT DEFAULT NULL, actor_name VARCHAR(191) DEFAULT NULL, reason LONGTEXT DEFAULT NULL, created_at INT NOT NULL, appointment_id INT NOT NULL, UNIQUE INDEX UNIQ_14D9E804D17F50A6 (uuid), INDEX IDX_14D9E804E5B533F9 (appointment_id), INDEX idx_appointment_events_appt (appointment_id, created_at), PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');
+ $this->addSql('ALTER TABLE appointment_events ADD CONSTRAINT FK_14D9E804E5B533F9 FOREIGN KEY (appointment_id) REFERENCES appointments (id) ON DELETE CASCADE');
+ }
+
+ public function down(Schema $schema): void
+ {
+ $this->addSql('ALTER TABLE appointment_events DROP FOREIGN KEY FK_14D9E804E5B533F9');
+ $this->addSql('DROP TABLE appointment_events');
+ }
+}
diff --git a/src/Appointment/Controller/AppointmentController.php b/src/Appointment/Controller/AppointmentController.php
index 0083bb77..d482baf6 100644
--- a/src/Appointment/Controller/AppointmentController.php
+++ b/src/Appointment/Controller/AppointmentController.php
@@ -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));
+ }
}
diff --git a/src/Appointment/Entity/AppointmentEvent.php b/src/Appointment/Entity/AppointmentEvent.php
new file mode 100644
index 00000000..b197b3cc
--- /dev/null
+++ b/src/Appointment/Entity/AppointmentEvent.php
@@ -0,0 +1,77 @@
+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,
+ ];
+ }
+}
diff --git a/src/Appointment/Repository/AppointmentEventRepository.php b/src/Appointment/Repository/AppointmentEventRepository.php
new file mode 100644
index 00000000..6d5d33f5
--- /dev/null
+++ b/src/Appointment/Repository/AppointmentEventRepository.php
@@ -0,0 +1,31 @@
+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();
+ }
+}