src/Controller/Api/LetterController.php line 158

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Api;
  3. use App\Enum\LetterStatusEnum;
  4. use App\Enum\LetterTypeEnum;
  5. use App\Enum\OrganizationForwardingFrequencyEnum;
  6. use App\Message\ResendLetterMessage;
  7. use App\Repository\LetterRepository;
  8. use App\Repository\OrganizationRepository;
  9. use App\Service\EncryptorDataUtils;
  10. use App\Service\LetterFilesService;
  11. use App\Service\OrganizationUtils;
  12. use App\Service\UserChecker;
  13. use App\Traits\SentryNotifyTrait;
  14. use App\Utils\UserUtils;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Doctrine\ORM\Query\QueryException;
  17. use Evo\Infrastructure\MappingORM\Letter;
  18. use Evo\Infrastructure\MappingORM\LetterForward;
  19. use Evo\Infrastructure\MappingORM\Organization;
  20. use Evo\Infrastructure\MappingORM\User;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Messenger\Bridge\AmazonSqs\Transport\AmazonSqsFifoStamp;
  26. use Symfony\Component\Messenger\Envelope;
  27. use Symfony\Component\Messenger\MessageBusInterface;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  30. use Symfony\Contracts\Translation\TranslatorInterface;
  31. /**
  32.  * @Route("/letter")
  33.  */
  34. class LetterController extends AbstractController
  35. {
  36.     use SentryNotifyTrait;
  37.     private OrganizationUtils $organizationUtils;
  38.     private LetterFilesService $letterFilesService;
  39.     private EncryptorDataUtils $encryptor;
  40.     private UserChecker $userChecker;
  41.     private EntityManagerInterface $entityManager;
  42.     private UserUtils $userUtils;
  43.     private MessageBusInterface $bus;
  44.     private LetterRepository $letterRepository;
  45.     private UrlGeneratorInterface $router;
  46.     /**
  47.      * LetterController constructor.
  48.      */
  49.     public function __construct(
  50.         OrganizationUtils $organizationUtils,
  51.         EncryptorDataUtils $encryptor,
  52.         LetterFilesService $letterFilesService,
  53.         UserChecker $userChecker,
  54.         UserUtils $userUtils,
  55.         EntityManagerInterface $entityManager,
  56.         MessageBusInterface $bus,
  57.         LetterRepository $letterRepository,
  58.         UrlGeneratorInterface $router
  59.     ) {
  60.         $this->organizationUtils $organizationUtils;
  61.         $this->letterFilesService $letterFilesService;
  62.         $this->encryptor $encryptor;
  63.         $this->userUtils $userUtils;
  64.         $this->userChecker $userChecker;
  65.         $this->entityManager $entityManager;
  66.         $this->bus $bus;
  67.         $this->letterRepository $letterRepository;
  68.         $this->router $router;
  69.     }
  70.     /**
  71.      * @Route("/get-types", name="app_letter_get_types", methods={"GET"})
  72.      *
  73.      * @return JsonResponse
  74.      */
  75.     public function getTypes(TranslatorInterface $translator)
  76.     {
  77.         $letterTypes = [];
  78.         $letterEnums LetterTypeEnum::getChoices();
  79.         foreach ($letterEnums as $key => $value) {
  80.             $letterTypes[$translator->trans($key)] = $value;
  81.         }
  82.         return $this->json($letterTypes);
  83.     }
  84.     /**
  85.      * @Route("/get-status-translations", name="app_letter_get_status_translations", methods={"GET"})
  86.      *
  87.      * @return JsonResponse
  88.      */
  89.     public function getStatusTranslations(TranslatorInterface $translator)
  90.     {
  91.         $letterStatus = [];
  92.         $letterEnums LetterStatusEnum::getChoices();
  93.         foreach ($letterEnums as $key => $value) {
  94.             $letterStatus[$value] = $translator->trans($key);
  95.         }
  96.         return $this->json($letterStatus);
  97.     }
  98.     /**
  99.      * @Route("/redirect-all-by-organization/{id}", name="app_letter_redirect_all_by_organization", methods={"GET"})
  100.      *
  101.      * @return JsonResponse
  102.      */
  103.     public function redirectAllByOrganization($id)
  104.     {
  105.         $em $this->getDoctrine()->getManager();
  106.         $organizations $em->getRepository(Organization::class)->findBy(['id' => $id]);
  107.         $this->forwardLetters($organizationstrue);
  108.         return $this->json(['ok']);
  109.     }
  110.     private function forwardLetters(array $organizationsbool $isCheckReex false): bool
  111.     {
  112.         $em $this->getDoctrine()->getManager();
  113.         /** @var Organization $organization */
  114.         foreach ($organizations as $organization) {
  115.             if ($this->organizationUtils->hasReexpedition($organization) || $isCheckReex) {
  116.                 $letters $em->getRepository(Letter::class)->getLetterToForward($organization->getId(), new \DateTime());
  117.                 $letterForward = new LetterForward();
  118.                 $letterForward->setOrganization($organization);
  119.                 $letterForward->setIsDone(true);
  120.                 /** @var Letter $letter */
  121.                 foreach ($letters as $letter) {
  122.                     $letter->setStatus(LetterStatusEnum::SENT);
  123.                     $em->persist($letter);
  124.                     $letterForward->addLetter($letter);
  125.                 }
  126.                 if (count($letterForward->getLetters()) > 0) {
  127.                     $em->persist($letterForward);
  128.                     $em->flush();
  129.                 }
  130.             }
  131.         }
  132.         return true;
  133.     }
  134.     /**
  135.      * @Route("/resend-letter-organizations/{postalCode}/{frequency}/{isDomisimple}", name="app_letter_weekly_redirect_all_organizations", methods={"GET"})
  136.      *
  137.      * @throws QueryException
  138.      */
  139.     public function weeklyRedirectByOrganization(Request $requestint $postalCodestring $frequencybool $isDomisimple false): JsonResponse
  140.     {
  141.         $dateString $request->query->get('datetime', (new \DateTime())->format('Y-m-d H:i:s'));
  142.         $date = new \DateTime($dateString);
  143.         $em $this->getDoctrine()->getManager();
  144.         /** @var OrganizationRepository $orgaRepo */
  145.         $orgaRepo $em->getRepository(Organization::class);
  146.         $organizations $orgaRepo->findByForwardable($postalCodeOrganizationForwardingFrequencyEnum::getEnum($frequency), $isDomisimple);
  147.         $organizationsCount iterator_count($orgaRepo->findByForwardable($postalCodeOrganizationForwardingFrequencyEnum::getEnum($frequency), $isDomisimple));
  148.         foreach ($organizations as $organization) {
  149.             $this->bus->dispatch(
  150.                 (new Envelope(new ResendLetterMessage(
  151.                     $date,
  152.                     $organization['id'],
  153.                     $organization['forwardingFrequency'],
  154.                     $organization['legalName'],
  155.                     $organization['bal'],
  156.                     $organization['statusInvoicePayed'],
  157.                     $organization['uniqId'],
  158.                 )))->with(
  159.                 new AmazonSqsFifoStamp('Letter'uniqid(''true))
  160.             )
  161.             );
  162.         }
  163.         // envoi d'un message de fin avec nombre initial d'orga a traité + nombre restant qui devrait etre 0
  164.         $this->bus->dispatch(
  165.             (new Envelope(new ResendLetterMessage(
  166.                 $date,
  167.                 'END',
  168.                 OrganizationForwardingFrequencyEnum::WEEKLY,
  169.                 null,
  170.                 null,
  171.                 null,
  172.                 null,
  173.                 $postalCode,
  174.                 $organizationsCount
  175.             )))->with(
  176.             new AmazonSqsFifoStamp('Letter'uniqid(''true))
  177.             )
  178.         );
  179.         return $this->json(["La réexpédition a débuté, $organizationsCount organisation(s) en cours de traitement."]);
  180.     }
  181.     /**
  182.      * @Route("/domisimple-redirect-all-organizations/{postalCode}/list", name="app_letter_domisimple_redirect_all_organizations_list", methods={"GET"})
  183.      */
  184.     public function domisimpleRedirectByOrganizationList(int $postalCode): JsonResponse
  185.     {
  186.         $em $this->getDoctrine()->getManager();
  187.         $organizations $em->getRepository(Organization::class)->findByForwardable(
  188.             $postalCode,
  189.             OrganizationForwardingFrequencyEnum::QUARTERLY,
  190.             true
  191.         );
  192.         return $this->json($organizations);
  193.     }
  194.     /**
  195.      * @Route("/view/{id}/type/{type}/{token}", name="app_letter_view", methods={"GET"})
  196.      *
  197.      * @return JsonResponse
  198.      */
  199.     public function viewDocument(Request $request$id$type$token null)
  200.     {
  201.         $repository $this->entityManager->getRepository(Letter::class);
  202.         /** @var User $user */
  203.         $user $this->userChecker->checkUserByToken($token);
  204.         $id $this->encryptor->decrypt($id);
  205.         /** @var Letter $letter */
  206.         $letter $repository->find($id);
  207.         if (!$user || !$letter) {
  208.             return $this->json(['result' => 'Document not found'], Response::HTTP_NOT_FOUND);
  209.         }
  210.         $prescriberOrganizations $this->userUtils->getOrganizationPrescribersID($user);
  211.         $organization $letter->getOrganization();
  212.         if ($organization
  213.             && (in_array($user$organization->getUsers())
  214.                 || in_array('ROLE_ADMIN'$user->getRoles()) || ($organization->getPrescriber() && in_array($organization->getPrescriber()->getId(), $prescriberOrganizations)))) {
  215.             if ($request->query->get('download')) {
  216.                 $this->letterFilesService->downloadLetter($letter->getContentPathAWS());
  217.             }
  218.             $this->letterFilesService->viewLetter($letter$type);
  219.         }
  220.         return $this->json(['result' => 'Document not found'], Response::HTTP_NOT_FOUND);
  221.     }
  222.     /**
  223.      * @Route("/get-nbr-letter/{type}/{orgaId}", name="app_letter_parcel", methods={"GET"})
  224.      */
  225.     public function letterParcel(string $typeint $orgaIdLetterRepository $letterRepository): JsonResponse
  226.     {
  227.         $arrStatus $this->convertStatusToArray($type);
  228.         $result $letterRepository->getNumberLetterOrParcel($arrStatus$orgaId);
  229.         return $this->json(['result' => count($result)], Response::HTTP_OK);
  230.     }
  231.     private function convertStatusToArray(string $status): array
  232.     {
  233.         return explode(','$status);
  234.     }
  235.     /**
  236.      * @Route("/zapier", name="app_letter_invoice", methods={"GET"})
  237.      */
  238.     public function getLastLetterByOrganisation(): JsonResponse
  239.     {
  240.         $userRepository $this->entityManager->getRepository(User::class);
  241.         $organizations $userRepository->getOrganizationsByUser($this->getUser()->getUsername());
  242.         if (is_array($organizations) && !empty($organizations)) {
  243.             $letter $this->letterRepository->getLastLetterWithOrganization($organizations);
  244.             if (is_array($letter) && !empty($letter)) {
  245.                 $url $this->router->generate(
  246.                     'app_letter_view',
  247.                     ['id' => $this->encryptor->encrypt($letter['id']), 'type' => 'recto'],
  248.                     UrlGeneratorInterface::ABSOLUTE_URL
  249.                 );
  250.                 $letter['contentUrl'] = $url;
  251.                 $letter['createdAt'] = $letter['createdAt']->format('d/m/Y');
  252.                 return new JsonResponse([$letter]);
  253.             }
  254.             return new JsonResponse(['error' => 'Letter not found']);
  255.         }
  256.         return new JsonResponse(['error' => 'Organization not found']);
  257.     }
  258. }