src/Controller/AppController.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  7. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Psr\Log\LoggerInterface;
  13. use App\Entity\Okpd;
  14. class AppController extends AbstractController
  15. {
  16. /*
  17.  * Страница с формой
  18.  */
  19.     public function index(): Response
  20.     {
  21.         if (!$this->isAlarmMode()) return $this->redirect($this->getParameter('app.fgis_url'));
  22.         
  23.         return $this->render('app/index.html.twig');
  24.     }
  25.     
  26. /*
  27.  * Поиск ОКПД
  28.  */
  29.     public function getOkpd(ManagerRegistry $doctrineRequest $request): JsonResponse
  30.     {
  31.         if (!$this->isAlarmMode()) return $this->redirect($this->getParameter('app.fgis_url'));
  32.         
  33.         $query $request->get('q');
  34.         $type = (int)$request->get('t');
  35.         
  36.         $okpds $doctrine->getManager()->getRepository(Okpd::class)->searchOkpd($query$type);
  37.         
  38.         return new JsonResponse(['results' => $okpds]);
  39.     }
  40.     
  41. /*
  42.  * Получаем список свойств
  43.  */
  44.     public function getAttributes(ManagerRegistry $doctrineRequest $request): JsonResponse
  45.     {
  46.         if (!$this->isAlarmMode()) return $this->redirect($this->getParameter('app.fgis_url'));
  47.         
  48.         $em $doctrine->getManager();
  49.         try {
  50.             $okpd $request->get('okpd');
  51.             if (!$okpd) throw new \Exception('Ошибка! Не указан код ОКПД2.');
  52.             $direction = (int)$request->get('direction');
  53.             if (!$direction) throw new \Exception('Ошибка! Не указан вид использования.');
  54.             $country $request->get('country');
  55.             if ($direction === && !$country) throw new \Exception('Ошибка! Не указана страна назначения.');
  56.             
  57.             $attributes $em->getRepository(Okpd::class)->getAttributes($okpd$direction$country);
  58.             
  59.             $response = [
  60.                 'success' => true,
  61.                 'attributes' => $attributes
  62.             ];
  63.             
  64.         } catch (\Exception $ex) {
  65.             $response = [
  66.                 'success' => false,
  67.                 'message' => $ex->getMessage()
  68.             ];
  69.         }
  70.         
  71.         return new JsonResponse($response);
  72.     }
  73.     
  74. /*
  75.  * Генерим номера документов
  76.  */
  77.     
  78.     public function generateNumbers($packTypeManagerRegistry $doctrineRequest $requestLoggerInterface $loggerMailerInterface $mailer): JsonResponse
  79.     {
  80.         if (!$this->isAlarmMode()) return $this->redirect($this->getParameter('app.fgis_url'));
  81.         
  82.         $em $doctrine->getManager();
  83.         $inn $request->get('fieldInn');
  84.         $kpp $request->get('fieldKpp');
  85.         $mailto $request->get('fieldEmail');
  86.         try {
  87.             $data $em->getRepository(Okpd::class)->processSubmit($request$packType);
  88.             if (!$data || !is_array($data) || !is_array($data['partnumbers']) || !is_array($data['sdiznumbers'])) throw new \Exception('Ошибка при генерации номеров документов.');
  89.             
  90.             $file 'https://' $request->getHost() . '/download/' $inn '/' $data['id'];
  91.             
  92.             $logger->info('Документы успешно созданы', [
  93.                 'ip' => $request->getClientIp(),
  94.                 'inn' => $inn,
  95.                 'packtype' => $packType,
  96.                 'packid' => $data['id']
  97.             ]);
  98.             
  99.             $email = (new TemplatedEmail())
  100.                 ->from('Аварийная форма Зерно <alarm@specagro.ru>')
  101.                 ->to($mailto)
  102.                 ->subject('ФГИС Зерно. Номера ' . ($packType === 'parts' 'партий' : ($packType === 'sdiz' 'СДИЗ' 'партий и СДИЗ')))
  103.                 ->htmlTemplate('emails/pack.html.twig')
  104.                 ->context([
  105.                     'file' => $file,
  106.                     'partnumbers' => $data['partnumbers'],
  107.                     'sdiznumbers' => $data['sdiznumbers'],
  108.                     'inn' => $inn,
  109.                     'kpp' => $kpp,
  110.                     'okpd' => $data['okpd'],
  111.                     'date' => $data['date']
  112.                 ]);
  113.             $mailer->send($email);
  114.             
  115.             $response = [
  116.                 'success' => true,
  117.                 'file' => $file
  118.             ];
  119.             
  120.         } catch (\Throwable $ex) {
  121.             
  122.             if (get_class($ex) === 'Doctrine\DBAL\Exception' || is_subclass_of($ex'Doctrine\DBAL\Exception')) {
  123.                 $message "Ошибка при работе с БД. Попробуйте позже.";
  124.             } else {
  125.                 $message $ex->getMessage();
  126.             }
  127.             
  128.             $logger->critical('Ошибка при генерации документов', [
  129.                 'ip' => $request->getClientIp(),
  130.                 'inn' => $inn,
  131.                 'error' => $ex->getMessage()
  132.             ]);
  133.             
  134.             $response = [
  135.                 'success' => false,
  136.                 'message' => $message
  137.             ];
  138.         }
  139.         
  140.         return new JsonResponse($response);
  141.     }
  142.     
  143. /*
  144.  * Скачиваем документы
  145.  */
  146.     public function downloadDocuments($inn$packIdManagerRegistry $doctrine): BinaryFileResponse
  147.     {
  148.         //if (!$this->isAlarmMode()) return $this->redirect($this->getParameter('app.fgis_url'));
  149.         
  150.         $em $doctrine->getManager();
  151.         $packInfo $em->getRepository(Okpd::class)->getPack($inn$packId);
  152.         if (!$packInfo)  throw $this->createNotFoundException();
  153.         
  154.         $cacheDir $this->getParameter('kernel.cache_dir') . '/../packs/';
  155.         $tempDir $this->getParameter('kernel.cache_dir') . '/../temp/' $inn '-' $packId;
  156.         $filename $packId '.zip';
  157.         $cachedFile $cacheDir $inn '-' $filename;
  158.         $parts null;
  159.         $sdiz null;
  160.         
  161.         // Сначала ищем в кэше
  162.         if (file_exists($cachedFile)) { // Если найден, то просто отдаем, ничего не делаем
  163.         } else { // Если не найден, то генерим
  164.             
  165.             mkdir($tempDir);
  166.             
  167.             // Собираем номера
  168.             if ($packInfo['packtype'] === 'parts' || $packInfo['packtype'] === 'all') {
  169.                 $parts $em->getRepository(Okpd::class)->getParts($packInfo['inn'], $packInfo['packid']);
  170.                 if (count($parts) === 0$parts null;
  171.             }
  172.             if ($packInfo['packtype'] === 'sdiz' || $packInfo['packtype'] === 'all') {
  173.                 $sdiz $em->getRepository(Okpd::class)->getSdiz($packInfo['inn'], $packInfo['packid']);
  174.                 if (count($sdiz) === 0$sdiz null;
  175.             }
  176.             $em->getRepository(Okpd::class)->generateNumbersFile($tempDir$packInfo$parts$sdiz); // Генерим файл с номерами и свойствами
  177.             if ($packInfo['packtype'] === 'sdiz' || $packInfo['packtype'] === 'all') { // Генерим файлы СДИЗов
  178.                 $em->getRepository(Okpd::class)->generateSdizFiles($tempDir$packInfo$sdiz$parts);
  179.             }
  180.             
  181.             $zip = new \ZipArchive();
  182.             $zip->open($cachedFile, \ZipArchive::CREATE);
  183.             $zip->addGlob($tempDir '/*.{xlsx}'GLOB_BRACE, ['remove_all_path' => TRUE]);
  184.             $zip->close();
  185.             
  186.             $this->removeDirectory($tempDir);
  187.         }
  188.         
  189.         $response = new BinaryFileResponse($cachedFile);
  190.         $response->headers->set('Content-Type''application/zip');
  191.         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT$filename);
  192.         return $response;
  193.     }
  194.     
  195.     private function removeDirectory($dir)
  196.     {
  197.         if ($objs glob($dir "/*")) {
  198.             foreach($objs as $obj) {
  199.                 is_dir($obj) ? removeDirectory($obj) : unlink($obj);
  200.             }
  201.         }
  202.         rmdir($dir);
  203.     }
  204.     
  205.     private function isAlarmMode()
  206.     {
  207.         return strtolower($this->getParameter('app.alarm_mode')) === 'true';
  208.     }
  209. }