feat: add insurance and location management

- Introduced InsuranceType enum for insurance categorization.
- Created InsuranceRepository for managing insurance entities.
- Developed LocationController for handling provinces and cities, including CRUD operations.
- Implemented City and Province entities with necessary fields and relationships.
- Added CityRepository and ProvinceRepository for database interactions.
- Established Specialty management with SpecialtyController, including CRUD operations.
- Created Specialty and Tag entities with appropriate fields and relationships.
- Implemented TagController for managing tags, including CRUD operations.
- Added TagRepository for database interactions with tags.
This commit is contained in:
hamed
2026-06-10 14:22:26 +03:30
parent 4b8504df91
commit 5066fcbd91
36 changed files with 2937 additions and 1241 deletions
+202 -45
View File
@@ -3,36 +3,196 @@
namespace App\Insurance\Controller;
use App\Auth\Entity\User;
use App\Category\Repository\CategoryRepository;
use App\Doctor\Repository\DoctorRepository;
use App\Insurance\Entity\DoctorInsurance;
use App\Insurance\Entity\Insurance;
use App\Insurance\Enum\InsuranceType;
use App\Insurance\Repository\DoctorInsuranceRepository;
use App\Insurance\Repository\InsuranceRepository;
use App\Shared\Constant\ErrorCodes;
use App\Shared\Controller\BaseController;
use App\Shared\Service\FileValidatorService;
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;
use Symfony\Component\Uid\Uuid;
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class InsuranceController extends BaseController
{
public function __construct(
private readonly DoctorInsuranceRepository $repository,
private readonly InsuranceRepository $insuranceRepo,
private readonly DoctorInsuranceRepository $doctorInsuranceRepo,
private readonly DoctorRepository $doctorRepo,
private readonly CategoryRepository $categoryRepo,
private readonly FileValidatorService $fileValidator,
private readonly string $projectDir,
) {}
#[Route('/api/v1/insurance/', methods: ['POST'])]
public function create(Request $request, #[CurrentUser] User $user): JsonResponse
{
$data = json_decode($request->getContent(), true) ?? [];
$doctorId = $data['doctor_id'] ?? null;
$categoryId = $data['category_id'] ?? null;
// ── Public list ───────────────────────────────────────────────────────────
if (!$doctorId || !$categoryId) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'doctor_id و category_id الزامی است', 422);
#[Route('/api/v1/insurances', methods: ['GET'])]
public function list(Request $request): JsonResponse
{
$typeParam = $request->query->get('type');
$type = null;
if ($typeParam !== null) {
$type = InsuranceType::tryFrom($typeParam);
}
$items = array_map(fn(Insurance $i) => $i->toArray(), $this->insuranceRepo->findActive($type));
return $this->success(['data' => $items]);
}
// ── Admin CRUD — Insurance ────────────────────────────────────────────────
#[Route('/api/v1/admin/insurance', methods: ['POST'])]
#[IsGranted('ROLE_ADMIN')]
public function create(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true) ?? [];
$name = trim($data['name'] ?? '');
$typeVal = $data['type'] ?? null;
if ($name === '') {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'name الزامی است', 422, 'name');
}
$type = InsuranceType::tryFrom((string) $typeVal);
if ($type === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'type باید basic یا supplementary باشد', 422, 'type');
}
$insurance = new Insurance($name, $type);
if (isset($data['logo_url'])) $insurance->setLogoUrl($data['logo_url']);
if (isset($data['status'])) $insurance->setStatus((int) $data['status']);
$this->insuranceRepo->save($insurance);
return $this->success(['data' => $insurance->toArray()], 201);
}
#[Route('/api/v1/admin/insurance/{id}', methods: ['PATCH'])]
#[IsGranted('ROLE_ADMIN')]
public function update(int $id, Request $request): JsonResponse
{
$insurance = $this->insuranceRepo->find($id);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
}
$data = json_decode($request->getContent(), true) ?? [];
if (isset($data['name'])) $insurance->setName($data['name']);
if (isset($data['type'])) {
$type = InsuranceType::tryFrom($data['type']);
if ($type !== null) $insurance->setType($type);
}
if (array_key_exists('logo_url', $data)) $insurance->setLogoUrl($data['logo_url']);
if (isset($data['status'])) $insurance->setStatus((int) $data['status']);
$this->insuranceRepo->save($insurance);
return $this->success(['data' => $insurance->toArray()]);
}
#[Route('/api/v1/admin/insurance/{id}', methods: ['DELETE'])]
#[IsGranted('ROLE_ADMIN')]
public function delete(int $id): JsonResponse
{
$insurance = $this->insuranceRepo->find($id);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
}
$this->insuranceRepo->remove($insurance);
return $this->success(['message' => 'بیمه با موفقیت حذف شد']);
}
#[Route('/api/v1/admin/insurances', methods: ['GET'])]
#[IsGranted('ROLE_ADMIN')]
public function adminList(Request $request): JsonResponse
{
$page = max(1, (int) $request->query->get('page', 1));
$limit = min(100, max(1, (int) $request->query->get('limit', 15)));
$search = trim((string) $request->query->get('search', ''));
$typeParam = $request->query->get('type');
$qb = $this->insuranceRepo->createQueryBuilder('i')->orderBy('i.name', 'ASC');
if ($search !== '') {
$qb->andWhere('i.name LIKE :s')->setParameter('s', '%' . $search . '%');
}
if ($typeParam !== null && $typeParam !== '') {
$qb->andWhere('i.type = :t')->setParameter('t', $typeParam);
}
$total = (clone $qb)->select('COUNT(i.id)')->getQuery()->getSingleScalarResult();
$rows = $qb->setFirstResult(($page - 1) * $limit)->setMaxResults($limit)->getQuery()->getResult();
return $this->paginated(
array_map(fn(Insurance $i) => $i->toArray(), $rows),
(int) $total, $page, $limit
);
}
// ── Upload logo ───────────────────────────────────────────────────────────
#[Route('/api/v1/admin/insurance/{id}/upload-logo', methods: ['POST'])]
#[IsGranted('ROLE_ADMIN')]
public function uploadLogo(int $id, Request $request): JsonResponse
{
$insurance = $this->insuranceRepo->find($id);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
}
$content = $request->getContent();
$disposition = $request->headers->get('Content-Disposition', '');
preg_match('/filename=["\']?([^"\';\s]+)["\']?/i', $disposition, $m);
$filename = $m[1] ?? 'logo.jpg';
$tmpPath = sys_get_temp_dir() . '/' . uniqid('upload_', true);
file_put_contents($tmpPath, $content);
try {
$safeFilename = $this->fileValidator->sanitizeFilename($filename);
$mime = $this->fileValidator->detectMimeType($tmpPath);
$year = date('Y');
$month = date('m');
$dir = $this->projectDir . '/public/uploads/insurances/logo/' . $year . '-' . $month;
if (!is_dir($dir)) mkdir($dir, 0755, true);
$storedName = uniqid('', true) . '_' . $safeFilename;
rename($tmpPath, $dir . '/' . $storedName);
$url = '/uploads/insurances/logo/' . $year . '-' . $month . '/' . $storedName;
$insurance->setLogoUrl($url);
$this->insuranceRepo->save($insurance);
return $this->success([
'url' => $url,
'uuid' => Uuid::v4()->toRfc4122(),
'filename' => $safeFilename,
'filemime' => $mime,
'filesize' => strlen($content),
]);
} catch (\Throwable $e) {
if (file_exists($tmpPath)) unlink($tmpPath);
return $this->error(ErrorCodes::ERR_VALIDATION_001, $e->getMessage(), 422);
}
}
// ── DoctorInsurance CRUD ──────────────────────────────────────────────────
#[Route('/api/v1/insurance/', methods: ['POST'])]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function addDoctorInsurance(Request $request, #[CurrentUser] User $user): JsonResponse
{
$data = json_decode($request->getContent(), true) ?? [];
$doctorId = $data['doctor_id'] ?? null;
$insuranceId = $data['insurance_id'] ?? null;
if (!$doctorId || !$insuranceId) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'doctor_id و insurance_id الزامی است', 422);
}
$doctor = $this->doctorRepo->find((int) $doctorId);
@@ -40,79 +200,76 @@ class InsuranceController extends BaseController
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دکتر یافت نشد', 404);
}
// Only the doctor owner or admin can add insurance
if ($doctor->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$category = $this->categoryRepo->find((int) $categoryId);
if ($category === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'دسته‌بندی بیمه یافت نشد', 404);
$insurance = $this->insuranceRepo->find((int) $insuranceId);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
}
// Check duplicate
$existing = $this->repository->findOneBy(['doctor' => $doctor, 'category' => $category]);
$existing = $this->doctorInsuranceRepo->findOneBy(['doctor' => $doctor, 'insurance' => $insurance]);
if ($existing !== null) {
return $this->error(ErrorCodes::ERR_VALIDATION_001, 'این بیمه قبلاً اضافه شده است', 409);
}
$insurance = new DoctorInsurance($doctor, $category);
$doctorInsurance = new DoctorInsurance($doctor, $insurance);
if (isset($data['price'])) {
$insurance->setPrice((int) $data['price']);
$doctorInsurance->setPrice((int) $data['price']);
}
$this->repository->save($insurance);
return $this->success(['data' => $insurance->toArray()], 201);
$this->doctorInsuranceRepo->save($doctorInsurance);
return $this->success(['data' => $doctorInsurance->toArray()], 201);
}
#[Route('/api/v1/insurance/{id}', methods: ['GET'])]
public function show(int $id): JsonResponse
public function showDoctorInsurance(int $id): JsonResponse
{
$insurance = $this->repository->find($id);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
$doctorInsurance = $this->doctorInsuranceRepo->find($id);
if ($doctorInsurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه پزشک یافت نشد', 404);
}
return $this->success(['data' => $insurance->toArray()]);
return $this->success(['data' => $doctorInsurance->toArray()]);
}
#[Route('/api/v1/insurance/{id}', methods: ['PATCH'])]
public function update(int $id, Request $request, #[CurrentUser] User $user): JsonResponse
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function updateDoctorInsurance(int $id, Request $request, #[CurrentUser] User $user): JsonResponse
{
$insurance = $this->repository->find($id);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
$doctorInsurance = $this->doctorInsuranceRepo->find($id);
if ($doctorInsurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه پزشک یافت نشد', 404);
}
if ($insurance->getDoctor()->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
if ($doctorInsurance->getDoctor()->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$data = json_decode($request->getContent(), true) ?? [];
if (array_key_exists('price', $data)) {
$insurance->setPrice($data['price'] !== null ? (int) $data['price'] : null);
$doctorInsurance->setPrice($data['price'] !== null ? (int) $data['price'] : null);
}
$this->repository->save($insurance);
return $this->success(['data' => $insurance->toArray()]);
$this->doctorInsuranceRepo->save($doctorInsurance);
return $this->success(['data' => $doctorInsurance->toArray()]);
}
#[Route('/api/v1/insurance/{id}', methods: ['DELETE'])]
public function delete(int $id, #[CurrentUser] User $user): JsonResponse
#[IsGranted('IS_AUTHENTICATED_FULLY')]
public function deleteDoctorInsurance(int $id, #[CurrentUser] User $user): JsonResponse
{
$insurance = $this->repository->find($id);
if ($insurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه یافت نشد', 404);
$doctorInsurance = $this->doctorInsuranceRepo->find($id);
if ($doctorInsurance === null) {
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'بیمه پزشک یافت نشد', 404);
}
if ($insurance->getDoctor()->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
if ($doctorInsurance->getDoctor()->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
}
$this->repository->remove($insurance);
return $this->success(['message' => 'بیمه با موفقیت حذف شد']);
$this->doctorInsuranceRepo->remove($doctorInsurance);
return $this->success(['message' => 'بیمه پزشک با موفقیت حذف شد']);
}
}
+20 -20
View File
@@ -2,14 +2,14 @@
namespace App\Insurance\Entity;
use App\Category\Entity\Category;
use App\Doctor\Entity\Doctor;
use App\Insurance\Repository\DoctorInsuranceRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Entity(repositoryClass: DoctorInsuranceRepository::class)]
#[ORM\Table(name: 'doctor_insurances')]
#[ORM\UniqueConstraint(name: 'idx_doctor_insurance', columns: ['doctor_id', 'category_id'])]
#[ORM\Index(columns: ['category_id'], name: 'idx_doctor_insurance_cat')]
#[ORM\UniqueConstraint(name: 'idx_doctor_insurance', columns: ['doctor_id', 'insurance_id'])]
#[ORM\Index(columns: ['insurance_id'], name: 'idx_doctor_insurance_ins')]
class DoctorInsurance
{
#[ORM\Id]
@@ -21,35 +21,35 @@ class DoctorInsurance
#[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
private Doctor $doctor;
#[ORM\ManyToOne(targetEntity: Category::class)]
#[ORM\JoinColumn(name: 'category_id', referencedColumnName: 'id', nullable: false)]
private Category $category;
#[ORM\ManyToOne(targetEntity: Insurance::class)]
#[ORM\JoinColumn(name: 'insurance_id', referencedColumnName: 'id', nullable: false)]
private Insurance $insurance;
#[ORM\Column(type: 'integer', nullable: true)]
private ?int $price = null;
public function __construct(Doctor $doctor, Category $category)
public function __construct(Doctor $doctor, Insurance $insurance)
{
$this->doctor = $doctor;
$this->category = $category;
$this->doctor = $doctor;
$this->insurance = $insurance;
}
public function getId(): ?int { return $this->id; }
public function getDoctor(): Doctor { return $this->doctor; }
public function getCategory(): Category { return $this->category; }
public function getPrice(): ?int { return $this->price; }
public function getId(): ?int { return $this->id; }
public function getDoctor(): Doctor { return $this->doctor; }
public function getInsurance(): Insurance { return $this->insurance; }
public function getPrice(): ?int { return $this->price; }
public function setPrice(?int $v): self { $this->price = $v; return $this; }
public function toArray(): array
{
return [
'id' => $this->id,
'doctor_id' => $this->doctor->getId(),
'category_id' => $this->category->getId(),
'category_name' => $this->category->getLabel(),
'bundle' => $this->category->getBundle(),
'price' => $this->price,
'id' => $this->id,
'doctor_id' => $this->doctor->getId(),
'insurance_id' => $this->insurance->getId(),
'insurance_name' => $this->insurance->getName(),
'type' => $this->insurance->getType()->value,
'price' => $this->price,
];
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Insurance\Entity;
use App\Insurance\Enum\InsuranceType;
use App\Insurance\Repository\InsuranceRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;
#[ORM\Entity(repositoryClass: InsuranceRepository::class)]
#[ORM\Table(name: 'insurances')]
#[ORM\Index(columns: ['type'], name: 'idx_insurances_type')]
#[ORM\Index(columns: ['status'], name: 'idx_insurances_status')]
class Insurance
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 36, unique: true)]
private string $uuid;
#[ORM\Column(type: 'string', length: 255)]
private string $name;
#[ORM\Column(type: 'string', length: 20, enumType: InsuranceType::class)]
private InsuranceType $type;
#[ORM\Column(name: 'logo_url', type: 'string', length: 500, nullable: true)]
private ?string $logoUrl = null;
#[ORM\Column(type: 'smallint')]
private int $status = 1;
public function __construct(string $name, InsuranceType $type)
{
$this->uuid = Uuid::v4()->toRfc4122();
$this->name = $name;
$this->type = $type;
}
public function getId(): ?int { return $this->id; }
public function getUuid(): string { return $this->uuid; }
public function getName(): string { return $this->name; }
public function getType(): InsuranceType { return $this->type; }
public function getLogoUrl(): ?string { return $this->logoUrl; }
public function getStatus(): int { return $this->status; }
public function setName(string $v): self { $this->name = $v; return $this; }
public function setType(InsuranceType $v): self { $this->type = $v; return $this; }
public function setLogoUrl(?string $v): self { $this->logoUrl = $v; return $this; }
public function setStatus(int $v): self { $this->status = $v; return $this; }
public function toArray(): array
{
return [
'id' => $this->id,
'uuid' => $this->uuid,
'name' => $this->name,
'type' => $this->type->value,
'logo_url' => $this->logoUrl,
'status' => $this->status,
];
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Insurance\Enum;
enum InsuranceType: string
{
case Basic = 'basic';
case Supplementary = 'supplementary';
public function label(): string
{
return match($this) {
self::Basic => 'بیمه پایه',
self::Supplementary => 'بیمه تکمیلی',
};
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Insurance\Repository;
use App\Insurance\Entity\Insurance;
use App\Insurance\Enum\InsuranceType;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
class InsuranceRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Insurance::class);
}
/** @return Insurance[] */
public function findActive(?InsuranceType $type = null): array
{
$qb = $this->createQueryBuilder('i')
->where('i.status = 1')
->orderBy('i.name', 'ASC');
if ($type !== null) {
$qb->andWhere('i.type = :type')->setParameter('type', $type->value);
}
return $qb->getQuery()->getResult();
}
public function save(Insurance $insurance, bool $flush = true): void
{
$this->getEntityManager()->persist($insurance);
if ($flush) $this->getEntityManager()->flush();
}
public function remove(Insurance $insurance, bool $flush = true): void
{
$this->getEntityManager()->remove($insurance);
if ($flush) $this->getEntityManager()->flush();
}
}