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,219 @@
<?php
namespace App\Cancellation\Controller;
use App\Appointment\Entity\Appointment;
use App\Appointment\Repository\AppointmentRepository;
use App\Auth\Entity\User;
use App\Branch\Service\BranchResolver;
use App\Cancellation\Entity\CancellationPolicy;
use App\Cancellation\Repository\CancellationPolicyRepository;
use App\Cancellation\Service\CancellationService;
use App\Cancellation\Service\NoShowService;
use App\Cancellation\Service\PenaltyCalculator;
use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Repository\ServiceItemRepository;
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 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: 'Cancellation')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class CancellationController extends BaseController
{
public function __construct(
private readonly CancellationPolicyRepository $policies,
private readonly AppointmentRepository $appointments,
private readonly ServiceItemRepository $items,
private readonly PatientRecordRepository $patients,
private readonly PenaltyCalculator $calculator,
private readonly CancellationService $cancellation,
private readonly NoShowService $noShow,
private readonly BranchResolver $branches,
private readonly TenantOwnershipChecker $ownership,
) {}
#[Route('/api/v1/cancellation-policy', name: 'cancellation_policy_show', methods: ['GET'])]
public function show(#[CurrentUser] User $user): JsonResponse
{
[$entityType, $entityId] = $this->branches->pair($user);
return $this->success([
'default' => $this->policies->findDefault($entityType, $entityId)?->toArray(),
'overrides' => array_values(array_map(
static fn (CancellationPolicy $p): array => $p->toArray(),
array_filter(
$this->policies->findForPair($entityType, $entityId),
static fn (CancellationPolicy $p): bool => $p->getServiceItem() !== null,
),
)),
]);
}
/** سیاست پیش‌فرض محیط — ساخته می‌شود اگر نبود. */
#[Route('/api/v1/cancellation-policy', name: 'cancellation_policy_save', methods: ['PUT'])]
public function save(#[CurrentUser] User $user, Request $request): JsonResponse
{
[$entityType, $entityId] = $this->branches->pair($user);
$policy = $this->policies->findDefault($entityType, $entityId)
?? new CancellationPolicy($entityType, $entityId);
return $this->applyAndSave($policy, $request);
}
#[Route('/api/v1/service-item/{uuid}/cancellation-policy', name: 'cancellation_policy_service', methods: ['PUT'])]
public function saveForService(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
[$entityType, $entityId] = $this->branches->pair($user);
$service = $this->requireItem($user, $uuid);
$policy = $this->policies->findForService($entityType, $entityId, $service)
?? new CancellationPolicy($entityType, $entityId, $service);
return $this->applyAndSave($policy, $request);
}
/**
* جریمه و بازگشت **پیش از** لغو.
*
* همان محاسبه‌ای که خودِ لغو انجام می‌دهد؛ بیمار نباید عددی ببیند که با آنچه کسر
* می‌شود فرق دارد.
*/
#[Route('/api/v1/appointment/{uuid}/cancellation-preview', name: 'cancellation_preview', methods: ['GET'])]
public function preview(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$appointment = $this->requireAppointment($user, $uuid);
$by = $request->query->get('by') === 'doctor'
? Appointment::STATUS_CANCELLED_BY_DOCTOR
: Appointment::STATUS_CANCELLED_BY_USER;
return $this->success(
$this->calculator->calculate($appointment, $by)->toArray()
+ ['paid_rials' => $this->calculator->paidRials($appointment)],
);
}
#[Route('/api/v1/appointment/{uuid}/cancel', name: 'cancellation_cancel', methods: ['POST'])]
public function cancel(#[CurrentUser] User $user, string $uuid, Request $request): JsonResponse
{
$appointment = $this->requireAppointment($user, $uuid);
$data = json_decode($request->getContent(), true);
$by = is_array($data) && ($data['by'] ?? null) === 'doctor'
? Appointment::STATUS_CANCELLED_BY_DOCTOR
: Appointment::STATUS_CANCELLED_BY_USER;
return $this->success($this->cancellation->cancel($appointment, $by, $user));
}
/** ثبت عدم حضور — برچسب پرریسک اگر آستانه رد شود. */
#[Route('/api/v1/appointment/{uuid}/no-show', name: 'cancellation_no_show', methods: ['POST'])]
public function markNoShow(#[CurrentUser] User $user, string $uuid): JsonResponse
{
$appointment = $this->requireAppointment($user, $uuid);
[$entityType, $entityId] = $this->branches->pair($user);
$patient = $this->patients->findOneBy([
'user' => $appointment->getUser(),
'entityType' => $entityType,
'entityId' => $entityId,
]);
if ($patient === null) {
return $this->error(ErrorCodes::ERR_NOT_FOUND_001, 'پروندهٔ بیمار در این محیط یافت نشد', 404);
}
if ($appointment->getStatus() !== Appointment::STATUS_NO_SHOW) {
$appointment->transitionTo(Appointment::STATUS_NO_SHOW);
$this->appointments->save($appointment);
}
return $this->success($this->noShow->record($appointment, $patient, $user));
}
private function applyAndSave(CancellationPolicy $policy, Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!is_array($data)) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'بدنهٔ درخواست نامعتبر است', 422);
}
if (is_numeric($data['free_window_hours'] ?? null)) {
$policy->setFreeWindowHours((int) $data['free_window_hours']);
}
if (isset($data['penalty_mode'])) {
try {
$policy->setPenalty(
(string) $data['penalty_mode'],
is_numeric($data['penalty_value'] ?? null) ? (int) $data['penalty_value'] : 0,
);
} catch (\InvalidArgumentException $e) {
return $this->error(
ErrorCodes::ERR_VALIDATION_001,
str_contains($e->getMessage(), 'percentage')
? 'درصد جریمه باید بین ۰ تا ۱۰۰ باشد'
: 'حالت جریمه نامعتبر است',
422,
'penalty_mode',
);
}
}
foreach (['deposit_refundable' => 'setDepositRefundable', 'credit_refundable' => 'setCreditRefundable', 'active' => 'setActive'] as $field => $setter) {
if (isset($data[$field])) {
$policy->{$setter}((bool) $data[$field]);
}
}
if (is_numeric($data['no_show_threshold'] ?? null)) {
$policy->setNoShowThreshold((int) $data['no_show_threshold']);
}
if (array_key_exists('risk_tag_uuid', $data)) {
$policy->setRiskTagUuid(is_string($data['risk_tag_uuid']) ? $data['risk_tag_uuid'] : null);
}
$this->policies->save($policy);
return $this->success($policy->toArray());
}
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 requireAppointment(User $user, string $uuid): Appointment
{
$appointment = $this->appointments->findByUuid($uuid);
[$entityType, $entityId] = $this->branches->pair($user);
if ($appointment === null || !$this->ownership->belongsToPair($entityType, $entityId, $appointment)) {
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'نوبت یافت نشد', 404);
}
return $appointment;
}
}
@@ -0,0 +1,157 @@
<?php
namespace App\Cancellation\Entity;
use App\Cancellation\Repository\CancellationPolicyRepository;
use App\ClinicService\Entity\ServiceItem;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* سیاست لغو یک محیط، یا override یک سرویس.
*
* `serviceItem === null` یعنی پیش‌فرض محیط. سرویسی که سیاست خودش را دارد، همان برنده
* است — بدون ترکیب و بدون وراثت جزئی، چون «۲۴ ساعت از محیط ولی ۵۰٪ از سرویس» چیزی
* است که هیچ اپراتوری نمی‌تواند در ذهنش شبیه‌سازی کند.
*
* پیش‌فرض عمداً **بدون جریمه** است: اگر پیش‌فرض جریمه‌دار بود، لحظهٔ deploy همهٔ
* بیمارانِ با نوبت نزدیک مشمول جریمه می‌شدند و کلینیک خبر نداشت.
*/
#[ORM\Entity(repositoryClass: CancellationPolicyRepository::class)]
#[ORM\Table(name: 'cancellation_policies')]
#[ORM\UniqueConstraint(name: 'uniq_cancel_policy_scope', columns: ['entity_type', 'entity_id', 'service_item_id'])]
#[ORM\Index(columns: ['entity_type', 'entity_id', 'active'], name: 'idx_cancel_policies_tenant')]
class CancellationPolicy
{
use TenantOwnedTrait;
public const MODE_NONE = 'none';
public const MODE_PERCENT = 'percent';
public const MODE_FIXED = 'fixed';
public const MODES = [self::MODE_NONE, self::MODE_PERCENT, self::MODE_FIXED];
#[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: ServiceItem::class)]
#[ORM\JoinColumn(name: 'service_item_id', nullable: true, onDelete: 'CASCADE')]
private ?ServiceItem $serviceItem = null;
#[ORM\Column(name: 'free_window_hours', type: 'smallint', options: ['default' => 24])]
private int $freeWindowHours = 24;
#[ORM\Column(name: 'penalty_mode', type: 'string', length: 10, options: ['default' => self::MODE_NONE])]
private string $penaltyMode = self::MODE_NONE;
/** درصد ۰..۱۰۰ یا مبلغ ریالی، بسته به `penaltyMode`. */
#[ORM\Column(name: 'penalty_value', type: 'integer', options: ['default' => 0])]
private int $penaltyValue = 0;
#[ORM\Column(name: 'deposit_refundable', type: 'boolean', options: ['default' => false])]
private bool $depositRefundable = false;
#[ORM\Column(name: 'credit_refundable', type: 'boolean', options: ['default' => true])]
private bool $creditRefundable = true;
#[ORM\Column(name: 'no_show_threshold', type: 'smallint', options: ['default' => 3])]
private int $noShowThreshold = 3;
/** بدون FK — همان الگوی `DiscountRule.target_tag_uuid` موجود پروژه. */
#[ORM\Column(name: 'risk_tag_uuid', type: 'string', length: 36, nullable: true)]
private ?string $riskTagUuid = null;
#[ORM\Column(type: 'boolean', options: ['default' => true])]
private bool $active = true;
#[ORM\Column(name: 'created_at', type: 'integer')]
private int $createdAt;
#[ORM\Column(name: 'updated_at', type: 'integer')]
private int $updatedAt;
public function __construct(string $entityType, int $entityId, ?ServiceItem $serviceItem = null)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->serviceItem = $serviceItem;
$this->createdAt = time();
$this->updatedAt = time();
$this->assignTenantPair($entityType, $entityId);
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getServiceItem(): ?ServiceItem { return $this->serviceItem; }
public function getFreeWindowHours(): int { return $this->freeWindowHours; }
public function getPenaltyMode(): string { return $this->penaltyMode; }
public function getPenaltyValue(): int { return $this->penaltyValue; }
public function isDepositRefundable(): bool { return $this->depositRefundable; }
public function isCreditRefundable(): bool { return $this->creditRefundable; }
public function getNoShowThreshold(): int { return $this->noShowThreshold; }
public function getRiskTagUuid(): ?string { return $this->riskTagUuid; }
public function isActive(): bool { return $this->active; }
public function setFreeWindowHours(int $v): self { $this->freeWindowHours = max(0, $v); return $this->touch(); }
public function setDepositRefundable(bool $v): self { $this->depositRefundable = $v; return $this->touch(); }
public function setCreditRefundable(bool $v): self { $this->creditRefundable = $v; return $this->touch(); }
public function setRiskTagUuid(?string $v): self { $this->riskTagUuid = $v; return $this->touch(); }
public function setActive(bool $v): self { $this->active = $v; return $this->touch(); }
public function setNoShowThreshold(int $v): self
{
// آستانهٔ صفر یعنی هر بیماری از همان نوبت اول پرریسک است.
$this->noShowThreshold = max(1, $v);
return $this->touch();
}
/** @throws \InvalidArgumentException روی حالت ناشناخته یا درصد بیرون بازه */
public function setPenalty(string $mode, int $value): self
{
if (!in_array($mode, self::MODES, true)) {
throw new \InvalidArgumentException(sprintf('Unknown penalty mode "%s".', $mode));
}
if ($mode === self::MODE_PERCENT && ($value < 0 || $value > 100)) {
throw new \InvalidArgumentException('A percentage penalty must be between 0 and 100.');
}
$this->penaltyMode = $mode;
$this->penaltyValue = $mode === self::MODE_NONE ? 0 : max(0, $value);
return $this->touch();
}
private function touch(): self
{
$this->updatedAt = time();
return $this;
}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'service_uuid' => $this->serviceItem?->getUuid(),
'service_name' => $this->serviceItem?->getName(),
'free_window_hours' => $this->freeWindowHours,
'penalty_mode' => $this->penaltyMode,
'penalty_value' => $this->penaltyValue,
'deposit_refundable' => $this->depositRefundable,
'credit_refundable' => $this->creditRefundable,
'no_show_threshold' => $this->noShowThreshold,
'risk_tag_uuid' => $this->riskTagUuid,
'active' => $this->active,
'created_at' => $this->createdAt,
];
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace App\Cancellation\Entity;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Cancellation\Repository\NoShowRecordRepository;
use App\Patient\Entity\PatientRecord;
use App\Shared\Tenant\TenantOwnedTrait;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
/**
* یک بار عدم حضور — جدول جدا، نه شمارنده روی بیمار.
*
* همان استدلال دفتر اعتبار تسک ۱۱: شمارنده «چه زمانی و کدام نوبت» را از دست می‌دهد و
* پنجرهٔ ۱۲ ماهه را غیرقابل محاسبه می‌کند. بیماری که سه سال پیش سه بار نیامده، امروز
* پرریسک نیست.
*/
#[ORM\Entity(repositoryClass: NoShowRecordRepository::class)]
#[ORM\Table(name: 'no_show_records')]
#[ORM\UniqueConstraint(name: 'uniq_no_show_appointment', columns: ['appointment_id'])]
#[ORM\Index(columns: ['patient_record_id', 'recorded_at'], name: 'idx_no_show_patient')]
#[ORM\Index(columns: ['entity_type', 'entity_id', 'recorded_at'], name: 'idx_no_show_tenant')]
class NoShowRecord
{
use TenantOwnedTrait;
#[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: Appointment::class)]
#[ORM\JoinColumn(name: 'appointment_id', nullable: false, onDelete: 'CASCADE')]
private Appointment $appointment;
#[ORM\Column(name: 'recorded_at', type: 'integer')]
private int $recordedAt;
#[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(name: 'recorded_by', nullable: true, onDelete: 'SET NULL')]
private ?User $recordedBy = null;
public function __construct(PatientRecord $patientRecord, Appointment $appointment, ?User $recordedBy = null, ?int $at = null)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->patientRecord = $patientRecord;
$this->appointment = $appointment;
$this->recordedBy = $recordedBy;
$this->recordedAt = $at ?? time();
$this->assignTenantPair($appointment->getEntityType(), $appointment->getEntityId());
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getPatientRecord(): PatientRecord { return $this->patientRecord; }
public function getAppointment(): Appointment { return $this->appointment; }
public function getRecordedAt(): int { return $this->recordedAt; }
public function getRecordedBy(): ?User { return $this->recordedBy; }
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'uuid' => $this->uuid,
'appointment_uuid' => $this->appointment->getUuid(),
'slot_start' => $this->appointment->getSlotStart(),
'recorded_at' => $this->recordedAt,
];
}
}
@@ -0,0 +1,76 @@
<?php
namespace App\Cancellation\Repository;
use App\Cancellation\Entity\CancellationPolicy;
use App\ClinicService\Entity\ServiceItem;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** @extends ServiceEntityRepository<CancellationPolicy> */
class CancellationPolicyRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, CancellationPolicy::class);
}
public function findByUuid(string $uuid): ?CancellationPolicy
{
return $this->findOneBy(['uuid' => $uuid]);
}
/** سیاست پیش‌فرض محیط — `serviceItem` تهی. */
public function findDefault(string $entityType, int $entityId): ?CancellationPolicy
{
return $this->findOneBy(['entityType' => $entityType, 'entityId' => $entityId, 'serviceItem' => null]);
}
public function findForService(string $entityType, int $entityId, ServiceItem $service): ?CancellationPolicy
{
return $this->findOneBy(['entityType' => $entityType, 'entityId' => $entityId, 'serviceItem' => $service]);
}
/**
* سیاست حاکم: override سرویس، وگرنه پیش‌فرض محیط.
*
* ترکیب نمی‌شوند — «۲۴ ساعت از محیط ولی ۵۰٪ از سرویس» چیزی است که هیچ اپراتوری
* نمی‌تواند در ذهنش شبیه‌سازی کند.
*/
public function resolve(string $entityType, int $entityId, ?ServiceItem $service): ?CancellationPolicy
{
if ($service !== null) {
$override = $this->findForService($entityType, $entityId, $service);
if ($override !== null && $override->isActive()) {
return $override;
}
}
$default = $this->findDefault($entityType, $entityId);
return $default?->isActive() === true ? $default : null;
}
/** @return CancellationPolicy[] */
public function findForPair(string $entityType, int $entityId): array
{
return $this->createQueryBuilder('p')
->where('p.entityType = :type')
->andWhere('p.entityId = :id')
->setParameter('type', $entityType)
->setParameter('id', $entityId)
->orderBy('p.serviceItem', 'ASC')
->getQuery()
->getResult();
}
public function save(CancellationPolicy $policy, bool $flush = true): void
{
$this->getEntityManager()->persist($policy);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Cancellation\Repository;
use App\Appointment\Entity\Appointment;
use App\Cancellation\Entity\NoShowRecord;
use App\Patient\Entity\PatientRecord;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/** @extends ServiceEntityRepository<NoShowRecord> */
class NoShowRecordRepository extends ServiceEntityRepository
{
/** پنجرهٔ شمارش — عدم حضورِ سه سال پیش امروز معنایی ندارد. */
public const WINDOW_DAYS = 365;
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, NoShowRecord::class);
}
public function findForAppointment(Appointment $appointment): ?NoShowRecord
{
return $this->findOneBy(['appointment' => $appointment]);
}
public function countRecent(PatientRecord $patient, ?int $now = null): int
{
$since = ($now ?? time()) - self::WINDOW_DAYS * 86400;
return (int) $this->createQueryBuilder('r')
->select('COUNT(r.id)')
->where('r.patientRecord = :patient')
->andWhere('r.recordedAt >= :since')
->setParameter('patient', $patient)
->setParameter('since', $since)
->getQuery()
->getSingleScalarResult();
}
/** @return NoShowRecord[] */
public function historyFor(PatientRecord $patient, int $limit = 20): array
{
return $this->createQueryBuilder('r')
->where('r.patientRecord = :patient')
->setParameter('patient', $patient)
->orderBy('r.recordedAt', 'DESC')
->setMaxResults($limit)
->getQuery()
->getResult();
}
}
@@ -0,0 +1,139 @@
<?php
namespace App\Cancellation\Service;
use App\Appointment\Booking\Service\BookingService;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Cancellation\ValueObject\PenaltyResult;
use App\Package\Service\CreditLedgerService;
use App\Settlement\Service\WalletService;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Exception\AppException;
use App\Waitlist\Service\WaitlistNotifier;
use Doctrine\ORM\EntityManagerInterface;
/**
* لغو نوبت با اعمال سیاست.
*
* ترتیب کارها عمدی است: اول اعتبارسنجی، بعد آزادسازی ظرفیت، بعد پول، و آخر اطلاع به
* لیست انتظار. اگر اطلاع‌رسانی اول بود، ممکن بود ده نفر برای ظرفیتی خبر شوند که هنوز
* آزاد نشده.
*/
final class CancellationService
{
public function __construct(
private readonly PenaltyCalculator $calculator,
private readonly BookingService $booking,
private readonly WalletService $wallet,
private readonly CreditLedgerService $credits,
private readonly WaitlistNotifier $waitlist,
private readonly EntityManagerInterface $em,
) {}
/**
* @return array<string, mixed>
* @throws AppException ۴۲۲ روی نوبت گذشته، ۴۰۹ روی نوبتِ از قبل لغوشده
*/
public function cancel(Appointment $appointment, string $status, ?User $actor = null, ?int $now = null): array
{
$now = $now ?? time();
if (in_array($appointment->getStatus(), [
Appointment::STATUS_CANCELLED_BY_USER,
Appointment::STATUS_CANCELLED_BY_DOCTOR,
], true)) {
// idempotent: همان وضعیت برمی‌گردد، نه یک لغو دوباره.
throw new AppException(ErrorCodes::ERR_SLOT_TAKEN, 'این نوبت قبلاً لغو شده است', 409);
}
if ($appointment->getSlotStart() < $now) {
// برای گذشته `no_show` یا `completed` معنا دارد، نه لغو.
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'نوبت گذشته لغو نمی‌شود؛ وضعیت عدم حضور یا انجام‌شده را ثبت کنید', 422);
}
$penalty = $this->calculator->calculate($appointment, $status, $now);
$appointment->transitionTo($status);
$this->em->flush();
// آزادسازی منابع و بازگشت اعتبار پکیج و جلسهٔ دوره — همه در `cancel` بوکینگ.
$released = $this->booking->cancel($appointment);
if (!$penalty->creditRefundable) {
$this->revokeRefundedCredit($appointment);
}
$charged = $this->chargePenalty($appointment, $penalty, $actor);
$notified = $this->waitlist->notifyForFreedSlot($appointment);
return [
'appointment_uuid' => $appointment->getUuid(),
'status' => $appointment->getStatus(),
'released_resources' => $released,
'waitlist_notified' => $notified,
'penalty_charged' => $charged,
] + $penalty->toArray();
}
/**
* جریمه از کیف پول کسر می‌شود، و اگر موجودی نبود **کسر نمی‌شود**.
*
* موجودی ناکافی نباید لغو را شکست بدهد: نوبت باید آزاد شود حتی اگر پول بعداً
* وصول شود. بدهی مسئلهٔ صورتحساب است، نه یک عدد منفی پنهان در کیف پول.
*/
private function chargePenalty(Appointment $appointment, PenaltyResult $penalty, ?User $actor): bool
{
if ($penalty->penaltyRials <= 0) {
return false;
}
try {
$this->wallet->withdraw(
$appointment->getUser(),
$penalty->penaltyRials,
$actor,
'جریمهٔ لغو نوبت',
null,
$appointment->getUuid(),
// بدون این، کلینیک الف جریمهٔ ثبت‌شده در کلینیک ب را می‌بیند.
$appointment->getEntityType(),
$appointment->getEntityId(),
);
} catch (AppException) {
return false;
}
return true;
}
/**
* سیاستی که اعتبار را برنمی‌گرداند: ردیف `refund` که `BookingService::cancel()`
* نوشته با یک `adjustment` منفی خنثی می‌شود.
*
* حذف ردیف قبلی ممنوع است — دفتر append-only می‌ماند و تاریخچه نشان می‌دهد
* اعتبار برگشت و بعد طبق سیاست پس گرفته شد.
*/
private function revokeRefundedCredit(Appointment $appointment): void
{
$refund = $this->em->getRepository(\App\Package\Entity\SessionCreditLedger::class)
->findOneBy([
'appointment' => $appointment,
'kind' => \App\Package\Entity\SessionCreditLedger::KIND_REFUND,
]);
if ($refund === null) {
return;
}
$this->credits->record(
$refund->getPatientPackage(),
\App\Package\Entity\SessionCreditLedger::KIND_ADJUSTMENT,
-$refund->getDelta(),
null,
$refund->getServiceItem(),
'سیاست لغو: اعتبار این جلسه برنمی‌گردد',
);
}
}
@@ -0,0 +1,88 @@
<?php
namespace App\Cancellation\Service;
use App\Appointment\Entity\Appointment;
use App\Auth\Entity\User;
use App\Cancellation\Entity\NoShowRecord;
use App\Cancellation\Repository\CancellationPolicyRepository;
use App\Cancellation\Repository\NoShowRecordRepository;
use App\Patient\Entity\PatientRecord;
use App\Tag\Entity\TenantTag;
use Doctrine\ORM\EntityManagerInterface;
/**
* ثبت عدم حضور و برچسب‌گذاری بیمار پرریسک.
*
* برچسب **مسدود نمی‌کند**. مسدودسازی یک قانون `eligibility` (تسک ۰۹) روی همین برچسب
* است؛ اینجا فقط واقعیت ثبت می‌شود. تفکیکش عمدی است: کلینیکی که می‌خواهد بیمار پرریسک
* را ببیند ولی بیعانه بگیرد، نباید مجبور شود برچسب را خاموش کند.
*/
final class NoShowService
{
public function __construct(
private readonly NoShowRecordRepository $records,
private readonly CancellationPolicyRepository $policies,
private readonly EntityManagerInterface $em,
) {}
/**
* @return array{recorded: bool, count: int, threshold: int, tagged: bool}
*/
public function record(Appointment $appointment, PatientRecord $patient, ?User $actor = null, ?int $now = null): array
{
$now = $now ?? time();
// تغییر وضعیت به `no_show` ممکن است دو بار اتفاق بیفتد؛ رکورد دوم ثبت نشود.
$existing = $this->records->findForAppointment($appointment);
$policy = $this->policies->resolve(
$appointment->getEntityType(),
$appointment->getEntityId(),
$appointment->getServiceItem(),
);
$threshold = $policy?->getNoShowThreshold() ?? 3;
if ($existing !== null) {
return [
'recorded' => false,
'count' => $this->records->countRecent($patient, $now),
'threshold' => $threshold,
'tagged' => false,
];
}
$this->em->persist(new NoShowRecord($patient, $appointment, $actor, $now));
$this->em->flush();
$count = $this->records->countRecent($patient, $now);
$tagged = false;
if ($count >= $threshold && $policy?->getRiskTagUuid() !== null) {
$tagged = $this->applyRiskTag($patient, $policy->getRiskTagUuid());
}
return ['recorded' => true, 'count' => $count, 'threshold' => $threshold, 'tagged' => $tagged];
}
/** @return bool `false` یعنی برچسب از قبل بود یا وجود ندارد */
private function applyRiskTag(PatientRecord $patient, string $tagUuid): bool
{
$tag = $this->em->getRepository(TenantTag::class)->findOneBy(['uuid' => $tagUuid]);
if ($tag === null || $patient->getTags()->contains($tag)) {
return false;
}
$patient->getTags()->add($tag);
$this->em->flush();
return true;
}
public function countFor(PatientRecord $patient, ?int $now = null): int
{
return $this->records->countRecent($patient, $now);
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Cancellation\Service;
use App\Appointment\Entity\Appointment;
use App\Cancellation\Entity\CancellationPolicy;
use App\Cancellation\Repository\CancellationPolicyRepository;
use App\Cancellation\ValueObject\PenaltyResult;
use App\Payment\Entity\Payment;
use Doctrine\ORM\EntityManagerInterface;
/**
* محاسبهٔ جریمهٔ لغو — خالص، بدون هیچ نوشتنی.
*
* همین کلاس هم پیش‌نمایش را می‌دهد و هم عددی که واقعاً کسر می‌شود؛ دو مسیر جدا یعنی
* بالاخره روزی دو عدد متفاوت.
*/
final class PenaltyCalculator
{
public function __construct(
private readonly CancellationPolicyRepository $policies,
private readonly EntityManagerInterface $em,
) {}
public function calculate(Appointment $appointment, string $cancelledBy, ?int $now = null): PenaltyResult
{
// ⚠️ این شرط باید **اولین** خط باشد. اگر بعد از محاسبهٔ پنجرهٔ زمانی بیاید، یک
// refactor می‌تواند ترتیب را عوض کند و کلینیک از بیمار برای لغو خودش جریمه بگیرد.
if ($cancelledBy === Appointment::STATUS_CANCELLED_BY_DOCTOR) {
return PenaltyResult::free(true, ['لغو توسط کلینیک هرگز جریمه ندارد']);
}
$now = $now ?? time();
$policy = $this->policies->resolve(
$appointment->getEntityType(),
$appointment->getEntityId(),
$appointment->getServiceItem(),
);
if ($policy === null) {
return PenaltyResult::free(true, ['برای این محیط سیاست لغو تعریف نشده است']);
}
$hoursLeft = ($appointment->getSlotStart() - $now) / 3600;
if ($hoursLeft >= $policy->getFreeWindowHours()) {
return PenaltyResult::free(true);
}
$paid = $this->paidRials($appointment);
$penalty = $this->rawPenalty($policy, $appointment, $paid);
$notes = [];
// جریمهٔ بیشتر از پرداختی یعنی بدهی، و بدهی مسئلهٔ صورتحساب است نه لغو.
if ($penalty > $paid) {
$notes[] = $paid === 0
? 'این نوبت پرداختی نداشته، پس جریمه‌ای کسر نمی‌شود'
: 'جریمه تا سقف مبلغ پرداختی کاهش یافت';
$penalty = $paid;
}
return new PenaltyResult(
penaltyRials: $penalty,
depositRefundable: $policy->isDepositRefundable(),
creditRefundable: $policy->isCreditRefundable(),
withinFreeWindow: false,
notes: $notes,
);
}
private function rawPenalty(CancellationPolicy $policy, Appointment $appointment, int $paid): int
{
return match ($policy->getPenaltyMode()) {
CancellationPolicy::MODE_PERCENT => (int) floor($this->baseFor($appointment, $paid) * $policy->getPenaltyValue() / 100),
CancellationPolicy::MODE_FIXED => $policy->getPenaltyValue(),
default => 0,
};
}
/**
* مبنای درصد: مبلغ ثبت‌شدهٔ نوبت، و اگر نبود آنچه واقعاً پرداخت شده.
*
* درصدِ «قیمت امروزِ سرویس» غلط است: بیمار روی قیمت آن روز توافق کرده.
*/
private function baseFor(Appointment $appointment, int $paid): int
{
return (int) ($appointment->getVisitPriceRials() ?? $paid);
}
/** جمع پرداخت‌های موفق همین نوبت. */
public function paidRials(Appointment $appointment): int
{
return (int) $this->em->createQueryBuilder()
->select('COALESCE(SUM(p.amountRials), 0)')
->from(Payment::class, 'p')
->where('p.appointment = :appointment')
->andWhere('p.status = :status')
->setParameter('appointment', $appointment)
->setParameter('status', Payment::STATUS_SUCCESS)
->getQuery()
->getSingleScalarResult();
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Cancellation\ValueObject;
/**
* نتیجهٔ محاسبهٔ لغو — پیش از اینکه چیزی اتفاق بیفتد.
*
* همان شکل در پیش‌نمایش و در لغو واقعی برمی‌گردد: بیمار نباید عددی ببیند که با آنچه
* واقعاً کسر می‌شود فرق دارد.
*/
final readonly class PenaltyResult
{
/** @param list<string> $notes */
public function __construct(
public int $penaltyRials,
public bool $depositRefundable,
public bool $creditRefundable,
public bool $withinFreeWindow,
public array $notes = [],
) {}
/** لغو توسط کلینیک، یا داخل پنجرهٔ رایگان. */
public static function free(bool $withinFreeWindow = true, array $notes = []): self
{
return new self(0, true, true, $withinFreeWindow, $notes);
}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'penalty_rials' => $this->penaltyRials,
'deposit_refundable' => $this->depositRefundable,
'credit_refundable' => $this->creditRefundable,
'within_free_window' => $this->withinFreeWindow,
'notes' => $this->notes,
];
}
}
@@ -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),
);
}
}