fix(appointments): file the case file on every confirmation path

Confirming an appointment was supposed to create the patient's record and its
session, and PatientService already knew how. Only two of the five paths that
confirm an appointment ever called it, and the one that mattered most did not:
a booking paid for online was confirmed inside the payment callback, which
never ran the side-effects. Every Nobat724 booking therefore went unfiled — 7
confirmed appointments in dev had no session at all.

The side-effects now run through AppointmentConfirmationService, which every
path calls: the payment callback, both PATCH endpoints, and panel/admin
bookings. Creating the record can no longer roll back a confirmation or a
payment; a failure is logged and can be repaired with the new
app:appointment:backfill-sessions command.

Two related defects fixed along the way:

- A doctor working at a clinic got two records for one appointment, one under
  the doctor and one under the clinic, so a single visit's revenue was counted
  twice. The booking context now decides, and it decides once.
- That context was inferred from address_id, falling back to "the doctor's only
  clinic" — a guess that files an appointment under the wrong practice now that
  schedules are per-context. It is stored as appointments.clinic_id instead.

Panel and admin bookings were left pending forever: nothing confirmed them and
no payment was expected. They are created confirmed.

Repeat confirmations no longer duplicate the session; an archived one still
counts as filed, so archiving a mistaken visit does not resurrect it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-18 16:55:39 +03:30
co-authored by Claude Opus 4.8
parent 7baa4df3d4
commit e6422014d1
15 changed files with 995 additions and 28 deletions
@@ -0,0 +1,118 @@
<?php
namespace App\Appointment\Command;
use App\Appointment\Entity\Appointment;
use App\Appointment\Repository\AppointmentRepository;
use App\Appointment\Service\AppointmentConfirmationService;
use App\Patient\Repository\PatientSessionRepository;
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;
/**
* Finds appointments that were confirmed without getting a patient session.
*
* Until the confirmation side-effects were funnelled through
* AppointmentConfirmationService, only the two PATCH endpoints created records —
* anything confirmed by an online payment never did. Those appointments are
* still missing their case file, and completed ones need it just as much: a
* visit that was never filed does not stop mattering because time passed.
*/
#[AsCommand(name: 'app:appointment:backfill-sessions', description: 'Report (and optionally create) missing patient sessions for confirmed appointments')]
class BackfillAppointmentSessionsCommand extends Command
{
private const FILED_STATUSES = [
Appointment::STATUS_CONFIRMED,
Appointment::STATUS_COMPLETED,
];
public function __construct(
private readonly AppointmentRepository $appointmentRepo,
private readonly PatientSessionRepository $sessionRepo,
private readonly AppointmentConfirmationService $confirmation,
private readonly EntityManagerInterface $em,
) {
parent::__construct();
}
protected function configure(): void
{
$this->addOption('fix', null, InputOption::VALUE_NONE, 'Create the missing sessions instead of only reporting them');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$fix = (bool) $input->getOption('fix');
$appointments = $this->appointmentRepo->createQueryBuilder('a')
->where('a.status IN (:statuses)')
->andWhere('a.isReserve = false')
->setParameter('statuses', self::FILED_STATUSES)
->orderBy('a.id', 'ASC')
->getQuery()
->getResult();
$rows = [];
$missing = [];
foreach ($appointments as $appointment) {
$clinic = $appointment->getClinic();
[$entityType, $entityId] = $clinic !== null
? ['clinic', (int) $clinic->getId()]
: ['doctor', (int) $appointment->getDoctor()->getId()];
if ($this->sessionRepo->findByAppointmentAndEntity($appointment, $entityType, $entityId) !== null) {
continue;
}
$missing[] = [$appointment, $entityType, $entityId];
$rows[] = [
$appointment->getUuid(),
$appointment->getStatus(),
date('Y-m-d H:i', $appointment->getSlotStart()),
$appointment->getDoctor()->getName(),
$clinic !== null ? ($clinic->getName() ?? 'clinic') : 'personal',
];
}
if ($rows === []) {
$io->success('Every confirmed appointment already has its patient session.');
return Command::SUCCESS;
}
$io->table(['appointment', 'status', 'slot', 'doctor', 'context'], $rows);
if (!$fix) {
$io->warning(sprintf('%d appointment(s) without a session. Re-run with --fix to create them.', count($rows)));
return Command::SUCCESS;
}
$created = 0;
foreach ($missing as [$appointment, $entityType, $entityId]) {
$this->confirmation->onConfirmed($appointment);
$this->em->flush();
if ($this->sessionRepo->findByAppointmentAndEntity($appointment, $entityType, $entityId) !== null) {
$created++;
}
}
// آن‌هایی که ساخته نشدند عمداً رد شده‌اند (نبودِ ویژگی patient_records برای آن
// tenant)؛ جدا گزارش می‌شوند تا با شکست اشتباه گرفته نشوند.
$skipped = count($missing) - $created;
$io->success(sprintf('Created %d session(s).', $created));
if ($skipped > 0) {
$io->note(sprintf('%d skipped — their tenant has no patient_records feature.', $skipped));
}
return Command::SUCCESS;
}
}