src/WebBundle/Controller/OrderController.php line 335

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Controller;
  3. use Doctrine\ORM\NonUniqueResultException;
  4. use Doctrine\ORM\NoResultException;
  5. use Exception;
  6. use OpenApi\Annotations as OA;
  7. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  13. use WebBundle\Entity\BuyOrder;
  14. use WebBundle\Entity\BuyOrderArticle;
  15. use WebBundle\Entity\OrderAddress;
  16. use WebBundle\Enum\BuyOrderStatusEnum;
  17. use WebBundle\Filler\OrderFiller;
  18. use WebBundle\Helper\App;
  19. use WebBundle\Helper\OrderHelper;
  20. use WebBundle\Helper\ResponseApiHelper;
  21. use WebBundle\Helper\UserHelper;
  22. use WebBundle\Repository\BuyOrderRepository;
  23. use WebBundle\Repository\OrderAddressRepository;
  24. use WebBundle\Repository\UserRepository;
  25. use WebBundle\Service\OrderAddressService;
  26. use WebBundle\Service\OrderHistoryService;
  27. use WebBundle\Service\OrderRefundService;
  28. use WebBundle\Service\OrderService;
  29. use WebBundle\Service\UserService;
  30. use WebBundle\Service\VatService;
  31. class OrderController extends ExtendedController
  32. {
  33.     /** @required */
  34.     public OrderFiller $orderFiller;
  35.     /** @required */
  36.     public OrderRefundService $orderRefundService;
  37.     /** @required */
  38.     public UserService $userService;
  39.     public const COUNT_ORDERS_ON_POPUP 6;
  40.     public const HEIGHT_STRING 60;
  41.     protected BuyOrderRepository $buyOrderRepository;
  42.     protected OrderService $orderService;
  43.     protected OrderAddressService $orderAddressService;
  44.     protected OrderHistoryService $orderHistoryService;
  45.     private OrderAddressRepository $orderAddressRepository;
  46.     private VatService $vatService;
  47.     protected array $messages = [
  48.         'notToken' => 'Token is not correct',
  49.         'notOrder' => 'Order not found',
  50.         'notArticle' => 'Article not found',
  51.         'notPay' => 'Order not ready to pay'
  52.     ];
  53.     /**
  54.      * @param OrderService $orderService
  55.      * @param OrderAddressService $orderAddressService
  56.      * @param OrderHistoryService $orderHistoryService
  57.      * @param VatService $vatService
  58.      * @param BuyOrderRepository $buyOrderRepository
  59.      * @param UserRepository $userRepository
  60.      * @param OrderAddressRepository $orderAddressRepository
  61.      * @throws Exception
  62.      */
  63.     public function __construct(
  64.         OrderService $orderService,
  65.         OrderAddressService $orderAddressService,
  66.         OrderHistoryService $orderHistoryService,
  67.         VatService $vatService,
  68.         BuyOrderRepository $buyOrderRepository,
  69.         OrderAddressRepository $orderAddressRepository
  70.     ) {
  71.         parent::__construct();
  72.         $this->orderService $orderService;
  73.         $this->orderAddressService $orderAddressService;
  74.         $this->orderHistoryService $orderHistoryService;
  75.         $this->vatService $vatService;
  76.         $this->buyOrderRepository $buyOrderRepository;
  77.         $this->orderAddressRepository $orderAddressRepository;
  78.     }
  79.     /**
  80.      * @IsGranted("ROLE_ADMIN")
  81.      * @param string $hash
  82.      * @return JsonResponse|RedirectResponse
  83.      * @throws NonUniqueResultException
  84.      * @throws Exception
  85.      */
  86.     public function sendEmailTest(string $hash)
  87.     {
  88.         $res = [];
  89.         if (App::isDev()) {
  90.             if ($order $this->orderService->getOrderObj($hash)) {
  91.                 if ($order->getStatus() > BuyOrderStatusEnum::AWAITING_CALCULATION) {
  92.                     $this->orderHistoryService->saveHistoryAndSendEmail(
  93.                         $order,
  94.                         'delivery_calculated',
  95.                         OrderHistoryService::SEND_EMAIL
  96.                     );
  97.                     return $this->redirectToRoute('app_buy_order', ['orderId' => $hash]);
  98.                 } else {
  99.                     $res['err'] = 'Order status must be three or more.';
  100.                 }
  101.             } else {
  102.                 $res['err'] = 'Order not found';
  103.             }
  104.         } else {
  105.             $res['err'] = 'Production environment';
  106.         }
  107.         return new JsonResponse($res);
  108.     }
  109.     /**
  110.      * Создание черновика заказа
  111.      *
  112.      * @param Request $request
  113.      * @return JsonResponse
  114.      * @throws Exception
  115.      *
  116.      * @OA\Response(
  117.      *     response=200,
  118.      *     description="ОК. Создание нового заказа",
  119.      *     @OA\JsonContent(
  120.      *         type="object",
  121.      *         @OA\Property(property="order", type="object", description="Информация по целевому заказу",
  122.      *              @OA\Property(property="hash", description="Уникальный идентификатор заказа", example="0917aac1aec6197ccf38afa3c9314192"),
  123.      *              @OA\Property(property="name", description="Назваине проекта", example="Подборка для ванной"),
  124.      *              @OA\Property(property="createDate", description="Дата создания текстом", example="16 августа 2020 г."),
  125.      *              @OA\Property(property="createDateTimestamp", description="Дата создания в формате милисекунд", example="1470805363"),
  126.      *              @OA\Property(property="updateDate", description="Дата обновления текстом", example="22 сентября 2021 г."),
  127.      *              @OA\Property(property="updateDateTimestamp", description="Дата обновления в формате милисекунд", example="1470805363"),
  128.      *              @OA\Property(property="items", description="количество артикулов в заказе", example="3"),
  129.      *              @OA\Property(property="weight", description="Общий вес заказа", example="55 kg"),
  130.      *              @OA\Property(property="totalPrice", description="Общая стоимость заказа", example="505 €"),
  131.      *              @OA\Property(property="status", type="object", description="Статус заказа",
  132.      *                  @OA\Property(property="id", description="Цировой код статуса", example="1"),
  133.      *                  @OA\Property(property="text", description="Статус заказа текстом", example="Черновик заказа")
  134.      *              )
  135.      *         ),
  136.      *         @OA\Property(property="list", type="array", description="Список заказов пользователя",
  137.      *              @OA\Items(
  138.      *                  @OA\Property(property="hash", description="Уникальный идентификатор заказа", example="0917aac1aec6197ccf38afa3c9314192"),
  139.      *                  @OA\Property(property="name", description="Назваине проекта", example="Подборка для ванной"),
  140.      *                  @OA\Property(property="createDate", description="Дата создания текстом", example="16 августа 2020 г."),
  141.      *                  @OA\Property(property="createDateTimestamp", description="Дата создания в формате милисекунд", example="1470805363"),
  142.      *                  @OA\Property(property="updateDate", description="Дата обновления текстом", example="22 сентября 2021 г."),
  143.      *                  @OA\Property(property="updateDateTimestamp", description="Дата обновления в формате милисекунд", example="1470805363"),
  144.      *                  @OA\Property(property="items", description="количество артикулов в заказе", example="3"),
  145.      *                  @OA\Property(property="weight", description="Общий вес заказа", example="55 kg"),
  146.      *                  @OA\Property(property="totalPrice", description="Общая стоимость заказа", example="505 €"),
  147.      *                  @OA\Property(property="status", type="object", description="Статус заказа",
  148.      *                  @OA\Property(property="id", description="Цировой код статуса", example="1"),
  149.      *                  @OA\Property(property="text", description="Статус заказа текстом", example="Черновик заказа")
  150.      *              )
  151.      *              )
  152.      *         )
  153.      *     )
  154.      * )
  155.      * @OA\RequestBody(
  156.      *     description="Вмесмто обычного post['name'] параметра можно передать json в теле запроса",
  157.      *     @OA\JsonContent(
  158.      *         type="object",
  159.      *         @OA\Property(property="name", description="Название заказа", example="Test order")
  160.      *     )
  161.      * )
  162.      * @OA\Parameter(
  163.      *     name="_locale",
  164.      *     in="path",
  165.      *     required=true,
  166.      *     description="локаль",
  167.      *     @OA\Schema(type="string")
  168.      * )
  169.      * @OA\Parameter(
  170.      *     name="name",
  171.      *     in="query",
  172.      *     required=false,
  173.      *     description="Название заказа, так же можно передать через json в теле запроса",
  174.      *     @OA\Schema(type="string")
  175.      * )
  176.      * @OA\Tag(name="Заказы")
  177.      */
  178.     public function create(Request $request): JsonResponse
  179.     {
  180.         $token UserHelper::getInstance()->getToken();
  181.         $name $request->request->get('name');
  182.         if (!$name) {
  183.             $json json_decode($request->getContent(), true);
  184.             if (empty($json['name'])) {
  185.                 return new JsonResponse(['status' => false'message' => 'Name is not defined'], 400);
  186.             } else {
  187.                 $name $json['name'];
  188.             }
  189.         }
  190.         $order $this->orderService->create($token$request->request->get('name'), true);
  191.         return new JsonResponse([
  192.             'order' => $order,
  193.             'list' => $this->orderService->getListOrder($token)
  194.         ]);
  195.     }
  196.     /**
  197.      * Редактирование имени заказа
  198.      *
  199.      * @param Request $request
  200.      * @return JsonResponse
  201.      * @throws Exception
  202.      *
  203.      * @OA\Response(
  204.      *     response=200,
  205.      *     description="ОК. Редактирование имени заказа",
  206.      *     @OA\JsonContent(
  207.      *         type="object",
  208.      *         @OA\Property(property="order", type="object", description="Информация по целевому заказу",
  209.      *              @OA\Property(property="hash", description="Уникальный идентификатор заказа", example="0917aac1aec6197ccf38afa3c9314192"),
  210.      *              @OA\Property(property="name", description="Назваине проекта", example="Подборка для ванной"),
  211.      *              @OA\Property(property="createDate", description="Дата создания текстом", example="16 августа 2020 г."),
  212.      *              @OA\Property(property="createDateTimestamp", description="Дата создания в формате милисекунд", example="1470805363"),
  213.      *              @OA\Property(property="updateDate", description="Дата обновления текстом", example="22 сентября 2021 г."),
  214.      *              @OA\Property(property="updateDateTimestamp", description="Дата обновления в формате милисекунд", example="1470805363"),
  215.      *              @OA\Property(property="items", description="количество артикулов в заказе", example="3"),
  216.      *              @OA\Property(property="weight", description="Общий вес заказа", example="55 kg"),
  217.      *              @OA\Property(property="totalPrice", description="Общая стоимость заказа", example="505 €"),
  218.      *              @OA\Property(property="status", type="object", description="Статус заказа",
  219.      *                  @OA\Property(property="id", description="Цировой код статуса", example="1"),
  220.      *                  @OA\Property(property="text", description="Статус заказа текстом", example="Черновик заказа")
  221.      *              )
  222.      *         ),
  223.      *         @OA\Property(property="list", type="array", description="Список заказов пользователя",
  224.      *              @OA\Items(
  225.      *                  @OA\Property(property="hash", description="Уникальный идентификатор заказа", example="0917aac1aec6197ccf38afa3c9314192"),
  226.      *                  @OA\Property(property="name", description="Назваине проекта", example="Подборка для ванной"),
  227.      *                  @OA\Property(property="createDate", description="Дата создания текстом", example="16 августа 2020 г."),
  228.      *                  @OA\Property(property="createDateTimestamp", description="Дата создания в формате милисекунд", example="1470805363"),
  229.      *                  @OA\Property(property="updateDate", description="Дата обновления текстом", example="22 сентября 2021 г."),
  230.      *                  @OA\Property(property="updateDateTimestamp", description="Дата обновления в формате милисекунд", example="1470805363"),
  231.      *                  @OA\Property(property="items", description="количество артикулов в заказе", example="3"),
  232.      *                  @OA\Property(property="weight", description="Общий вес заказа", example="55 kg"),
  233.      *                  @OA\Property(property="totalPrice", description="Общая стоимость заказа", example="505 €"),
  234.      *                  @OA\Property(property="status", type="object", description="Статус заказа",
  235.      *                  @OA\Property(property="id", description="Цировой код статуса", example="1"),
  236.      *                  @OA\Property(property="text", description="Статус заказа текстом", example="Черновик заказа")
  237.      *              )
  238.      *              )
  239.      *         )
  240.      *     )
  241.      * )
  242.      * @OA\RequestBody(
  243.      *     description="Вмесмто обычного post['name'] и post['hash'] параметра можно передать json в теле запроса",
  244.      *     @OA\JsonContent(
  245.      *         type="object",
  246.      *         @OA\Property(property="name", description="Название заказа", example="Test order"),
  247.      *         @OA\Property(property="hash", description="идентификатор заказ", example="0917aac1aec6197ccf38afa3c9314192")
  248.      *     )
  249.      * )
  250.      * @OA\Parameter(
  251.      *     name="_locale",
  252.      *     in="path",
  253.      *     required=true,
  254.      *     description="локаль",
  255.      *     @OA\Schema(type="string")
  256.      * )
  257.      * @OA\Parameter(
  258.      *     name="name",
  259.      *     in="query",
  260.      *     required=false,
  261.      *     description="Название заказа, так же можно передать через json в теле запроса",
  262.      *     @OA\Schema(type="string")
  263.      * )
  264.      * @OA\Parameter(
  265.      *     name="hash",
  266.      *     in="query",
  267.      *     required=false,
  268.      *     description="идентификатор заказа, так же можно передать через json в теле запроса",
  269.      *     @OA\Schema(type="string")
  270.      * )
  271.      * @OA\Tag(name="Заказы")
  272.      */
  273.     public function edit(Request $request): JsonResponse
  274.     {
  275.         $token UserHelper::getInstance()->getToken();
  276.         $name $request->request->get('name');
  277.         $hash $request->request->get('hash');
  278.         $json json_decode($request->getContent(), true);
  279.         if (!$name) {
  280.             if (empty($json['name'])) {
  281.                 return new JsonResponse(['status' => false'message' => 'Name is not defined'], 400);
  282.             } else {
  283.                 $name $json['name'];
  284.             }
  285.         }
  286.         if (!$hash) {
  287.             if (empty($json['hash'])) {
  288.                 return new JsonResponse(['status' => false'message' => 'Hash is not defined'], 400);
  289.             } else {
  290.                 $hash $json['hash'];
  291.             }
  292.         }
  293.         return new JsonResponse([
  294.             'order' => $this->orderService->editName($hash$name),
  295.             'list' => $this->orderService->getListOrder($token)
  296.         ]);
  297.     }
  298.     /**
  299.      * Страница заказа
  300.      *
  301.      * @param string $hash
  302.      * @return Response
  303.      * @throws Exception
  304.      */
  305.     public function indexAction(string $hash): Response
  306.     {
  307.         $res $this->orderService->checkHashRedirect($hash);
  308.         if ($res) {
  309.             return $res;
  310.         }
  311.         $order $this->orderService->getOrder($hashtrue);
  312.         $request App::getRequest();
  313.         if (!$order) {
  314.             throw $this->createNotFoundException('Order not found');
  315.         }
  316.         switch ($request->get('shareFormat')) {
  317.             case 'pdf':
  318.                 return $this->orderService->getPdfInPage(
  319.                     $this->generateUrl(
  320.                         'app_order',
  321.                         [
  322.                             '_locale' => App::getCurLocale(true),
  323.                             'hash' => $order['hash'],
  324.                             'share' => 'pdf'
  325.                         ],
  326.                         UrlGeneratorInterface::ABSOLUTE_URL
  327.                     ),
  328.                     ['orderNumber' => $order['number'] ?: $order['hash']]
  329.                 );
  330.             case 'excel':
  331.                 $exOrder $this->buyOrderRepository->getOrder($order['hash']);
  332.                 return $this->orderService->convertToExcel($exOrder);
  333.         }
  334.         return $this->renderReact('@Web/Order/show.html.twig', [
  335.             'title' => $order['title'],
  336.             'initialState' => ['order' => $order]
  337.         ]);
  338.     }
  339.     /**
  340.      * Функция для инициализации возврата средств клиентом в заказе
  341.      * https://te.remote.team/#/discus/81B16B1E-73F2-C38C-D1D3-66D826089072/
  342.      *
  343.      * @param Request $request
  344.      * @param string $hash
  345.      * @return JsonResponse
  346.      */
  347.     public function refundCompensation(Request $requeststring $hash): JsonResponse
  348.     {
  349.         return new JsonResponse($this->orderRefundService->refundOrCompensation($hash$request->request->all()));
  350.     }
  351.     /**
  352.      * @param string $hash
  353.      * @param int $responseOld
  354.      * @return JsonResponse
  355.      * @throws Exception
  356.      */
  357.     public function resetTimerAction(string $hashint $responseOld 0): JsonResponse
  358.     {
  359.         $this->orderService->timer true;
  360.         try {
  361.             $order $this->orderService->change($hash'{"reset":true}');
  362.         } catch (NoResultException $e) {
  363.             OrderHelper::Alert([
  364.                 'subject'      => 'Ошибка запроса reset-timer для заказа',
  365.                 'message'      => 'Заказа нет или он удалён',
  366.                 'hash '        => $hash,
  367.                 'responseOld ' => $responseOld,
  368.             ], 'rzagorudko|dfomenkov131122');
  369.             $order null;
  370.         }
  371.         if ($order) {
  372.             if (!empty($responseOld)) {
  373.                 $response $this->orderFiller->fillArrayWithOldOrderData($order);
  374.             } else {
  375.                 $response $this->orderService->orderData($order);
  376.                 $response['fetchRequestNum'] = App::getRequest()->request->get('fetchRequestNum');
  377.             }
  378.         } else {
  379.             $response = new ResponseApiHelper();
  380.             $response->validate('Order''''empty''NULL');
  381.             $response $response->result();
  382.         }
  383.         return new JsonResponse($response);
  384.     }
  385.     /**
  386.      * @param string $hash
  387.      * @param bool $full
  388.      * @return JsonResponse
  389.      * @throws Exception
  390.      */
  391.     public function apiOrderAction(string $hash, ?bool $full false): JsonResponse
  392.     {
  393.         if (App::getRequest()->request->get('data')) {
  394.             $order $this->orderService->change($hashApp::getRequest()->request->get('data'));
  395.             $orderArray $this->orderService->orderData($order, ['full' => $full]);
  396.         }
  397.         $response $orderArray ?? $this->orderService->getOrder($hash);
  398.         $response['fetchRequestNum'] = App::getRequest()->request->get('fetchRequestNum');
  399.         return new JsonResponse($response);
  400.     }
  401.     /**
  402.      * @param string $hash
  403.      * @param bool $debug
  404.      * @return JsonResponse
  405.      * @throws Exception
  406.      */
  407.     public function apiHistoryAction(string $hashbool $debug): JsonResponse
  408.     {
  409.         $history $this->orderService->getHistory($hash$debug);
  410.         return new JsonResponse($history);
  411.     }
  412.     /**
  413.      * Запросы ручного расчета доставки
  414.      *
  415.      * @param Request $request
  416.      * @param string $hash
  417.      * @return JsonResponse
  418.      * @throws Exception
  419.      */
  420.     public function requestDeliveryAction(Request $requeststring $hash): JsonResponse
  421.     {
  422.         $data json_decode($request->get('data'), true);
  423.         if (!App::getCurUser() || !empty($data['email'])) {
  424.             $data $this->userService->checkEmail($data['email'], $data['token'] ?? null);
  425.             if (!$data->getStatus()) {
  426.                 $response['email_exist'] = ['exist' => 'checked''message' => ''];
  427.                 $response['email_exist_db'] = ['exist' => !$data->getStatus(), 'message' => $data->getError()];
  428.                 $response['status'] = 200;
  429.                 return new JsonResponse($response);
  430.             }
  431.         }
  432.         if ($data) {
  433.             $order $this->orderService->requestCalculateDeliveryByHash($hash$request->get('data'));
  434.             return new JsonResponse($order ?? $this->orderService->getOrder($hash));
  435.         }
  436.         return new JsonResponse(['err' => 'Can not parsed json']);
  437.     }
  438.     /**
  439.      * Перемещение артикулов из заказов в другие заказы
  440.      *
  441.      * @param Request $request
  442.      * @return JsonResponse
  443.      * @throws Exception
  444.      */
  445.     public function transferItemsAction(Request $request): JsonResponse
  446.     {
  447.         $data json_decode($request->get('data'), true);
  448.         if ($data) {
  449.             return new JsonResponse($this->orderService->transferItems($data));
  450.         }
  451.         return new JsonResponse(['err' => 'Can not parsed json']);
  452.     }
  453.     /**
  454.      * Удаления артикула/ов из заказа
  455.      *
  456.      * @param Request $request
  457.      * @return JsonResponse
  458.      * @throws Exception
  459.      */
  460.     public function delItemsAction(Request $request): JsonResponse
  461.     {
  462.         $data json_decode($request->get('data'), true);
  463.         if (!$data){
  464.             return new JsonResponse(['err' => 'Can not parsed json']);
  465.         }
  466.         $error null;
  467.         $order null;
  468.         if (empty($data['ides']) || count($data['ides']) == 0) {
  469.             $error 'ides is empty';
  470.         } elseif (empty($data['hash'])) {
  471.             $error 'hash is empty';
  472.         } else {
  473.             /** @var BuyOrder $order */
  474.             $order $this->buyOrderRepository->getOrder($data['hash']);
  475.             if (!$order) {
  476.                 $error 'order not found';
  477.             } else {
  478.                 $order $this->orderService->delItems($order$data['ides']);
  479.             }
  480.         }
  481.         return new JsonResponse([
  482.             'error' => $error,
  483.             'order' => $order,
  484.         ]);
  485.     }
  486.     /**
  487.      * Удаления адреса заказа
  488.      *
  489.      * @param Request $request
  490.      * @return JsonResponse
  491.      * @throws Exception
  492.      */
  493.     public function delAddressesAction(Request $request): JsonResponse
  494.     {
  495.         $data json_decode($request->get('data'), true);
  496.         if (!$data) {
  497.             return new JsonResponse(['err' => 'Can not parsed json']);
  498.         }
  499.         $error null;
  500.         $status false;
  501.         if (empty($data['ides']) || count($data['ides']) == 0) {
  502.             $error 'ides is empty';
  503.         } else {
  504.             $token UserHelper::getInstance()->getToken();
  505.             $orderAddresses $this->orderAddressRepository->getAddressByIdes($data['ides']);
  506.                 /** @var OrderAddress $orderAddress */
  507.                 foreach ($orderAddresses as $orderAddress) {
  508.                     if (
  509.                         $orderAddress->getToken() == $token ||
  510.                         $this->get('security.authorization_checker')->isGranted('ROLE_ORDER_MASTER')
  511.                     ) {
  512.                         if (! $orderAddress->getFrozen()) {
  513.                             $this->orderAddressService->delete($orderAddress);
  514.                         }
  515.                         $status true;
  516.                     } else {
  517.                         $error 'Access denied';
  518.                     }
  519.                 }
  520.             }
  521.         return new JsonResponse([
  522.             'error' => $error,
  523.             'status' => $status,
  524.         ]);
  525.     }
  526.     /**
  527.      * Проверяем, что email не занят в другой учетной записи
  528.      *
  529.      * @return JsonResponse
  530.      * @throws Exception
  531.      */
  532.     public function checkEmailAction(Request $request): JsonResponse
  533.     {
  534.         $email $request->get('email');
  535.         $emailInfo $this->userService->checkEmail($email);
  536.         $responseArr = [
  537.             'status' => (int) $emailInfo->getStatus(),
  538.             'email_exist' => (int) !$emailInfo->getStatus(),
  539.         ];
  540.         if (!$emailInfo->getStatus()) {
  541.             $responseArr['err'] = $emailInfo->getError();
  542.         }
  543.         return new JsonResponse($responseArr);
  544.     }
  545.     /**
  546.      * @param string $vat
  547.      * @return JsonResponse
  548.      * @throws Exception
  549.      */
  550.     public function checkVATAction(string $vat): JsonResponse
  551.     {
  552.         return new JsonResponse($this->vatService->checkVAT($vat));
  553.     }
  554.     /**
  555.      * @return JsonResponse|null
  556.      * @throws Exception
  557.      */
  558.     public function ordersShortListAction(): ?JsonResponse
  559.     {
  560.         $token UserHelper::getInstance()->getToken();
  561.         return new JsonResponse($this->orderService->orderShortList($token));
  562.     }
  563.     /**
  564.      * Список заказов для выпадающего списка
  565.      *
  566.      * @param null $height
  567.      * @return Response
  568.      * @throws Exception
  569.      */
  570.     public function lastOrderAction($height null): Response
  571.     {
  572.         $countString = ($height) ? floor($height self::HEIGHT_STRING) : self::COUNT_ORDERS_ON_POPUP;
  573.         return $this->render('@Web/BuyOrder/last-orders.html.twig', [
  574.             'orders' => $this->orderService->getOrders(UserHelper::getInstance()->getToken()),
  575.             'countString' => $countString
  576.         ]);
  577.     }
  578.     /**
  579.      * Удаление формируемого заказа
  580.      * @param string $orderId
  581.      * @return JsonResponse
  582.      * @throws Exception
  583.      */
  584.     public function deleteAction(string $orderId): JsonResponse
  585.     {
  586.         $res $this->orderService->delete($orderId);
  587.         $res['list'] = $this->lastOrderAction()->getContent();
  588.         return new JsonResponse(['status' => 0'response' => $res]);
  589.     }
  590.     /**
  591.      * @param $hash
  592.      * @return RedirectResponse
  593.      * @throws NonUniqueResultException
  594.      */
  595.     public function recoveryCancelOrderAction($hash): RedirectResponse
  596.     {
  597.         return $this->orderService->recoveryCancelOrder($hash);
  598.     }
  599.     /**
  600.      * Удаление формируемого заказа
  601.      * @param string $hash
  602.      * @return JsonResponse
  603.      * @throws Exception
  604.      */
  605.     public function deleteAllDataUserAction(string $hash): JsonResponse
  606.     {
  607.         return new JsonResponse($this->orderService->delAllData($hash));
  608.     }
  609.     /**
  610.      * Добавление артикула в заказ
  611.      *
  612.      * @param int $itemId
  613.      * @param ?float $itemCount
  614.      * @param ?int $type
  615.      * @return JsonResponse
  616.      * @throws Exception
  617.      */
  618.     public function addItemAction(int $itemId, ?float $itemCount null, ?int $type BuyOrderArticle::TYPE_NORMAL): JsonResponse
  619.     {
  620.         $ordersAmount = [];
  621.         if (!empty($_POST['orders'])) {
  622.             $ordersAmount $_POST['orders'];
  623.         }
  624.         $result $this->orderService->changeElement($itemId$ordersAmount$itemCount$type);
  625.         if ($result) {
  626.             $result['action'] = 'add';
  627.         } else {
  628.             $result['err'] = 'Fail operation';
  629.         }
  630.         return new JsonResponse([
  631.             'status' => 0,
  632.             'response' => [
  633.                 'res' => $result,
  634.             ]
  635.         ]);
  636.     }
  637.     /**
  638.      * Редактирование имени заказа
  639.      *
  640.      * @param string $hash
  641.      * @param string $name
  642.      * @return JsonResponse
  643.      * @throws Exception
  644.      */
  645.     public function editAction(string $hashstring $name): JsonResponse
  646.     {
  647.         $this->orderService->changeName($hash$name);
  648.         return new JsonResponse([
  649.             'status' => 0,
  650.             'response' => [
  651.                 'res' => 'ok',
  652.                 'list' => $this->lastOrderAction()->getContent(),
  653.             ]
  654.         ]);
  655.     }
  656.     /**
  657.      * Список заказов для меню выбора
  658.      *
  659.      * @param Request $request
  660.      * @param int $articleId
  661.      * @param mixed $type
  662.      * @return JsonResponse|RedirectResponse
  663.      * @throws Exception
  664.      */
  665.     public function listAction(Request $requestint $articleId$type BuyOrderArticle::TYPE_NORMAL): Response
  666.     {
  667.         $response $this->orderService->getOrderAddList(
  668.             $articleId,
  669.             (int) $type,
  670.             (float) $request->request->get('articleCount'$request->request->get('itemCount'0.1))
  671.         );
  672.         if (!empty($response['redirect'])) {
  673.             return new RedirectResponse($response['redirect']);
  674.         }
  675.         return new JsonResponse($response);
  676.     }
  677.     /**
  678.      * Синхронизация заказа с 1с.
  679.      *
  680.      * @param $hash
  681.      * @return RedirectResponse
  682.      * @throws Exception
  683.      */
  684.     public function syncAction($hash): RedirectResponse
  685.     {
  686.         if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CONS')) {
  687.             $this->orderService->syncOrder($hash);
  688.         }
  689.         return $this->redirect(
  690.             $this->generateUrl('app_buy_order', ['orderId' => $hash], 0)
  691.         );
  692.     }
  693.     /**
  694.      * Переотправка заказа с 1с.
  695.      *
  696.      * @param string $hash
  697.      * @return RedirectResponse
  698.      * @throws Exception
  699.      */
  700.     public function recreateAction(string $hash): RedirectResponse
  701.     {
  702.         if ($this->isGranted('ROLE_ADMIN')
  703.             || $this->isGranted('ROLE_CONS')
  704.         ) {
  705.             $this->orderService->recreateOrderTo1C($hash);
  706.         }
  707.         return $this->redirect(
  708.             $this->generateUrl('app_buy_order', ['orderId' => $hash], 0)
  709.         );
  710.     }
  711.     public function overpaymentAction(Request $requeststring $orderIdbool $type): Response
  712.     {
  713.         $res = new ResponseApiHelper();
  714.         $result $this->orderRefundService->overPayment(
  715.             $orderId,
  716.             $type,
  717.             $request->get('redirect') && !$type ? ['redirect' => 1] : $request->request->all()
  718.         );
  719.         if (!empty($result['err'])) {
  720.             $res->setResponse('res''err');
  721.             $res->setResponse('err'$result['err']);
  722.         } else {
  723.             $res->setResponse('res''ok');
  724.             $res->setResponse('status'$result['status']);
  725.             $res->setResponse('id'$result['id']);
  726.         }
  727.         if ($request->get('redirect') == 1) {
  728.             $params = ['orderId' => $orderId];
  729.             if (isset($result['already'])) {
  730.                 if ($result['already']) {
  731.                     $params['msgVariant'] = $result['status']['id'];
  732.                 } else {
  733.                     $params['showRequisites'] = 1;
  734.                 }
  735.             }
  736.             return new RedirectResponse($this->generateUrl('app_buy_order'$params));
  737.         }
  738.         return $this->json($res->result());
  739.     }
  740.     /**
  741.      * @param string $hash
  742.      * @param string $id
  743.      * @return JsonResponse
  744.      * @throws Exception
  745.      */
  746.     public function emailResendAction(string $hashstring $id): JsonResponse
  747.     {
  748.         $order $this->orderService->getOrderObj($hash);
  749.         $success $this->orderHistoryService->emailResend($order$id);
  750.         return new JsonResponse(['success' => $success]);
  751.     }
  752.     /**
  753.      * Подписка или отписка на статусы заказа
  754.      *
  755.      * @param string $hash
  756.      * @return Response
  757.      * @throws Exception
  758.      */
  759.     public function subscribeOrUnsubscribeToOrderStatusesAction(string $hash): Response
  760.     {
  761.         $order $this->orderService->getOrderObj($hashtrue);
  762.         $newOrderStatus = !$order->getEmailSend();
  763.         $order->setEmailSend($newOrderStatus);
  764.         $this->buyOrderRepository->save($order);
  765.         $orderId $order->getId();
  766.         return $this->renderReact('@Web/Order/subscribe_status.html.twig', [
  767.             'orderId'         => $orderId,
  768.             'subscribeStatus' => $newOrderStatus,
  769.         ]);
  770.     }
  771. }