feat(resource): resource types, resources, skills and pools

The document's first golden rule is "the calendar belongs to the resource, not to
the doctor". Today the only thing that can be occupied is a doctor, and ClinicStaff
is a label on services and appointments with no calendar, capacity or skills. This
adds the layer underneath: anything that can be busy — doctor, operator, assistant,
device, room, bed, chair.

Two corrections to the planned schema:

- `address_id` → doctor_addresses, not `branch_id` → a new branches table. The
  branch already exists and is the address (task 01).
- UNIQUE is (doctor_id, address_id), not (doctor_id). A WeeklySchedule is per
  (doctor, clinic) but every session inside it carries its own location_id, so one
  doctor already works at several addresses within one environment. Keying on the
  doctor alone would have made that unrepresentable — and task 03 gives each
  resource its own calendar, which is exactly per-location.

Design points worth keeping:

- Resources bridge to Doctor/ClinicStaff/Room rather than absorbing them; those
  three have live consumers (appointments.doctor_id, service_item_staff, the public
  site) and subclassing would mean migrating all of them at once. At most one bridge
  column is non-null, enforced in the entity because MariaDB will not reliably
  enforce a multi-column CHECK.
- Capacity is concurrency: a three-bed injection room is one resource with capacity
  3, not three resources, so occupancy in task 06 stays a COUNT against a limit
  instead of a merge of three calendars. A person resource is refused capacity > 1.
- Skills are a table, not rules. With 50 operators and 200 services, expressing
  "who may operate what" as policy would mean 10,000 rules.
- findEligible() uses HAVING COUNT(DISTINCT …) because "skills A and B" means both;
  a plain IN would have matched a resource holding only one.
- setup/cleanup minutes occupy the resource without being part of the patient's
  appointment, and are per-resource — distinct from the existing per-doctor
  WeeklySchedule.meta.buffer_minutes, which stays untouched.

Two real bugs found by running the backfill against real data rather than fixtures:

ResourceLinker::systemType() persisted a type without flushing, so the next lookup
missed it and created a second — the run died on "Duplicate entry 'doctor-1-staff'
for key uniq_rt_tenant_code". It now keeps an identity map for the unit of work.

The command looped over every WeeklySchedule once per environment, which is
quadratic and never finished on real data. Doctors are now a single pass keyed by
the schedule's own environment. It also flushes per environment and accepts
--pair=clinic:12, so one bad row cannot close the EntityManager and abort a
fleet-wide run, and operators can re-run for a single clinic.

Staff are the one case that cannot be derived: nothing records which branch they
work at. Rather than guessing the first one and seating them in the wrong building,
multi-branch environments are skipped and reported.

88 tests, 230 assertions across tests/Resource and tests/Branch. phpstan clean on
src/Resource.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hamed
2026-07-30 17:34:36 +03:30
co-authored by Claude Opus 5
parent 92181bacff
commit 964c09cc00
33 changed files with 3824 additions and 0 deletions
@@ -0,0 +1,172 @@
<?php
namespace App\Resource\Repository;
use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorAddress;
use App\Branch\Entity\Room;
use App\Resource\Entity\ClinicResource;
use App\Resource\Entity\ResourceType;
use App\Staff\Entity\ClinicStaff;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ClinicResource>
*/
class ClinicResourceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ClinicResource::class);
}
public function findByUuid(string $uuid): ?ClinicResource
{
return $this->findOneBy(['uuid' => $uuid]);
}
/**
* فهرست منابع یک محیط با فیلترهای اختیاری.
*
* @param array{address?: ?DoctorAddress, type?: ?ResourceType, active?: ?bool, skillUuid?: ?string} $filters
* @return ClinicResource[]
*/
public function findForPair(string $entityType, int $entityId, array $filters = []): array
{
$qb = $this->createQueryBuilder('r')
->where('r.entityType = :tenantType')
->andWhere('r.entityId = :tenantId')
->setParameter('tenantType', $entityType)
->setParameter('tenantId', $entityId);
if (($filters['address'] ?? null) !== null) {
$qb->andWhere('r.address = :address')->setParameter('address', $filters['address']);
}
if (($filters['type'] ?? null) !== null) {
$qb->andWhere('r.type = :type')->setParameter('type', $filters['type']);
}
if (($filters['active'] ?? null) !== null) {
$qb->andWhere('r.active = :active')->setParameter('active', $filters['active']);
}
if (($filters['skillUuid'] ?? null) !== null) {
$qb->join('r.skills', 'flt_rs')
->join('flt_rs.skill', 'flt_s')
->andWhere('flt_s.uuid = :skillUuid')
->setParameter('skillUuid', $filters['skillUuid']);
}
return $qb->orderBy('r.name', 'ASC')->getQuery()->getResult();
}
/**
* پرس‌وجوی داغِ تسک ۰۶: «منابع فعالِ این شعبه از این نوع که **همهٔ** این مهارت‌ها
* را دارند».
*
* `HAVING COUNT(DISTINCT …)` عمدی است: نیازمندی «مهارت الف و ب» یعنی هر دو، نه
* یکی — که با یک `IN` ساده اشتباه پاسخ می‌گرفت.
*
* @param int[] $skillIds خالی یعنی بدون شرط مهارت
* @return ClinicResource[]
*/
public function findEligible(DoctorAddress $address, ResourceType $type, array $skillIds = []): array
{
$qb = $this->createQueryBuilder('r')
->where('r.address = :address')
->andWhere('r.type = :type')
->andWhere('r.active = true')
->setParameter('address', $address)
->setParameter('type', $type);
if ($skillIds !== []) {
$qb->join('r.skills', 'rs')
->andWhere('rs.skill IN (:skills)')
->setParameter('skills', $skillIds)
->groupBy('r.id')
->having('COUNT(DISTINCT rs.skill) = :skillCount')
->setParameter('skillCount', count(array_unique($skillIds)));
}
return $qb->orderBy('r.name', 'ASC')->getQuery()->getResult();
}
public function findForSubject(Doctor|ClinicStaff|Room $subject, ?DoctorAddress $address = null): ?ClinicResource
{
$field = match (true) {
$subject instanceof Doctor => 'doctor',
$subject instanceof ClinicStaff => 'staff',
$subject instanceof Room => 'room',
};
$qb = $this->createQueryBuilder('r')
->where("r.$field = :subject")
->setParameter('subject', $subject);
// اتاق فقط در یک آدرس است، پس آدرس برایش شرط اضافه نیست.
if ($address !== null && !$subject instanceof Room) {
$qb->andWhere('r.address = :address')->setParameter('address', $address);
}
return $qb->setMaxResults(1)->getQuery()->getOneOrNullResult();
}
/**
* همهٔ منابعِ یک موجودیت در همهٔ شعبه‌ها — پزشکی که در دو شعبه کار می‌کند دو منبع
* دارد و غیرفعال شدنش باید هر دو را ببندد.
*
* @return ClinicResource[]
*/
public function findAllForSubject(Doctor|ClinicStaff|Room $subject): array
{
$field = match (true) {
$subject instanceof Doctor => 'doctor',
$subject instanceof ClinicStaff => 'staff',
$subject instanceof Room => 'room',
};
return $this->createQueryBuilder('r')
->where("r.$field = :subject")
->setParameter('subject', $subject)
->getQuery()
->getResult();
}
public function countForType(ResourceType $type): int
{
return (int) $this->createQueryBuilder('r')
->select('COUNT(r.id)')
->where('r.type = :type')
->setParameter('type', $type)
->getQuery()
->getSingleScalarResult();
}
/**
* @param int[] $typeIds
* @return array<int, int> شناسهٔ نوع => تعداد منبع
*/
public function countByTypeIds(array $typeIds): array
{
if ($typeIds === []) {
return [];
}
$rows = $this->createQueryBuilder('r')
->select('IDENTITY(r.type) AS type_id, COUNT(r.id) AS total')
->where('r.type IN (:ids)')
->setParameter('ids', $typeIds)
->groupBy('r.type')
->getQuery()
->getArrayResult();
$counts = [];
foreach ($rows as $row) {
$counts[(int) $row['type_id']] = (int) $row['total'];
}
return $counts;
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Resource\Repository;
use App\Resource\Entity\ResourcePool;
use App\Resource\Entity\ResourcePoolMember;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ResourcePoolMember>
*/
class ResourcePoolMemberRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ResourcePoolMember::class);
}
public function deleteForPool(ResourcePool $pool): int
{
return (int) $this->createQueryBuilder('m')
->delete()
->where('m.pool = :pool')
->setParameter('pool', $pool)
->getQuery()
->execute();
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Resource\Repository;
use App\Resource\Entity\ResourcePool;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ResourcePool>
*/
class ResourcePoolRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ResourcePool::class);
}
public function findByUuid(string $uuid): ?ResourcePool
{
return $this->findOneBy(['uuid' => $uuid]);
}
/** @return ResourcePool[] */
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.name', 'ASC')
->getQuery()
->getResult();
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Resource\Repository;
use App\Resource\Entity\ClinicResource;
use App\Resource\Entity\ResourceSkill;
use App\Resource\Entity\Skill;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ResourceSkill>
*/
class ResourceSkillRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ResourceSkill::class);
}
public function countForSkill(Skill $skill): int
{
return (int) $this->createQueryBuilder('rs')
->select('COUNT(rs.id)')
->where('rs.skill = :skill')
->setParameter('skill', $skill)
->getQuery()
->getSingleScalarResult();
}
/**
* @param int[] $skillIds
* @return array<int, int> شناسهٔ مهارت => تعداد منبعی که دارد
*/
public function countBySkillIds(array $skillIds): array
{
if ($skillIds === []) {
return [];
}
$rows = $this->createQueryBuilder('rs')
->select('IDENTITY(rs.skill) AS skill_id, COUNT(rs.id) AS total')
->where('rs.skill IN (:ids)')
->setParameter('ids', $skillIds)
->groupBy('rs.skill')
->getQuery()
->getArrayResult();
$counts = [];
foreach ($rows as $row) {
$counts[(int) $row['skill_id']] = (int) $row['total'];
}
return $counts;
}
public function deleteForResource(ClinicResource $resource): int
{
return (int) $this->createQueryBuilder('rs')
->delete()
->where('rs.resource = :resource')
->setParameter('resource', $resource)
->getQuery()
->execute();
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Resource\Repository;
use App\Resource\Entity\ResourceType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<ResourceType>
*/
class ResourceTypeRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ResourceType::class);
}
public function findByUuid(string $uuid): ?ResourceType
{
return $this->findOneBy(['uuid' => $uuid]);
}
/** @return ResourceType[] */
public function findForPair(string $entityType, int $entityId): array
{
return $this->createQueryBuilder('t')
->where('t.entityType = :type')
->andWhere('t.entityId = :id')
->setParameter('type', $entityType)
->setParameter('id', $entityId)
->orderBy('t.isSystem', 'DESC')
->addOrderBy('t.name', 'ASC')
->getQuery()
->getResult();
}
public function findByCode(string $entityType, int $entityId, string $code): ?ResourceType
{
return $this->findOneBy(['entityType' => $entityType, 'entityId' => $entityId, 'code' => $code]);
}
}
@@ -0,0 +1,53 @@
<?php
namespace App\Resource\Repository;
use App\Resource\Entity\Skill;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Skill>
*/
class SkillRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Skill::class);
}
public function findByUuid(string $uuid): ?Skill
{
return $this->findOneBy(['uuid' => $uuid]);
}
/** @return Skill[] */
public function findForPair(string $entityType, int $entityId): array
{
return $this->createQueryBuilder('s')
->where('s.entityType = :type')
->andWhere('s.entityId = :id')
->setParameter('type', $entityType)
->setParameter('id', $entityId)
->orderBy('s.name', 'ASC')
->getQuery()
->getResult();
}
/**
* @param string[] $uuids
* @return Skill[]
*/
public function findByUuids(array $uuids): array
{
if ($uuids === []) {
return [];
}
return $this->createQueryBuilder('s')
->where('s.uuid IN (:uuids)')
->setParameter('uuids', $uuids)
->getQuery()
->getResult();
}
}