feat: enhance DoctorAddress entity to support clinic addresses and types

- Added `clinic_id` and `type` fields to `DoctorAddress` entity to differentiate between personal and clinic addresses.
- Updated constructor to support creation of addresses for both doctors and clinics.
- Modified repository methods to handle new address types and added methods for counting and finding addresses by clinic.
- Implemented migration to update the database schema accordingly.
- Removed deprecated endpoint for creating addresses from clinics and updated related controller methods.
- Added new endpoints for managing clinic addresses, including CRUD operations.
- Updated frontend components to handle new address types and display accordingly.
This commit is contained in:
hamed
2026-06-12 13:39:37 +03:30
parent 63073c6a42
commit 0333b24071
13 changed files with 1446 additions and 89 deletions
@@ -9,6 +9,10 @@ use App\Appointment\Repository\DateOverrideRepository;
use App\Appointment\Repository\HolidayRepository;
use App\Appointment\Repository\WeeklyScheduleRepository;
use App\Auth\Entity\User;
use App\Clinic\Entity\Clinic;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Entity\DoctorAddress;
use App\Doctor\Repository\DoctorAddressRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
@@ -26,6 +30,8 @@ class AppointmentSettingsController extends BaseController
private readonly DateOverrideRepository $overrideRepo,
private readonly HolidayRepository $holidayRepo,
private readonly DoctorRepository $doctorRepo,
private readonly DoctorAddressRepository $addressRepo,
private readonly ClinicRepository $clinicRepo,
) {}
// ── Weekly Schedule ───────────────────────────────────────────────────────
@@ -313,4 +319,32 @@ class AppointmentSettingsController extends BaseController
return $this->success(['data' => $holiday->toArray()]);
}
// ── Available Locations ───────────────────────────────────────────────────
#[Route('/api/v1/appointment-settings/available-locations/{doctorUuid}', methods: ['GET'])]
public function availableLocations(string $doctorUuid): JsonResponse
{
$doctor = $this->doctorRepo->findByUuid($doctorUuid);
if ($doctor === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دکتر یافت نشد', 404);
}
$clinics = $this->clinicRepo->findByDoctor($doctor);
$clinicIds = array_map(fn(Clinic $c) => $c->getId(), $clinics);
$clinicMap = [];
foreach ($clinics as $clinic) {
$clinicMap[$clinic->getId()] = $clinic->getName();
}
$addresses = $this->addressRepo->findAvailableForDoctor($doctor, $clinicIds);
$result = array_map(function (DoctorAddress $a) use ($clinicMap): array {
$data = $a->toArray();
$data['clinic_name'] = $a->getClinicId() !== null ? ($clinicMap[$a->getClinicId()] ?? null) : null;
return $data;
}, $addresses);
return $this->success(['data' => $result]);
}
}
+117 -9
View File
@@ -7,6 +7,8 @@ use App\Auth\Repository\UserRepository;
use App\Clinic\Entity\Clinic;
use App\Clinic\Repository\ClinicRepository;
use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorAddress;
use App\Doctor\Repository\DoctorAddressRepository;
use App\Doctor\Repository\DoctorRepository;
use App\DoctorService\Repository\DoctorServiceRepository;
use App\Insurance\Repository\InsuranceRepository;
@@ -28,16 +30,17 @@ use Symfony\Component\Uid\Uuid;
class ClinicController extends BaseController
{
public function __construct(
private readonly ClinicRepository $clinicRepo,
private readonly DoctorRepository $doctorRepo,
private readonly SpecialtyRepository $specialtyRepo,
private readonly ClinicRepository $clinicRepo,
private readonly DoctorRepository $doctorRepo,
private readonly DoctorAddressRepository $addressRepo,
private readonly SpecialtyRepository $specialtyRepo,
private readonly DoctorServiceRepository $serviceRepo,
private readonly InsuranceRepository $insuranceRepo,
private readonly ProvinceRepository $provinceRepo,
private readonly CityRepository $cityRepo,
private readonly UserRepository $userRepo,
private readonly FileValidatorService $fileValidator,
private readonly string $projectDir,
private readonly InsuranceRepository $insuranceRepo,
private readonly ProvinceRepository $provinceRepo,
private readonly CityRepository $cityRepo,
private readonly UserRepository $userRepo,
private readonly FileValidatorService $fileValidator,
private readonly string $projectDir,
) {}
#[OA\Post(
@@ -535,4 +538,109 @@ class ClinicController extends BaseController
return $this->error(ErrorCodes::ERR_VALIDATION_001, $e->getMessage(), 422);
}
}
// ── Clinic Addresses ─────────────────────────────────────────────────────
#[Route('/api/v1/clinic/{clinicUuid}/addresses', methods: ['GET'])]
public function listAddresses(string $clinicUuid): JsonResponse
{
$clinic = $this->clinicRepo->findByUuid($clinicUuid);
if ($clinic === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
}
$addresses = $this->addressRepo->findBy(['clinicId' => $clinic->getId()]);
return $this->success(['data' => array_map(fn(DoctorAddress $a) => $a->toArray(), $addresses)]);
}
#[Route('/api/v1/clinic/{clinicUuid}/address', methods: ['POST'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function createAddress(string $clinicUuid, Request $request, #[CurrentUser] User $user): JsonResponse
{
$clinic = $this->clinicRepo->findByUuid($clinicUuid);
if ($clinic === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
}
if ($clinic->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$data = json_decode($request->getContent(), true) ?? [];
$address = DoctorAddress::forClinic($clinic->getId());
$this->hydrateClinicAddress($address, $data);
$this->addressRepo->save($address);
return $this->success(['data' => $address->toArray()], 201);
}
#[Route('/api/v1/clinic/{clinicUuid}/address/{addressUuid}', methods: ['PATCH'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function updateAddress(string $clinicUuid, string $addressUuid, Request $request, #[CurrentUser] User $user): JsonResponse
{
$clinic = $this->clinicRepo->findByUuid($clinicUuid);
if ($clinic === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
}
if ($clinic->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$address = $this->addressRepo->findByUuidAndClinic($addressUuid, $clinic->getId());
if ($address === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'آدرس یافت نشد', 404);
}
$data = json_decode($request->getContent(), true) ?? [];
$this->hydrateClinicAddress($address, $data);
$this->addressRepo->save($address);
return $this->success(['data' => $address->toArray()]);
}
#[Route('/api/v1/clinic/{clinicUuid}/address/{addressUuid}', methods: ['DELETE'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function deleteAddress(string $clinicUuid, string $addressUuid, #[CurrentUser] User $user): JsonResponse
{
$clinic = $this->clinicRepo->findByUuid($clinicUuid);
if ($clinic === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
}
if ($clinic->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$address = $this->addressRepo->findByUuidAndClinic($addressUuid, $clinic->getId());
if ($address === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'آدرس یافت نشد', 404);
}
$remaining = $this->addressRepo->countByClinic($clinic->getId());
if ($remaining <= 1) {
return $this->error(ErrorCodes::ERR_CONFLICT_001, 'کلینیک باید حداقل یک آدرس داشته باشد', 409);
}
$this->addressRepo->remove($address);
return $this->success(['message' => 'آدرس با موفقیت حذف شد']);
}
private function hydrateClinicAddress(DoctorAddress $address, array $data): void
{
if (array_key_exists('name', $data)) $address->setName($data['name']);
if (array_key_exists('address', $data)) $address->setAddress($data['address']);
if (array_key_exists('telephone', $data)) $address->setTelephone($data['telephone']);
if (array_key_exists('latitude', $data)) $address->setLatitude($data['latitude'] !== null ? (float) $data['latitude'] : null);
if (array_key_exists('longitude', $data)) $address->setLongitude($data['longitude'] !== null ? (float) $data['longitude'] : null);
if (array_key_exists('city_id', $data)) {
$address->setCity($data['city_id'] !== null ? $this->cityRepo->find((int) $data['city_id']) : null);
}
if (array_key_exists('province_id', $data)) {
$address->setProvince($data['province_id'] !== null ? $this->provinceRepo->find((int) $data['province_id']) : null);
}
}
}
+11 -51
View File
@@ -469,7 +469,7 @@ class DoctorController extends BaseController
}
}
$address = new DoctorAddress($doctor);
$address = DoctorAddress::forDoctor($doctor);
$this->hydrateAddress($address, $data);
$this->addressRepo->save($address);
@@ -554,7 +554,11 @@ class DoctorController extends BaseController
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'آدرس یافت نشد', 404);
}
if ($address->getDoctor()->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
if ($address->getType() !== DoctorAddress::TYPE_PERSONAL) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'آدرس کلینیک از طریق مدیریت کلینیک ویرایش می‌شود', 403);
}
if ($address->getDoctor()?->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
@@ -599,7 +603,11 @@ class DoctorController extends BaseController
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'آدرس یافت نشد', 404);
}
if ($address->getDoctor()->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
if ($address->getType() !== DoctorAddress::TYPE_PERSONAL) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'آدرس کلینیک از طریق مدیریت کلینیک حذف می‌شود', 403);
}
if ($address->getDoctor()?->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
@@ -724,52 +732,4 @@ class DoctorController extends BaseController
}
}
#[Route('/api/v1/clinic-pro/doctor-address/from-clinic/{clinicUuid}', methods: ['POST'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function createAddressFromClinic(string $clinicUuid, #[CurrentUser] User $user): JsonResponse
{
$doctor = $this->doctorRepo->findByUser($user);
if ($doctor === null) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'فقط دکتر می‌تواند آدرس اضافه کند', 403);
}
$clinic = $this->clinicRepo->findByUuid($clinicUuid);
if ($clinic === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
}
// Verify doctor belongs to this clinic
$clinics = $this->clinicRepo->findByDoctor($doctor);
$belongs = array_filter($clinics, fn(Clinic $c) => $c->getUuid() === $clinicUuid);
if (empty($belongs)) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'این دکتر عضو این کلینیک نیست', 403);
}
// Prevent duplicate: if this doctor already has an address for this clinic (same name), skip
foreach ($doctor->getAddresses() as $existing) {
if ($existing->getName() === $clinic->getName()) {
return $this->success(['data' => $existing->toArray()]);
}
}
$address = new DoctorAddress($doctor);
$address->setName($clinic->getName());
$address->setAddress($clinic->getAddress());
$address->setTelephone($clinic->getTelephone());
$address->setLatitude($clinic->getLatitude());
$address->setLongitude($clinic->getLongitude());
if ($clinic->getCityId() !== null) {
$city = $this->cityRepo->find($clinic->getCityId());
$address->setCity($city);
}
if ($clinic->getProvinceId() !== null) {
$province = $this->provinceRepo->find($clinic->getProvinceId());
$address->setProvince($province);
}
$this->addressRepo->save($address);
return $this->success(['data' => $address->toArray()], 201);
}
}
+49 -20
View File
@@ -10,8 +10,12 @@ use Symfony\Component\Uid\Uuid;
#[ORM\Entity]
#[ORM\Table(name: 'doctor_addresses')]
#[ORM\Index(columns: ['doctor_id'], name: 'idx_doctor_addresses_doctor')]
#[ORM\Index(columns: ['clinic_id'], name: 'idx_doctor_addr_clinic')]
class DoctorAddress
{
public const TYPE_PERSONAL = 'personal';
public const TYPE_CLINIC = 'clinic';
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
@@ -21,8 +25,14 @@ class DoctorAddress
private string $uuid;
#[ORM\ManyToOne(targetEntity: Doctor::class, inversedBy: 'addresses')]
#[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
private Doctor $doctor;
#[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: true, onDelete: 'CASCADE')]
private ?Doctor $doctor = null;
#[ORM\Column(name: 'clinic_id', type: 'integer', nullable: true)]
private ?int $clinicId = null;
#[ORM\Column(type: 'string', length: 10)]
private string $type = self::TYPE_PERSONAL;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private ?string $name = null;
@@ -53,23 +63,40 @@ class DoctorAddress
#[ORM\Column(name: 'updated_at', type: 'integer')]
private int $updatedAt;
public function __construct(Doctor $doctor)
private function __construct()
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->doctor = $doctor;
$this->createdAt = time();
$this->updatedAt = time();
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getDoctor(): Doctor { return $this->doctor; }
public function getName(): ?string { return $this->name; }
public function getAddress(): ?string { return $this->address; }
public static function forDoctor(Doctor $doctor): self
{
$a = new self();
$a->type = self::TYPE_PERSONAL;
$a->doctor = $doctor;
return $a;
}
public static function forClinic(int $clinicId): self
{
$a = new self();
$a->type = self::TYPE_CLINIC;
$a->clinicId = $clinicId;
return $a;
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getDoctor(): ?Doctor { return $this->doctor; }
public function getClinicId(): ?int { return $this->clinicId; }
public function getType(): string { return $this->type; }
public function getName(): ?string { return $this->name; }
public function getAddress(): ?string { return $this->address; }
public function getTelephone(): ?string { return $this->telephone; }
public function getLatitude(): ?float { return $this->latitude; }
public function getLongitude(): ?float { return $this->longitude; }
public function getCity(): ?City { return $this->city; }
public function getLatitude(): ?float { return $this->latitude; }
public function getLongitude(): ?float { return $this->longitude; }
public function getCity(): ?City { return $this->city; }
public function getProvince(): ?Province { return $this->province; }
public function setName(?string $v): self { $this->name = $v; return $this; }
@@ -85,20 +112,22 @@ class DoctorAddress
public function toArray(): array
{
return [
'id' => (string) $this->id,
'uuid' => $this->uuid,
'name' => $this->name,
'map' => [
'id' => (string) $this->id,
'uuid' => $this->uuid,
'type' => $this->type,
'clinic_id' => $this->clinicId,
'name' => $this->name,
'map' => [
'latitude' => $this->latitude !== null ? (string) $this->latitude : null,
'longitude' => $this->longitude !== null ? (string) $this->longitude : null,
],
'address' => $this->address,
'telephone' => $this->telephone,
'city' => $this->city !== null ? [
'address' => $this->address,
'telephone' => $this->telephone,
'city' => $this->city !== null ? [
'id' => (string) $this->city->getId(),
'name' => $this->city->getName(),
] : null,
'province' => $this->province !== null ? [
'province' => $this->province !== null ? [
'id' => (string) $this->province->getId(),
'name' => $this->province->getName(),
] : null,
@@ -2,6 +2,7 @@
namespace App\Doctor\Repository;
use App\Doctor\Entity\Doctor;
use App\Doctor\Entity\DoctorAddress;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
@@ -28,4 +29,48 @@ class DoctorAddressRepository extends ServiceEntityRepository
$this->getEntityManager()->flush();
}
}
public function findByUuidAndClinic(string $uuid, int $clinicId): ?DoctorAddress
{
return $this->createQueryBuilder('a')
->where('a.uuid = :uuid')
->andWhere('a.clinicId = :clinicId')
->setParameter('uuid', $uuid)
->setParameter('clinicId', $clinicId)
->getQuery()
->getOneOrNullResult();
}
public function countByClinic(int $clinicId): int
{
return (int) $this->createQueryBuilder('a')
->select('COUNT(a.id)')
->where('a.clinicId = :clinicId')
->setParameter('clinicId', $clinicId)
->getQuery()
->getSingleScalarResult();
}
public function findAvailableForDoctor(Doctor $doctor, array $clinicIds): array
{
$qb = $this->createQueryBuilder('a');
$qb->where(
$qb->expr()->orX(
$qb->expr()->andX(
$qb->expr()->eq('a.doctor', ':doctor'),
$qb->expr()->eq('a.type', ':personal')
),
$qb->expr()->andX(
$qb->expr()->in('a.clinicId', ':clinicIds'),
$qb->expr()->eq('a.type', ':clinic')
)
)
)
->setParameter('doctor', $doctor)
->setParameter('personal', DoctorAddress::TYPE_PERSONAL)
->setParameter('clinicIds', empty($clinicIds) ? [0] : $clinicIds)
->setParameter('clinic', DoctorAddress::TYPE_CLINIC);
return $qb->getQuery()->getResult();
}
}