src/Controller/OrderController.php line 45

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Certificate;
  4. use App\Entity\HistorySend;
  5. use App\Entity\Order;
  6. use App\Entity\OrderItem;
  7. use App\Entity\LifeCycle;
  8. use App\Enums\ResponseStatusEnum;
  9. use App\Form\OrderSearchType;
  10. use App\Form\OrderType;
  11. use App\Repository\CertificateRepository;
  12. use App\Repository\HistorySendRepository;
  13. use App\Repository\LifeCycleRepository;
  14. use App\Repository\OrderRepository;
  15. use App\Repository\WidgetRepository;
  16. use App\Repository\WidgetUserRepository;
  17. use App\Services\Contracts\OrderServiceInterface;
  18. use App\Services\LogService\CertificateLogService;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use Error;
  21. use Exception;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\Routing\Annotation\Route;
  28. use Symfony\Component\Validator\Constraints\Uuid;
  29. use Symfony\Component\Validator\Validation;
  30. use Throwable;
  31. class OrderController extends AbstractController
  32. {
  33. /**
  34. * @param Request $request
  35. * @param OrderRepository $orderRepository
  36. * @param WidgetUserRepository $userRepository
  37. * @param WidgetRepository $widgetRepository
  38. * @return Response
  39. * @Route("/backend/orders/statistics", name="backend_order_statistics")
  40. * @Security("is_granted('ROLE_CLIENT') or is_granted('ROLE_MERCHANT') or is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  41. */
  42. public function statistics(Request $request, OrderRepository $orderRepository, WidgetUserRepository $userRepository, WidgetRepository $widgetRepository): Response
  43. {
  44. $form = $this->createForm('App\Form\StatisticsSearchType');
  45. $form->handleRequest($request);
  46. if (!$this->isGranted('ROLE_SUPERADMINISTRATOR')) {
  47. $user = $userRepository->find($this->getUser()->getId());
  48. $widgets = $user->getAvailableWidgets();
  49. } else {
  50. $widgets = $widgetRepository->findAll();
  51. }
  52. $createView = $form->createView();
  53. if(!empty($createView->children['Widget'])) {
  54. $keys = [];
  55. foreach ($createView->children['Widget']->vars['choices'] as $key => $choice)
  56. foreach ($widgets as $widget)
  57. if ($widget->getId() == $choice->value)
  58. $keys[] = $key;
  59. foreach ($createView->children['Widget']->vars['choices'] as $key => $row)
  60. if (!in_array($key, $keys))
  61. unset($createView->children['Widget']->vars['choices'][$key]);
  62. }
  63. return $this->render('order/statistics.html.twig', [
  64. 'statistics_search' => $createView,
  65. 'orders' => [],
  66. 'orders_count' => 0,
  67. 'amount_orders' => 0,
  68. 'average_check' => '',
  69. 'sales_count' => 0,
  70. 'get_params' => (!empty($_GET['order_search']['columns'])?$_GET['order_search']['columns']:Order::FIELDS),
  71. 'total' => 0,
  72. 'pages' => 0,
  73. 'widgets' => $createView->children['Widget']->vars['choices'],
  74. 'page' => 0,
  75. 'params' => '&'.preg_replace('/(&page|page)=[0-9]/', '', $request->getQueryString())
  76. ]);
  77. }
  78. /**
  79. * @param Request $request
  80. * @param OrderRepository $orderRepository
  81. * @param WidgetUserRepository $userRepository
  82. * @param CertificateRepository $certificateRepository
  83. * @param WidgetRepository $widgetRepository
  84. * @return Response
  85. * @Security("is_granted('ROLE_CLIENT') or is_granted('ROLE_MERCHANT') or is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  86. */
  87. #[Route('/backend/orders/statistics_data', name: "backend_order_statistics_data", methods: ['GET'])]
  88. public function statisticsData(Request $request, OrderRepository $orderRepository, WidgetUserRepository $userRepository, CertificateRepository $certificateRepository, WidgetRepository $widgetRepository): Response
  89. {
  90. $form = $this->createForm('App\Form\StatisticsSearchType');
  91. $form->handleRequest($request);
  92. $user = $userRepository->find($this->getUser()->getId());
  93. $getData = $form->getData();
  94. $getData['paymentStatus'] = ['succeeded'];
  95. $getData['statistics'] = 1;
  96. $result = [];
  97. if($form->isSubmitted() && $form->isValid()) {
  98. $result = $orderRepository->getListFilteredOrders(
  99. $user,
  100. $getData,
  101. $request->get('page', 1));
  102. }
  103. $daysOrders = [];
  104. $ordersCount = $certificationsCount = $ordersSum = $smsCount = $emailCount = $otherCount = $meCount = 0;
  105. $orderItemIds = [];
  106. foreach($result['items'] as $row){
  107. $orderItemIds[] = $row['id'];
  108. $dataItem = [
  109. 'amount' => $row['amount'],
  110. 'quantity' => $row['quantity'],
  111. 'sum' => $row['amount']*$row['quantity'],
  112. 'recipient_type' => $row['recipientType'],
  113. 'delivery_type' => $row['deliveryType']
  114. ];
  115. $daysOrders['orders'][$row['createdAt']->format('Y-m-d')][] = $dataItem;
  116. $ordersCount++;
  117. $otherCount += ($dataItem['recipient_type'] == 'other')?1:0;
  118. $meCount += ($dataItem['recipient_type'] == 'me')?1:0;
  119. $certificationsCount += $dataItem['quantity'] ?? 0;
  120. $ordersSum += $dataItem['sum'] ?? 0;
  121. $smsCount += (isset($dataItem['delivery_type'][0]) && $dataItem['delivery_type'][0] == 'sms')?1:0;
  122. $emailCount += (isset($dataItem['delivery_type'][0]) && $dataItem['delivery_type'][0] == 'email')?1:0;
  123. }
  124. $amountsCount = [];
  125. $nominals = $certificateRepository->getCountNominalsByOrderItemIds($orderItemIds);
  126. foreach($nominals as $nominal){
  127. $amountsCount[$nominal['nominal']] = $nominal['count'];
  128. }
  129. $averageAmount = ($ordersSum && $ordersCount)?($ordersSum/$ordersCount):0;
  130. $daysOrders['data']=[
  131. 'orders_count' => $ordersCount,
  132. 'certifications_count' => $certificationsCount,
  133. 'orders_sum' => $ordersSum,
  134. 'average_amount' => $averageAmount,
  135. 'other_count' => $otherCount,
  136. 'me_count' => $meCount,
  137. 'sms_count' => $smsCount,
  138. 'email_count' => $emailCount,
  139. 'nominals' => $amountsCount
  140. ];
  141. return $this->json($daysOrders);
  142. }
  143. /**
  144. * @param Request $request
  145. * @param OrderRepository $orderRepository
  146. * @param WidgetUserRepository $userRepository
  147. * @param WidgetRepository $widgetRepository
  148. * @param LifeCycleRepository $lifeCycleRepository
  149. * @return Response
  150. * @Route("/backend/orders", name="backend_order_index")
  151. * @Security("is_granted('ROLE_CLIENT') or is_granted('ROLE_MERCHANT') or is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  152. */
  153. public function index(Request $request, OrderRepository $orderRepository, WidgetUserRepository $userRepository, WidgetRepository $widgetRepository, LifeCycleRepository $lifeCycleRepository): Response
  154. {
  155. $form = $this->createForm(OrderSearchType::class);
  156. $form->handleRequest($request);
  157. $user = $userRepository->find($this->getUser()->getId());
  158. $errors = [];
  159. $orderId = $form->get('orderId')->getData();
  160. if (!empty($orderId)) {
  161. $validator = Validation::createValidator();
  162. $uuidConstrain = new Uuid();
  163. $errorUid = $validator->validate($orderId, $uuidConstrain);
  164. if (0 !== count($errorUid)){
  165. $errors['orderId'] = 'Некорректный № заказа Виджета';
  166. $this->addFlash('error', 'Некорректный формат № заказа Виджета');
  167. }
  168. }
  169. if(0 == count($errors) && $form->isSubmitted() && $form->isValid()) {
  170. $result = $orderRepository->getListFilteredOrders(
  171. $user,
  172. $form->getData(),
  173. $request->get('page', 1));
  174. } else {
  175. $result = $orderRepository->getListOrdersByUser(
  176. $user,
  177. $request->get('page', 1)
  178. );
  179. }
  180. if (!$this->isGranted('ROLE_SUPERADMINISTRATOR')) {
  181. $user = $userRepository->find($this->getUser()->getId());
  182. $widgets = $user->getAvailableWidgets();
  183. } else {
  184. $widgets = $widgetRepository->findAll();
  185. }
  186. $createView = $form->createView();
  187. if(!empty($createView->children['Widget'])) {
  188. $keys = [];
  189. foreach ($createView->children['Widget']->vars['choices'] as $key => $choice)
  190. foreach ($widgets as $widget)
  191. if ($widget->getId() == $choice->value)
  192. $keys[] = $key;
  193. foreach ($createView->children['Widget']->vars['choices'] as $key => $row)
  194. if (!in_array($key, $keys))
  195. unset($createView->children['Widget']->vars['choices'][$key]);
  196. }
  197. foreach ($result['items'] as &$item) {
  198. $lifeCycle = $lifeCycleRepository->findOneBy(['order_id' => $item->getId()], ['id' => 'DESC']);
  199. $item->lifeStatus = $lifeCycle ? LifeCycle::STATUS_LIFE[$lifeCycle->getStatus()] : '';
  200. }
  201. return $this->render('order/report.html.twig', [
  202. 'order_search' => $createView,
  203. 'orders' => $result['items'],
  204. 'get_params' => (!empty($_GET['order_search']['columns'])?$_GET['order_search']['columns']:Order::FIELDS),
  205. 'total' => $result['total'],
  206. 'pages' => $result['pages'],
  207. 'page' => $request->get('page', 1),
  208. 'params' => '&'.preg_replace('/(&page|page)=[0-9]/', '', $request->getQueryString())
  209. ]);
  210. }
  211. /**
  212. * @param Request $request
  213. * @param OrderRepository $orderRepository
  214. * @param WidgetUserRepository $userRepository
  215. * @param WidgetRepository $widgetRepository
  216. * @return Response
  217. * @Route("/backend/orders/csv", name="backend_order_csv")
  218. * @Security("is_granted('ROLE_CLIENT') or is_granted('ROLE_MERCHANT') or is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  219. */
  220. public function exportCSV(Request $request, OrderRepository $orderRepository, WidgetUserRepository $userRepository, WidgetRepository $widgetRepository): Response
  221. {
  222. $form = $this->createForm(OrderSearchType::class);
  223. $form->handleRequest($request);
  224. $user = $userRepository->find($this->getUser()->getId());
  225. $pages = 1;
  226. $items = [];
  227. $fields_GET = (!empty($_GET['order_search']['columns'])?$_GET['order_search']['columns']:Order::FIELDS);
  228. foreach(Order::FIELDS as $key => $row){
  229. if(in_array($row, $fields_GET))
  230. $fields[$key] = $row;
  231. }
  232. $i=0;
  233. for ($page = 1; $page <= $pages; $page++) {
  234. if ($form->isSubmitted() && $form->isValid()) {
  235. $result = $orderRepository->getListFilteredOrders(
  236. $user,
  237. $form->getData(),
  238. $request->get('page', $page));
  239. } else {
  240. $result = $orderRepository->getListOrdersByUser(
  241. $user,
  242. $request->get('page', $page)
  243. );
  244. }
  245. $pages = $result['pages'];
  246. if(empty($result['items'])) continue;
  247. /** @var Order $order */
  248. foreach($result['items'] as $order){
  249. foreach($order->getOrderItems() as $item){
  250. foreach($fields as $field){
  251. switch ($field){
  252. case 'widgetName':
  253. $items[$i][$field] = (string) $order->getWidget()->getName();
  254. break;
  255. case 'createdAt':
  256. $items[$i][$field] = $order->getCreatedAt()->format('Y-m-d H:i:s');
  257. break;
  258. case 'updatedAt':
  259. $items[$i][$field] = $order->getUpdatedAt()->format('Y-m-d H:i:s');
  260. break;
  261. case 'recipientType':
  262. $items[$i][$field] = $item->getRecipientType();
  263. break;
  264. case 'deliveryType':
  265. $items[$i][$field] = implode(',', $item->getDeliveryType());
  266. break;
  267. case 'recipientName':
  268. $items[$i][$field] = $item->getRecipientName();
  269. break;
  270. case 'senderName':
  271. $items[$i][$field] = $item->getSenderName();
  272. break;
  273. case 'tiberiumOrderId':
  274. $items[$i][$field] = $item->getTiberiumOrderId();
  275. break;
  276. case 'widgetOrderId':
  277. $items[$i][$field] = $order->getId();
  278. break;
  279. case 'getStatusText':
  280. $items[$i][$field] = $order->getStatusText();
  281. break;
  282. case 'senderEmail':
  283. $items[$i][$field] = $item->getSenderEmail();
  284. break;
  285. case 'recipientEmail':
  286. $items[$i][$field] = $item->getRecipientEmail();
  287. break;
  288. case 'paymentDataId':
  289. $items[$i][$field] = !empty($order->getPaymentData()['id'])?$order->getPaymentData()['id']:'';
  290. break;
  291. case 'quantity':
  292. $items[$i][$field] = $item->getQuantity();
  293. break;
  294. case 'amount':
  295. $items[$i][$field] = $item->getAmount();
  296. break;
  297. case 'summ':
  298. $items[$i][$field] = $item->getAmount()*$item->getQuantity();
  299. break;
  300. }
  301. }
  302. $i++;
  303. }
  304. }
  305. }
  306. $fields = array_flip($fields);
  307. array_unshift($items , $fields);
  308. $fp = fopen('php://temp', 'w');
  309. foreach ($items as $row) {
  310. fputcsv($fp, $row, ';');
  311. }
  312. rewind($fp);
  313. $response = new Response(chr(0xEF).chr(0xBB).chr(0xBF).stream_get_contents($fp));
  314. fclose($fp);
  315. $response->headers->set('Content-Encoding', 'UTF-8');
  316. $response->headers->set('Content-Type', 'application/csv; charset=UTF-8');
  317. $response->headers->set('Content-Disposition', 'attachment; filename="orders_'.date('Y-m-d').'.csv"');
  318. return $response;
  319. }
  320. /**
  321. * @param Request $request
  322. * @param EntityManagerInterface $entityManager
  323. * @param CertificateLogService $certificateService
  324. * @param Order|null $order
  325. * @return Response
  326. * @Route("/backend/order/{id}/edit", name="backend_order_edit")
  327. * @Security("is_granted('ROLE_MERCHANT') or is_granted('ROLE_MANAGER') or is_granted('ROLE_CLIENT')")
  328. */
  329. public function edit(Request $request, EntityManagerInterface $entityManager, CertificateLogService $certificateService, Order $order = null): Response
  330. {
  331. if(null === $order) {
  332. return $this->redirectToRoute('backend_order_index');
  333. }
  334. $form = $this->createForm(OrderType::class, $order);
  335. $form->handleRequest($request);
  336. if($form->isSubmitted() && $form->isValid()) {
  337. $entityManager->persist($order);
  338. $entityManager->flush();
  339. return $this->redirectToRoute('backend_order_edit', ['id' => $request->get('id')]);
  340. }
  341. $certificateGoals = $certificateService->getCertificateGoals($order);
  342. $publicDir = $this->getParameter('aws.site');
  343. return $this->render('order/edit.html.twig', [
  344. 'certificateGoals' => $certificateGoals,
  345. 'order_form' => $form->createView(),
  346. 'order' => $order,
  347. 'public' => $publicDir,
  348. 'cover_dir' => '/' . $order->getWidget()->getHashedId() . $this->getParameter('app.cover_dir'),
  349. 'user_files_dir' => $this->getParameter('app.user_files_dir')
  350. ]);
  351. }
  352. /**
  353. * Переотправить сертификаты и отбивки по заказу
  354. *
  355. * @param OrderServiceInterface $orderService
  356. * @param Order|null $order
  357. * @return Response
  358. * @Route("/order/{id}/send", name="order_send")
  359. * @Security("is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  360. */
  361. public function send(OrderServiceInterface $orderService, Order $order = null): Response
  362. {
  363. if (!$order) {
  364. $response['status'] = ResponseStatusEnum::error;
  365. $response['data'] = 'OrderNotFound';
  366. $response['message'] = 'OrderNotFound';
  367. return $this->json($response, Response::HTTP_NOT_FOUND);
  368. }
  369. try {
  370. $orderService->reSendCertificatesByOrder($order);
  371. } catch (Throwable|Error $e) {
  372. $response['status'] = ResponseStatusEnum::error;
  373. $response['data'] = 'Resend Certificates Error';
  374. $response['message'] = $e->getMessage();
  375. return $this->json($response, Response::HTTP_UNPROCESSABLE_ENTITY);
  376. }
  377. $response['status'] = ResponseStatusEnum::ok;
  378. $response['data'] = null;
  379. $response['message'] = 'Resend Certificates Success';
  380. return $this->json($response);
  381. }
  382. /**
  383. *
  384. *
  385. * @param Request $request
  386. * @param EntityManagerInterface $entityManager
  387. * @param Order|null $order
  388. * @return Response
  389. * @Route("/order/{id}/remove", name="order_remove")
  390. * @Security("is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  391. */
  392. public function remove(OrderServiceInterface $orderService, Request $request, EntityManagerInterface $entityManager, Order $order = null): Response
  393. {
  394. $removeOrderItemId = $request->query->get('order_item_id');
  395. try {
  396. $orderItems = $order->getOrderItems();
  397. $orderService->removeOrderItem($entityManager, $orderItems, $removeOrderItemId);
  398. } catch (Throwable|Error $e) {
  399. $response['status'] = ResponseStatusEnum::error;
  400. $response['data'] = 'Remove orderItem Error';
  401. $response['message'] = $e->getMessage();
  402. return $this->json($response, Response::HTTP_UNPROCESSABLE_ENTITY);
  403. }
  404. $response['status'] = ResponseStatusEnum::ok;
  405. $response['data'] = null;
  406. $response['message'] = 'Remove orderItem Success';
  407. return $this->json($response);
  408. }
  409. /**
  410. * @param Request $request
  411. * @param HistorySendRepository $historySendRepository
  412. * @return Response
  413. * @Route("/backend/order/{id}/history", name="backend_order_history_send")
  414. * @IsGranted("ROLE_SUPERADMINISTRATOR")
  415. */
  416. public function history(Request $request, HistorySendRepository $historySendRepository): Response
  417. {
  418. $result = $historySendRepository->findBy(['order' => $request->get('id')]);
  419. return $this->render('order/history.html.twig', ['history' => $result]);
  420. }
  421. /**
  422. * @Route("/orderItem/{id}/receipt", name="order_get_receipt")
  423. * @Security("is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  424. */
  425. public function getOrderReceipt(OrderItem $orderItem, OrderServiceInterface $orderService): Response
  426. {
  427. try {
  428. $receipt = $orderService->getReceiptLinkByOrderItem($orderItem);
  429. } catch (Exception|Error $e) {
  430. $error = $e->getMessage();
  431. }
  432. return $this->render('order/receipt.html.twig', [
  433. 'orderItem' => $orderItem,
  434. 'error' => $error ?? null,
  435. 'receipt' => $receipt ?? null,
  436. ]);
  437. }
  438. /**
  439. * Пересоздать заказ поставщику (ПЦ)
  440. *
  441. * @Route("/order/{id}/reorder", name="order_reorder")
  442. * @Security("is_granted('ROLE_MANAGER') or is_granted('ROLE_SUPERADMINISTRATOR')")
  443. */
  444. public function reSendOrderToVendor(OrderServiceInterface $orderService, Order $order = null): Response
  445. {
  446. if (!$order) {
  447. $response['status'] = ResponseStatusEnum::error;
  448. $response['data'] = 'OrderNotFound';
  449. $response['message'] = 'OrderNotFound';
  450. return $this->json($response, Response::HTTP_NOT_FOUND);
  451. }
  452. try {
  453. $orderService->reSendOrderToVendor($order);
  454. } catch (Throwable|Error $e) {
  455. $response['status'] = ResponseStatusEnum::error;
  456. $response['data'] = 'Reorder Error';
  457. $response['message'] = $e->getMessage();
  458. return $this->json($response, Response::HTTP_UNPROCESSABLE_ENTITY);
  459. }
  460. $response['status'] = ResponseStatusEnum::ok;
  461. $response['data'] = null;
  462. $response['message'] = 'Reorder Success';
  463. return $this->json($response);
  464. }
  465. }