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
@@ -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({
</div>
<div className="modal-body">
<p style={{ color: 'var(--text-2)', lineHeight: 1.75, margin: 0 }}>{message}</p>
{children}
</div>
<div className="modal-foot" style={{ justifyContent: 'flex-end' }}>
<button className="btn ghost sm" onClick={onCancel} disabled={loading}>
+59 -4
View File
@@ -5,7 +5,7 @@ import { ArrowRightIcon } from '@heroicons/react/24/outline';
import { toast } from 'sonner';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import type { Appointment, AppointmentStatus } from '../types';
import type { Appointment, AppointmentStatus, AppointmentEvent } from '../types';
import { formatDate, formatDateTime, toDate } from '../lib/utils';
import PageHeader from '../components/ui/PageHeader';
import StatusBadge from '../components/ui/StatusBadge';
@@ -50,6 +50,7 @@ export default function AppointmentDetailPage() {
const navigate = useNavigate();
const qc = useQueryClient();
const [cancelOpen, setCancelOpen] = useState(false);
const [cancelReason, setCancelReason] = useState('');
const [newStatus, setNewStatus] = useState('');
const { data, isLoading } = useQuery({
@@ -58,22 +59,35 @@ export default function AppointmentDetailPage() {
enabled: !!uuid,
});
const eventsQuery = useQuery({
queryKey: ['appointment-events', uuid],
queryFn: () => api.get<ApiResponse<AppointmentEvent[]>>(`/api/v1/appointment/${uuid}/events`),
enabled: !!uuid,
});
const events: AppointmentEvent[] = (eventsQuery.data?.data as any) ?? [];
const statusMutation = useMutation({
mutationFn: (status: string) =>
api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, { status }),
onSuccess: () => {
toast.success('وضعیت نوبت بروزرسانی شد');
qc.invalidateQueries({ queryKey: ['appointment', uuid] });
qc.invalidateQueries({ queryKey: ['appointment-events', uuid] });
},
onError: (err: Error) => toast.error(err.message),
});
const cancelMutation = useMutation({
mutationFn: () => api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, { status: 'cancelled_by_doctor' }),
mutationFn: () => api.patch<ApiResponse<null>>(`/api/v1/appointment/${uuid}/status`, {
status: 'cancelled_by_doctor',
...(cancelReason.trim() ? { cancel_reason: cancelReason.trim() } : {}),
}),
onSuccess: () => {
toast.success('نوبت لغو شد');
setCancelOpen(false);
setCancelReason('');
qc.invalidateQueries({ queryKey: ['appointment', uuid] });
qc.invalidateQueries({ queryKey: ['appointment-events', uuid] });
},
onError: (err: Error) => toast.error(err.message),
});
@@ -161,6 +175,35 @@ export default function AppointmentDetailPage() {
</button>
</div>
</div>
<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 lg:col-span-2">
<h3 className="font-semibold text-gray-800 mb-4">تاریخچه رویدادها</h3>
{eventsQuery.isLoading ? (
<div className="h-6 w-40 rounded skeleton" />
) : events.length === 0 ? (
<p className="text-sm text-gray-400">رویدادی برای این نوبت ثبت نشده است.</p>
) : (
<ol className="space-y-4">
{events.map((ev, i) => (
<li key={i} className="flex gap-3">
<span className="mt-1.5 w-2.5 h-2.5 rounded-full bg-red-500 shrink-0" />
<div className="flex-1">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium text-gray-800">{ev.title}</span>
<span className="text-xs text-gray-400">{formatDateTime(ev.created_at)}</span>
</div>
{ev.actor_name && (
<div className="text-xs text-gray-500 mt-0.5">توسط: {ev.actor_name}</div>
)}
{ev.reason && (
<div className="text-xs text-gray-600 mt-0.5">دلیل: {ev.reason}</div>
)}
</div>
</li>
))}
</ol>
)}
</div>
</div>
) : (
<div className="bg-white rounded-2xl border border-gray-100 p-16 text-center text-gray-400">
@@ -176,8 +219,20 @@ export default function AppointmentDetailPage() {
danger
loading={cancelMutation.isPending}
onConfirm={() => cancelMutation.mutate()}
onCancel={() => setCancelOpen(false)}
/>
onCancel={() => { setCancelOpen(false); setCancelReason(''); }}
>
<div style={{ marginTop: 14 }}>
<label className="cp-label mb-2">دلیل لغو (اختیاری)</label>
<textarea
className="cp-input"
rows={2}
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
placeholder="دلیل لغو نوبت را وارد کنید..."
style={{ width: '100%', resize: 'vertical' }}
/>
</div>
</ConfirmDialog>
</div>
);
}
+8
View File
@@ -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"
+43 -3
View File
@@ -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: <appointment.toArray()> } }`
+31
View File
@@ -0,0 +1,31 @@
<?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 Version20260717073617 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add appointment_events table (appointment Timeline / audit events)';
}
public function up(Schema $schema): void
{
$this->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');
}
}
@@ -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();
}
}