src/Controller/OrderController.php line 43

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