src/Controller/ApiV2/Residents/ProblemController.php line 92

Open in your IDE?
  1. <?php
  2. namespace App\Controller\ApiV2\Residents;
  3. use App\Controller\ApiV2\AbstractController;
  4. use App\Entity\Task;
  5. use App\Enums\AttachmentTypeEnum;
  6. use App\Exception\FormException;
  7. use App\Form\ApiV2\BuildingProblemType;
  8. use App\Repository\BuildingRepository;
  9. use App\Repository\FlatRepository;
  10. use App\Repository\TaskFileRepository;
  11. use App\Repository\TaskRepository;
  12. use App\Repository\TaskTypeRepository;
  13. use App\Repository\UserRepository;
  14. use App\Security\Voter\FlatVoter;
  15. use App\Services\MailService;
  16. use App\Services\NotificationTokenService;
  17. use App\Services\TaskFileService;
  18. use App\Services\TaskService;
  19. use Doctrine\ORM\NonUniqueResultException;
  20. use Doctrine\ORM\NoResultException;
  21. use Exception;
  22. use FOS\RestBundle\Controller\Annotations as Rest;
  23. use GuzzleHttp\Exception\GuzzleException;
  24. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  25. use Symfony\Component\HttpFoundation\File\UploadedFile;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpKernel\Exception\HttpException;
  28. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  29. class ProblemController extends AbstractController
  30. {
  31.     private FlatRepository $flatRepository;
  32.     private TaskRepository $taskRepository;
  33.     private TaskTypeRepository $taskTypeRepository;
  34.     private TaskFileService $taskFileService;
  35.     private TaskFileRepository $taskFileRepository;
  36.     private TaskService $taskService;
  37.     private NotificationTokenService $notificationTokenService;
  38.     private UserRepository $userRepository;
  39.     private MailService $mailService;
  40.     private string $projectDir;
  41.     /**
  42.      * @param BuildingRepository $buildingRepository
  43.      * @param UserRepository $userRepository
  44.      * @param FlatRepository $flatRepository
  45.      * @param TaskRepository $taskRepository
  46.      * @param TaskTypeRepository $taskTypeRepository
  47.      * @param TaskFileRepository $taskFileRepository
  48.      * @param TaskFileService $taskFileService
  49.      * @param TaskService $taskService
  50.      * @param NotificationTokenService $notificationTokenService
  51.      * @param MailService $mailService
  52.      * @param string $projectDir
  53.      */
  54.     public function __construct(
  55.         BuildingRepository $buildingRepository,
  56.         UserRepository $userRepository,
  57.         FlatRepository $flatRepository,
  58.         TaskRepository $taskRepository,
  59.         TaskTypeRepository $taskTypeRepository,
  60.         TaskFileRepository $taskFileRepository,
  61.         TaskFileService $taskFileService,
  62.         TaskService $taskService,
  63.         NotificationTokenService $notificationTokenService,
  64.         MailService $mailService,
  65.         string $projectDir
  66.     ) {
  67.         parent::__construct($buildingRepository);
  68.         $this->flatRepository $flatRepository;
  69.         $this->taskRepository $taskRepository;
  70.         $this->taskTypeRepository $taskTypeRepository;
  71.         $this->taskFileService $taskFileService;
  72.         $this->taskFileRepository $taskFileRepository;
  73.         $this->taskService $taskService;
  74.         $this->notificationTokenService $notificationTokenService;
  75.         $this->userRepository $userRepository;
  76.         $this->mailService $mailService;
  77.         $this->projectDir $projectDir;
  78.     }
  79.     /**
  80.      * @Rest\Get("/", name="residents_flats_problems_index")
  81.      * @param Request $request
  82.      * @param int $id
  83.      * @return array<string, mixed>
  84.      * @throws NoResultException
  85.      * @throws NonUniqueResultException
  86.      */
  87.     public function index(Request $requestint $id): array
  88.     {
  89.         $flat $this->flatRepository->find($id);
  90.         if (!$flat) {
  91.             $this->createNotFoundException();
  92.         }
  93.         $this->denyAccessUnlessGranted(FlatVoter::FLAT_BELONGS_TO_RESIDENT$flat);
  94.         $options $this->getListOptions($request);
  95.         $status $request->get('status');
  96.         $tasks $this->taskRepository->findTasksByBuildingPaginated2(
  97.             $flat->getBuilding(),
  98.             $options,
  99.             $status
  100.         );
  101.         $countTask $this->taskRepository->countTasksByBuildingPaginated2(
  102.             $flat->getBuilding(),
  103.             $options,
  104.             $status
  105.         );
  106.         return [
  107.             'data' => $tasks,
  108.             'count' => $countTask
  109.         ];
  110.     }
  111.     /**
  112.      * @Rest\Post("/", name="residents_flats_problems_store")
  113.      * @param Request $request
  114.      * @param int $id
  115.      * @return array<mixed>
  116.      * @throws Exception
  117.      * @throws GuzzleException
  118.      */
  119.     public function store(Request $requestint $id): array
  120.     {
  121.         $flat $this->flatRepository->find($id);
  122.         if (!$flat) {
  123.             throw $this->createNotFoundException('Ovaj stan ne postoji.');
  124.         }
  125.         $this->denyAccessUnlessGranted(FlatVoter::FLAT_BELONGS_TO_RESIDENT$flat);
  126.         $building $flat->getBuilding();
  127.         $problemTypes $this->taskTypeRepository->findAllTaskTypeIds();
  128.         try {
  129.             $problemData $this->validateForm($requestBuildingProblemType::class, null, [
  130.                 'types' => $problemTypes
  131.             ]);
  132.             $problemData['flatNumber'] = $flat->getDisplayFlatId();
  133.             $problemData['email'] = $flat->getOwnerEmail();
  134.             $problemData['phoneNumber'] = $flat->getOwnerContact();
  135.             $problemData['resident'] = $this->getUser();
  136.             $result $this->taskService->saveTask(null$building$problemData);
  137.             if (!($result instanceof Task)) {
  138.                 throw new HttpException($result['code'], $result['message']);
  139.             }
  140.             $this->notificationTokenService->sendPushNotificationAction($building$problemData);
  141.             $task $result;
  142.             /** @var array<UploadedFile> $uploadedTaskFiles */
  143.             $uploadedTaskFiles $request->files->get('file') ?? [];
  144.             foreach ($uploadedTaskFiles as $uploadedTaskFile) {
  145.                 $originalFilename pathinfo($uploadedTaskFile->getClientOriginalName(), PATHINFO_FILENAME);
  146.                 $safeFilename transliterator_transliterate(
  147.                     'Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()',
  148.                     $originalFilename
  149.                 );
  150.                 $newFilename sprintf("%s-%s.%s"$safeFilenameuniqid(), $uploadedTaskFile->guessClientExtension());
  151.                 try {
  152.                     $uploadedTaskFile->move(
  153.                         $this->getParameter('tasks_files_directory'),
  154.                         $newFilename
  155.                     );
  156.                 } catch (FileException $fileException) {
  157.                 }
  158.                 $taskFile $this->taskFileService->createTaskFile($newFilename$task);
  159.                 $task->addFile($taskFile);
  160.                 $this->taskFileRepository->save($taskFile);
  161.             }
  162.             return [
  163.                 'data' => $task
  164.             ];
  165.         } catch (FormException $exception) {
  166.             return $exception->getFormError();
  167.         }
  168.     }
  169.     /**
  170.      * @Rest\Post("/v3", name="residents_flats_problems_store_new")
  171.      * @param Request $request
  172.      * @param int $id
  173.      * @return array<mixed>
  174.      * @throws Exception
  175.      * @throws GuzzleException|TransportExceptionInterface
  176.      */
  177.     public function storeNew(Request $requestint $id): array
  178.     {
  179.         $flat $this->flatRepository->find($id);
  180.         if (!$flat) {
  181.             throw $this->createNotFoundException('Ovaj stan ne postoji.');
  182.         }
  183.         $this->denyAccessUnlessGranted(FlatVoter::FLAT_BELONGS_TO_RESIDENT$flat);
  184.         $building $flat->getBuilding();
  185.         $problemTypes $this->taskTypeRepository->findAllTaskTypeIds();
  186.         try {
  187.             $problemData $this->validateForm($requestBuildingProblemType::class, null, [
  188.                 'types' => $problemTypes
  189.             ]);
  190.             $problemData['flatNumber'] = $flat->getDisplayFlatId();
  191.             $problemData['email'] = $flat->getOwnerEmail();
  192.             $problemData['resident'] = $this->getUser();
  193.             $result $this->taskService->saveTask(null$building$problemData);
  194.             if (!($result instanceof Task)) {
  195.                 throw new HttpException($result['code'], $result['message']);
  196.             }
  197.             $this->notificationTokenService->sendPushNotificationAction($building$problemData);
  198.             $task $result;
  199.             $user $this->userRepository->findOneBy(['id' => $flat->getUser()->getId()]);
  200.             /** @var UploadedFile|null $uploadedTaskFile */
  201.             $uploadedTaskFile $request->files->get('file') ?? [];
  202.             $newFilename null;
  203.             $route null;
  204.             if (!empty($uploadedTaskFile)) {
  205.                 try {
  206.                     $originalFilename pathinfo($uploadedTaskFile->getClientOriginalName(), PATHINFO_FILENAME);
  207.                     $safeFilename transliterator_transliterate(
  208.                         'Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()',
  209.                         $originalFilename
  210.                     );
  211.                     $newFilename sprintf(
  212.                         "%s-%s.%s",
  213.                         $safeFilename,
  214.                         uniqid(),
  215.                         $uploadedTaskFile->guessClientExtension()
  216.                     );
  217.                     list($w$h) = getimagesize($uploadedTaskFile);
  218.                     $new_width 735;
  219.                     $new_height 1000;
  220.                     $dst imagecreatetruecolor($new_width$new_height);
  221.                     $src imagecreatefromjpeg($uploadedTaskFile);
  222.                     imagecopyresampled($dst$src0000$new_width$new_height$w$h);
  223.                     $path sprintf("%s/src/uploads/residentProblems/%s"$this->projectDir$building->getId());
  224.                     if (!is_dir($path)) {
  225.                         mkdir($path0777true);
  226.                     }
  227.                     $path sprintf("%s/%s"$path$newFilename);
  228.                     imagejpeg($dst$path);
  229.                     $route sprintf(
  230.                         "%s%s/%s",
  231.                         $this->getParameter('tasks_files_directory'),
  232.                         $building->getId(),
  233.                         $newFilename
  234.                     );
  235.                     $taskFile $this->taskFileService->createTaskFile($newFilename$task);
  236.                     $task->addFile($taskFile);
  237.                     $this->taskFileRepository->save($taskFile);
  238.                 } catch (Exception $fileException) {
  239.                     throw new Exception($fileException->getMessage());
  240.                 }
  241.             }
  242.             $subject 'Prijava problema';
  243.             $recipient $user->getTaskNotificationEmail() ? $user->getTaskNotificationEmail() : $user->getEmail();
  244.             $subtype ' ';
  245.             if (($st $result->getTaskSubtype()) != null) {
  246.                 $subtype sprintf(', podtip %s, '$st->getName());
  247.             }
  248.             $text sprintf(
  249.                 "Poštovani,<br/><br/>Prijavljen problem za zgradu %s<br/>Tip problema: %s%s<br/>Opis problema: %s<br/>
  250.             Broj stana koji je prijavio problem: %s<br/>Broj telefona stanara: %s<br/><br/>Srdačan pozdrav.",
  251.                 $building->getAddress(),
  252.                 $result->getTaskType()->getName(),
  253.                 $subtype,
  254.                 $result->getDescription(),
  255.                 $result->getDisplayFlatId(),
  256.                 $result->getPhoneNumber()
  257.             );
  258.             $this->mailService->sendEmail(
  259.                 $subject,
  260.                 $recipient,
  261.                 $text,
  262.                 [],
  263.                 $newFilename == null null AttachmentTypeEnum::FROM_PATH->value,
  264.                 $route,
  265.                 $newFilename,
  266.                 null,
  267.                 true
  268.             );
  269.             return [
  270.                 'data' => $task
  271.             ];
  272.         } catch (FormException $exception) {
  273.             return $exception->getFormError();
  274.         }
  275.     }
  276. }