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' => 'بیمه پزشک با موفقیت حذف شد']);
}
}