feat(cancellation): cancellation policy, no-show tracking and a waitlist

Cancelling worked but had no policy behind it: no window, no penalty, nothing
happened to the deposit, and the no_show status had no effect at all.

Two rules that are expensive to get wrong, and both are load-bearing:
- The clinic cancelling its own appointment is never charged. That check is the
  first line of the calculation, not somewhere in the middle, so a later
  refactor cannot reorder it into charging patients for the clinic's decision.
- A penalty never exceeds what was actually paid. Anything above that is a
  debt, and debt belongs to billing, not to cancellation. An unpaid appointment
  is charged nothing and the response says why.

The default is no penalty at all — a penalising default would have made every
patient with a near appointment liable the moment this deployed.

No-shows are rows, not a counter on the patient: a counter loses which
appointment and when, which makes the 12-month window impossible. Crossing the
threshold adds an existing TenantTag; it never blocks the patient, because
blocking is an eligibility policy (task 09) written on top of that same tag.

Waitlist notifies up to ten matching people and the first to book wins. An
exclusive queue reads fairer but means a freed slot sits locked for half an
hour while someone ignores their phone — so the SMS says so explicitly instead.

Insufficient wallet balance does not fail the cancellation: the slot is freed
either way. A slot should not be held hostage to money.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-31 12:06:48 +03:30
co-authored by Claude Opus 5
parent d831ce2c1c
commit fba1555f22
26 changed files with 3122 additions and 77 deletions
@@ -0,0 +1,181 @@
<?php
namespace App\Waitlist\Controller;
use App\Auth\Entity\User;
use App\Branch\Service\BranchResolver;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Repository\ServiceItemRepository;
use App\Patient\Entity\PatientRecord;
use App\Patient\Repository\PatientRecordRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Exception\AppException;
use App\Shared\Tenant\TenantOwnershipChecker;
use App\Waitlist\Entity\WaitlistEntry;
use App\Waitlist\Repository\WaitlistEntryRepository;
use Doctrine\ORM\EntityManagerInterface;
use OpenApi\Attributes as OA;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[OA\Tag(name: 'Waitlist')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class WaitlistController extends BaseController
{
public function __construct(
private readonly WaitlistEntryRepository $entries,
private readonly ServiceItemRepository $items,
private readonly PatientRecordRepository $patients,
private readonly BranchResolver $branches,
private readonly TenantOwnershipChecker $ownership,
private readonly EntityManagerInterface $em,
) {}
#[Route('/api/v1/waitlist', name: 'waitlist_index', methods: ['GET'])]
public function index(#[CurrentUser] User $user, Request $request): JsonResponse
{
[$entityType, $entityId] = $this->branches->pair($user);
$status = $request->query->get('status');
return $this->success(array_map(
static fn (WaitlistEntry $e): array => $e->toArray(),
$this->entries->findForPair($entityType, $entityId, is_string($status) && $status !== '' ? $status : null),
));
}
#[Route('/api/v1/waitlist', name: 'waitlist_create', methods: ['POST'])]
public function create(#[CurrentUser] User $user, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data) || !is_string($data['patient_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'شناسهٔ بیمار الزامی است', 422, 'patient_uuid');
}
if (!is_string($data['service_uuid'] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'شناسهٔ سرویس الزامی است', 422, 'service_uuid');
}
foreach (['desired_from', 'desired_to'] as $field) {
if (!is_numeric($data[$field] ?? null)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, sprintf('فیلد %s الزامی است', $field), 422, $field);
}
}
$from = (int) $data['desired_from'];
$to = (int) $data['desired_to'];
// بازهٔ گذشته یعنی انتظاری که هرگز به نتیجه نمی‌رسد.
if ($to <= time()) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'بازهٔ انتظار باید در آینده باشد', 422, 'desired_to');
}
if ($to <= $from) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'پایان بازه باید بعد از شروع آن باشد', 422, 'desired_to');
}
$patient = $this->requirePatient($user, $data['patient_uuid']);
$service = $this->requireItem($user, $data['service_uuid']);
$branchId = null;
if (is_string($data['branch_uuid'] ?? null)) {
$branchId = $this->branches->resolve($user, $data['branch_uuid'])->getId();
}
$entry = new WaitlistEntry($patient, $service, $from, $to, $branchId);
if (is_array($data['preferred_day_parts'] ?? null)) {
$entry->setPreferredDayParts($data['preferred_day_parts']);
}
if (is_numeric($data['priority'] ?? null)) {
$entry->setPriority((int) $data['priority']);
}
$this->entries->save($entry);
return $this->success($entry->toArray(), 201);
}
#[Route('/api/v1/waitlist/{uuid}', name: 'waitlist_delete', methods: ['DELETE'])]
public function delete(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$entry = $this->requireEntry($user, $uuid);
$this->em->remove($entry);
$this->em->flush();
return $this->success(null);
}
/**
* درخواست‌هایی که با یک زمان مشخص می‌خوانند — ابزار پنل هنگام آزاد شدن ظرفیت.
*/
#[Route('/api/v1/waitlist/matches', name: 'waitlist_matches', methods: ['GET'])]
public function matches(#[CurrentUser] User $user, Request $request): JsonResponse
{
$serviceUuid = $request->query->get('service_uuid');
$start = $request->query->get('start');
if (!is_string($serviceUuid) || !is_numeric($start)) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلدهای service_uuid و start الزامی‌اند', 422, 'service_uuid');
}
$service = $this->requireItem($user, $serviceUuid);
$branch = $request->query->get('branch_uuid');
$branchId = is_string($branch) ? $this->branches->resolve($user, $branch)->getId() : null;
return $this->success(array_map(
static fn (WaitlistEntry $e): array => $e->toArray(),
$this->entries->findMatching($service, (int) $start, $branchId),
));
}
private function requirePatient(User $user, string $uuid): PatientRecord
{
$patient = $this->patients->findOneBy(['uuid' => $uuid]);
[$entityType, $entityId] = $this->branches->pair($user);
if ($patient === null
|| $patient->getEntityType() !== $entityType
|| $patient->getEntityId() !== $entityId
) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'بیمار یافت نشد', 404);
}
return $patient;
}
private function requireItem(User $user, string $uuid): ServiceItem
{
$item = $this->items->findByUuid($uuid);
[$entityType, $entityId] = $this->branches->pair($user);
if ($item === null
|| $item->getSection()->getEntityType() !== $entityType
|| $item->getSection()->getEntityId() !== $entityId
) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'سرویس یافت نشد', 404);
}
return $item;
}
private function requireEntry(User $user, string $uuid): WaitlistEntry
{
$entry = $this->entries->findByUuid($uuid);
[$entityType, $entityId] = $this->branches->pair($user);
if ($entry === null || !$this->ownership->belongsToPair($entityType, $entityId, $entry)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'درخواست لیست انتظار یافت نشد', 404);
}
return $entry;
}
}
+198
View File
@@ -0,0 +1,198 @@
<?php
namespace App\Waitlist\Entity;
use App\Appointment\Entity\Appointment;
use App\ClinicService\Entity\ServiceItem;
use App\Patient\Entity\PatientRecord;
use App\Shared\Tenant\TenantOwnedTrait;
use App\Waitlist\Repository\WaitlistEntryRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* «اگر وقتی در این بازه آزاد شد، خبرم کن.»
*
* توسعهٔ همان ایدهٔ `Appointment.is_reserve` موجود، ولی با بازهٔ صریح و وضعیت — تا
* بشود گفت چه کسی، برای چه، در چه بازه‌ای منتظر است.
*/
#[ORM\Entity(repositoryClass: WaitlistEntryRepository::class)]
#[ORM\Table(name: 'waitlist_entries')]
#[ORM\Index(columns: ['service_item_id', 'branch_id', 'status', 'desired_from', 'desired_to'], name: 'idx_waitlist_match')]
#[ORM\Index(columns: ['entity_type', 'entity_id', 'status', 'created_at'], name: 'idx_waitlist_tenant')]
#[ORM\Index(columns: ['patient_record_id', 'status'], name: 'idx_waitlist_patient')]
class WaitlistEntry
{
use TenantOwnedTrait;
public const STATUS_WAITING = 'waiting';
public const STATUS_NOTIFIED = 'notified';
public const STATUS_CONVERTED = 'converted';
public const STATUS_EXPIRED = 'expired';
/** سقف اطلاع‌رسانی — بدون آن، یک بازهٔ پرلغو به منبع اسپم تبدیل می‌شود. */
public const MAX_NOTIFICATIONS = 3;
#[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: PatientRecord::class)]
#[ORM\JoinColumn(name: 'patient_record_id', nullable: false, onDelete: 'CASCADE')]
private PatientRecord $patientRecord;
#[ORM\ManyToOne(targetEntity: ServiceItem::class)]
#[ORM\JoinColumn(name: 'service_item_id', nullable: false, onDelete: 'CASCADE')]
private ServiceItem $serviceItem;
#[ORM\Column(name: 'branch_id', type: 'integer', nullable: true)]
private ?int $branchId = null;
#[ORM\Column(name: 'desired_from', type: 'integer')]
private int $desiredFrom;
#[ORM\Column(name: 'desired_to', type: 'integer')]
private int $desiredTo;
/** @var list<string>|null `["morning","evening"]` */
#[ORM\Column(name: 'preferred_day_parts', type: 'json', nullable: true)]
private ?array $preferredDayParts = null;
#[ORM\Column(type: 'smallint', options: ['default' => 0])]
private int $priority = 0;
#[ORM\Column(type: 'string', length: 12, options: ['default' => self::STATUS_WAITING])]
private string $status = self::STATUS_WAITING;
#[ORM\Column(name: 'notified_at', type: 'integer', nullable: true)]
private ?int $notifiedAt = null;
#[ORM\Column(name: 'notify_count', type: 'smallint', options: ['default' => 0])]
private int $notifyCount = 0;
#[ORM\ManyToOne(targetEntity: Appointment::class)]
#[ORM\JoinColumn(name: 'converted_appointment_id', nullable: true, onDelete: 'SET NULL')]
private ?Appointment $convertedAppointment = null;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
#[ORM\Column(name: 'updated_at', type: 'integer')]
private int $updatedAt;
public function __construct(
PatientRecord $patientRecord,
ServiceItem $serviceItem,
int $desiredFrom,
int $desiredTo,
?int $branchId = null,
) {
if ($desiredTo <= $desiredFrom) {
throw new \InvalidArgumentException('The waitlist window must end after it starts.');
}
$this->uuid = Uuid::v4()->toRfc4122();
$this->patientRecord = $patientRecord;
$this->serviceItem = $serviceItem;
$this->desiredFrom = $desiredFrom;
$this->desiredTo = $desiredTo;
$this->branchId = $branchId;
$this->createdAt = time();
$this->updatedAt = time();
$this->assignTenantPair($patientRecord->getEntityType(), $patientRecord->getEntityId());
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getPatientRecord(): PatientRecord { return $this->patientRecord; }
public function getServiceItem(): ServiceItem { return $this->serviceItem; }
public function getBranchId(): ?int { return $this->branchId; }
public function getDesiredFrom(): int { return $this->desiredFrom; }
public function getDesiredTo(): int { return $this->desiredTo; }
public function getPreferredDayParts(): array { return $this->preferredDayParts ?? []; }
public function getPriority(): int { return $this->priority; }
public function getStatus(): string { return $this->status; }
public function getNotifiedAt(): ?int { return $this->notifiedAt; }
public function getNotifyCount(): int { return $this->notifyCount; }
/** @param list<string> $parts */
public function setPreferredDayParts(array $parts): self
{
$this->preferredDayParts = $parts === [] ? null : array_values(array_filter($parts, 'is_string'));
return $this->touch();
}
public function setPriority(int $v): self { $this->priority = $v; return $this->touch(); }
public function markNotified(?int $at = null): self
{
$this->status = self::STATUS_NOTIFIED;
$this->notifiedAt = $at ?? time();
$this->notifyCount++;
return $this->touch();
}
public function markConverted(Appointment $appointment): self
{
$this->status = self::STATUS_CONVERTED;
$this->convertedAppointment = $appointment;
return $this->touch();
}
public function markExpired(): self
{
$this->status = self::STATUS_EXPIRED;
return $this->touch();
}
/** هنوز منتظر است و سقف اطلاع‌رسانی را رد نکرده. */
public function isNotifiable(?int $now = null): bool
{
$now = $now ?? time();
return in_array($this->status, [self::STATUS_WAITING, self::STATUS_NOTIFIED], true)
&& $this->notifyCount < self::MAX_NOTIFICATIONS
&& $this->desiredTo >= $now;
}
public function covers(int $start): bool
{
return $start >= $this->desiredFrom && $start <= $this->desiredTo;
}
private function touch(): self
{
$this->updatedAt = time();
return $this;
}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'patient_uuid' => $this->patientRecord->getUuid(),
'service_uuid' => $this->serviceItem->getUuid(),
'service_name' => $this->serviceItem->getName(),
'branch_id' => $this->branchId,
'desired_from' => $this->desiredFrom,
'desired_to' => $this->desiredTo,
'preferred_day_parts' => $this->preferredDayParts ?? [],
'priority' => $this->priority,
'status' => $this->status,
'notified_at' => $this->notifiedAt,
'notify_count' => $this->notifyCount,
'created_at' => $this->createdAt,
];
}
}
@@ -0,0 +1,92 @@
<?php
namespace App\Waitlist\Repository;
use App\ClinicService\Entity\ServiceItem;
use App\Patient\Entity\PatientRecord;
use App\Waitlist\Entity\WaitlistEntry;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** @extends ServiceEntityRepository<WaitlistEntry> */
class WaitlistEntryRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, WaitlistEntry::class);
}
public function findByUuid(string $uuid): ?WaitlistEntry
{
return $this->findOneBy(['uuid' => $uuid]);
}
/**
* چه کسانی منتظر این سرویس در این لحظه‌اند؟ — کوئری داغِ لحظهٔ لغو.
*
* شعبهٔ تهی یعنی «هر شعبه»؛ کسی که شعبه مشخص کرده فقط برای همان شعبه خبر می‌شود.
*
* @return WaitlistEntry[] مرتب بر اساس اولویت، بعد قدمت
*/
public function findMatching(ServiceItem $service, int $start, ?int $branchId, ?int $now = null): array
{
$now = $now ?? time();
$qb = $this->createQueryBuilder('w')
->where('w.serviceItem = :service')
->andWhere('w.status IN (:open)')
->andWhere('w.desiredFrom <= :start')
->andWhere('w.desiredTo >= :start')
->andWhere('w.desiredTo >= :now')
->andWhere('w.notifyCount < :maxNotifications')
->setParameter('service', $service)
->setParameter('open', [WaitlistEntry::STATUS_WAITING, WaitlistEntry::STATUS_NOTIFIED])
->setParameter('start', $start)
->setParameter('now', $now)
->setParameter('maxNotifications', WaitlistEntry::MAX_NOTIFICATIONS)
->orderBy('w.priority', 'DESC')
->addOrderBy('w.createdAt', 'ASC');
// شعبهٔ تهی روی خودِ ردیف یعنی «هر شعبه»؛ پس وقتی ظرفیت یک شعبهٔ مشخص آزاد
// می‌شود، هم بی‌قیدها خبر می‌شوند هم آن‌هایی که همان شعبه را خواسته‌اند.
if ($branchId !== null) {
$qb->andWhere('w.branchId IS NULL OR w.branchId = :branch')
->setParameter('branch', $branchId);
}
return $qb->getQuery()->getResult();
}
/** @return WaitlistEntry[] */
public function findForPair(string $entityType, int $entityId, ?string $status = null): array
{
$qb = $this->createQueryBuilder('w')
->where('w.entityType = :type')
->andWhere('w.entityId = :id')
->setParameter('type', $entityType)
->setParameter('id', $entityId)
->orderBy('w.priority', 'DESC')
->addOrderBy('w.createdAt', 'DESC');
if ($status !== null) {
$qb->andWhere('w.status = :status')->setParameter('status', $status);
}
return $qb->getQuery()->getResult();
}
/** @return WaitlistEntry[] */
public function findForPatient(PatientRecord $patient): array
{
return $this->findBy(['patientRecord' => $patient], ['createdAt' => 'DESC']);
}
public function save(WaitlistEntry $entry, bool $flush = true): void
{
$this->getEntityManager()->persist($entry);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App\Waitlist\Service;
use App\Appointment\Entity\Appointment;
use App\Representation\Service\JalaliDateService;
use App\Sms\Service\SmsService;
use App\Waitlist\Entity\WaitlistEntry;
use App\Waitlist\Repository\WaitlistEntryRepository;
use Doctrine\ORM\EntityManagerInterface;
/**
* اطلاع‌رسانی به لیست انتظار وقتی ظرفیتی آزاد می‌شود.
*
* ## چرا broadcast و نه صف انحصاری
*
* ظرفیت آزادشده به حداکثر ده نفر خبر داده می‌شود و **اولین رزروکننده می‌برد**. صف
* انحصاری («فقط نفر اول ۳۰ دقیقه فرصت دارد») روی کاغذ عادلانه‌تر است، ولی در عمل
* یعنی وقتی که کسی جوابش را نمی‌دهد نیم ساعت قفل بماند و بعد به نفر دوم برسد — و
* ظرفیت آزادشدهٔ دو ساعت مانده به نوبت، نیم ساعت وقت تلف‌کردنی ندارد.
*
* در عوض، متن پیامک **اجباراً** این را می‌گوید تا کسی احساس نکند وعده‌ای شکسته شده.
*/
final class WaitlistNotifier
{
public const MAX_RECIPIENTS = 10;
public function __construct(
private readonly WaitlistEntryRepository $entries,
private readonly SmsService $sms,
private readonly JalaliDateService $jalali,
private readonly EntityManagerInterface $em,
) {}
/**
* @return int تعداد کسانی که خبر شدند
*/
public function notifyForFreedSlot(Appointment $appointment, ?int $now = null): int
{
$service = $appointment->getServiceItem();
if ($service === null) {
return 0;
}
$matches = $this->entries->findMatching(
$service,
$appointment->getSlotStart(),
$appointment->getAddressId(),
$now,
);
$notified = 0;
foreach (array_slice($matches, 0, self::MAX_RECIPIENTS) as $entry) {
if (!$entry->isNotifiable($now)) {
continue;
}
$this->notify($entry, $appointment->getSlotStart());
$notified++;
}
if ($notified > 0) {
$this->em->flush();
}
return $notified;
}
private function notify(WaitlistEntry $entry, int $slotStart): void
{
$mobile = $entry->getPatientRecord()->getUser()->getMobileNumber();
if ($mobile !== '') {
$this->sms->dispatchAsync($mobile, $this->messageFor($entry, $slotStart));
}
$entry->markNotified();
}
/** جملهٔ «اولین نفر می‌برد» اجباری است — وگرنه انتظارِ اشتباه می‌سازد. */
private function messageFor(WaitlistEntry $entry, int $slotStart): string
{
return sprintf(
'یک وقت برای «%s» در تاریخ %s آزاد شد. اولین نفری که رزرو کند آن را می‌گیرد.',
$entry->getServiceItem()->getName(),
$this->jalali->formatDateTime($slotStart),
);
}
}