feat(resource): calendar UI, holiday admin, backfill and interval algebra

Completes task 03. The resource calendar page edits weekly shifts, records leave and
maintenance, and previews two weeks of availability with a Persian reason for every
empty day — showing the raw server key ("outside_branch_hours") to a user would have
been a meaningless message. The preview is labelled raw on the page itself, because
booked appointments are not subtracted yet and mistaking it for bookable time leads
to overbooking.

The interval algebra moved to src/Shared/Time/TimeInterval.php with twelve unit
tests: tasks 05 and 06 need the same union/intersect/subtract, and a second
implementation is how two subtly different definitions of "overlap" get born. The
half-open [start, end) contract is what makes a shift ending at 13:00 and one
starting at 13:00 not overlap.

AvailabilityQueryCountTest locks the query count flat: one day and ninety days cost
exactly the same number of queries. Without it the first refactor can put a query
inside the day loop and a 90-day response quietly becomes hundreds of queries —
something only production would reveal.

app:resource:calendar:backfill derives shifts from existing WeeklySchedule sessions,
so the resources created in task 02 are not left with empty calendars. It skips any
resource a user has already configured, which is also what makes it idempotent. The
weekly schedule itself is untouched: this is a copy, not a migration.

Also added --replace to the holiday import. upsert keys on the date, so a row written
with a *wrong* date can never correct itself — re-running just creates the right row
beside the wrong one. That is exactly what happened after fixing the Jalali
conversion bug, and it was caught while capturing real responses for the docs.

Deferred with reasons recorded in the checklist: seasonal shift validity (two
nullable columns can be added later without backfill, so "needed from day one" does
not hold), and a Jalali date picker in the exception form.

1154 tests / 3229 assertions. phpstan at its 14-error baseline, none in touched
files. tsc clean, vitest 622 tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-30 18:28:48 +03:30
co-authored by Claude Opus 5
parent 1fdfdf9e48
commit 4d722830e3
20 changed files with 1640 additions and 63 deletions
@@ -0,0 +1,169 @@
<?php
namespace App\Resource\Command;
use App\Appointment\Entity\WeeklySchedule;
use App\Resource\Entity\ClinicResource;
use App\Resource\Entity\ResourceCalendar;
use App\Resource\Repository\ClinicResourceRepository;
use App\Resource\Repository\ResourceCalendarRepository;
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;
/**
* شیفت منابعِ پزشک را از `WeeklySchedule` موجود می‌سازد.
*
* بدون این، منابعی که تسک ۰۲ ساخته هیچ شیفتی ندارند و ساعت آزادشان همیشه خالی است —
* یعنی لایهٔ منبع تا وقتی کسی دستی شیفت وارد نکند بی‌اثر می‌ماند.
*
* فقط منابعی که **هیچ** شیفتی ندارند پر می‌شوند: منبعی که کاربر خودش تنظیمش کرده
* دست نمی‌خورد. همین idempotent بودن را هم تضمین می‌کند.
*
* برنامهٔ هفتگی دست‌نخورده می‌ماند؛ این کپی است نه مهاجرت.
*/
#[AsCommand(
name: 'app:resource:calendar:backfill',
description: 'Derive resource shifts from existing doctor weekly schedules',
)]
class BackfillResourceCalendarCommand extends Command
{
public function __construct(
private readonly EntityManagerInterface $em,
private readonly ClinicResourceRepository $resources,
private readonly ResourceCalendarRepository $calendars,
) {
parent::__construct();
}
protected function configure(): void
{
$this->addOption('force', null, InputOption::VALUE_NONE, 'Actually write; without it the command only reports');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$force = (bool) $input->getOption('force');
if (!$force) {
$io->note('Dry run — nothing will be written. Re-run with --force to apply.');
}
$rows = [];
$skipped = 0;
foreach ($this->em->getRepository(WeeklySchedule::class)->findAll() as $schedule) {
$doctor = $schedule->getDoctor();
foreach ($this->shiftsByLocation($schedule) as $locationId => $shifts) {
$resource = $this->resourceFor($doctor, $locationId);
if ($resource === null) {
continue; // منبعی برای این آدرس ساخته نشده؛ اول app:resource:backfill
}
if ($this->calendars->findForResource($resource) !== []) {
$skipped++;
continue; // کاربر خودش تنظیم کرده — دست نمی‌زنیم
}
$rows[] = [$resource->getName(), $resource->getAddress()->getName() ?? '—', count($shifts)];
if ($force) {
foreach ($shifts as $shift) {
$this->em->persist(new ResourceCalendar(
$resource,
$shift['day'],
$shift['start'],
$shift['end'],
$shift['sequence'],
));
}
}
}
}
if ($force) {
$this->em->flush();
}
if ($rows !== []) {
$io->table(['منبع', 'شعبه', 'تعداد شیفت'], $rows);
}
$io->success(sprintf(
'%s — %d منبع · %d منبع از قبل شیفت داشت و دست‌نخورده ماند',
$force ? 'ساخته شد' : 'ساخته می‌شود',
count($rows),
$skipped,
));
return Command::SUCCESS;
}
private function resourceFor(\App\Doctor\Entity\Doctor $doctor, int $locationId): ?ClinicResource
{
$address = $this->em->getRepository(\App\Doctor\Entity\DoctorAddress::class)->find($locationId);
return $address === null ? null : $this->resources->findForSubject($doctor, $address);
}
/**
* @return array<int, list<array{day: int, start: int, end: int, sequence: int}>>
* شناسهٔ آدرس => شیفت‌ها
*/
private function shiftsByLocation(WeeklySchedule $schedule): array
{
$byLocation = [];
foreach ($schedule->getSetting() as $rawDay => $day) {
if (!is_numeric($rawDay)) {
continue;
}
$sequences = [];
foreach (($day['sessions'] ?? []) as $session) {
if (!($session['active'] ?? false)) {
continue;
}
$locationId = $session['location_id'] ?? null;
$start = $this->toMinutes($session['start_time'] ?? null);
$end = $this->toMinutes($session['end_time'] ?? null);
if (!is_numeric($locationId) || $start === null || $end === null || $end <= $start) {
continue;
}
$locationId = (int) $locationId;
$sequences[$locationId] ??= 0;
$byLocation[$locationId][] = [
'day' => (int) $rawDay,
'start' => $start,
'end' => $end,
'sequence' => $sequences[$locationId]++,
];
}
}
return $byLocation;
}
private function toMinutes(mixed $time): ?int
{
if (!is_string($time) || preg_match('/^(\d{1,2}):(\d{2})$/', $time, $m) !== 1) {
return null;
}
$minutes = (int) $m[1] * 60 + (int) $m[2];
return $minutes >= 0 && $minutes <= ResourceCalendar::MINUTES_IN_DAY ? $minutes : null;
}
}
@@ -48,6 +48,12 @@ class ImportHolidayCommand extends Command
{
$this->addOption('year', null, InputOption::VALUE_REQUIRED, 'Jalali year, e.g. 1405');
$this->addOption('force', null, InputOption::VALUE_NONE, 'Actually write; without it the command only reports');
$this->addOption(
'replace',
null,
InputOption::VALUE_NONE,
'Delete this year rows first — use when previously imported dates were wrong',
);
$this->addOption(
'extra',
null,
@@ -88,6 +94,14 @@ class ImportHolidayCommand extends Command
$io->note('Dry run — nothing will be written. Re-run with --force to apply.');
}
// upsert روی `date` کلید می‌خورد، پس ردیفی که با تاریخِ **غلط** نوشته شده هرگز
// خودش را تصحیح نمی‌کند: اجرای دوباره ردیف درست را کنارش می‌سازد و غلط سرِ
// جایش می‌ماند. دقیقاً همین بعد از اصلاح باگ تبدیل شمسی پیش آمد.
if ($force && $input->getOption('replace')) {
$removed = $this->holidays->purgeYear($year);
$io->note(sprintf('%d ردیف سال %d پاک شد.', $removed, $year));
}
$rows = [];
foreach ($entries as [$month, $day, $title]) {
+11
View File
@@ -76,6 +76,17 @@ final class HolidayService
return $holiday;
}
/**
* همهٔ تعطیلات یک سال را پاک می‌کند — تنها راه تصحیحِ ردیفی که با تاریخ غلط
* نوشته شده، چون upsert روی `date` کلید می‌خورد و ردیف غلط را نمی‌شناسد.
*/
public function purgeYear(int $jalaliYear): int
{
return (int) $this->em->createQuery(
'DELETE FROM App\Resource\Entity\NationalHoliday h WHERE h.jalaliYear = :year'
)->setParameter('year', $jalaliYear)->execute();
}
/** @return NationalHoliday[] */
public function forYear(int $jalaliYear): array
{
@@ -10,7 +10,7 @@ use App\Resource\Repository\ResourceCalendarRepository;
use App\Resource\Repository\ResourceExceptionRepository;
use App\Resource\Repository\TenantHolidayOverrideRepository;
use App\Resource\ValueObject\DayAvailability;
use App\Resource\ValueObject\TimeInterval;
use App\Shared\Time\TimeInterval;
/**
* «ساعت آزادِ خامِ یک منبع در یک بازه» — لایه‌های ۱ تا ۴ از کسرِ بند ۹ مستند:
@@ -2,6 +2,8 @@
namespace App\Resource\ValueObject;
use App\Shared\Time\TimeInterval;
/**
* ساعت آزادِ خامِ یک منبع در یک روز.
*
-131
View File
@@ -1,131 +0,0 @@
<?php
namespace App\Resource\ValueObject;
/**
* یک بازهٔ نیم‌باز `[start, end)`.
*
* واحدش عمداً تعیین نشده: در تقویم هفتگی «دقیقه از نیمه‌شب» است و بعد از
* `shiftedBy()` می‌شود timestamp مطلق. جبرِ زیر در هر دو حالت یکسان کار می‌کند، و
* همین باعث می‌شود تقاطع ساعت شعبه با شیفت منبع و کسر مرخصی، یک کد باشند نه دو تا.
*/
final readonly class TimeInterval
{
public function __construct(
public int $start,
public int $end,
) {
if ($end <= $start) {
throw new \InvalidArgumentException(sprintf('Interval end (%d) must be after start (%d).', $end, $start));
}
}
/**
* بازه را از «دقیقه از نیمه‌شب» به timestamp مطلق می‌برد.
*
* نامش عمداً `shiftedBy` نیست: جمع ساده، دقیقه را با ثانیه قاطی می‌کرد و بازهٔ
* هشت‌ساعته را هشت **ثانیه** می‌ساخت — دقیقاً همان باگی که
* ResourceAvailabilityTest اولین بار گرفت.
*/
public function minutesToAbsolute(int $midnight): self
{
return new self($midnight + $this->start * 60, $midnight + $this->end * 60);
}
public function toArray(): array
{
return ['start' => $this->start, 'end' => $this->end];
}
/**
* بازه‌های هم‌پوشان یا چسبیده را یکی می‌کند. خروجی مرتب است.
*
* @param list<self> $intervals
* @return list<self>
*/
public static function mergeAll(array $intervals): array
{
if ($intervals === []) {
return [];
}
usort($intervals, static fn (self $a, self $b): int => $a->start <=> $b->start);
$merged = [array_shift($intervals)];
foreach ($intervals as $next) {
$last = $merged[count($merged) - 1];
if ($next->start <= $last->end) {
// چسبیده هم ادغام می‌شود: [9,13) و [13,17) یعنی [9,17)، نه دو بازه.
$merged[count($merged) - 1] = new self($last->start, max($last->end, $next->end));
continue;
}
$merged[] = $next;
}
return $merged;
}
/**
* تقاطع دو مجموعه بازه.
*
* @param list<self> $left
* @param list<self> $right
* @return list<self>
*/
public static function intersectAll(array $left, array $right): array
{
$out = [];
foreach (self::mergeAll($left) as $a) {
foreach (self::mergeAll($right) as $b) {
$start = max($a->start, $b->start);
$end = min($a->end, $b->end);
if ($end > $start) {
$out[] = new self($start, $end);
}
}
}
return self::mergeAll($out);
}
/**
* `$from` منهای `$blocks`. بازهٔ نیم‌روزه فقط همان تکه را می‌بُرد و بقیهٔ روز
* سرِ جایش می‌ماند.
*
* @param list<self> $from
* @param list<self> $blocks
* @return list<self>
*/
public static function subtractAll(array $from, array $blocks): array
{
$result = self::mergeAll($from);
foreach (self::mergeAll($blocks) as $block) {
$next = [];
foreach ($result as $interval) {
if ($block->end <= $interval->start || $block->start >= $interval->end) {
$next[] = $interval; // بی‌تداخل
continue;
}
if ($block->start > $interval->start) {
$next[] = new self($interval->start, $block->start);
}
if ($block->end < $interval->end) {
$next[] = new self($block->end, $interval->end);
}
}
$result = $next;
}
return $result;
}
}