feat: close the last four domain events, and the panel paths they describe

Every one of the fourteen named events now has an emit point. The four that
were missing all sat on paths owned by earlier tasks:

- AppointmentCompleted fires from both status-change routes, after the row is
  saved. A rejected transition or a version conflict leaves no event; otherwise
  the completed count runs ahead of the appointments themselves.
- AppointmentRescheduled is a third event, not a replacement. A rebook is a
  confirm plus a cancel, and a consumer that only hears the cancel messages a
  patient who still has an appointment.
- ResourceBlocked / ResourceReleased are a pair. Capacity coming back has to be
  as audible as capacity going away, or the resource reads as permanently taken.

Publishing is now on the scheduler rather than an unregistered command: the
logic moved out of PublishDomainEventsCommand into OutboxPublisher so the
recurring message and the manual command share it, and the existing
worker-scheduler container consumes it. The scheduler message carries no data
on purpose — what to publish is read from the table, so an event recorded
between two ticks is not skipped. DomainEventMessage routes to async, since a
slow consumer was otherwise slowing the drain itself and its failure marked a
row failed that had in fact been delivered.

Panel work that these paths made reachable:

- Cancelling from the appointment page now goes through the policy-aware
  endpoint and shows the penalty preview before the confirm, so the operator
  does not discover the patient's penalty after the fact. The cancellation
  service writes the timeline entry itself and accepts a reason, which that
  path previously dropped on the floor.
- Rescheduling reuses the booking page under ?rebook=<uuid> — the search and
  hold steps are identical and only the final step differs. The doctor picker
  is hidden there: a reschedule is not an invitation to change doctors.
- A new GET /appointment/{uuid}/segments exposes the recorded plan. An empty
  list is not an error, it means the appointment is slot-based, and that is
  exactly what gates the resource-mode reschedule button.

AppointmentInvoiceCard no longer crashes the whole detail page when an older
invoice has no discount breakdown.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-31 21:27:55 +03:30
co-authored by Claude Opus 5
parent b55c33f686
commit 4049daf071
29 changed files with 977 additions and 118 deletions
@@ -10,6 +10,8 @@ use App\Resource\Entity\ClinicResource;
use App\Resource\Repository\ClinicResourceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Event\DomainEventPublisher;
use App\Shared\Event\DomainEvents;
use App\Shared\Exception\AppException;
use App\Shared\Tenant\TenantOwnershipChecker;
use Doctrine\ORM\EntityManagerInterface;
@@ -43,6 +45,7 @@ class ResourceBlockController extends BaseController
private readonly ResourceOccupancyRepository $occupancy,
private readonly BranchResolver $branches,
private readonly TenantOwnershipChecker $ownership,
private readonly DomainEventPublisher $domainEvents,
private readonly EntityManagerInterface $em,
) {}
@@ -95,6 +98,19 @@ class ResourceBlockController extends BaseController
);
$this->em->persist($block);
$this->domainEvents->record(
$resource->getEntityType(),
$resource->getEntityId(),
DomainEvents::RESOURCE_BLOCKED,
[
'resource_uuid' => $resource->getUuid(),
'block_uuid' => $block->getUuid(),
'starts_at' => $startsAt,
'ends_at' => $endsAt,
],
);
$this->em->flush();
return $this->success($block->toArray(), 201);
@@ -120,6 +136,19 @@ class ResourceBlockController extends BaseController
);
}
// پیش از `remove` ثبت می‌شود چون بعد از آن، uuid و بازه فقط در حافظه‌اند و
// خواندنشان از یک entity حذف‌شده به رفتار Doctrine وابسته می‌ماند.
$this->domainEvents->record(
$entityType,
$entityId,
DomainEvents::RESOURCE_RELEASED,
[
'block_uuid' => $block->getUuid(),
'starts_at' => $block->getStartsAt(),
'ends_at' => $block->getEndsAt(),
],
);
$this->em->remove($block);
$this->em->flush();
@@ -3,7 +3,9 @@
namespace App\Appointment\Booking\Controller;
use App\Appointment\Booking\Entity\AppointmentHold;
use App\Appointment\Booking\Entity\AppointmentSegment;
use App\Appointment\Booking\Repository\AppointmentHoldRepository;
use App\Appointment\Booking\Repository\AppointmentSegmentRepository;
use App\Appointment\Booking\Service\BookingService;
use App\Appointment\Booking\Service\HoldService;
use App\Appointment\Entity\Appointment;
@@ -23,6 +25,8 @@ use App\Resource\Entity\ClinicResource;
use App\Resource\Repository\ClinicResourceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Event\DomainEventPublisher;
use App\Shared\Event\DomainEvents;
use App\Shared\Exception\AppException;
use App\Shared\Tenant\TenantOwnershipChecker;
use Doctrine\ORM\EntityManagerInterface;
@@ -55,6 +59,8 @@ class BookingController extends BaseController
private readonly BookingPolicyGuard $guard,
private readonly PackageConsumptionService $packages,
private readonly TenantOwnershipChecker $ownership,
private readonly AppointmentSegmentRepository $segments,
private readonly DomainEventPublisher $domainEvents,
private readonly EntityManagerInterface $em,
) {}
@@ -200,6 +206,29 @@ class BookingController extends BaseController
* ترتیب عمدی است — اگر رزرو جدید شکست بخورد، نوبت قدیمی دست‌نخورده می‌ماند و
* بیمار بی‌نوبت نمی‌شود. ترتیب برعکس، در بدترین حالت هر دو را از دست می‌داد.
*/
/**
* بخش‌های ثبت‌شدهٔ یک نوبت — عکسِ لحظهٔ رزرو، نه الگوی امروزِ خدمت.
*
* فهرست خالی یعنی نوبت اسلاتی است؛ خطا نیست. پنل با همین تفاوت می‌فهمد کدام نوبت
* را می‌شود منبع‌محور جابه‌جا کرد.
*/
#[Route('/api/v1/appointment/{uuid}/segments', name: 'appointment_segments', methods: ['GET'])]
public function segments(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$appointment = $this->em->getRepository(Appointment::class)->findOneBy(['uuid' => $uuid]);
[$entityType, $entityId] = $this->branches->pair($user);
if ($appointment === null || !$this->ownership->belongsToPair($entityType, $entityId, $appointment)) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'نوبت یافت نشد', 404);
}
return $this->success(array_map(
static fn (AppointmentSegment $s): array => $s->toArray(),
$this->segments->findForAppointment($appointment),
));
}
#[Route('/api/v1/appointment/{uuid}/rebook', name: 'appointment_rebook', methods: ['POST'])]
public function rebook(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
@@ -220,10 +249,26 @@ class BookingController extends BaseController
$hold = $this->requireHold($user, $data['hold_uuid']);
$previousStart = $appointment->getSlotStart();
// رزرو جدید از قبل گرفته شده؛ اینجا فقط تأیید و سپس آزادسازی قدیم.
$this->booking->confirm($hold, $appointment);
$released = $this->booking->cancel($appointment);
// `confirm` و `cancel` هرکدام رویداد خودشان را ثبت کرده‌اند؛ این سومی می‌گوید آن دو
// یک جابه‌جایی بوده‌اند نه یک لغو و یک رزروِ بی‌ربط. مصرف‌کننده‌ای که فقط
// `AppointmentCancelled` را بشنود، برای بیماری که هنوز نوبت دارد پیام لغو می‌فرستد.
$this->domainEvents->recordAndFlush(
$appointment->getEntityType(),
$appointment->getEntityId(),
DomainEvents::APPOINTMENT_RESCHEDULED,
[
'appointment_uuid' => $appointment->getUuid(),
'previous_start' => $previousStart,
'new_start' => $hold->getStartsAt(),
],
);
return $this->success([
'appointment_uuid' => $appointment->getUuid(),
'released_intervals' => $released,
@@ -45,6 +45,7 @@ class AppointmentController extends BaseController
private readonly \App\Appointment\Service\AppointmentInsuranceService $appointmentInsurance,
private readonly \App\Appointment\Service\ServiceBookingCalculator $serviceCalculator,
private readonly \App\Appointment\Service\ServiceRescheduleService $rescheduleService,
private readonly \App\Shared\Event\DomainEventPublisher $domainEvents,
private readonly \Psr\Log\LoggerInterface $logger,
) {}
@@ -72,6 +73,27 @@ class AppointmentController extends BaseController
));
}
/**
* ثبت رویداد دامنهٔ «نوبت انجام شد».
*
* جدا از `AppointmentEvent` است و جایگزینش نمی‌شود: آن، تایم‌لاینِ خوانده‌شده توسط
* اپراتور است و این، صندوق خروجی برای مصرف‌کننده‌های بیرونی. هر دو مسیرِ تغییر
* وضعیت (اندپوینت اختصاصی و `PATCH`) بعد از ذخیرهٔ موفق به اینجا می‌رسند، چون
* رویدادِ کاری که هنوز ذخیره نشده، دروغ است.
*/
private function recordCompletion(Appointment $appointment): void
{
$this->domainEvents->recordAndFlush(
$appointment->getEntityType(),
$appointment->getEntityId(),
\App\Shared\Event\DomainEvents::APPOINTMENT_COMPLETED,
[
'appointment_uuid' => $appointment->getUuid(),
'slot_start' => $appointment->getSlotStart(),
],
);
}
// ── Public: available slots ───────────────────────────────────────────────
#[OA\Get(
@@ -970,6 +992,10 @@ class AppointmentController extends BaseController
$this->recordCancellation($appointment, $newStatus, $reason !== '' ? $reason : null, $user);
}
if ($newStatus === Appointment::STATUS_COMPLETED) {
$this->recordCompletion($appointment);
}
return $this->success(['data' => $appointment->toArray()]);
}
@@ -1211,6 +1237,7 @@ class AppointmentController extends BaseController
// Optional status transition, same rules as the dedicated endpoint.
$newStatus = trim((string) ($data['status'] ?? ''));
$cancelledTo = null;
$completed = false;
if ($newStatus !== '' && $newStatus !== $appointment->getStatus()) {
if (!$appointment->canTransitionTo($newStatus)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, sprintf(
@@ -1224,6 +1251,7 @@ class AppointmentController extends BaseController
if (in_array($newStatus, self::CANCEL_STATUSES, true)) {
$cancelledTo = $newStatus;
}
$completed = $newStatus === Appointment::STATUS_COMPLETED;
}
try {
@@ -1240,6 +1268,10 @@ class AppointmentController extends BaseController
$this->recordCancellation($appointment, $cancelledTo, $reason !== '' ? $reason : null, $user);
}
if ($completed) {
$this->recordCompletion($appointment);
}
return $this->success(['data' => $appointment->toArray()]);
}
@@ -113,7 +113,11 @@ class CancellationController extends BaseController
? Appointment::STATUS_CANCELLED_BY_DOCTOR
: Appointment::STATUS_CANCELLED_BY_USER;
return $this->success($this->cancellation->cancel($appointment, $by, $user));
$reason = is_array($data) && is_string($data['reason'] ?? null) && trim($data['reason']) !== ''
? trim($data['reason'])
: null;
return $this->success($this->cancellation->cancel($appointment, $by, $user, null, $reason));
}
/** ثبت عدم حضور — برچسب پرریسک اگر آستانه رد شود. */
@@ -4,6 +4,7 @@ namespace App\Cancellation\Service;
use App\Appointment\Booking\Service\BookingService;
use App\Appointment\Entity\Appointment;
use App\Appointment\Entity\AppointmentEvent;
use App\Auth\Entity\User;
use App\Cancellation\ValueObject\PenaltyResult;
use App\Package\Service\CreditLedgerService;
@@ -35,7 +36,7 @@ final class CancellationService
* @return array<string, mixed>
* @throws AppException ۴۲۲ روی نوبت گذشته، ۴۰۹ روی نوبتِ از قبل لغوشده
*/
public function cancel(Appointment $appointment, string $status, ?User $actor = null, ?int $now = null): array
public function cancel(Appointment $appointment, string $status, ?User $actor = null, ?int $now = null, ?string $reason = null): array
{
$now = $now ?? time();
@@ -68,6 +69,8 @@ final class CancellationService
$notified = $this->waitlist->notifyForFreedSlot($appointment);
$this->recordTimelineEntry($appointment, $actor, $reason);
return [
'appointment_uuid' => $appointment->getUuid(),
'status' => $appointment->getStatus(),
@@ -77,6 +80,26 @@ final class CancellationService
] + $penalty->toArray();
}
/**
* ردیف تایم‌لاین — همان چیزی که اپراتور در صفحهٔ نوبت می‌بیند.
*
* جدا از رویداد دامنه است و جایگزینش نمی‌شود: آن برای مصرف‌کنندهٔ بیرونی است و این
* برای آدمی که می‌خواهد بداند چه کسی و چرا لغو کرد. بدون این، لغو از مسیر سیاست
* هیچ ردی در تاریخچهٔ نوبت نمی‌گذاشت.
*/
private function recordTimelineEntry(Appointment $appointment, ?User $actor, ?string $reason): void
{
$event = new AppointmentEvent($appointment, AppointmentEvent::TYPE_CANCELLED, 'نوبت لغو شد');
$event->setReason($reason);
if ($actor !== null) {
$event->setActor($actor->getId(), $actor->getRealName() ?: $actor->getMobileNumber());
}
$this->em->persist($event);
$this->em->flush();
}
/**
* جریمه از کیف پول کسر می‌شود، و اگر موجودی نبود **کسر نمی‌شود**.
*
+7
View File
@@ -4,6 +4,7 @@ namespace App;
use App\Appointment\Message\ExpireAppointmentsMessage;
use App\Blog\Message\PublishScheduledBlogsMessage;
use App\Shared\Event\Message\PublishDomainEventsMessage;
use App\Shared\Logging\Message\PruneLogsMessage;
use Symfony\Component\Scheduler\Attribute\AsSchedule;
use Symfony\Component\Scheduler\RecurringMessage;
@@ -32,6 +33,12 @@ class Schedule implements ScheduleProviderInterface
)
->add(
RecurringMessage::every('1 minute', new PublishScheduledBlogsMessage())
)
// صندوق خروجی رویدادها. `stateful` بالا یعنی تیکِ ازدست‌رفته بعد از ری‌استارت
// جبران می‌شود، و چون خودِ publisher از جدول می‌خواند، یک اجرا کافی است تا
// هرچه در فاصله جمع شده برود.
->add(
RecurringMessage::every('1 minute', new PublishDomainEventsMessage())
);
}
}
@@ -4,28 +4,26 @@ namespace App\Shared\Event\Command;
use App\Shared\Event\Entity\DomainEventLog;
use App\Shared\Event\Repository\DomainEventLogRepository;
use Doctrine\ORM\EntityManagerInterface;
use App\Shared\Event\Service\OutboxPublisher;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Messenger\MessageBusInterface;
/**
* انتشار صندوق خروجی: ردیف‌های `published_at IS NULL` به messenger می‌روند.
* اجرای دستیِ انتشار صندوق خروجی.
*
* شکست انتشار ردیف را نمی‌کشد؛ `attempts` بالا می‌رود و خطا ثبت می‌شود. بعد از سقف
* تلاش، ردیف با خطایش باقی می‌ماند تا ادمین ببیند — حذف خاموش یعنی رویداد گم‌شدهٔ بی‌رد.
* منطقش در `OutboxPublisher` است چون زمان‌بند هم همان را هر دقیقه صدا می‌زند؛ این دستور
* برای وقتی می‌ماند که صف عقب افتاده و باید همین حالا تخلیه شود.
*/
#[AsCommand(name: 'app:events:publish', description: 'Publish pending domain events from the outbox.')]
class PublishDomainEventsCommand extends Command
{
public function __construct(
private readonly OutboxPublisher $publisher,
private readonly DomainEventLogRepository $events,
private readonly MessageBusInterface $bus,
private readonly EntityManagerInterface $em,
) {
parent::__construct();
}
@@ -37,36 +35,10 @@ class PublishDomainEventsCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$pending = $this->events->findPending(max(1, (int) $input->getOption('limit')));
$io = new SymfonyStyle($input, $output);
$result = $this->publisher->publish((int) $input->getOption('limit'));
$published = 0;
$failed = 0;
foreach ($pending as $event) {
try {
$this->bus->dispatch(new \App\Shared\Event\Message\DomainEventMessage(
$event->getUuid(),
$event->getName(),
$event->getEntityType(),
$event->getEntityId(),
$event->getPayload(),
$event->getOccurredAt(),
));
$event->markPublished();
$published++;
} catch (\Throwable $e) {
$event->markFailed($e->getMessage());
$failed++;
}
}
if ($pending !== []) {
$this->em->flush();
}
$io->success(sprintf('%d رویداد منتشر شد، %d ناموفق.', $published, $failed));
$io->success(sprintf('%d رویداد منتشر شد، %d ناموفق.', $result['published'], $result['failed']));
return Command::SUCCESS;
}
@@ -0,0 +1,13 @@
<?php
namespace App\Shared\Event\Message;
/**
* پیام نشانه‌ای که زمان‌بند هر دقیقه می‌فرستد تا صندوق خروجی تخلیه شود.
*
* خودش داده ندارد: «چه چیزی منتشر شود» را `OutboxPublisher` از جدول می‌خواند، نه از
* پیام — وگرنه رویدادی که بین دو تیکِ زمان‌بند ثبت شده جا می‌ماند.
*/
final class PublishDomainEventsMessage
{
}
@@ -0,0 +1,18 @@
<?php
namespace App\Shared\Event\MessageHandler;
use App\Shared\Event\Message\PublishDomainEventsMessage;
use App\Shared\Event\Service\OutboxPublisher;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
final class PublishDomainEventsHandler
{
public function __construct(private readonly OutboxPublisher $publisher) {}
public function __invoke(PublishDomainEventsMessage $message): void
{
$this->publisher->publish();
}
}
@@ -0,0 +1,62 @@
<?php
namespace App\Shared\Event\Service;
use App\Shared\Event\Message\DomainEventMessage;
use App\Shared\Event\Repository\DomainEventLogRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\MessageBusInterface;
/**
* تخلیهٔ صندوق خروجی — ردیف‌های `published_at IS NULL` به messenger می‌روند.
*
* منطق اینجاست نه در Command، چون دو فراخوان دارد: دستور دستی برای وقتی که صف عقب
* افتاده، و زمان‌بند برای اجرای همیشگی. اگر در Command می‌ماند، زمان‌بند مجبور بود
* پروسهٔ کنسول اجرا کند و خطاهایش را از exit code حدس بزند.
*/
final class OutboxPublisher
{
public function __construct(
private readonly DomainEventLogRepository $events,
private readonly MessageBusInterface $bus,
private readonly EntityManagerInterface $em,
) {}
/**
* شکستِ یک ردیف بقیه را متوقف نمی‌کند؛ `attempts` بالا می‌رود و خطا روی خودِ ردیف
* می‌نشیند تا بعد از سقف تلاش، با دلیلش قابل دیدن بماند.
*
* @return array{published: int, failed: int}
*/
public function publish(int $limit = 100): array
{
$pending = $this->events->findPending(max(1, $limit));
$published = 0;
$failed = 0;
foreach ($pending as $event) {
try {
$this->bus->dispatch(new DomainEventMessage(
$event->getUuid(),
$event->getName(),
$event->getEntityType(),
$event->getEntityId(),
$event->getPayload(),
$event->getOccurredAt(),
));
$event->markPublished();
$published++;
} catch (\Throwable $e) {
$event->markFailed($e->getMessage());
$failed++;
}
}
if ($pending !== []) {
$this->em->flush();
}
return ['published' => $published, 'failed' => $failed];
}
}