feat(events): domain event outbox and the two reports that close the loop
Tasks 07 through 13 each changed something the rest of the system might want to know about, with no contract for saying so. And task 05 shipped a powerful segment editor with no feedback on whether a clinic defined its segments right. Events - A closed list of names, because a consumer branches on the string and a one-letter typo would produce an event nobody hears and no error either - Payloads carry uuids and scalars only; non-scalars are dropped, not serialised, so a consumer always fetches fresh rather than reading a stale detached entity - record() deliberately does not flush: the event row commits with the change it describes, so a rolled-back transaction leaves no event behind. A test pins exactly that - app:events:publish drains the outbox; five failed attempts park a row with its error rather than deleting it, because a silently dropped event is a loss with no trace. app:events:prune only ever removes published rows Reports - Resource utilisation separates available, occupied and active minutes. The gap between occupied and active is what exposes a bad segment definition, and available is multiplied by capacity so a three-chair room does not read as permanently over 100% - A resource with no calendar reports utilization: null, not zero — dividing by zero means something different from being idle - Plan accuracy compares planned against actual duration per service and flags both directions: running short wastes capacity that could have been sold. Its row links straight to editing that service's segments, because a report with no route to a fix does not get read Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -10,6 +10,8 @@ use App\Package\Service\CreditLedgerService;
|
||||
use App\Course\Service\CourseSessionLinker;
|
||||
use App\Package\Service\PackageConsumptionService;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use App\Shared\Exception\AppException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
@@ -27,6 +29,7 @@ final class BookingService
|
||||
private readonly PackageConsumptionService $packages,
|
||||
private readonly CreditLedgerService $credits,
|
||||
private readonly CourseSessionLinker $courseSessions,
|
||||
private readonly DomainEventPublisher $events,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
@@ -58,6 +61,16 @@ final class BookingService
|
||||
$this->writeSegments($hold, $appointment);
|
||||
$hold->markConfirmed($now);
|
||||
|
||||
// رویداد در همان flushِ ثبت نوبت میرود؛ اگر این تراکنش برگردد، رویدادی هم
|
||||
// نمیماند که کسی به آن واکنش نشان دهد.
|
||||
$this->events->record(
|
||||
$appointment->getEntityType(),
|
||||
$appointment->getEntityId(),
|
||||
DomainEvents::APPOINTMENT_BOOKED,
|
||||
['appointment_uuid' => $appointment->getUuid(), 'hold_uuid' => $hold->getUuid()],
|
||||
$now,
|
||||
);
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
// مصرف اعتبار **اینجا**ست نه در پیشنمایش قیمت: تنها لحظهای که نوبت واقعاً
|
||||
@@ -112,6 +125,13 @@ final class BookingService
|
||||
// جلسهٔ دوره به `planned` برمیگردد؛ بقیهٔ جلسات دستنخورده میمانند.
|
||||
$this->courseSessions->unlink($appointment);
|
||||
|
||||
$this->events->recordAndFlush(
|
||||
$appointment->getEntityType(),
|
||||
$appointment->getEntityId(),
|
||||
DomainEvents::APPOINTMENT_CANCELLED,
|
||||
['appointment_uuid' => $appointment->getUuid(), 'released_resources' => count($occupancies)],
|
||||
);
|
||||
|
||||
return count($occupancies);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ use App\Appointment\Plan\ValueObject\AppointmentPlan;
|
||||
use App\Auth\Entity\User;
|
||||
use App\Resource\Entity\ClinicResource;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use App\Shared\Exception\AppException;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
@@ -34,6 +36,7 @@ use Doctrine\ORM\EntityManagerInterface;
|
||||
final class HoldService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DomainEventPublisher $events,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
@@ -95,6 +98,16 @@ final class HoldService
|
||||
throw $e;
|
||||
}
|
||||
|
||||
// بعد از اینکه **همهٔ** منابع گرفته شدند، نه پیش از آن: رزروی که وسط کار
|
||||
// شکسته، رویدادی هم ندارد.
|
||||
$this->events->recordAndFlush(
|
||||
$entityType,
|
||||
$entityId,
|
||||
DomainEvents::HOLD_CREATED,
|
||||
['hold_uuid' => $hold->getUuid(), 'starts_at' => $startsAt, 'resources' => count($taken)],
|
||||
$now,
|
||||
);
|
||||
|
||||
return $hold;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ use App\Cancellation\Entity\NoShowRecord;
|
||||
use App\Cancellation\Repository\CancellationPolicyRepository;
|
||||
use App\Cancellation\Repository\NoShowRecordRepository;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use App\Tag\Entity\TenantTag;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
@@ -23,6 +25,7 @@ final class NoShowService
|
||||
public function __construct(
|
||||
private readonly NoShowRecordRepository $records,
|
||||
private readonly CancellationPolicyRepository $policies,
|
||||
private readonly DomainEventPublisher $events,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
@@ -54,6 +57,15 @@ final class NoShowService
|
||||
}
|
||||
|
||||
$this->em->persist(new NoShowRecord($patient, $appointment, $actor, $now));
|
||||
|
||||
$this->events->record(
|
||||
$appointment->getEntityType(),
|
||||
$appointment->getEntityId(),
|
||||
DomainEvents::PATIENT_NO_SHOW,
|
||||
['appointment_uuid' => $appointment->getUuid(), 'patient_uuid' => $patient->getUuid()],
|
||||
$now,
|
||||
);
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
$count = $this->records->countRecent($patient, $now);
|
||||
|
||||
@@ -6,6 +6,8 @@ use App\Appointment\Entity\Appointment;
|
||||
use App\Course\Entity\CourseSession;
|
||||
use App\Course\Entity\TreatmentCourse;
|
||||
use App\Course\Repository\CourseSessionRepository;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
/**
|
||||
@@ -19,6 +21,7 @@ final class CourseSessionLinker
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CourseSessionRepository $sessions,
|
||||
private readonly DomainEventPublisher $events,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
@@ -67,8 +70,28 @@ final class CourseSessionLinker
|
||||
|
||||
$course = $session->getCourse();
|
||||
|
||||
$this->events->record(
|
||||
$course->getEntityType(),
|
||||
$course->getEntityId(),
|
||||
DomainEvents::COURSE_SESSION_COMPLETED,
|
||||
[
|
||||
'course_uuid' => $course->getUuid(),
|
||||
'session_uuid' => $session->getUuid(),
|
||||
'session_number' => $session->getSessionNumber(),
|
||||
],
|
||||
$at,
|
||||
);
|
||||
|
||||
if ($course->completedCount() >= $course->getSessionCount()) {
|
||||
$course->complete($at);
|
||||
|
||||
$this->events->record(
|
||||
$course->getEntityType(),
|
||||
$course->getEntityId(),
|
||||
DomainEvents::COURSE_COMPLETED,
|
||||
['course_uuid' => $course->getUuid()],
|
||||
$at,
|
||||
);
|
||||
}
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
@@ -9,6 +9,8 @@ use App\Course\Repository\TreatmentCourseRepository;
|
||||
use App\Package\Entity\PatientPackage;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
/**
|
||||
@@ -22,6 +24,7 @@ final class CourseStarter
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TreatmentCourseRepository $courses,
|
||||
private readonly DomainEventPublisher $events,
|
||||
) {}
|
||||
|
||||
public function start(
|
||||
@@ -63,6 +66,13 @@ final class CourseStarter
|
||||
new CourseSession($course, $number, $protocol->paramsFor($number));
|
||||
}
|
||||
|
||||
$this->events->record(
|
||||
$course->getEntityType(),
|
||||
$course->getEntityId(),
|
||||
DomainEvents::COURSE_STARTED,
|
||||
['course_uuid' => $course->getUuid(), 'session_count' => $course->getSessionCount()],
|
||||
);
|
||||
|
||||
$this->courses->save($course);
|
||||
|
||||
return $course;
|
||||
|
||||
@@ -8,6 +8,8 @@ use App\ClinicService\Entity\ServiceItem;
|
||||
use App\Package\Entity\PatientPackage;
|
||||
use App\Package\Entity\SessionCreditLedger;
|
||||
use App\Package\Repository\SessionCreditLedgerRepository;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Doctrine\DBAL\LockMode;
|
||||
|
||||
@@ -22,6 +24,7 @@ final class CreditLedgerService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SessionCreditLedgerRepository $ledger,
|
||||
private readonly DomainEventPublisher $events,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
@@ -87,6 +90,13 @@ final class CreditLedgerService
|
||||
|
||||
$this->record($locked, SessionCreditLedger::KIND_CONSUME, -1, $appointment, $service);
|
||||
|
||||
$this->events->recordAndFlush(
|
||||
$locked->getEntityType(),
|
||||
$locked->getEntityId(),
|
||||
DomainEvents::CREDIT_CONSUMED,
|
||||
['patient_package_uuid' => $locked->getUuid(), 'appointment_uuid' => $appointment->getUuid()],
|
||||
);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -122,6 +132,16 @@ final class CreditLedgerService
|
||||
$by,
|
||||
);
|
||||
|
||||
$this->events->recordAndFlush(
|
||||
$consumed->getPatientPackage()->getEntityType(),
|
||||
$consumed->getPatientPackage()->getEntityId(),
|
||||
DomainEvents::CREDIT_REFUNDED,
|
||||
[
|
||||
'patient_package_uuid' => $consumed->getPatientPackage()->getUuid(),
|
||||
'appointment_uuid' => $appointment->getUuid(),
|
||||
],
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ use App\Package\Entity\SessionCreditLedger;
|
||||
use App\Package\Repository\PatientPackageRepository;
|
||||
use App\Patient\Entity\PatientRecord;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Event\DomainEventPublisher;
|
||||
use App\Shared\Event\DomainEvents;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
/**
|
||||
@@ -22,6 +24,7 @@ final class PackageSalesService
|
||||
public function __construct(
|
||||
private readonly PatientPackageRepository $patientPackages,
|
||||
private readonly CreditLedgerService $ledger,
|
||||
private readonly DomainEventPublisher $events,
|
||||
) {}
|
||||
|
||||
public function sell(Package $package, PatientRecord $patient, ?User $by = null, ?int $pricePaid = null): PatientPackage
|
||||
@@ -54,6 +57,17 @@ final class PackageSalesService
|
||||
by: $by,
|
||||
);
|
||||
|
||||
$this->events->recordAndFlush(
|
||||
$sold->getEntityType(),
|
||||
$sold->getEntityId(),
|
||||
DomainEvents::PACKAGE_PURCHASED,
|
||||
[
|
||||
'patient_package_uuid' => $sold->getUuid(),
|
||||
'package_uuid' => $package->getUuid(),
|
||||
'session_count' => $sold->getSessionCount(),
|
||||
],
|
||||
);
|
||||
|
||||
return $sold;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Report\Controller;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Branch\Service\BranchResolver;
|
||||
use App\Report\Service\PlanAccuracyReporter;
|
||||
use App\Report\Service\ResourceUtilizationReporter;
|
||||
use App\Resource\Repository\ClinicResourceRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
use App\Shared\Event\Entity\DomainEventLog;
|
||||
use App\Shared\Event\Repository\DomainEventLogRepository;
|
||||
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: 'Report')]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
class ReportController extends BaseController
|
||||
{
|
||||
/** بازهٔ بزرگتر از این، هم کند است هم عملاً خوانده نمیشود. */
|
||||
private const MAX_RANGE_DAYS = 90;
|
||||
|
||||
public function __construct(
|
||||
private readonly ResourceUtilizationReporter $utilization,
|
||||
private readonly PlanAccuracyReporter $accuracy,
|
||||
private readonly ClinicResourceRepository $resources,
|
||||
private readonly DomainEventLogRepository $events,
|
||||
private readonly BranchResolver $branches,
|
||||
) {}
|
||||
|
||||
#[Route('/api/v1/reports/resource-utilization', name: 'report_resource_utilization', methods: ['GET'])]
|
||||
public function resourceUtilization(#[CurrentUser] User $user, Request $request): JsonResponse
|
||||
{
|
||||
$branch = $request->query->get('branch_uuid');
|
||||
|
||||
if (!is_string($branch)) {
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'فیلد branch_uuid الزامی است', 422, 'branch_uuid');
|
||||
}
|
||||
|
||||
$range = $this->range($request);
|
||||
|
||||
if ($range === null) {
|
||||
return $this->rangeError();
|
||||
}
|
||||
|
||||
[$from, $to] = $range;
|
||||
|
||||
$address = $this->branches->resolve($user, $branch);
|
||||
|
||||
return $this->success([
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'rows' => $this->utilization->report(
|
||||
$this->resources->findForAddress($address),
|
||||
$address,
|
||||
$from,
|
||||
$to,
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/reports/plan-accuracy', name: 'report_plan_accuracy', methods: ['GET'])]
|
||||
public function planAccuracy(#[CurrentUser] User $user, Request $request): JsonResponse
|
||||
{
|
||||
$range = $this->range($request);
|
||||
|
||||
if ($range === null) {
|
||||
return $this->rangeError();
|
||||
}
|
||||
|
||||
[$from, $to] = $range;
|
||||
[$entityType, $entityId] = $this->branches->pair($user);
|
||||
|
||||
return $this->success([
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'rows' => $this->accuracy->report($entityType, $entityId, $from, $to),
|
||||
]);
|
||||
}
|
||||
|
||||
/** عیبیابی صندوق خروجی — فقط ادمین. */
|
||||
#[Route('/api/v1/domain-events', name: 'domain_events_index', methods: ['GET'])]
|
||||
#[IsGranted('ROLE_ADMIN')]
|
||||
public function domainEvents(Request $request): JsonResponse
|
||||
{
|
||||
$name = $request->query->get('name');
|
||||
|
||||
return $this->success(array_map(
|
||||
static fn (DomainEventLog $e): array => $e->toArray(),
|
||||
$this->events->search(
|
||||
is_string($name) ? $name : null,
|
||||
null,
|
||||
null,
|
||||
$request->query->getInt('limit', 100),
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
/** @return array{0: int, 1: int}|null `null` یعنی بازه نامعتبر است */
|
||||
private function range(Request $request): ?array
|
||||
{
|
||||
$to = $request->query->has('to') ? $request->query->getInt('to') : time();
|
||||
$from = $request->query->has('from') ? $request->query->getInt('from') : $to - 7 * 86400;
|
||||
|
||||
if ($to <= $from || ($to - $from) > self::MAX_RANGE_DAYS * 86400) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [$from, $to];
|
||||
}
|
||||
|
||||
private function rangeError(): JsonResponse
|
||||
{
|
||||
return $this->error(
|
||||
ErrorCodes::ERR_VALIDATION_001,
|
||||
sprintf('بازهٔ گزارش باید مثبت و حداکثر %d روز باشد', self::MAX_RANGE_DAYS),
|
||||
422,
|
||||
'from',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Report\Service;
|
||||
|
||||
use App\Appointment\Entity\Appointment;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
/**
|
||||
* مدت پیشبینیشده در برابر مدت واقعی — تشخیص تعریف غلط بخشها.
|
||||
*
|
||||
* بند ۱۷ مستند، ریسک سوم: «کلینیک بخشهای نوبت را اشتباه تعریف کند → ظرفیت غلط حساب
|
||||
* میشود». سرویسی که یک ساعت پیشبینی شده ولی یکساعتونیم طول میکشد، هر روز نیم ساعت
|
||||
* از ظرفیت کلینیک را بیصدا میخورد و هیچ خطایی هم نمیدهد.
|
||||
*
|
||||
* مبنای «واقعی» فاصلهٔ ثبتشدهٔ اسلات است، نه ساعت ورود و خروج بیمار — چون آن دومی
|
||||
* جایی ثبت نمیشود و حدس زدنش بدتر از نداشتنش است.
|
||||
*/
|
||||
final class PlanAccuracyReporter
|
||||
{
|
||||
/** زیر این تعداد نمونه، میانگین معنا ندارد. */
|
||||
public const MIN_SAMPLE = 3;
|
||||
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>> مرتب بر اساس شدت انحراف
|
||||
*/
|
||||
public function report(string $entityType, int $entityId, int $from, int $to): array
|
||||
{
|
||||
$rows = $this->em->createQueryBuilder()
|
||||
->select(
|
||||
'si.uuid AS service_uuid',
|
||||
'si.name AS service_name',
|
||||
'COUNT(a.id) AS sample_size',
|
||||
'AVG(a.serviceTotalMinutes) AS planned',
|
||||
'AVG((a.slotEnd - a.slotStart) / 60) AS actual',
|
||||
)
|
||||
->from(Appointment::class, 'a')
|
||||
->join('a.serviceItem', 'si')
|
||||
->where('a.entityType = :type')
|
||||
->andWhere('a.entityId = :id')
|
||||
->andWhere('a.slotStart >= :from')
|
||||
->andWhere('a.slotStart < :to')
|
||||
->andWhere('a.status = :status')
|
||||
->andWhere('a.serviceTotalMinutes IS NOT NULL')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId)
|
||||
->setParameter('from', $from)
|
||||
->setParameter('to', $to)
|
||||
// فقط نوبتهای انجامشده: لغوشده چیزی دربارهٔ مدت واقعی نمیگوید.
|
||||
->setParameter('status', Appointment::STATUS_COMPLETED)
|
||||
->groupBy('si.uuid')
|
||||
->addGroupBy('si.name')
|
||||
->getQuery()
|
||||
->getArrayResult();
|
||||
|
||||
$out = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$sample = (int) $row['sample_size'];
|
||||
|
||||
if ($sample < self::MIN_SAMPLE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$planned = (float) $row['planned'];
|
||||
$actual = (float) $row['actual'];
|
||||
|
||||
if ($planned <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$deviation = (int) round(($actual - $planned) / $planned * 100);
|
||||
|
||||
$out[] = [
|
||||
'service_uuid' => $row['service_uuid'],
|
||||
'service_name' => $row['service_name'],
|
||||
'sample_size' => $sample,
|
||||
'planned_minutes' => (int) round($planned),
|
||||
'actual_minutes' => (int) round($actual),
|
||||
'deviation_percent' => $deviation,
|
||||
'severity' => $this->severityFor($deviation),
|
||||
];
|
||||
}
|
||||
|
||||
usort($out, static fn (array $a, array $b): int => abs($b['deviation_percent']) <=> abs($a['deviation_percent']));
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* شدت از **قدر مطلق** انحراف میآید: سرویسی که نصف زمان پیشبینیشده طول میکشد هم
|
||||
* غلط تعریف شده — ظرفیتی که میشد فروخت، خالی مانده.
|
||||
*/
|
||||
private function severityFor(int $deviationPercent): string
|
||||
{
|
||||
return match (true) {
|
||||
abs($deviationPercent) >= 30 => 'high',
|
||||
abs($deviationPercent) >= 15 => 'medium',
|
||||
abs($deviationPercent) >= 5 => 'low',
|
||||
default => 'none',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Report\Service;
|
||||
|
||||
use App\Appointment\Availability\Entity\ResourceOccupancy;
|
||||
use App\Doctor\Entity\DoctorAddress;
|
||||
use App\Resource\Entity\ClinicResource;
|
||||
use App\Resource\Service\ResourceAvailabilityService;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
/**
|
||||
* بهرهوری منابع — تنها ابزاری که به کلینیک میگوید تعریف بخشهایش درست است یا نه.
|
||||
*
|
||||
* سه عدد، سه معنای متفاوت:
|
||||
*
|
||||
* | عدد | یعنی |
|
||||
* |---|---|
|
||||
* | `available_minutes` | منبع طبق تقویمش چقدر در دسترس بوده |
|
||||
* | `occupied_minutes` | چقدر **گرفته** شده — شامل آمادهسازی، تمیزکاری و بخشهای انتظار |
|
||||
* | `active_minutes` | چقدر واقعاً کار انجام شده — فقط بخشهایی که بیمار حاضر بوده |
|
||||
*
|
||||
* فاصلهٔ `occupied` و `active` همان چیزی است که تعریف غلط بخشها را لو میدهد: منبعی که
|
||||
* هشت ساعت اشغال بوده ولی دو ساعت کار کرده، یا بخشهای `passive` زیادی گرفته یا
|
||||
* زمانهای انتظارش اشتباه به او نسبت داده شده.
|
||||
*/
|
||||
final class ResourceUtilizationReporter
|
||||
{
|
||||
/** زیر این نسبت، ظرفیت عملاً هدر میرود. */
|
||||
public const WASTE_THRESHOLD = 0.3;
|
||||
|
||||
public function __construct(
|
||||
private readonly ResourceAvailabilityService $calendars,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param ClinicResource[] $resources
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function report(array $resources, DoctorAddress $address, int $from, int $to): array
|
||||
{
|
||||
$occupied = $this->occupiedMinutes($resources, $from, $to);
|
||||
$active = $this->activeMinutes($resources, $from, $to);
|
||||
|
||||
$rows = [];
|
||||
|
||||
foreach ($resources as $resource) {
|
||||
$id = (int) $resource->getId();
|
||||
$available = $this->availableMinutes($resource, $from, $to);
|
||||
|
||||
$rows[] = $this->row(
|
||||
$resource,
|
||||
$available,
|
||||
$occupied[$id] ?? 0,
|
||||
$active[$id] ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function row(ClinicResource $resource, int $available, int $occupied, int $active): array
|
||||
{
|
||||
// تقسیم بر صفر معنای متفاوتی دارد: منبعی بدون تقویم «۰٪ بهرهوری» ندارد،
|
||||
// اصلاً بهرهوریاش تعریفنشده است.
|
||||
$utilization = $available > 0 ? round($occupied / $available, 2) : null;
|
||||
$activeRatio = $occupied > 0 ? round($active / $occupied, 2) : null;
|
||||
|
||||
return [
|
||||
'resource_uuid' => $resource->getUuid(),
|
||||
'resource_name' => $resource->getName(),
|
||||
'role' => $resource->getType()->getCode(),
|
||||
'available_minutes' => $available,
|
||||
'occupied_minutes' => $occupied,
|
||||
'active_minutes' => $active,
|
||||
'utilization' => $utilization,
|
||||
'active_ratio' => $activeRatio,
|
||||
'wasted_capacity' => $activeRatio !== null && $activeRatio < self::WASTE_THRESHOLD,
|
||||
];
|
||||
}
|
||||
|
||||
private function availableMinutes(ClinicResource $resource, int $from, int $to): int
|
||||
{
|
||||
// شعبه از خودِ منبع میآید؛ منبع بدون شعبه وجود ندارد.
|
||||
$days = $this->calendars->rawAvailability($resource, $from, $to);
|
||||
|
||||
$minutes = 0;
|
||||
|
||||
foreach ($days as $day) {
|
||||
$minutes += $day->totalMinutes();
|
||||
}
|
||||
|
||||
// ظرفیت ضرب میشود: اتاق سهتخته در یک ساعت، سه ساعت-منبع عرضه دارد. بدون آن،
|
||||
// هر منبع چندظرفیتی همیشه «بیش از ۱۰۰٪ بهرهوری» نشان میداد.
|
||||
return $minutes * max(1, $resource->getCapacity());
|
||||
}
|
||||
|
||||
/**
|
||||
* دقایق اشغال از `resource_occupancy` — شامل setup/cleanup، چون منبع واقعاً
|
||||
* اشغال بوده.
|
||||
*
|
||||
* @param ClinicResource[] $resources
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function occupiedMinutes(array $resources, int $from, int $to): array
|
||||
{
|
||||
if ($resources === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->em->createQueryBuilder()
|
||||
->select('IDENTITY(o.resource) AS resource_id', 'SUM(o.endsAt - o.startsAt) AS seconds')
|
||||
->from(ResourceOccupancy::class, 'o')
|
||||
->where('o.resource IN (:resources)')
|
||||
->andWhere('o.startsAt < :to')
|
||||
->andWhere('o.endsAt > :from')
|
||||
->andWhere('o.status IN (:statuses)')
|
||||
->setParameter('resources', $resources)
|
||||
->setParameter('from', $from)
|
||||
->setParameter('to', $to)
|
||||
// ردیف آزادشده اشغال نبوده؛ آوردنش یعنی هر لغو، بهرهوری را بالا ببرد.
|
||||
->setParameter('statuses', ResourceOccupancy::BLOCKING_STATUSES)
|
||||
->groupBy('resource_id')
|
||||
->getQuery()
|
||||
->getArrayResult();
|
||||
|
||||
$out = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$out[(int) $row['resource_id']] = (int) round(((int) $row['seconds']) / 60);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* دقایقی که بیمار حاضر بوده — بخشهای `passive` عمداً نمیآیند.
|
||||
*
|
||||
* @param ClinicResource[] $resources
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function activeMinutes(array $resources, int $from, int $to): array
|
||||
{
|
||||
if ($resources === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$sql = <<<'SQL'
|
||||
SELECT o.resource_id AS resource_id,
|
||||
SUM(LEAST(o.ends_at, s.ends_at) - GREATEST(o.starts_at, s.starts_at)) AS seconds
|
||||
FROM resource_occupancy o
|
||||
JOIN appointment_segments s
|
||||
ON s.appointment_id = o.appointment_id
|
||||
AND s.patient_present = 1
|
||||
AND s.starts_at < o.ends_at
|
||||
AND s.ends_at > o.starts_at
|
||||
WHERE o.resource_id IN (:resources)
|
||||
AND o.starts_at < :to
|
||||
AND o.ends_at > :from
|
||||
AND o.status IN (:statuses)
|
||||
GROUP BY o.resource_id
|
||||
SQL;
|
||||
|
||||
$rows = $this->em->getConnection()->fetchAllAssociative($sql, [
|
||||
'resources' => array_map(static fn (ClinicResource $r): int => (int) $r->getId(), $resources),
|
||||
'from' => $from,
|
||||
'to' => $to,
|
||||
'statuses' => ResourceOccupancy::BLOCKING_STATUSES,
|
||||
], [
|
||||
'resources' => \Doctrine\DBAL\ArrayParameterType::INTEGER,
|
||||
'statuses' => \Doctrine\DBAL\ArrayParameterType::STRING,
|
||||
]);
|
||||
|
||||
$out = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$out[(int) $row['resource_id']] = (int) round(((int) $row['seconds']) / 60);
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,25 @@ class ClinicResourceRepository extends ServiceEntityRepository
|
||||
return $qb->orderBy('r.name', 'ASC')->getQuery()->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* همهٔ منابع فعال یک شعبه — ورودی گزارش بهرهوری.
|
||||
*
|
||||
* @return ClinicResource[]
|
||||
*/
|
||||
public function findForAddress(DoctorAddress $address): array
|
||||
{
|
||||
return $this->createQueryBuilder('r')
|
||||
->addSelect('t')
|
||||
->join('r.type', 't')
|
||||
->where('r.address = :address')
|
||||
->andWhere('r.active = true')
|
||||
->setParameter('address', $address)
|
||||
->orderBy('t.code', 'ASC')
|
||||
->addOrderBy('r.name', 'ASC')
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* پرسوجوی داغِ تسک ۰۶: «منابع فعالِ این شعبه از این نوع که **همهٔ** این مهارتها
|
||||
* را دارند».
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event\Command;
|
||||
|
||||
use Doctrine\DBAL\Connection;
|
||||
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;
|
||||
|
||||
/**
|
||||
* پاکسازی رویدادهای **منتشرشدهٔ** قدیمی.
|
||||
*
|
||||
* ردیف منتشرنشده هرگز حذف نمیشود، حتی اگر سالخورده باشد: آن یک رویداد گمشده است و
|
||||
* حذفش یعنی پاک کردن مدرکِ همان گمشدن.
|
||||
*/
|
||||
#[AsCommand(name: 'app:events:prune', description: 'Delete published domain events older than a retention window.')]
|
||||
class PruneDomainEventsCommand extends Command
|
||||
{
|
||||
public function __construct(private readonly Connection $connection)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this
|
||||
->addOption('days', null, InputOption::VALUE_REQUIRED, 'Retention window in days', '180')
|
||||
->addOption('dry-run', null, InputOption::VALUE_NONE, 'Report without deleting');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
$before = time() - max(1, (int) $input->getOption('days')) * 86400;
|
||||
|
||||
$count = (int) $this->connection->fetchOne(
|
||||
'SELECT COUNT(*) FROM domain_events WHERE published_at IS NOT NULL AND occurred_at < ?',
|
||||
[$before],
|
||||
);
|
||||
|
||||
if ($count === 0) {
|
||||
$io->success('رویداد قابل حذفی نیست.');
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
if ($input->getOption('dry-run')) {
|
||||
$io->note(sprintf('%d رویداد حذف میشد.', $count));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
$this->connection->executeStatement(
|
||||
'DELETE FROM domain_events WHERE published_at IS NOT NULL AND occurred_at < ?',
|
||||
[$before],
|
||||
);
|
||||
|
||||
$io->success(sprintf('%d رویداد حذف شد.', $count));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event\Command;
|
||||
|
||||
use App\Shared\Event\Entity\DomainEventLog;
|
||||
use App\Shared\Event\Repository\DomainEventLogRepository;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
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` بالا میرود و خطا ثبت میشود. بعد از سقف
|
||||
* تلاش، ردیف با خطایش باقی میماند تا ادمین ببیند — حذف خاموش یعنی رویداد گمشدهٔ بیرد.
|
||||
*/
|
||||
#[AsCommand(name: 'app:events:publish', description: 'Publish pending domain events from the outbox.')]
|
||||
class PublishDomainEventsCommand extends Command
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DomainEventLogRepository $events,
|
||||
private readonly MessageBusInterface $bus,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
$this->addOption('limit', null, InputOption::VALUE_REQUIRED, 'How many events to publish per run', '100');
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$io = new SymfonyStyle($input, $output);
|
||||
$pending = $this->events->findPending(max(1, (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));
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
/** @return DomainEventLog[] */
|
||||
public function pending(int $limit = 100): array
|
||||
{
|
||||
return $this->events->findPending($limit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event;
|
||||
|
||||
use App\Shared\Event\Entity\DomainEventLog;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
/**
|
||||
* تنها نقطهٔ ثبت رویداد دامنه.
|
||||
*
|
||||
* `record()` عمداً **flush نمیکند**: ردیف رویداد باید در همان تراکنشی commit شود که
|
||||
* خودِ تغییر را انجام میدهد. اگر اینجا flush میکردیم، rollbackِ تراکنش اصلی رویدادی
|
||||
* را جا میگذاشت که هرگز اتفاق نیفتاده.
|
||||
*/
|
||||
final class DomainEventPublisher
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload فقط uuid و اسکالر
|
||||
*/
|
||||
public function record(string $entityType, int $entityId, string $name, array $payload, ?int $occurredAt = null): DomainEventLog
|
||||
{
|
||||
if (!in_array($name, DomainEvents::ALL, true)) {
|
||||
throw new \InvalidArgumentException(sprintf('Unknown domain event "%s".', $name));
|
||||
}
|
||||
|
||||
$event = new DomainEventLog($entityType, $entityId, $name, $payload, $occurredAt);
|
||||
|
||||
$this->em->persist($event);
|
||||
|
||||
return $event;
|
||||
}
|
||||
|
||||
/**
|
||||
* ثبت + flush — برای جاهایی که فراخوان تراکنش باز ندارد.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
*/
|
||||
public function recordAndFlush(string $entityType, int $entityId, string $name, array $payload, ?int $occurredAt = null): DomainEventLog
|
||||
{
|
||||
$event = $this->record($entityType, $entityId, $name, $payload, $occurredAt);
|
||||
$this->em->flush();
|
||||
|
||||
return $event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event;
|
||||
|
||||
/**
|
||||
* فهرست بستهٔ نام رویدادها — بند ۱۶ مستند.
|
||||
*
|
||||
* نام رویداد قرارداد عمومی است: مصرفکننده روی رشته شرط میگذارد. تایپوی یک حرفی
|
||||
* یعنی رویدادی که هیچکس نمیشنود و هیچ خطایی هم نمیدهد، پس فهرست بسته است.
|
||||
*/
|
||||
final class DomainEvents
|
||||
{
|
||||
public const HOLD_CREATED = 'HoldCreated';
|
||||
public const APPOINTMENT_BOOKED = 'AppointmentBooked';
|
||||
public const APPOINTMENT_CANCELLED = 'AppointmentCancelled';
|
||||
public const APPOINTMENT_RESCHEDULED = 'AppointmentRescheduled';
|
||||
public const PATIENT_NO_SHOW = 'PatientNoShow';
|
||||
public const APPOINTMENT_COMPLETED = 'AppointmentCompleted';
|
||||
public const RESOURCE_BLOCKED = 'ResourceBlocked';
|
||||
public const RESOURCE_RELEASED = 'ResourceReleased';
|
||||
public const COURSE_STARTED = 'CourseStarted';
|
||||
public const COURSE_SESSION_COMPLETED = 'CourseSessionCompleted';
|
||||
public const COURSE_COMPLETED = 'CourseCompleted';
|
||||
public const PACKAGE_PURCHASED = 'PackagePurchased';
|
||||
public const CREDIT_CONSUMED = 'CreditConsumed';
|
||||
public const CREDIT_REFUNDED = 'CreditRefunded';
|
||||
|
||||
public const ALL = [
|
||||
self::HOLD_CREATED,
|
||||
self::APPOINTMENT_BOOKED,
|
||||
self::APPOINTMENT_CANCELLED,
|
||||
self::APPOINTMENT_RESCHEDULED,
|
||||
self::PATIENT_NO_SHOW,
|
||||
self::APPOINTMENT_COMPLETED,
|
||||
self::RESOURCE_BLOCKED,
|
||||
self::RESOURCE_RELEASED,
|
||||
self::COURSE_STARTED,
|
||||
self::COURSE_SESSION_COMPLETED,
|
||||
self::COURSE_COMPLETED,
|
||||
self::PACKAGE_PURCHASED,
|
||||
self::CREDIT_CONSUMED,
|
||||
self::CREDIT_REFUNDED,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event\Entity;
|
||||
|
||||
use App\Shared\Event\Repository\DomainEventLogRepository;
|
||||
use App\Shared\Tenant\TenantOwnedTrait;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* صندوق خروجی رویدادهای دامنه (outbox).
|
||||
*
|
||||
* ردیف رویداد **در همان تراکنشی** نوشته میشود که خودِ تغییر را انجام میدهد، و یک
|
||||
* worker بعداً منتشرش میکند. بدون این الگو دو حالت شکست ممکن است:
|
||||
*
|
||||
* | حالت | نتیجه |
|
||||
* |---|---|
|
||||
* | انتشار پیش از commit، بعد rollback | پیامک رفته، نوبتی وجود ندارد |
|
||||
* | commit موفق، انتشار شکست خورد | نوبت هست، هیچکس مطلع نشد |
|
||||
*
|
||||
* با outbox حداکثر **تأخیر** داریم، هرگز گمشدن.
|
||||
*
|
||||
* این جدول با `AppointmentEvent` موجود اشتباه نشود: آن تاریخچهٔ وضعیت یک نوبت است،
|
||||
* این اعلان تغییر به بیرونِ دامنه.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: DomainEventLogRepository::class)]
|
||||
#[ORM\Table(name: 'domain_events')]
|
||||
#[ORM\Index(columns: ['published_at', 'occurred_at'], name: 'idx_de_pending')]
|
||||
#[ORM\Index(columns: ['entity_type', 'entity_id', 'occurred_at'], name: 'idx_de_tenant')]
|
||||
#[ORM\Index(columns: ['name', 'occurred_at'], name: 'idx_de_name')]
|
||||
class DomainEventLog
|
||||
{
|
||||
use TenantOwnedTrait;
|
||||
|
||||
/** سقف تلاش — ردیف مرده با خطایش میماند تا دیده شود، حذف نمیشود. */
|
||||
public const MAX_ATTEMPTS = 5;
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'bigint')]
|
||||
private ?string $id = null;
|
||||
|
||||
/** شناسهٔ idempotency برای مصرفکننده. */
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 60)]
|
||||
private string $name;
|
||||
|
||||
/** @var array<string, scalar|null> */
|
||||
#[ORM\Column(type: 'json')]
|
||||
private array $payload;
|
||||
|
||||
/** زمان **وقوع**، نه انتشار. */
|
||||
#[ORM\Column(name: 'occurred_at', type: 'integer')]
|
||||
private int $occurredAt;
|
||||
|
||||
#[ORM\Column(name: 'published_at', type: 'integer', nullable: true)]
|
||||
private ?int $publishedAt = null;
|
||||
|
||||
#[ORM\Column(type: 'smallint', options: ['default' => 0])]
|
||||
private int $attempts = 0;
|
||||
|
||||
#[ORM\Column(name: 'last_error', type: 'string', length: 255, nullable: true)]
|
||||
private ?string $lastError = null;
|
||||
|
||||
/** @param array<string, mixed> $payload */
|
||||
public function __construct(string $entityType, int $entityId, string $name, array $payload, ?int $occurredAt = null)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->name = $name;
|
||||
$this->payload = self::scalarsOnly($payload);
|
||||
$this->occurredAt = $occurredAt ?? time();
|
||||
|
||||
$this->assignTenantPair($entityType, $entityId);
|
||||
}
|
||||
|
||||
/**
|
||||
* هیچ entity ای در رویداد نیست — فقط uuid و اسکالر.
|
||||
*
|
||||
* entity در پیام async یعنی سریالسازی، detach شدن، و دادهٔ کهنه؛ مصرفکننده باید
|
||||
* خودش با uuid واکشی کند تا همیشه تازهترین حالت را ببیند.
|
||||
*
|
||||
* @param array<string, mixed> $payload
|
||||
* @return array<string, scalar|null>
|
||||
*/
|
||||
private static function scalarsOnly(array $payload): array
|
||||
{
|
||||
return array_filter($payload, static fn (mixed $v): bool => is_scalar($v) || $v === null);
|
||||
}
|
||||
|
||||
public function getId(): ?string { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getName(): string { return $this->name; }
|
||||
public function getPayload(): array { return $this->payload; }
|
||||
public function getOccurredAt(): int { return $this->occurredAt; }
|
||||
public function getPublishedAt(): ?int { return $this->publishedAt; }
|
||||
public function getAttempts(): int { return $this->attempts; }
|
||||
public function getLastError(): ?string { return $this->lastError; }
|
||||
public function isPublished(): bool { return $this->publishedAt !== null; }
|
||||
|
||||
public function markPublished(?int $at = null): self
|
||||
{
|
||||
$this->publishedAt = $at ?? time();
|
||||
$this->lastError = null;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function markFailed(string $error): self
|
||||
{
|
||||
$this->attempts++;
|
||||
$this->lastError = mb_substr($error, 0, 255);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'name' => $this->name,
|
||||
'payload' => (object) $this->payload,
|
||||
'occurred_at' => $this->occurredAt,
|
||||
'published_at' => $this->publishedAt,
|
||||
'attempts' => $this->attempts,
|
||||
'last_error' => $this->lastError,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event\Message;
|
||||
|
||||
/**
|
||||
* پیام async یک رویداد دامنه.
|
||||
*
|
||||
* `uuid` شناسهٔ idempotency است: messenger ممکن است پیام را دوباره تحویل بدهد، و
|
||||
* **مصرفکننده** باید تکراری را تشخیص بدهد — نه اینکه رویداد تضمین یکتایی بدهد.
|
||||
*/
|
||||
final readonly class DomainEventMessage
|
||||
{
|
||||
/** @param array<string, scalar|null> $payload */
|
||||
public function __construct(
|
||||
public string $uuid,
|
||||
public string $name,
|
||||
public string $entityType,
|
||||
public int $entityId,
|
||||
public array $payload,
|
||||
public int $occurredAt,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event\MessageHandler;
|
||||
|
||||
use App\Shared\Event\Message\DomainEventMessage;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
|
||||
|
||||
/**
|
||||
* درزِ اتصال مصرفکنندهها.
|
||||
*
|
||||
* خودش کاری جز ثبت لاگ نمیکند و **نباید بکند**: پیامک، حسابداری و گزارش هر کدام
|
||||
* مصرفکنندهٔ خودشان را کنار این ثبت میکنند. وجودش لازم است چون messenger پیامِ
|
||||
* بدون handler را خطا میدهد، و آن خطا در صندوق خروجی بهعنوان «شکست انتشار» ثبت
|
||||
* میشد — یعنی یک ایراد پیکربندی، شبیه یک رویداد گمشده به نظر میرسید.
|
||||
*
|
||||
* مصرفکنندهٔ تازه باید **idempotent** باشد: messenger ممکن است پیام را دوباره تحویل
|
||||
* بدهد و `DomainEventMessage::$uuid` همان شناسهای است که با آن تکراری را میشناسد.
|
||||
*/
|
||||
#[AsMessageHandler]
|
||||
final class DomainEventHandler
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
public function __invoke(DomainEventMessage $message): void
|
||||
{
|
||||
$this->logger->info('domain event published', [
|
||||
'uuid' => $message->uuid,
|
||||
'name' => $message->name,
|
||||
'entity_type' => $message->entityType,
|
||||
'entity_id' => $message->entityId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Shared\Event\Repository;
|
||||
|
||||
use App\Shared\Event\Entity\DomainEventLog;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/** @extends ServiceEntityRepository<DomainEventLog> */
|
||||
class DomainEventLogRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, DomainEventLog::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* ردیفهای منتشرنشدهای که هنوز سقف تلاش را رد نکردهاند.
|
||||
*
|
||||
* @return DomainEventLog[]
|
||||
*/
|
||||
public function findPending(int $limit = 100): array
|
||||
{
|
||||
return $this->createQueryBuilder('e')
|
||||
->where('e.publishedAt IS NULL')
|
||||
->andWhere('e.attempts < :max')
|
||||
->setParameter('max', DomainEventLog::MAX_ATTEMPTS)
|
||||
->orderBy('e.occurredAt', 'ASC')
|
||||
->addOrderBy('e.id', 'ASC')
|
||||
->setMaxResults($limit)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return DomainEventLog[]
|
||||
*/
|
||||
public function search(?string $name, ?string $entityType, ?int $entityId, int $limit = 100): array
|
||||
{
|
||||
$qb = $this->createQueryBuilder('e')
|
||||
->orderBy('e.occurredAt', 'DESC')
|
||||
->addOrderBy('e.id', 'DESC')
|
||||
->setMaxResults(min($limit, 500));
|
||||
|
||||
if ($name !== null && $name !== '') {
|
||||
$qb->andWhere('e.name = :name')->setParameter('name', $name);
|
||||
}
|
||||
|
||||
if ($entityType !== null && $entityId !== null) {
|
||||
$qb->andWhere('e.entityType = :type')
|
||||
->andWhere('e.entityId = :id')
|
||||
->setParameter('type', $entityType)
|
||||
->setParameter('id', $entityId);
|
||||
}
|
||||
|
||||
return $qb->getQuery()->getResult();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user