src/Controller/Api/LetterController.php line 228

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.         /** @var OrganizationRepository $orgaRepo */
  144.         $orgaRepo $this->entityManager->getRepository(Organization::class);
  145.         $organizations $orgaRepo->findByForwardable($date$postalCodeOrganizationForwardingFrequencyEnum::getEnum($frequency));
  146.         $organizationsCount iterator_count(
  147.             $orgaRepo->findByForwardable($date$postalCodeOrganizationForwardingFrequencyEnum::getEnum($frequency))
  148.         );
  149.         foreach ($organizations as $organization) {
  150.             $this->bus->dispatch(
  151.                 (new Envelope(new ResendLetterMessage(
  152.                     $date,
  153.                     $organization['id'],
  154.                     $organization['forwardingFrequency'],
  155.                     $organization['legalName'],
  156.                     $organization['bal'],
  157.                     $organization['statusInvoicePayed'],
  158.                     $organization['uniqId'],
  159.                 )))->with(
  160.                     new AmazonSqsFifoStamp('Letter'uniqid(''true))
  161.                 )
  162.             );
  163.         }
  164.         // envoi d'un message de fin avec nombre initial d'orga a traité + nombre restant qui devrait etre 0
  165.         $this->bus->dispatch(
  166.             (new Envelope(new ResendLetterMessage(
  167.                 $date,
  168.                 'END',
  169.                 OrganizationForwardingFrequencyEnum::WEEKLY,
  170.                 null,
  171.                 null,
  172.                 null,
  173.                 null,
  174.                 $postalCode,
  175.                 $organizationsCount
  176.             )))->with(
  177.                 new AmazonSqsFifoStamp('Letter'uniqid(''true))
  178.             )
  179.         );
  180.         return $this->json(["La réexpédition a débuté, $organizationsCount organisation(s) en cours de traitement."]);
  181.     }
  182.     /**
  183.      * @Route("/domisimple-redirect-all-organizations/{postalCode}/list", name="app_letter_domisimple_redirect_all_organizations_list", methods={"GET"})
  184.      */
  185.     public function domisimpleRedirectByOrganizationList(int $postalCode): JsonResponse
  186.     {
  187.         $em $this->getDoctrine()->getManager();
  188.         $organizations $em->getRepository(Organization::class)->findByForwardable(
  189.             new \DateTime('now'),
  190.             $postalCode,
  191.             OrganizationForwardingFrequencyEnum::QUARTERLY,
  192.             true
  193.         );
  194.         return $this->json($organizations);
  195.     }
  196.     /**
  197.      * @Route("/view/{id}/type/{type}/{token}", name="app_letter_view", methods={"GET"})
  198.      *
  199.      * @return JsonResponse
  200.      */
  201.     public function viewDocument(Request $request$id$type$token null)
  202.     {
  203.         $repository $this->entityManager->getRepository(Letter::class);
  204.         /** @var User $user */
  205.         $user $this->userChecker->checkUserByToken($token);
  206.         $id $this->encryptor->decrypt($id);
  207.         /** @var Letter $letter */
  208.         $letter $repository->find($id);
  209.         if (!$user || !$letter) {
  210.             return $this->json(['result' => 'Document not found'], Response::HTTP_NOT_FOUND);
  211.         }
  212.         $prescriberOrganizations $this->userUtils->getOrganizationPrescribersID($user);
  213.         $organization $letter->getOrganization();
  214.         if ($organization
  215.             && (in_array($user$organization->getUsers())
  216.                 || in_array('ROLE_ADMIN'$user->getRoles()) || ($organization->getPrescriber() && in_array($organization->getPrescriber()->getId(), $prescriberOrganizations)))) {
  217.             if ($request->query->get('download')) {
  218.                 $this->letterFilesService->downloadLetter($letter->getContentPathAWS());
  219.             }
  220.             $this->letterFilesService->viewLetter($letter$type);
  221.         }
  222.         return $this->json(['result' => 'Document not found'], Response::HTTP_NOT_FOUND);
  223.     }
  224.     /**
  225.      * @Route("/get-nbr-letter/{type}/{orgaId}", name="app_letter_parcel", methods={"GET"})
  226.      */
  227.     public function letterParcel(string $typeint $orgaIdLetterRepository $letterRepository): JsonResponse
  228.     {
  229.         $arrStatus $this->convertStatusToArray($type);
  230.         $result $letterRepository->getNumberLetterOrParcel($arrStatus$orgaId);
  231.         return $this->json(['result' => count($result)], Response::HTTP_OK);
  232.     }
  233.     private function convertStatusToArray(string $status): array
  234.     {
  235.         return explode(','$status);
  236.     }
  237.     /**
  238.      * @Route("/zapier", name="app_letter_invoice", methods={"GET"})
  239.      */
  240.     public function getLastLetterByOrganisation(): JsonResponse
  241.     {
  242.         $userRepository $this->entityManager->getRepository(User::class);
  243.         $organizations $userRepository->getOrganizationsByUser($this->getUser()->getUsername());
  244.         if (is_array($organizations) && !empty($organizations)) {
  245.             $letter $this->letterRepository->getLastLetterWithOrganization($organizations);
  246.             if (is_array($letter) && !empty($letter)) {
  247.                 $url $this->router->generate(
  248.                     'app_letter_view',
  249.                     ['id' => $this->encryptor->encrypt($letter['id']), 'type' => 'recto'],
  250.                     UrlGeneratorInterface::ABSOLUTE_URL
  251.                 );
  252.                 $letter['contentUrl'] = $url;
  253.                 $letter['createdAt'] = $letter['createdAt']->format('d/m/Y');
  254.                 return new JsonResponse([$letter]);
  255.             }
  256.             return new JsonResponse(['error' => 'Letter not found']);
  257.         }
  258.         return new JsonResponse(['error' => 'Organization not found']);
  259.     }
  260. }