src/AtechNet/CoreBundle/Controller/DefaultController.php line 85

Open in your IDE?
  1. <?php
  2. namespace App\AtechNet\CoreBundle\Controller;
  3. use App\AtechNet\CoreBundle\AtechNetCoreBundle;
  4. use App\AtechNet\CoreBundle\Entity\Attribute;
  5. use App\AtechNet\CoreBundle\Entity\CategoryPage;
  6. use App\AtechNet\CoreBundle\Entity\CategoryPageFilterAttribute;
  7. use App\AtechNet\CoreBundle\Entity\CategoryPagesPriorityProducts;
  8. use App\AtechNet\CoreBundle\Entity\ClaimMedia;
  9. use App\AtechNet\CoreBundle\Entity\Dashboard;
  10. use App\AtechNet\CoreBundle\Entity\Document;
  11. use App\AtechNet\CoreBundle\Entity\DocumentGroup;
  12. use App\AtechNet\CoreBundle\Entity\Domain;
  13. use App\AtechNet\CoreBundle\Entity\ExternalInvoiceValue;
  14. use App\AtechNet\CoreBundle\Entity\Meal;
  15. use App\AtechNet\CoreBundle\Entity\Photo;
  16. use App\AtechNet\CoreBundle\Entity\Product;
  17. use App\AtechNet\CoreBundle\Entity\ProductTag;
  18. use App\AtechNet\CoreBundle\Entity\ProductType;
  19. use App\AtechNet\CoreBundle\Entity\SeoUrl;
  20. use App\AtechNet\CoreBundle\Entity\StockItem;
  21. use App\AtechNet\CoreBundle\Entity\StockMovement;
  22. use App\AtechNet\CoreBundle\Entity\User;
  23. use App\AtechNet\CoreBundle\Entity\Vendor;
  24. use App\AtechNet\CoreBundle\Form\SettingsType;
  25. use App\AtechNet\CoreBundle\Helper\DeliveryUtil;
  26. use App\AtechNet\CoreBundle\Service\Stock\StockItemService;
  27. use App\AtechNet\CoreBundle\Helper\DigitalOceanSpaces;
  28. use App\AtechNet\CoreBundle\Helper\Furbify\Image;
  29. use App\AtechNet\CoreBundle\Translation\DatabaseTranslator;
  30. use Doctrine\ORM\EntityManager;
  31. use Mpdf\Container\NotFoundException;
  32. use Phinx\Console\PhinxApplication;
  33. use Symfony\Bundle\FrameworkBundle\Console\Application;
  34. use Symfony\Component\Console\Input\ArrayInput;
  35. use Symfony\Component\Console\Input\StringInput;
  36. use Symfony\Component\Console\Output\BufferedOutput;
  37. use Symfony\Component\Form\FormInterface;
  38. use Symfony\Component\HttpFoundation\JsonResponse;
  39. use Symfony\Component\HttpFoundation\RedirectResponse;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\HttpFoundation\Response;
  42. use Symfony\Component\Mime\MimeTypes;
  43. use Symfony\Component\Routing\Annotation\Route;
  44. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  45. use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;
  46. /**
  47. * Default controller.
  48. */
  49. class DefaultController extends BaseController
  50. {
  51. /**
  52. * @return RedirectResponse
  53. */
  54. public function homeAction(): RedirectResponse
  55. {
  56. if (!$this->isGranted('ROLE_ADMIN')) {
  57. return $this->redirectToRoute('atech_net_core_login');
  58. }
  59. return $this->redirectToRoute('atech_net_core_product_all_list');
  60. }
  61. /**
  62. * @param $current_page
  63. * @return Response
  64. */
  65. public function navigationAction($current_page): Response
  66. {
  67. $menuItems = [];
  68. return $this->render('AtechNetCoreBundle/Default/navigation.html.twig', [
  69. 'menuItems' => $menuItems,
  70. 'current_page' => $current_page,
  71. ]);
  72. }
  73. /**
  74. * @Route("/login", name="atech_net_core_login")
  75. * @param AuthenticationUtils $authenticationUtils
  76. * @return Response
  77. */
  78. public function loginAction(AuthenticationUtils $authenticationUtils): Response
  79. {
  80. // get the login error if there is one
  81. $error = $authenticationUtils->getLastAuthenticationError();
  82. // last username entered by the user
  83. $lastUsername = $authenticationUtils->getLastUsername();
  84. return $this->render(
  85. 'AtechNetCoreBundle/Default/page_login.html.twig',
  86. [
  87. 'last_username' => $lastUsername,
  88. 'error' => $error,
  89. ]
  90. );
  91. }
  92. /**
  93. * @Route("/logout", name="atech_net_core_logout", methods={"GET"})
  94. */
  95. public function logout(): void
  96. {
  97. }
  98. /**
  99. * @return Response
  100. */
  101. public function settingsShowAction(): Response
  102. {
  103. return $this->render('AtechNetCoreBundle/Default/page_settings_show.html.twig', [
  104. 'settings' => $this->getSettings(),
  105. 'languages' => AtechNetCoreBundle::$languages,
  106. ]);
  107. }
  108. /**
  109. * @return Response
  110. */
  111. public function settingsEditAction(): Response
  112. {
  113. $settings = $this->getSettings();
  114. $editForm = $this->createEditForm($settings);
  115. return $this->render('AtechNetCoreBundle/Default/page_settings_edit.html.twig', [
  116. 'settings' => $settings,
  117. 'languages' => AtechNetCoreBundle::$languages,
  118. 'edit_form' => $editForm->createView(),
  119. ]);
  120. }
  121. /**
  122. * @param Request $request
  123. * @return RedirectResponse|Response
  124. */
  125. public function settingsUpdateAction(Request $request): RedirectResponse|Response
  126. {
  127. $settings = $this->getSettings();
  128. if (!$settings) {
  129. throw $this->createNotFoundException('Unable to find Settings entity.');
  130. }
  131. $editForm = $this->createEditForm($settings);
  132. $editForm->handleRequest($request);
  133. if ($editForm->isValid()) {
  134. $entityManager = $this->getEntityManager();
  135. $entityManager->persist($settings);
  136. $entityManager->flush();
  137. return $this->redirectToRoute('atech_net_core_settings_show');
  138. }
  139. return $this->render('AtechNetCoreBundle/Default/page_settings_edit.html.twig', [
  140. 'settings' => $settings,
  141. 'languages' => AtechNetCoreBundle::$languages,
  142. 'edit_form' => $editForm->createView(),
  143. ]);
  144. }
  145. /**
  146. * @param $settings
  147. * @return FormInterface
  148. */
  149. private function createEditForm($settings): FormInterface
  150. {
  151. $form = $this->createForm(new SettingsType(), $settings, [
  152. 'action' => $this->generateUrl('atech_net_core_settings_update'),
  153. 'method' => 'POST',
  154. ]);
  155. $form->add('submit', 'submit', [
  156. 'label' => 'admin.save',
  157. 'attr' => [
  158. 'class' => 'action-button',
  159. ],
  160. ]);
  161. return $form;
  162. }
  163. /**
  164. * @Route("/add-variable-to-session", name="atech_net_core_add_variable_to_session")
  165. *
  166. * @param Request $request
  167. * @return Response
  168. */
  169. public function addVariableToSessionAction(Request $request): Response
  170. {
  171. $session = $request->getSession();
  172. $posts = $request->request->all();
  173. if (count($posts) > 0) {
  174. foreach ($posts as $name => $value) {
  175. $session->set($name, $value);
  176. }
  177. }
  178. return new Response('yeah');
  179. }
  180. /**
  181. * @Route("/live-search", name="atech_net_core_live_search")
  182. *
  183. * @param Request $request
  184. * @return JsonResponse
  185. */
  186. public function liveSearchAction(Request $request): JsonResponse
  187. {
  188. $entityCode = $request->request->get('entityCode');
  189. /** @var array $fields */
  190. $fields = $request->request->get('fields', []);
  191. $otherSelects = $request->request->get('otherSelects');
  192. $otherLeftJoins = $request->request->get('otherLeftJoins');
  193. $searchString = trim($request->request->get('searchString'));
  194. $limit = $request->request->get('limit');
  195. $orderBy = $request->request->get('orderBy');
  196. $destPath = $request->request->get('destPath');
  197. $selects = implode(',', $fields);
  198. $selects .= ',' . $entityCode . '.id';
  199. $likes = '';
  200. foreach ($otherSelects as $otherSelect) {
  201. $selects .= ',' . $otherSelect;
  202. $selectSeparated = explode(' ', $otherSelect);
  203. if ($likes == '') {
  204. $likes .= ' ' . $selectSeparated[0] . " LIKE '%" . $searchString . "%' ";
  205. } else {
  206. $likes .= ' OR ' . $selectSeparated[0] . " LIKE '%" . $searchString . "%' ";
  207. }
  208. }
  209. $leftJoins = '';
  210. $addedParameters = [];
  211. foreach ($fields as $field) {
  212. $parameters = explode('.', $field);
  213. if ($parameters[0] != $entityCode && !in_array($parameters[0], $addedParameters)) {
  214. $leftJoins .= ' LEFT JOIN ' . $entityCode . '.' . strtolower($this->getLiveSearchEntityList()[$parameters[0]]) . ' ' . $parameters[0];
  215. $addedParameters[] = $parameters[0];
  216. }
  217. if ($likes == '') {
  218. $likes .= ' ' . $field . " LIKE '%" . $searchString . "%' ";
  219. } else {
  220. $likes .= ' OR ' . $field . " LIKE '%" . $searchString . "%' ";
  221. }
  222. }
  223. if (in_array('c.firstName', $fields) && in_array('c.lastName', $fields)) {
  224. if ($likes == '') {
  225. $likes .= " CONCAT(c.firstName, ' ', c.lastName) LIKE '%" . $searchString . "%' OR CONCAT(c.lastName, ' ', c.firstName) LIKE '%" . $searchString . "%' ";
  226. } else {
  227. $likes .= " OR CONCAT(c.firstName, ' ', c.lastName) LIKE '%" . $searchString . "%' OR CONCAT(c.lastName, ' ', c.firstName) LIKE '%" . $searchString . "%' ";
  228. }
  229. }
  230. foreach ($otherLeftJoins as $otherLeftJoin) {
  231. $leftJoins .= ' LEFT JOIN ' . $otherLeftJoin;
  232. }
  233. $query = 'SELECT ' . $selects . '
  234. FROM AtechNetCoreBundle:' . $this->getLiveSearchEntityList()[$entityCode] . ' ' . $entityCode . '
  235. ' . $leftJoins . '
  236. WHERE ' . $likes . '
  237. ORDER BY ' . $orderBy;
  238. $results = $this->getEntityManager()
  239. ->createQuery($query)
  240. ->setMaxResults($limit)
  241. ->getResult();
  242. foreach ($results as $key => $result) {
  243. $results[$key]['link'] = $this->generateUrl($destPath, [
  244. 'id' => $result['id'],
  245. ]);
  246. }
  247. return (new JsonResponse())->setData([
  248. 'data' => $results,
  249. ]);
  250. }
  251. /**
  252. * @return array
  253. */
  254. protected function getLiveSearchEntityList(): array
  255. {
  256. return [
  257. 'd' => 'Domain',
  258. 'v' => 'Vendor',
  259. 'p' => 'Product',
  260. 'pm' => 'ProductMeta',
  261. 'pc' => 'ProductCommission',
  262. 'c' => 'Customer',
  263. 'o' => 'Order',
  264. 'oi' => 'OrderItem',
  265. 'ioao' => 'OrderItemAttributeOption',
  266. ];
  267. }
  268. /**
  269. * @Route("/auto-complete-search", name="atech_net_core_auto_complete_search")
  270. *
  271. * @param Request $request
  272. * @return JsonResponse
  273. */
  274. public function autoCompleteSearchAction(Request $request): JsonResponse
  275. {
  276. $entityManager = $this->getEntityManager();
  277. $creditNoteOnly = $request->request->getBoolean('creditNoteOnly');
  278. $entityName = trim($request->request->get('entityName'));
  279. $searchFor = trim($request->request->get('searchFor'));
  280. $searchIn = $request->request->get('searchIn');
  281. $searchInIndex = $request->request->get('searchInIndex');
  282. $searchResultsContain = $request->request->get('searchResultsContain');
  283. $searchArchived = $request->request->get('searchArchived');
  284. $groupBy = $request->request->get('groupBy');
  285. $queryLimit = $request->request->get('queryLimit');
  286. $exactMatch = $request->request->getBoolean('exactMatch', false);
  287. $isV2Search = $request->request->getBoolean('isV2Search', false);
  288. if($entityName == 'User') {
  289. $query = "SELECT DISTINCT u.firstName,u.lastName, u.id FROM AtechNetCoreBundle:User u WHERE u.isActive = 1 AND (u.firstName LIKE '%$searchFor%' OR u.lastName LIKE '%$searchFor%')";
  290. $results = $entityManager->createQuery($query)
  291. ->setMaxResults($queryLimit)
  292. ->getResult();
  293. return (new JsonResponse())->setData([
  294. 'data' => $results,
  295. ]);
  296. }
  297. if ($entityName == 'Product') {
  298. $filterOnlyInStock = $request->query->get('filterOnlyInStock');
  299. $filterProductId = $request->query->get('filterProductId');
  300. $filterProductType = $request->request->get('filterProductType');
  301. $filterVendor = $request->request->get('filterVendor');
  302. } else {
  303. $filterOnlyInStock = $filterProductId = $filterProductType = $filterVendor = null;
  304. }
  305. $leftJoin = '';
  306. $where = '1=1';
  307. $searchInFields = $this->parseSearchInColumns($searchIn, 'e.');
  308. $searchInIndexFields = $this->parseSearchInColumns($searchInIndex, 'e.');
  309. if ($entityName == 'Product') {
  310. $selectFields = [
  311. 'e.id', 'e.code', 'pt.title', 'pt.id AS __productTypeId', 'pmpt.title model_product_type',
  312. 'v.name AS vendor', 'pmv.name model_product_vendor', 'e.name',
  313. 'e.cacheDescription', 'e.avgPrice AS __avgPrice',
  314. 'e.scannable AS __scannable', 'pt.scannable AS __typeScannable', 'pmpt.scannable AS __typeScannableModel',
  315. 'e.available', 'e.inStock, pm.isProductV2', 'pm.id AS productModelId',
  316. 'e.sparePartCard AS __sparePartCard', 'e.sparePartPrice AS __sparePartPrice',
  317. ];
  318. $leftJoin = 'LEFT JOIN e.type pt LEFT JOIN e.vendor v ';
  319. //V2
  320. $leftJoin .= 'LEFT JOIN e.productModel pm LEFT JOIN pm.type pmpt LEFT JOIN pm.vendor pmv ';
  321. if ($isV2Search) {
  322. $where .= ' AND pm.isProductV2 = 1 ';
  323. }
  324. if ($creditNoteOnly) {
  325. $leftJoin .= 'LEFT JOIN e.group pg ';
  326. $where .= 'AND pg.id = '. DocumentGroup::TYPE_INVOICE_CREDIT_NOTE . ' ';
  327. }
  328. if (!is_null($searchArchived)) {
  329. if ((int)$searchArchived > -1) {
  330. $where .= " AND e.archived = " . (int)$searchArchived . " AND e.container = 0";
  331. } else {
  332. $where .= " AND e.container = 0";
  333. }
  334. } else {
  335. $where .= " AND e.archived = 0 AND e.container = 0";
  336. }
  337. if ($filterOnlyInStock == 'not-scannable') {
  338. if ((int)$filterProductId > 0) {
  339. $where .= " AND (( e.inStock > 0 OR e.scannable = 1 ) OR e.id = " . (int)$filterProductId . ")";
  340. } else {
  341. $where .= " AND ( e.inStock > 0 OR e.scannable = 1 )";
  342. }
  343. }
  344. if (is_array($filterProductType)) {
  345. $where .= " AND pt.id IN (" . implode(',', array_map(function ($value) {
  346. return (int)$value;
  347. }, $filterProductType)) . ")";
  348. } elseif ((int)$filterProductType > 0) {
  349. $where .= " AND pt.id = " . (int)$filterProductType;
  350. }
  351. if ((int)$filterVendor > 0) {
  352. $where .= " AND v.id = " . (int)$filterVendor;
  353. }
  354. array_push($searchInFields, 'pt.title', 'v.name');
  355. if ($request->request->has('origin') && $request->request->get('origin') == 'statistics-product-sales') {
  356. // Decodes URL-encoded searchFor
  357. $searchFor = urldecode($searchFor);
  358. // Search in selected fields
  359. $whereOr = [];
  360. foreach ($searchInFields as $field) {
  361. $whereOr[] = "$field LIKE '%$searchFor%'";
  362. }
  363. // Search in field combinations
  364. $whereOr[] = "CONCAT(v.name, ' ', pt.title, ' ', e.name) LIKE '%$searchFor%'";
  365. $whereOr[] = "CONCAT(pt.title, ' ', v.name, ' ', e.name) LIKE '%$searchFor%'";
  366. // Search by expressions
  367. $expressions = $hits = [];
  368. // Split search string
  369. $expression = strtok($searchFor, ' ');
  370. while ($expression !== false) {
  371. $_expression = trim($expression);
  372. if (strlen($_expression) == 1) {
  373. $_expression = ' ' . $_expression;
  374. }
  375. $expressions[] = $_expression;
  376. $expression = strtok(' ');
  377. }
  378. if (count($expressions) > 1) {
  379. foreach ($expressions as $expression) {
  380. $hits[] = "( CASE WHEN ( e.name LIKE '%$expression%' OR v.name LIKE '%$expression%' OR pt.title LIKE '%$expression%' ) THEN 1 ELSE 0 END )";
  381. }
  382. $whereOr[] = "( " . implode(' + ', $hits) . " ) >= " . count($expressions);
  383. }
  384. // Add where
  385. $where .= " AND (" . implode(" OR ", $whereOr) . ")";
  386. } else {
  387. $searchWords = $searchInIndex != 'serialNumber' ? explode(' ', $searchFor) : [
  388. 0 => $searchFor,
  389. ];
  390. if (count($searchInFields) > 0) {
  391. $concatedColumns = $this->prepareSearchInColumns($searchInFields);
  392. $searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '%", "%'"); // search all words in the concatenated string
  393. $where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
  394. }
  395. if (count($searchInIndexFields) > 0) {
  396. $concatedColumns = $this->prepareSearchInColumns($searchInIndexFields);
  397. $searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '", "%'"); // search all words in the concatenated string
  398. $where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
  399. }
  400. }
  401. } else {
  402. $selectColumns = explode(',', $searchResultsContain);
  403. if (!in_array('id', $selectColumns)) {
  404. array_unshift($selectColumns, 'id');
  405. }
  406. $selectFields = $this->wrapElements($selectColumns, 'e.');
  407. if ( $entityName == 'Order' && in_array('domain', $selectColumns) ) {
  408. $key = array_search('e.domain', $selectFields);
  409. if ( $key !== false ) {
  410. $selectFields[$key] = 'IDENTITY(e.domain) AS domainId';
  411. }
  412. }
  413. $productId = $request->request->get('productId');
  414. if ($isV2Search && $entityName == 'ProductModel') {
  415. $where .= ' AND e.isProductV2 = 1';
  416. }
  417. if ($entityName == 'StockItem' && $productId != null && $productId != 0 && is_numeric($productId)) {
  418. $leftJoin = 'LEFT JOIN e.movementItems mi LEFT JOIN mi.product p ';
  419. $where .= " AND p.id = " . $productId;
  420. }
  421. if ($entityName == 'Customer') {
  422. $leftJoin = 'LEFT JOIN e.domain d ';
  423. // remove invalid field name if present
  424. $selectColumns = array_filter($selectColumns, fn($col) => $col !== 'currency');
  425. $selectFields = $this->wrapElements($selectColumns, 'e.');
  426. $selectFields[] = "CONCAT('(', d.name, ')') AS domain";
  427. $selectFields[] = "d.currency AS currency";
  428. }
  429. $searchWords = $searchInIndex != 'serialNumber' && !$exactMatch ? explode(' ', $searchFor) : [
  430. 0 => $searchFor,
  431. ];
  432. if (count($searchInFields) > 0) {
  433. if ($exactMatch) {
  434. $concatedColumns = $searchInFields[0];
  435. $where .= " AND (" . "$concatedColumns Like '%" . $searchWords[0]."%'" . ')';
  436. } else {
  437. $concatedColumns = $this->prepareSearchInColumns($searchInFields);
  438. $searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '%", "%'"); // search all words in the concatenated string
  439. $where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
  440. }
  441. }
  442. if (count($searchInIndexFields) > 0) {
  443. $concatedColumns = $this->prepareSearchInColumns($searchInIndexFields);
  444. $searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '", "%'"); // search all words in the concatenated string
  445. $where .= ' AND (' . implode(' AND ', $searchQueries) . ')';
  446. }
  447. }
  448. $querySelect = implode(',', $selectFields);
  449. $query = "SELECT DISTINCT $querySelect FROM AtechNetCoreBundle:$entityName e $leftJoin WHERE $where";
  450. if ($entityName == 'Product' && $groupBy == 'name') {
  451. $query .= " GROUP BY e.name";
  452. }
  453. if ($entityName == 'ProductModel') {
  454. $query .= " ORDER BY e.isProductV2 DESC";
  455. }
  456. $results = $entityManager->createQuery($query)
  457. ->setMaxResults($queryLimit)
  458. ->getResult();
  459. if ($entityName == 'Product') {
  460. foreach ($results as $key =>$result) {
  461. if (is_null($result['title'])) {
  462. $results[$key]['title'] = $result['model_product_type'];
  463. }
  464. if (is_null($result['vendor'])) {
  465. $results[$key]['vendor'] = $result['model_product_vendor'];
  466. }
  467. }
  468. }
  469. if ($entityName == 'StockItem') { // add last stock movement type
  470. $stockItemRepo = $entityManager->getRepository(StockItem::class);
  471. foreach ($results as $key => $result) {
  472. $si = null;
  473. $si = $stockItemRepo->find($result['id']);
  474. if ($si && $si->getLastMovement()) {
  475. $results[$key]['last_stock_movement_type'] = $si->getLastMovement()->getType();
  476. $results[$key]['last_stock_movement_id'] = $si->getLastMovement()->getId();
  477. $results[$key]['lastPrice'] = $si->getLastMovementItem()->getTotalPricePerItem();
  478. $results[$key]['__lastPrice'] = $si->getLastMovementItem()->getPricePerItem(true);
  479. }
  480. /**
  481. * @var StockItem $si
  482. * @var StockMovement $sm
  483. */
  484. foreach ($si->getMovements() as $sm) {
  485. $createDate = $sm->getCreated()->format('YmdHi');
  486. $results[$key]['movements'][$createDate]['id'] = $sm->getId();
  487. $results[$key]['movements'][$createDate]['type'] = $sm->getType();
  488. $results[$key]['movements'][$createDate]['date'] = $createDate;
  489. }
  490. $results[$key]['errorCodes'] = [];
  491. if (isset($si) && !is_null($si)) {
  492. $results[$key]['errorCodes'] = $this->errorCodesToErrorText($si->getErrorCodes());
  493. }
  494. $lastMovementItem = $si->getLastMovementItem();
  495. if ($lastMovementItem !== null) {
  496. $results[$key]['quality'] = StockItemService::determineQuality($lastMovementItem->getProduct()->getQualityStatus());
  497. }
  498. }
  499. }
  500. return (new JsonResponse())->setData([
  501. 'data' => $results,
  502. ]);
  503. }
  504. /**
  505. * @Route("/auto-complete-search-coupon", name="atech_net_core_auto_complete_search_coupon")
  506. *
  507. * @param Request $request
  508. * @return JsonResponse
  509. */
  510. public function autoCompleteSearchCouponAction(Request $request): JsonResponse
  511. {
  512. $entityManager = $this->getEntityManager();
  513. $searchFilterCoupon = $request->request->get('filterCoupon');
  514. $results = $entityManager->createQuery("SELECT c.code
  515. FROM AtechNetCoreBundle:Coupon c
  516. Where c.code Like '%" . $searchFilterCoupon . "%'
  517. Group by c.code")
  518. ->getResult();
  519. return (new JsonResponse())->setData([
  520. 'data' => $results,
  521. ]);
  522. }
  523. /**
  524. * @param $searchInStr
  525. * @param $prefix
  526. * @return array
  527. */
  528. private function parseSearchInColumns($searchInStr, $prefix)
  529. {
  530. $searchInStr = trim($searchInStr != null ? $searchInStr : "");
  531. if ($searchInStr != "") {
  532. return $this->wrapElements(explode(',', $searchInStr), $prefix);
  533. } else {
  534. return [];
  535. }
  536. }
  537. /**
  538. * @param array $searchInField
  539. * @return array|mixed|string
  540. */
  541. private function prepareSearchInColumns(array $searchInField)
  542. {
  543. $count = count($searchInField);
  544. if ($count > 1) {
  545. $searchInFieldsWrapped = $this->wrapElements($searchInField, "COALESCE(", ",' ')"); // fix for null values
  546. return 'CONCAT(' . implode(', \' \',', $searchInFieldsWrapped) . ')'; // concatenate columns into 1 string
  547. } elseif ($count == 1) {
  548. return $searchInField[0];
  549. } else {
  550. return [];
  551. }
  552. }
  553. /**
  554. * @Route("/auto-complete-product", name="atech_net_core_auto_complete_product")
  555. *
  556. * @param Request $request
  557. * @return JsonResponse
  558. */
  559. public function autoCompleteProductAction(Request $request): JsonResponse
  560. {
  561. $entityManager = $this->getEntityManager();
  562. $searchInFields = ['e.code', 'e.name', 'pt.title', 'v.name'];
  563. $searchInFieldsWrapped = $this->wrapElements($searchInFields, "COALESCE(", ",' ')"); // fix for null values
  564. $concatedColumns = 'CONCAT(' . implode(',', $searchInFieldsWrapped) . ')'; // concatenate columns into 1 string
  565. $searchFor = $request->query->get('term');
  566. $searchWords = explode(' ', $searchFor);
  567. $searchQueries = $this->wrapElements($searchWords, "$concatedColumns LIKE '%", "%'"); // search all words in the concatenated string
  568. $query = "SELECT DISTINCT e.id, e.code, pt.title, pt.id AS typeId, v.name AS vendor, e.name, e.cacheDescription, e.scannable AS scannable, pt.scannable AS typeScannable, e.inStock, e.available
  569. FROM AtechNetCoreBundle:Product e LEFT JOIN e.type pt LEFT JOIN e.vendor v WHERE e.archived = 0 AND e.container = 0 AND (" . implode(' AND ', $searchQueries) . ")";
  570. $results = $entityManager->createQuery($query)
  571. ->setMaxResults(10)
  572. ->getResult();
  573. if (count($results) > 0) {
  574. $productIds = array_column($results, 'id');
  575. $metaResults = $entityManager->createQuery("SELECT m, PARTIAL p.{id}, PARTIAL d.{id} FROM AtechNetCoreBundle:ProductMeta m
  576. JOIN m.product p JOIN m.domain d WHERE p.id IN (:prodIds)")
  577. ->setParameter("prodIds", $productIds)
  578. ->getScalarResult();
  579. $metas = [];
  580. foreach ($metaResults as $key => $mr) {
  581. $prodId = $mr['p_id'];
  582. $domainId = $mr['d_id'];
  583. $metas[$prodId][$domainId]['price'] = $mr['m_price'];
  584. $metas[$prodId][$domainId]['discount'] = $mr['m_discount'];
  585. }
  586. foreach ($results as $key => $result) {
  587. $prodId = $result['id'];
  588. $results[$key]['metas'] = $metas[$prodId];
  589. }
  590. }
  591. return new JsonResponse($results);
  592. }
  593. /**
  594. * @Route("/auto-complete-product-tag", name="atech_net_core_auto_complete_product_tag")
  595. *
  596. * @param Request $request
  597. * @return JsonResponse
  598. */
  599. public function autoCompleteProductTagAction(Request $request): JsonResponse
  600. {
  601. $entityManager = $this->getEntityManager();
  602. $searchInFields = ['productTag.title'];
  603. $searchInFieldsWrapped = $this->wrapElements($searchInFields, "COALESCE(", ",' ')"); // fix for null values
  604. $concatedColumns = 'CONCAT(' . implode(',', $searchInFieldsWrapped) . ')'; // concatenate columns into 1 string
  605. $searchFor = $request->query->get('term');
  606. $searchWords = explode(' ', $searchFor);
  607. $searchQueries = $this->wrapElements($searchWords, "productTag.title LIKE '%", "%'"); // search all words in the concatenated string
  608. $query = "SELECT DISTINCT productTag.id, productTag.title
  609. FROM AtechNetCoreBundle:ProductTag productTag
  610. WHERE (" . implode(' AND ', $searchQueries) . ")";
  611. $results = $entityManager->createQuery($query)
  612. ->setMaxResults(10)
  613. ->getResult();
  614. return new JsonResponse($results);
  615. }
  616. /**
  617. * @param $arr
  618. * @param $prefix
  619. * @param string $suffix
  620. * @return array
  621. */
  622. private function wrapElements($arr, $prefix, string $suffix = ''): array
  623. {
  624. $result = [];
  625. foreach ($arr as $e) {
  626. $result[] = $prefix . str_replace("'", "", $e) . $suffix;
  627. }
  628. return $result;
  629. }
  630. /**
  631. * @Route("/clear-cache", name="atech_net_core_clear_cache")
  632. *
  633. * @return Response
  634. */
  635. public function clearCacheAction(): Response
  636. {
  637. ini_set("memory_limit", '1000M');
  638. $application = new Application($this->kernel);
  639. $application->setAutoExit(false);
  640. $input = new StringInput('cache:clear --env=prod');
  641. $output = new BufferedOutput();
  642. $resultCode = $application->run($input, $output);
  643. $response = $output->fetch();
  644. return new Response('Result code: ' . $resultCode . '<br/><code>' . nl2br($response) . '</code>');
  645. }
  646. /**
  647. * @Route("/create-stock-movement/{id}", name="atech_net_core_create_stock_movement")
  648. *
  649. * @param int $id
  650. * @return Response
  651. * @throws \Exception
  652. */
  653. public function createStockMovementFromOrderAction(int $id): Response
  654. {
  655. $application = new Application($this->kernel);
  656. $application->setAutoExit(false);
  657. $input = new ArrayInput([
  658. 'command' => 'centralis:create-stock-movement-from-domain',
  659. 'orderId' => $id,
  660. '--env' => $this->kernel->getEnvironment(),
  661. ]);
  662. $output = new BufferedOutput();
  663. $application->run($input, $output);
  664. return new Response($output->fetch());
  665. }
  666. /**
  667. * @Route("/create-controlling-product-list", name="create_controlling_product_list")
  668. *
  669. * @return Response
  670. * @throws \Exception
  671. */
  672. public function createControllingProductListAction(): Response
  673. {
  674. $application = new Application($this->kernel);
  675. $application->setAutoExit(false);
  676. $input = new ArrayInput([
  677. 'command' => 'centralis:export-product-list-for-controlling',
  678. '--env' => $this->kernel->getEnvironment(),
  679. ]);
  680. $output = new BufferedOutput();
  681. $application->run($input, $output);
  682. return new Response($output->fetch());
  683. }
  684. /**
  685. * @Route("/migrate-db", name="atech_net_core_migrate_db")
  686. *
  687. * @param Request $request
  688. * @return Response
  689. * @throws \Exception
  690. */
  691. public function migrateDbAction(Request $request): Response
  692. {
  693. $phinx = new PhinxApplication();
  694. $phinx->setAutoExit(false);
  695. $input = new ArrayInput([
  696. 'command' => 'migrate',
  697. '-c' => $this->getParameter('kernel.project_dir') . '/phinx.yml',
  698. '-e' => $this->kernel->getEnvironment(),
  699. ]);
  700. $output = new BufferedOutput();
  701. $phinx->run($input, $output);
  702. $output = preg_replace('/^.+\n/', '', $output->fetch());
  703. if (!empty($request->headers->get('User-Agent'))
  704. && strstr($request->headers->get('User-Agent'), 'curl') === false
  705. ) {
  706. $output = nl2br($output);
  707. }
  708. return new Response($output);
  709. }
  710. /**
  711. * @Route("/check-scannable-products", name="atech_net_core_check_scannable_products")
  712. *
  713. * @param Request $request
  714. * @return JsonResponse
  715. */
  716. public function checkScannedProductsAction(Request $request): JsonResponse
  717. {
  718. $productsRepo = $this->getEntityManager()->getRepository(Product::class);
  719. $products = $request->request->get('products');
  720. foreach ($products as $key => $prodId) {
  721. $product = $productsRepo->find($prodId);
  722. if (!$product) {
  723. unset($products[$key]);
  724. }
  725. if (!$product->isScannable() || !$product->getType()->isScannable()) {
  726. unset($products[$key]);
  727. }
  728. }
  729. return (new JsonResponse())->setData([
  730. 'data' => $products,
  731. ]);
  732. }
  733. /**
  734. * @Route("/export-vat-values", name="export_vat_values")
  735. *
  736. * @throws \Exception
  737. */
  738. public function exportVatValuesAction(): Response
  739. {
  740. $data = [];
  741. $entityManager = $this->getEntityManager();
  742. $documents = $entityManager->createQuery("SELECT PARTIAL d.{id,code,vat,createdDate,chargeabilityDate,group,totalPrice,totalVatPrice,updatedByTime,relatedDocument,externalNumber},
  743. PARTIAL dg.{id,title,type,prefix,language}
  744. FROM AtechNetCoreBundle:Document d
  745. LEFT JOIN d.group dg
  746. WHERE dg.type = :invoiceIn OR dg.type = :invoiceOut OR dg.type = :creditNote
  747. ORDER BY dg.prefix ASC, d.code DESC")
  748. ->setParameters([
  749. 'invoiceIn' => DocumentGroup::TYPE_INVOICE_IN,
  750. 'invoiceOut' => DocumentGroup::TYPE_INVOICE_OUT,
  751. 'creditNote' => DocumentGroup::TYPE_INVOICE_CREDIT_NOTE,
  752. ])
  753. ->getResult();
  754. $documentGroups = $entityManager->createQuery("SELECT dg
  755. FROM AtechNetCoreBundle:DocumentGroup dg
  756. WHERE dg.type = :invoiceIn OR dg.type = :invoiceOut OR dg.type = :creditNote")
  757. ->setParameters([
  758. 'invoiceIn' => DocumentGroup::TYPE_INVOICE_IN,
  759. 'invoiceOut' => DocumentGroup::TYPE_INVOICE_OUT,
  760. 'creditNote' => DocumentGroup::TYPE_INVOICE_CREDIT_NOTE,
  761. ])
  762. ->getResult();
  763. $dataSum = [];
  764. $exchangeRateService = $this->getHistoricalEuroRate();
  765. foreach ($documents as $doc) {
  766. if ($doc->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_IN) {
  767. $year = $doc->getCreatedDate()->format('Y');
  768. $yearShort = $doc->getCreatedDate()->format('y');
  769. $month = $doc->getCreatedDate()->format('m');
  770. } else {
  771. $year = $doc->getChargeabilityDate()->format('Y');
  772. $yearShort = $doc->getChargeabilityDate()->format('y');
  773. $month = $doc->getChargeabilityDate()->format('m');
  774. }
  775. switch ($doc->getGroup()->getLanguage()) {
  776. case 'SK':
  777. case 'EN':
  778. $currency = 'EUR';
  779. break;
  780. case 'HU':
  781. $currency = 'HUF';
  782. break;
  783. case 'CZ':
  784. $currency = 'CZK';
  785. break;
  786. default:
  787. $currency = 'EUR';
  788. }
  789. switch ($doc->getGroup()->getType()) {
  790. case DocumentGroup::TYPE_INVOICE_IN:
  791. case DocumentGroup::TYPE_INVOICE_CREDIT_NOTE:
  792. $negative = true;
  793. break;
  794. case DocumentGroup::TYPE_INVOICE_OUT:
  795. $negative = false;
  796. break;
  797. }
  798. $vatValue = $doc->getTotalVatPrice() - $doc->getTotalPrice();
  799. /**
  800. * @var Document $doc
  801. */
  802. if ($doc->getGroup()->getPrefix() == '30') {
  803. $documentCode = $doc->getExternalNumber();
  804. } else {
  805. $documentCode = $doc->getCode();
  806. }
  807. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['code'] = $documentCode;
  808. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['vat'] = $doc->getVat();
  809. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['vatValue'] = $negative ? -$vatValue : $vatValue;
  810. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['eurValue'] = 0;
  811. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['currency'] = $currency;
  812. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['updated'] = $doc->getUpdatedByTime();
  813. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['updatedLater'] = $doc->getUpdatedByTime()->format('Y-m') != $year . '-' . $month ? true : false;
  814. if (!isset($dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort])) {
  815. $dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['currency'] = $currency;
  816. $dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['value'] = 0;
  817. $dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['eurValue'] = 0;
  818. $dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['groupTitle'] = $doc->getGroup()->getTitle();
  819. }
  820. $dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['value'] += $negative ? -$vatValue : $vatValue;
  821. if ($currency != 'EUR' && $vatValue != 0) {
  822. $exchangeRate = 1;
  823. if ($currency != '') {
  824. if ($doc->getExchangeRate() == 0) {
  825. if ($doc->getGroup()->getType() == DocumentGroup::TYPE_INVOICE_CREDIT_NOTE && !is_null($doc->getRelatedDocument())) {
  826. $date1DayBefore = $doc->getRelatedDocument()->getCreatedDate()->format('Y-m-d');
  827. } else {
  828. $date1DayBefore = $doc->getCreatedDate()->sub(new \DateInterval('P1D'))->format('Y-m-d');
  829. }
  830. $exchangeRate = $exchangeRateService->getRate($currency, $date1DayBefore);
  831. } else {
  832. $exchangeRate = $doc->getExchangeRate();
  833. }
  834. }
  835. $eurValue = number_format($vatValue / $exchangeRate, 2, '.', '');
  836. $data[$year . '-' . $month][$doc->getGroup()->getPrefix()][$doc->getCode()]['eurValue'] = $negative ? -$eurValue : $eurValue;
  837. $dataSum[$year . '-' . $month][$doc->getGroup()->getPrefix() . $yearShort]['eurValue'] += $negative ? -$eurValue : $eurValue;
  838. }
  839. }
  840. $externalInvoiceValues = $entityManager->getRepository(ExternalInvoiceValue::class)->findAll();
  841. $extInvVTypes = ExternalInvoiceValue::getTypeChoices();
  842. foreach ($externalInvoiceValues as $extInvV) {
  843. foreach ($extInvVTypes as $extInvVType) {
  844. $groupCode = $extInvVType . $extInvV->getTargetDate()->format('Y');
  845. $dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['groupTitle'] = $groupCode;
  846. $dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['eurValue'] = 0;
  847. $dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['currency'] = 'EUR';
  848. $dataSum[$extInvV->getTargetDate()->format('Y') . '-' . $extInvV->getTargetDate()->format('m')][$groupCode]['value'] = $extInvV->{'getValue' . $extInvVType}();
  849. }
  850. }
  851. /**
  852. * @var DocumentGroup $dg
  853. */
  854. foreach ($dataSum as $sumDate => $dt) {
  855. $sumDateYear = substr($sumDate, 0, 4);
  856. foreach ($documentGroups as $dg) {
  857. $year = $dg->getYear()->getYear();
  858. if ($year != $sumDateYear) {
  859. continue;
  860. }
  861. $shortYear = substr($year, -2);
  862. if (!isset($dt[$dg->getPrefix() . $shortYear])) {
  863. $dataSum[$sumDate][$dg->getPrefix() . $shortYear]['groupTitle'] = $dg->getTitle();
  864. $dataSum[$sumDate][$dg->getPrefix() . $shortYear]['eurValue'] = 0;
  865. $dataSum[$sumDate][$dg->getPrefix() . $shortYear]['currency'] = 'EUR';
  866. $dataSum[$sumDate][$dg->getPrefix() . $shortYear]['value'] = 0;
  867. }
  868. }
  869. foreach ($extInvVTypes as $extInvVType) {
  870. if (!isset($dt[$extInvVType . $sumDateYear])) {
  871. $dataSum[$sumDate][$extInvVType . $sumDateYear]['groupTitle'] = $extInvVType . $sumDateYear;
  872. $dataSum[$sumDate][$extInvVType . $sumDateYear]['eurValue'] = 0;
  873. $dataSum[$sumDate][$extInvVType . $sumDateYear]['currency'] = 'EUR';
  874. $dataSum[$sumDate][$extInvVType . $sumDateYear]['value'] = 0;
  875. }
  876. }
  877. }
  878. foreach ($dataSum as $key => $date) {
  879. ksort($date);
  880. $dataSum[$key] = $date;
  881. }
  882. krsort($data);
  883. return $this->render('AtechNetCoreBundle/Default/vatValues.html.twig', [
  884. 'data' => $data,
  885. 'dataSum' => $dataSum,
  886. ]);
  887. }
  888. /**
  889. * @Route("/links", name="atech_net_core_links")
  890. *
  891. * @return Response
  892. */
  893. public function linksAction(): Response
  894. {
  895. return $this->render('AtechNetCoreBundle/Default/links.html.twig', []);
  896. }
  897. /**
  898. * @Route("/deliveryData", name="atech_net_core_delivery_data")
  899. *
  900. * @param Request $request
  901. * @return JsonResponse
  902. */
  903. public function deliveryDataAction(Request $request): JsonResponse
  904. {
  905. try {
  906. $domainId = $request->get('domainId');
  907. if ($domainId == null || trim($domainId) == '') {
  908. return new JsonResponse([
  909. 'error' => 'Empty domainId',
  910. ]);
  911. }
  912. return new JsonResponse([
  913. 'deliveryDates' => DeliveryUtil::getAvailableDeliveryDates($domainId),
  914. 'holidays' => DeliveryUtil::getHolidays($domainId),
  915. ]);
  916. } catch (\Exception $exception) {
  917. return new JsonResponse([
  918. 'error' => $exception->getMessage(),
  919. ]);
  920. }
  921. }
  922. /**
  923. * @Route("/sales-goal", name="sales_goal")
  924. *
  925. * @param Breadcrumbs $breadcrumbs
  926. * @return Response
  927. */
  928. public function salesGoalAction(Breadcrumbs $breadcrumbs): Response
  929. {
  930. $this->getBreadcrumbs($breadcrumbs)->addItem('Sales goal');
  931. $dashboardRepo = $this->getEntityManager()->getRepository(Dashboard::class);
  932. $goal = 100000;
  933. $data = $dashboardRepo->getSalesStatistics($goal);
  934. return $this->render('AtechNetCoreBundle/Default/sales-goal.html.twig', [
  935. 'data' => $data,
  936. ]);
  937. }
  938. /**
  939. * @Route("/discount-rss/{domainId}", name="atech_net_core_discount_rss")
  940. *
  941. * @param int $domainId
  942. * @return Response
  943. * @throws \Exception
  944. */
  945. public function discountRssAction(int $domainId): Response
  946. {
  947. /** @var EntityManager $entityManager */
  948. $entityManager = $this->getEntityManager();
  949. $domain = $entityManager->getRepository(Domain::class)->find($domainId);
  950. $language = $domain->getLanguage();
  951. $discountedProducts = $entityManager->createQuery('SELECT p FROM AtechNetCoreBundle:Product p
  952. LEFT JOIN p.metas pm
  953. LEFT JOIN p.type pt
  954. WHERE p.available > 0 AND pm.product = p AND pm.domain = ' . $domainId . ' AND pm.discount > 0 AND pm.discounted = 1 AND pm.active = 1 AND pm.listed = 1 AND pm.orderable = 1 AND (pt.id = 60 OR pt.id = 52 OR pt.id = 44)
  955. ORDER BY pm.discount ASC')
  956. ->getResult();
  957. $translator = new DatabaseTranslator($entityManager, $domainId);
  958. if ($domain->getLanguage()->getCode() == 'hu') {
  959. $oldPriceTxt = 'Eredeti ár:';
  960. } else {
  961. $oldPriceTxt = 'Pôvodná cena:';
  962. }
  963. $rss = '<?xml version="1.0" encoding="UTF-8" ?>
  964. <rss version="2.0">';
  965. foreach ($discountedProducts as $dp) {
  966. if ($domainId == 5) {
  967. $pageName = $dp->getPageFileName($translator);
  968. $link = $domain->getUrl() . '/eshop/' . $pageName;
  969. } else {
  970. $query = 'product_id=' . $dp->getId();
  971. $url = $entityManager->getRepository(SeoUrl::class)->findOneBy([
  972. 'query' => $query,
  973. 'language' => $language,
  974. ]);
  975. $link = 'https://www.furbify.' . $language->getCode() . '/';
  976. if ($url) {
  977. $link .= $url->getKeyword();
  978. } else {
  979. $link .= $query;
  980. }
  981. }
  982. $utm = '?utm_source=ActiveCampaign&utm_medium=email&utm_campaign=autofeed';
  983. $pm = $dp->getDomainMeta($domain);
  984. if ($dp->getAlbum()->getPhotos()->count() > 0) {
  985. $image = $dp->getAlbum()->getPhotos()->first()->getCdnUrl('ProductViewPop');
  986. $rss .= '<channel>
  987. <title>' . $dp->getVendor()->getName() . ' ' . $dp->getName() . '</title>
  988. <link>' . $link . '</link>
  989. <description>' . $dp->getDescription() . '</description>
  990. <item>
  991. <title>' . $dp->getVendor()->getName() . ' ' . $dp->getName() . '</title>
  992. <link><![CDATA[' . $link . $utm . ']]></link>
  993. <description>' . $dp->getDescription() . '</description>
  994. <price>' . $domain->createVatPrice($pm->getDiscount()) . ' ' . $domain->getCurrency() . '</price>
  995. <old_price>' . $oldPriceTxt . ' ' . $domain->createVatPrice($pm->getPrice()) . ' ' . $domain->getCurrency() . '</old_price>
  996. <image>
  997. <url>' . $image . '</url>
  998. </image>
  999. </item>
  1000. </channel>';
  1001. }
  1002. }
  1003. $rss .= '</rss>';
  1004. $response = new Response($rss);
  1005. $response->headers->set('Content-Type', 'rss+xml');
  1006. return $response;
  1007. }
  1008. /**
  1009. * @Route("/automatization", name="atech_net_core_automatizations")
  1010. *
  1011. * @param Breadcrumbs $breadcrumbs
  1012. * @return Response
  1013. */
  1014. public function automatizationAction(Breadcrumbs $breadcrumbs): Response
  1015. {
  1016. $this->hasPermission(User::PERMISSION_AUTOMATIZATIONS, User::MODULE_OTHER);
  1017. $this->getBreadcrumbs($breadcrumbs)->addItem('Automatizations');
  1018. $data = [
  1019. [
  1020. 'time' => 'Every day at 00:01',
  1021. 'command' => 'update-document-status',
  1022. 'title' => 'Update document status',
  1023. 'desc' => '',
  1024. ],
  1025. [
  1026. 'time' => 'Every day at 23:50',
  1027. 'command' => 'create-stock-status-snapshot',
  1028. 'title' => 'Create stock status snapshot',
  1029. 'desc' => '',
  1030. ],
  1031. [
  1032. 'time' => 'Every day at 23:55',
  1033. 'command' => 'create-commitment-receivable-snapshot',
  1034. 'title' => 'Create commitment receivable snapshot',
  1035. 'desc' => '',
  1036. ],
  1037. [
  1038. 'time' => 'Every day at 00:30',
  1039. 'command' => 'update-exchange-rate-files',
  1040. 'title' => 'Update exchange rate files',
  1041. 'desc' => '',
  1042. ],
  1043. [
  1044. 'time' => 'Every day at 15:00',
  1045. 'command' => 'notify-past-due-date',
  1046. 'title' => 'Notify past due date',
  1047. 'desc' => '',
  1048. ],
  1049. [
  1050. 'time' => 'Every day at 21:55',
  1051. 'command' => 'create-out-invoice-for-achu',
  1052. 'title' => 'Create out invoice for AC HU',
  1053. 'desc' => '',
  1054. ],
  1055. [
  1056. 'time' => 'Every Saturday at 23:30',
  1057. 'command' => 'archive-products',
  1058. 'title' => 'Archive products',
  1059. 'desc' => '',
  1060. ],
  1061. [
  1062. 'time' => 'Every day at 23:40',
  1063. 'command' => 'convert-shipment-config-change-create',
  1064. 'title' => 'Convert shipment config change create',
  1065. 'desc' => '',
  1066. ],
  1067. [
  1068. 'time' => 'Every day at 23:45',
  1069. 'command' => 'create-in-stock-day-stats',
  1070. 'title' => 'Create in stock day stats',
  1071. 'desc' => '',
  1072. ],
  1073. [
  1074. 'time' => 'Every day at 23:46',
  1075. 'command' => 'create-quality-status-stats',
  1076. 'title' => 'Create quality status stats',
  1077. 'desc' => '',
  1078. ],
  1079. [
  1080. 'time' => 'Every day at 08:30 (0), 09:00 (1), 09:30 (2), 07:45 (3), 09:20 (5)',
  1081. 'command' => 'remind-meal-group',
  1082. 'title' => 'Remind meal group',
  1083. 'desc' => 'Arg = meal group id',
  1084. ],
  1085. [
  1086. 'time' => 'At 14:00 on Sunday',
  1087. 'command' => 'remind-about-next-week-absences',
  1088. 'title' => 'Remind about next week absences',
  1089. 'desc' => '',
  1090. ],
  1091. [
  1092. 'time' => 'Every hour at :00',
  1093. 'command' => 'service-manager-sync',
  1094. 'title' => 'Service manager sync',
  1095. 'desc' => '',
  1096. ],
  1097. [
  1098. 'time' => 'Every weekday at 20:00, 22:00',
  1099. 'command' => 'set-ready-to-ship-orders-to-completed',
  1100. 'title' => 'Set ready to ship orders to completed',
  1101. 'desc' => '',
  1102. ],
  1103. [
  1104. 'time' => 'Every weekday at 19:00, 21:00',
  1105. 'command' => 'finalize-marketplace-orders',
  1106. 'title' => 'Finalize marketplace orders',
  1107. 'desc' => '',
  1108. ],
  1109. [
  1110. 'time' => 'Every day at 04:00',
  1111. 'command' => 'arukereso-feed',
  1112. 'title' => 'Arukereso.hu XML feed update',
  1113. 'desc' => '',
  1114. ],
  1115. [
  1116. 'time' => 'Every day at 04:01',
  1117. 'command' => 'argep-feed',
  1118. 'title' => 'Argep.hu XML feed update',
  1119. 'desc' => '',
  1120. ],
  1121. [
  1122. 'time' => 'Every day at 23:40',
  1123. 'command' => 'import-gls-pickup-points',
  1124. 'title' => 'Import GLS pickup points',
  1125. 'desc' => '',
  1126. ],
  1127. [
  1128. 'time' => 'Every hour at :00',
  1129. 'command' => 'update-timed-sale-product-states',
  1130. 'title' => 'Update timed sale product states',
  1131. 'desc' => '',
  1132. ],
  1133. [
  1134. 'time' => 'Every day at 07:30, 10:00, 12:00, 15:00, 16:30 (1), 07:46 (2), 07:47 (3)',
  1135. 'command' => 'remind-unfinished-stock-movements',
  1136. 'title' => 'Remind unfinished stock movements',
  1137. 'desc' => 'Arg = reminder level',
  1138. ],
  1139. [
  1140. 'time' => 'Every day at 23:51',
  1141. 'command' => 'create-daily-product-statistics',
  1142. 'title' => 'Create daily product statistics',
  1143. 'desc' => '',
  1144. ],
  1145. [
  1146. 'time' => 'Every day at 23:52',
  1147. 'command' => 'update-stock-movements-exchange-rates',
  1148. 'title' => 'Update stock movements exchange rates',
  1149. 'desc' => '',
  1150. ],
  1151. [
  1152. 'time' => 'Every weekday 06:05–17:05 hourly; weekend at 08:05',
  1153. 'command' => 'export-in-production-products',
  1154. 'title' => 'Export in production products',
  1155. 'desc' => '',
  1156. ],
  1157. [
  1158. 'time' => '1st of month at 10:00 (2), 12:00 (3)',
  1159. 'command' => 'export-furbify-not-paid-documents',
  1160. 'title' => 'Export Furbify not paid documents',
  1161. 'desc' => 'Arg = company',
  1162. ],
  1163. [
  1164. 'time' => 'Every hour at :30',
  1165. 'command' => 'price-monitor-notification',
  1166. 'title' => 'Price monitor notification',
  1167. 'desc' => '',
  1168. ],
  1169. [
  1170. 'time' => '1st of month at 00:05',
  1171. 'command' => 'create-in-invoice-from-hu',
  1172. 'title' => 'Create in invoice from HU',
  1173. 'desc' => '',
  1174. ],
  1175. [
  1176. 'time' => 'Every day at :05 and :35 between 05:00–21:00',
  1177. 'command' => 'update-product-positions',
  1178. 'title' => 'Update product positions',
  1179. 'desc' => '',
  1180. ],
  1181. [
  1182. 'time' => 'Every day at 22:50',
  1183. 'command' => 'create-old-stock-items-snapshot',
  1184. 'title' => 'Create old stock items snapshot',
  1185. 'desc' => '',
  1186. ],
  1187. [
  1188. 'time' => 'Every day at 05:xx, 15:xx and 06:xx, 16:xx (staggered per domain)',
  1189. 'command' => 'generate-cache-for-domain',
  1190. 'title' => 'Generate cache for domain',
  1191. 'desc' => 'RT_SK, WS_SK, RT_HU, WS_HU, RT_CZ, WS_CZ, RT_EU, WS_EU',
  1192. ],
  1193. [
  1194. 'time' => '1st of month at 00:05',
  1195. 'command' => 'export-incoming-cards-table',
  1196. 'title' => 'Export incoming cards table',
  1197. 'desc' => '',
  1198. ],
  1199. [
  1200. 'time' => 'Every day at :10 of 07, 09, 11, 13, 15, 16, 17',
  1201. 'command' => 'repair-order-stock-movement-exchange-rate',
  1202. 'title' => 'Repair order stock movement exchange rate',
  1203. 'desc' => '',
  1204. ],
  1205. [
  1206. 'time' => 'Every day at 20:02',
  1207. 'command' => 'update-price-monitor-connected-orders',
  1208. 'title' => 'Update price monitor connected orders',
  1209. 'desc' => '',
  1210. ],
  1211. [
  1212. 'time' => 'Every 15 minutes (:02, :17, :32, :47)',
  1213. 'command' => 'import-marketplace-orders',
  1214. 'title' => 'Import marketplace orders',
  1215. 'desc' => '',
  1216. ],
  1217. [
  1218. 'time' => 'Every 15 minutes (:08, :23, :38, :53)',
  1219. 'command' => 'check-canceled-marketplace-orders',
  1220. 'title' => 'Check canceled marketplace orders',
  1221. 'desc' => '',
  1222. ],
  1223. [
  1224. 'time' => 'Every day at 20:05',
  1225. 'command' => 'repair-product-last-and-averages-prices',
  1226. 'title' => 'Repair product last and average prices',
  1227. 'desc' => '',
  1228. ],
  1229. [
  1230. 'time' => 'Every minute during hour 00 and 15',
  1231. 'command' => 'chown -R www-data:www-data var/cache',
  1232. 'title' => 'Fix cache ownership',
  1233. 'desc' => 'System command (not a console command)',
  1234. ],
  1235. [
  1236. 'time' => 'Every day at 22:20',
  1237. 'command' => 'update-products-with-over-limit-stock-movements',
  1238. 'title' => 'Update products with over limit stock movements',
  1239. 'desc' => '',
  1240. ],
  1241. [
  1242. 'time' => 'Every day at 22:10',
  1243. 'command' => 'export-orders-to-controlling-db',
  1244. 'title' => 'Export orders to controlling DB',
  1245. 'desc' => '',
  1246. ],
  1247. [
  1248. 'time' => 'Every day at 03:40',
  1249. 'command' => 'correction-job-create',
  1250. 'title' => 'Correction job create',
  1251. 'desc' => '',
  1252. ],
  1253. [
  1254. 'time' => 'Every day at 17:00',
  1255. 'command' => 'export-sales-manager-orders-for-controlling',
  1256. 'title' => 'Export sales manager orders for controlling',
  1257. 'desc' => '',
  1258. ],
  1259. [
  1260. 'time' => 'Every weekday at 09:00',
  1261. 'command' => 'notify-for-low-available-stock',
  1262. 'title' => 'Notify for low available stock',
  1263. 'desc' => '',
  1264. ],
  1265. [
  1266. 'time' => 'Every day at 22:59, 02:59, 11:59',
  1267. 'command' => 'update-backmarket-pbh-tracking-and-confirm-order',
  1268. 'title' => 'Update Backmarket PBH tracking and confirm order',
  1269. 'desc' => '',
  1270. ],
  1271. [
  1272. 'time' => 'Every day at 20:10',
  1273. 'command' => 'notify-for-finished-backmarket-orders-with-manually-created-shipment',
  1274. 'title' => 'Notify for finished Backmarket orders with manual shipment',
  1275. 'desc' => '',
  1276. ],
  1277. [
  1278. 'time' => 'Every day at 20:12',
  1279. 'command' => 'export-invoices-to-pastpay',
  1280. 'title' => 'Export invoices to PastPay',
  1281. 'desc' => '',
  1282. ],
  1283. [
  1284. 'time' => 'Every hour at :02',
  1285. 'command' => 'create-order-product-changelog',
  1286. 'title' => 'Create order product changelog',
  1287. 'desc' => '',
  1288. ],
  1289. [
  1290. 'time' => 'Every day at 20:17',
  1291. 'command' => 'update-product-sold-during-timeframe',
  1292. 'title' => 'Update product sold during timeframe',
  1293. 'desc' => '',
  1294. ],
  1295. [
  1296. 'time' => 'Every day at 21:13',
  1297. 'command' => 'create-attributes',
  1298. 'title' => 'Create attributes',
  1299. 'desc' => '',
  1300. ],
  1301. [
  1302. 'time' => 'Every 15 minutes (:04, :19, :34, :49)',
  1303. 'command' => 'check-prepare-and-run-marketplace-jobs',
  1304. 'title' => 'Check, prepare and run marketplace jobs',
  1305. 'desc' => '',
  1306. ],
  1307. [
  1308. 'time' => 'Every 15 minutes (:12, :27, :42, :57)',
  1309. 'command' => 'check-price-change-jobs',
  1310. 'title' => 'Check price change jobs',
  1311. 'desc' => '',
  1312. ],
  1313. [
  1314. 'time' => 'Every day at 19:55',
  1315. 'command' => 'b2c-credit-note-send',
  1316. 'title' => 'B2C credit note send',
  1317. 'desc' => '',
  1318. ],
  1319. [
  1320. 'time' => 'Every day at 20:14',
  1321. 'command' => 'check-category-pages-with-product-tags',
  1322. 'title' => 'Check category pages with product tags',
  1323. 'desc' => '',
  1324. ],
  1325. [
  1326. 'time' => 'Every weekday, every 15 minutes (:09, :24, :39, :54)',
  1327. 'command' => 'finalize-refurbed-orders',
  1328. 'title' => 'Finalize Refurbed orders',
  1329. 'desc' => '',
  1330. ],
  1331. [
  1332. 'time' => 'Every 2 hours at :10',
  1333. 'command' => 'update-bnpl-orders-status-after-certain-time',
  1334. 'title' => 'Update BNPL orders status after certain time',
  1335. 'desc' => '',
  1336. ],
  1337. [
  1338. 'time' => 'Every hour at :30',
  1339. 'command' => 'import-vub-transactions',
  1340. 'title' => 'Import VUB transactions',
  1341. 'desc' => '',
  1342. ],
  1343. [
  1344. 'time' => 'Every 15 minutes (:09, :24, :39, :54)',
  1345. 'command' => 'sync-unas-stock-from-centralis',
  1346. 'title' => 'Sync UNAS stock from Centralis',
  1347. 'desc' => '',
  1348. ],
  1349. [
  1350. 'time' => 'Every day at 03:15',
  1351. 'command' => 'sync-unas-from-centralis',
  1352. 'title' => 'Sync UNAS from Centralis',
  1353. 'desc' => '',
  1354. ],
  1355. [
  1356. 'time' => 'Every day at 01:30',
  1357. 'command' => 'product-listing-stats',
  1358. 'title' => 'Product listing stats',
  1359. 'desc' => '',
  1360. ],
  1361. [
  1362. 'time' => 'Every 15 minutes',
  1363. 'command' => 'create-pre-invoice-for-rt-ws',
  1364. 'title' => 'Create pre invoice for RT/WS',
  1365. 'desc' => 'Runs as www-data',
  1366. ],
  1367. [
  1368. 'time' => 'Every 15 minutes',
  1369. 'command' => 'check-credit-note-stock-movement-prices',
  1370. 'title' => 'Check credit note stock movement prices',
  1371. 'desc' => 'Runs as www-data',
  1372. ],
  1373. [
  1374. 'time' => 'Every day at 20:20',
  1375. 'command' => 'sync-centralis-customer-with-daktela',
  1376. 'title' => 'Sync Centralis customer with Daktela',
  1377. 'desc' => 'Runs as www-data',
  1378. ],
  1379. [
  1380. 'time' => 'Every day at 20:30',
  1381. 'command' => 'stock-position-stats',
  1382. 'title' => 'Stock position stats',
  1383. 'desc' => 'Runs as www-data',
  1384. ],
  1385. [
  1386. 'time' => 'Every 5 minutes',
  1387. 'command' => 'create-order-invoices',
  1388. 'title' => 'Create order invoices',
  1389. 'desc' => '',
  1390. ],
  1391. [
  1392. 'time' => 'Every day at 16:05',
  1393. 'command' => 'update-carrier-setting',
  1394. 'title' => 'Update carrier setting',
  1395. 'desc' => '',
  1396. ],
  1397. [
  1398. 'time' => 'Every day at 08:00, 20:00',
  1399. 'command' => 'check_not_paid_orders_klaviyo',
  1400. 'title' => 'Check not paid orders Klaviyo',
  1401. 'desc' => '',
  1402. ],
  1403. [
  1404. 'time' => 'Every 15 minutes',
  1405. 'command' => 'send-shipment-change-notifications',
  1406. 'title' => 'Send shipment change notifications',
  1407. 'desc' => '',
  1408. ],
  1409. [
  1410. 'time' => 'Every day at 21:10',
  1411. 'command' => 'fix-illegal-stock-movements',
  1412. 'title' => 'Fix illegal stock movements',
  1413. 'desc' => '',
  1414. ],
  1415. [
  1416. 'time' => 'Every day at 21:10',
  1417. 'command' => 'update-customer-order-dates',
  1418. 'title' => 'Update customer order dates',
  1419. 'desc' => '',
  1420. ],
  1421. [
  1422. 'time' => 'Every hour at :00',
  1423. 'command' => 'messenger:consume async --time-limit=3600',
  1424. 'title' => 'Consume async messages',
  1425. 'desc' => '',
  1426. ],
  1427. [
  1428. 'time' => 'Every day at 00:05',
  1429. 'command' => 'create-daily-order-snapshot',
  1430. 'title' => 'Create daily order snapshot',
  1431. 'desc' => '',
  1432. ],
  1433. [
  1434. 'time' => 'Every weekday at 09:15 (0), 09:30 (1), 09:45 (2)',
  1435. 'command' => 'remind-shipment-payment',
  1436. 'title' => 'Remind shipment payment',
  1437. 'desc' => 'Arg = reminder level',
  1438. ],
  1439. ];
  1440. return $this->render('AtechNetCoreBundle/Default/automatization.html.twig', [
  1441. 'data' => $data,
  1442. ]);
  1443. }
  1444. /**
  1445. * @Route("/product-type-search", name="product_type_search")
  1446. *
  1447. * @param Request $request
  1448. * @return JsonResponse
  1449. */
  1450. public function productTypeSearchAction(Request $request): JsonResponse
  1451. {
  1452. $searchQuery = $request->query->get('term');
  1453. $results = $this->getEntityManager()->createQuery("SELECT pt.id, pt.title
  1454. FROM AtechNetCoreBundle:ProductType pt
  1455. WHERE pt.title LIKE '%" . $searchQuery . "%'
  1456. ORDER BY pt.title ASC")
  1457. ->setMaxResults(10)
  1458. ->getResult()
  1459. ;
  1460. return new JsonResponse($results);
  1461. }
  1462. /**
  1463. * @Route("/add-product-type-to-category", name="add_product_type_to_category")
  1464. *
  1465. * @param Request $request
  1466. * @return JsonResponse
  1467. */
  1468. public function addProductTypeToCategoryAction(Request $request): JsonResponse
  1469. {
  1470. $entityManager = $this->getEntityManager();
  1471. $categoryId = $request->request->get('categoryId');
  1472. $productTypeId = $request->request->get('productTypeId');
  1473. $result = 'error';
  1474. /**
  1475. * @var CategoryPage $category
  1476. */
  1477. if (is_numeric($categoryId) && is_numeric($productTypeId)) {
  1478. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1479. $productType = $entityManager->getRepository(ProductType::class)->find($productTypeId);
  1480. if ($category && $productType) {
  1481. $category->addProductType($productType);
  1482. $entityManager->persist($category);
  1483. $entityManager->flush();
  1484. $result = 'success';
  1485. }
  1486. }
  1487. return new JsonResponse([
  1488. 'response' => $result,
  1489. ]);
  1490. }
  1491. /**
  1492. * @Route("/remove-product-type-to-category", name="remove_product_type_to_category")
  1493. *
  1494. * @param Request $request
  1495. * @return JsonResponse
  1496. */
  1497. public function removeProductTypeToCategoryAction(Request $request): JsonResponse
  1498. {
  1499. $entityManager = $this->getEntityManager();
  1500. $categoryId = $request->request->get('categoryId');
  1501. $productTypeId = $request->request->get('productTypeId');
  1502. $result = 'error';
  1503. /**
  1504. * @var CategoryPage $category
  1505. */
  1506. if (is_numeric($categoryId) && is_numeric($productTypeId)) {
  1507. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1508. $productType = $entityManager->getRepository(ProductType::class)->find($productTypeId);
  1509. if ($category && $productType) {
  1510. $category->removeProductType($productType);
  1511. $entityManager->persist($category);
  1512. $entityManager->flush();
  1513. $result = 'success';
  1514. }
  1515. }
  1516. return new JsonResponse([
  1517. 'response' => $result,
  1518. ]);
  1519. }
  1520. /**
  1521. * @Route("/product-search", name="product_search")
  1522. *
  1523. * @param Request $request
  1524. * @return JsonResponse
  1525. */
  1526. public function productSearchAction(Request $request): JsonResponse
  1527. {
  1528. $searchQuery = $request->query->get('term');
  1529. $results = $this->getEntityManager()->createQuery("SELECT p.id, p.code, p.name
  1530. FROM AtechNetCoreBundle:Product p
  1531. WHERE p.code LIKE '%" . $searchQuery . "%' OR p.name LIKE '%" . $searchQuery . "%'")
  1532. ->setMaxResults(5)
  1533. ->getResult();
  1534. return new JsonResponse($results);
  1535. }
  1536. /**
  1537. * @Route("/add-product-to-category", name="add_product_to_category")
  1538. *
  1539. * @param Request $request
  1540. * @return JsonResponse
  1541. */
  1542. public function addProductToCategoryAction(Request $request): JsonResponse
  1543. {
  1544. $categoryId = (int)$request->request->get('categoryId');
  1545. $productId = (int)$request->request->get('productId');
  1546. return new JsonResponse([
  1547. 'response' => $this->processProductToCategory(false, CategoryPage::PRODUCT_TYPE_NORMAL, $categoryId, $productId),
  1548. ]);
  1549. }
  1550. /**
  1551. * @Route("/add-priority-product-to-category", name="add_priority_product_to_category")
  1552. *
  1553. * @param Request $request
  1554. * @return JsonResponse
  1555. */
  1556. public function addPriorityProductToCategoryAction(Request $request): JsonResponse
  1557. {
  1558. $categoryId = (int)$request->request->get('categoryId');
  1559. $productId = (int)$request->request->get('productId');
  1560. return new JsonResponse([
  1561. 'response' => $this->processProductToCategory(false, CategoryPage::PRODUCT_TYPE_PRIORITY, $categoryId, $productId),
  1562. ]);
  1563. }
  1564. /**
  1565. * @Route("/add-popular-product-to-category", name="add_popular_product_to_category")
  1566. *
  1567. * @param Request $request
  1568. * @return JsonResponse
  1569. */
  1570. public function addPopularProductToCategoryAction(Request $request): JsonResponse
  1571. {
  1572. $categoryId = (int)$request->request->get('categoryId');
  1573. $productId = (int)$request->request->get('productId');
  1574. return new JsonResponse([
  1575. 'response' => $this->processProductToCategory(false, CategoryPage::PRODUCT_TYPE_POPULAR, $categoryId, $productId),
  1576. ]);
  1577. }
  1578. /**
  1579. * @Route("/remove-product-to-category", name="remove_product_to_category")
  1580. *
  1581. * @param Request $request
  1582. * @return JsonResponse
  1583. */
  1584. public function removeProductToCategoryAction(Request $request): JsonResponse
  1585. {
  1586. $categoryId = (int)$request->request->get('categoryId');
  1587. $productId = (int)$request->request->get('productId');
  1588. return new JsonResponse([
  1589. 'response' => $this->processProductToCategory(true, CategoryPage::PRODUCT_TYPE_NORMAL, $categoryId, $productId),
  1590. ]);
  1591. }
  1592. /**
  1593. * @Route("/remove-priority-product-to-category", name="remove_priority_product_to_category")
  1594. *
  1595. * @param Request $request
  1596. * @return JsonResponse
  1597. */
  1598. public function removePriorityProductToCategoryAction(Request $request): JsonResponse
  1599. {
  1600. $categoryId = (int)$request->request->get('categoryId');
  1601. $productId = (int)$request->request->get('productId');
  1602. return new JsonResponse([
  1603. 'response' => $this->processProductToCategory(true, CategoryPage::PRODUCT_TYPE_PRIORITY, $categoryId, $productId),
  1604. ]);
  1605. }
  1606. /**
  1607. * @Route("/remove-popular-product-from-category", name="remove_popular_product_from_category")
  1608. *
  1609. * @param Request $request
  1610. * @return JsonResponse
  1611. */
  1612. public function removePopularProductFromCategoryAction(Request $request): JsonResponse
  1613. {
  1614. $categoryId = (int)$request->request->get('categoryId');
  1615. $productId = (int)$request->request->get('productId');
  1616. return new JsonResponse([
  1617. 'response' => $this->processProductToCategory(true, CategoryPage::PRODUCT_TYPE_POPULAR, $categoryId, $productId),
  1618. ]);
  1619. }
  1620. /**
  1621. * @param bool $remove
  1622. * @param int $type
  1623. * @param int $categoryId
  1624. * @param int $productId
  1625. * @return string
  1626. */
  1627. private function processProductToCategory(bool $remove, int $type, int $categoryId, int $productId): string
  1628. {
  1629. $entityManager = $this->getEntityManager();
  1630. $result = 'error';
  1631. /**
  1632. * @var CategoryPage $category
  1633. */
  1634. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1635. $product = $entityManager->getRepository(Product::class)->find($productId);
  1636. if ($category && $product) {
  1637. if ($type == CategoryPage::PRODUCT_TYPE_POPULAR) {
  1638. if ($remove) {
  1639. $category->removePopularProduct($product);
  1640. } else {
  1641. $category->addPopularProduct($product);
  1642. }
  1643. } elseif ($type == CategoryPage::PRODUCT_TYPE_NORMAL) {
  1644. if ($remove) {
  1645. $category->removeProduct($product);
  1646. } else {
  1647. $category->addProduct($product);
  1648. }
  1649. } elseif ($type == CategoryPage::PRODUCT_TYPE_PRIORITY) {
  1650. if ($remove) {
  1651. $this->removePriorityProduct($category, $product);
  1652. } else {
  1653. $this->addPriorityProduct($category, $product);
  1654. }
  1655. }
  1656. $entityManager->persist($category);
  1657. $entityManager->flush();
  1658. $result = 'success';
  1659. }
  1660. return $result;
  1661. }
  1662. /**
  1663. * @param CategoryPage $category
  1664. * @param Product $product
  1665. * @return void
  1666. */
  1667. private function removePriorityProduct(CategoryPage $category, Product $product): void
  1668. {
  1669. $entityManager = $this->getEntityManager();
  1670. $entity = $entityManager->getRepository(CategoryPagesPriorityProducts::class)->findOneBy([
  1671. 'categoryPage' => $category,
  1672. 'product' => $product,
  1673. ]);
  1674. if ($entity) {
  1675. $entityManager->remove($entity);
  1676. $entityManager->flush();
  1677. }
  1678. }
  1679. /**
  1680. * @param CategoryPage $category
  1681. * @param Product $product
  1682. * @return void
  1683. */
  1684. private function addPriorityProduct(CategoryPage $category, Product $product): void
  1685. {
  1686. $entityManager = $this->getEntityManager();
  1687. $categoryPagePriorityProduct = new CategoryPagesPriorityProducts();
  1688. $categoryPagePriorityProduct->setCategoryPage($category);
  1689. $categoryPagePriorityProduct->setProduct($product);
  1690. $lastKnownSortIndex = $entityManager->getRepository(CategoryPage::class)
  1691. ->getLastSortIndexForPriorityProducts($category);
  1692. $categoryPagePriorityProduct->setSortIndex($lastKnownSortIndex + 1);
  1693. $entityManager->persist($categoryPagePriorityProduct);
  1694. $entityManager->flush();
  1695. }
  1696. /**
  1697. * @Route("/remove-all-connected-product-from-category", name="remove_all_connected_product_from_category")
  1698. *
  1699. * @param Request $request
  1700. * @return JsonResponse
  1701. */
  1702. public function removeAllProductFromCategoryAction(Request $request): JsonResponse
  1703. {
  1704. $categoryId = (int)$request->request->get('categoryId');
  1705. $type = (int)$request->request->get('type');
  1706. $entityManager = $this->getEntityManager();
  1707. /**
  1708. * @var CategoryPage $category
  1709. */
  1710. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1711. if (!$category) {
  1712. return new JsonResponse([
  1713. 'response' => 'error',
  1714. ]);
  1715. }
  1716. $productsToRemove = [
  1717. CategoryPage::PRODUCT_TYPE_NORMAL => $category->getProducts(),
  1718. CategoryPage::PRODUCT_TYPE_POPULAR => $category->getPopularProducts(),
  1719. ];
  1720. if ($type == CategoryPage::PRODUCT_TYPE_PRIORITY) {
  1721. $allPriorityProducts = $entityManager->getRepository(CategoryPagesPriorityProducts::class)->findBy([
  1722. 'categoryPage' => $category,
  1723. ]);
  1724. foreach ($allPriorityProducts as $priorityProduct) {
  1725. $entityManager->remove($priorityProduct);
  1726. }
  1727. $entityManager->flush();
  1728. $result = 'success';
  1729. return new JsonResponse([
  1730. 'response' => $result,
  1731. ]);
  1732. }
  1733. foreach ($productsToRemove[$type] as $product) {
  1734. if ($type == CategoryPage::PRODUCT_TYPE_POPULAR) {
  1735. $category->removePopularProduct($product);
  1736. } elseif ($type == CategoryPage::PRODUCT_TYPE_NORMAL) {
  1737. $category->removeProduct($product);
  1738. }
  1739. $entityManager->persist($category);
  1740. }
  1741. $entityManager->flush();
  1742. $result = 'success';
  1743. return new JsonResponse([
  1744. 'response' => $result,
  1745. ]);
  1746. }
  1747. /**
  1748. * @Route("/add-clipboard-products-to-category", name="add_products_from_clipboard_to_category")
  1749. *
  1750. * @param Request $request
  1751. * @return JsonResponse
  1752. */
  1753. public function addClipboardProductsToCategoryAction(Request $request): JsonResponse
  1754. {
  1755. $entityManager = $this->getEntityManager();
  1756. $categoryId = $request->request->get('categoryId');
  1757. /** @var array $pastedCodes */
  1758. $pastedCodes = $request->request->get('pastedCodes', []);
  1759. $type = $request->request->get('type');
  1760. $productsAdded = $notFoundCodes = [];
  1761. /**
  1762. * @var CategoryPage $category
  1763. */
  1764. if (is_numeric($categoryId) && count($pastedCodes) > 0 && is_numeric($type)) {
  1765. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1766. $products = $entityManager->getRepository(Product::class)
  1767. ->createQueryBuilder('p')
  1768. ->where('p.code IN (:codes)')
  1769. ->setParameter('codes', $pastedCodes)
  1770. ->getQuery()
  1771. ->getResult();
  1772. if ($category) {
  1773. if ($type == CategoryPage::PRODUCT_TYPE_NORMAL) {
  1774. /**
  1775. * @var Product $product
  1776. */
  1777. foreach ($products as $key => $product) {
  1778. if (($removableKey = array_search($product->getCode(), $pastedCodes)) !== false) {
  1779. unset($pastedCodes[$removableKey]);
  1780. }
  1781. $category->addProduct($product);
  1782. $entityManager->persist($category);
  1783. $entityManager->flush();
  1784. $productsAdded[] = [
  1785. 'id' => $product->getId(),
  1786. 'code' => $product->getCode(),
  1787. 'name' => $product->getName(),
  1788. ];
  1789. }
  1790. } elseif ($type == CategoryPage::PRODUCT_TYPE_PRIORITY) {
  1791. foreach ($products as $key => $product) {
  1792. if (($removableKey = array_search($product->getCode(), $pastedCodes)) !== false) {
  1793. unset($pastedCodes[$removableKey]);
  1794. }
  1795. $priorityProduct = new CategoryPagesPriorityProducts();
  1796. $priorityProduct->setCategoryPage($category);
  1797. $priorityProduct->setProduct($product);
  1798. $priorityProduct->setSortIndex($key);
  1799. $entityManager->persist($priorityProduct);
  1800. $entityManager->flush();
  1801. $productsAdded[] = [
  1802. 'id' => $product->getId(),
  1803. 'code' => $product->getCode(),
  1804. 'name' => $product->getName(),
  1805. ];
  1806. }
  1807. }
  1808. }
  1809. #$notFoundCodes = $pastedCodes;
  1810. }
  1811. $response = [
  1812. 'productsAdded' => $productsAdded,
  1813. 'notFoundCodes' => $notFoundCodes,
  1814. ];
  1815. return new JsonResponse([
  1816. 'response' => $response,
  1817. ]);
  1818. }
  1819. /**
  1820. * @Route("/add-products/category-page/from/product-tag", name="add_products_from_product_tag_to_category")
  1821. *
  1822. * @param Request $request
  1823. *
  1824. * @return JsonResponse
  1825. */
  1826. public function addProductsToCategoryPageFromProductTag(Request $request): JsonResponse
  1827. {
  1828. $categoryId = $request->request->get('categoryId');
  1829. $productTagId = $request->request->get('productTagId');
  1830. if (!is_numeric($categoryId) || !is_numeric($productTagId)) {
  1831. return new JsonResponse([
  1832. 'success' => 'false',
  1833. ]);
  1834. }
  1835. $entityManager = $this->getEntityManager();
  1836. $categoryPage = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1837. $productTag = $entityManager->getRepository(ProductTag::class)->find($productTagId);
  1838. if (!$categoryPage || !$productTag) {
  1839. return new JsonResponse([
  1840. 'success' => 'false',
  1841. ]);
  1842. }
  1843. $categoryPage->addProductTag($productTag);
  1844. /** @var Product $product */
  1845. foreach ($productTag->getProducts() as $product) {
  1846. $categoryPage->addProduct($product);
  1847. }
  1848. $entityManager->flush();
  1849. return new JsonResponse([
  1850. 'success' => 'true',
  1851. ]);
  1852. }
  1853. /**
  1854. * @Route("/remove-product-tag/remove-tag-products", name="remove_product_tag_remove_tag_products")
  1855. *
  1856. * @param Request $request
  1857. *
  1858. * @return JsonResponse
  1859. */
  1860. public function removeProductsToCategoryPageFromProductTag(Request $request): JsonResponse
  1861. {
  1862. $categoryId = $request->request->get('categoryId');
  1863. $productTagId = $request->request->get('productTagId');
  1864. if (!is_numeric($categoryId) || !is_numeric($productTagId)) {
  1865. return new JsonResponse([
  1866. 'success' => 'false',
  1867. ]);
  1868. }
  1869. $entityManager = $this->getEntityManager();
  1870. /**
  1871. * @var CategoryPage|null $categoryPage
  1872. * @var ProductTag|null $productTag
  1873. */
  1874. $categoryPage = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1875. $productTag = $entityManager->getRepository(ProductTag::class)->find($productTagId);
  1876. if (!$categoryPage || !$productTag) {
  1877. return new JsonResponse([
  1878. 'success' => 'false',
  1879. ]);
  1880. }
  1881. //Remove tag from the category page
  1882. $categoryPage->removeProductTag($productTag);
  1883. //Remove all product tage products from the category page
  1884. foreach ($productTag->getProducts() as $product) {
  1885. $categoryPage->removeProduct($product);
  1886. }
  1887. $entityManager->flush();
  1888. return new JsonResponse([
  1889. 'success' => 'true',
  1890. ]);
  1891. }
  1892. /**
  1893. * @Route("/category-page/priority-products/sort", name="category_page_priority_products_sort")
  1894. *
  1895. * @param Request $request
  1896. * @return void
  1897. */
  1898. public function updatePriorityProductsSortIndexAjaxAction(Request $request): JsonResponse
  1899. {
  1900. $categoryId = $request->request->get('categoryId');
  1901. $order = $request->request->get('order');
  1902. if (!is_numeric($categoryId) || !is_array($order)) {
  1903. return new JsonResponse([
  1904. 'error' => 'Invalid data provided',
  1905. ], 400);
  1906. }
  1907. $entityManager = $this->getEntityManager();
  1908. /**
  1909. * @var CategoryPage $categoryPage
  1910. */
  1911. $categoryPage = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1912. if (is_null($categoryPage)) {
  1913. return new JsonResponse([
  1914. 'error' => 'Category not found',
  1915. ], 404);
  1916. }
  1917. foreach ($order as $sortIndex => $productId) {
  1918. $categoryPagePriorityProduct = $categoryPage->getPriorityProducts()->findFirst(function ($key, $entity) use ($productId) {
  1919. return $entity->getProduct()->getId() == $productId;
  1920. });
  1921. if ($categoryPagePriorityProduct) {
  1922. $categoryPagePriorityProduct->setSortIndex($sortIndex);
  1923. }
  1924. }
  1925. $entityManager->flush();
  1926. return new JsonResponse([
  1927. 'success' => 'Order updated successfully',
  1928. ]);
  1929. }
  1930. /**
  1931. * @Route("/category-page-search", name="category_search")
  1932. *
  1933. * @param Request $request
  1934. * @return JsonResponse
  1935. */
  1936. public function categorySearchAction(Request $request): JsonResponse
  1937. {
  1938. $searchQuery = $request->query->get('term');
  1939. $results = $this->getEntityManager()->createQuery("SELECT cp.id, d.shortTitle AS domainTitle, pm.title
  1940. FROM AtechNetCoreBundle:PageMeta pm
  1941. INNER JOIN pm.categoryPage cp
  1942. INNER JOIN cp.domain d
  1943. WHERE pm.title LIKE '%$searchQuery%' OR cp.id = '$searchQuery'")
  1944. ->setMaxResults(10)
  1945. ->getResult();
  1946. $entityManager = $this->getEntityManager();
  1947. $categoryPageRepo = $entityManager->getRepository(CategoryPage::class);
  1948. /**
  1949. * @var CategoryPage $categoryPage
  1950. */
  1951. foreach ($results as $key => $result) {
  1952. $categoryPage = $categoryPageRepo->find($result['id']);
  1953. /**
  1954. * @var CategoryPageFilterAttribute $filterAttribute
  1955. */
  1956. foreach ($categoryPage->getFilterAttributes() as $filterAttribute) {
  1957. $results[$key]['filterList'][] = $filterAttribute->getAttribute()->getTitle();
  1958. }
  1959. }
  1960. return new JsonResponse($results);
  1961. }
  1962. /**
  1963. * @Route("/vendor_search-search", name="vendor_search")
  1964. *
  1965. * @param Request $request
  1966. * @return JsonResponse
  1967. *
  1968. * FOR SEARCHING VENDORS TO PRODUCT CATEGORY
  1969. */
  1970. public function vendorSearchAction(Request $request): JsonResponse
  1971. {
  1972. $searchQuery = $request->query->get('term');
  1973. $results = $this->getEntityManager()->createQuery("SELECT v.id, v.name
  1974. FROM AtechNetCoreBundle:Vendor v
  1975. WHERE v.name LIKE '%" . $searchQuery . "%'")
  1976. ->setMaxResults(5)
  1977. ->getResult();
  1978. return new JsonResponse($results);
  1979. }
  1980. /**
  1981. * @Route("/add-vendor-to-category", name="add_vendor_to_category")
  1982. *
  1983. * @param Request $request
  1984. * @return JsonResponse
  1985. *
  1986. * FOR ADDING VENDORS TO PRODUCT CATEGORY
  1987. */
  1988. public function addVendorToCategoryAction(Request $request): JsonResponse
  1989. {
  1990. $entityManager = $this->getEntityManager();
  1991. $categoryId = $request->request->get('categoryId');
  1992. $vendorId = $request->request->get('vendorId');
  1993. $result = 'error';
  1994. /**
  1995. * @var CategoryPage $category
  1996. */
  1997. if (is_numeric($categoryId) && is_numeric($vendorId)) {
  1998. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  1999. $vendor = $entityManager->getRepository(Vendor::class)->find($vendorId);
  2000. if ($category && $vendor) {
  2001. $category->addVendor($vendor);
  2002. $entityManager->persist($category);
  2003. $entityManager->flush();
  2004. $result = 'success';
  2005. }
  2006. }
  2007. return new JsonResponse([
  2008. 'response' => $result,
  2009. ]);
  2010. }
  2011. /**
  2012. * @Route("/remove-vendor-to-category", name="remove_vendor_to_category")
  2013. *
  2014. * @param Request $request
  2015. * @return JsonResponse
  2016. *
  2017. * FOR REMOVING VENDORS TO PRODUCT CATEGORY
  2018. */
  2019. public function removeVendorToCategoryAction(Request $request): JsonResponse
  2020. {
  2021. $entityManager = $this->getEntityManager();
  2022. $categoryId = $request->request->get('categoryId');
  2023. $vendorId = $request->request->get('vendorId');
  2024. $result = 'error';
  2025. /**
  2026. * @var CategoryPage $category
  2027. */
  2028. if (is_numeric($categoryId) && is_numeric($vendorId)) {
  2029. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  2030. $vendor = $entityManager->getRepository(Vendor::class)->find($vendorId);
  2031. if ($category && $vendor) {
  2032. $category->removeVendor($vendor);
  2033. $entityManager->persist($category);
  2034. $entityManager->flush();
  2035. $result = 'success';
  2036. }
  2037. }
  2038. return new JsonResponse([
  2039. 'response' => $result,
  2040. ]);
  2041. }
  2042. /**
  2043. * @Route("/filter-attribute-search", name="filter_attribute_search")
  2044. *
  2045. * @param Request $request
  2046. * @return JsonResponse
  2047. *
  2048. * FOR SEARCHING FILTER ATTRIBUTES TO PRODUCT CATEGORY
  2049. */
  2050. public function filterAttributeSearchAction(Request $request): JsonResponse
  2051. {
  2052. $searchQuery = $request->query->get('term');
  2053. $results = $this->getEntityManager()->createQuery("SELECT a.id, a.title, pt.title AS ptTitle
  2054. FROM AtechNetCoreBundle:Attribute a
  2055. LEFT JOIN a.productTypes pt
  2056. WHERE a.title LIKE '%" . $searchQuery . "%'")
  2057. ->setMaxResults(10)
  2058. ->getResult();
  2059. return new JsonResponse($results);
  2060. }
  2061. /**
  2062. * @Route("/add-filter-attribute-to-category", name="add_filter_attribute_to_category")
  2063. *
  2064. * @param Request $request
  2065. * @return JsonResponse
  2066. *
  2067. * FOR ADDING FILTER ATTRIBUTES TO PRODUCT CATEGORY
  2068. */
  2069. public function addFilterAttributeToCategoryAction(Request $request): JsonResponse
  2070. {
  2071. $entityManager = $this->getEntityManager();
  2072. $categoryId = (int)$request->request->get('categoryId');
  2073. $filterAttributeId = (int)$request->request->get('filterAttributeId');
  2074. $result = 'error';
  2075. /**
  2076. * @var CategoryPage $category
  2077. */
  2078. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  2079. $filterAttribute = $entityManager->getRepository(Attribute::class)->find($filterAttributeId);
  2080. if ($category && $filterAttribute) {
  2081. $addFilterAttribute = new CategoryPageFilterAttribute();
  2082. $addFilterAttribute->setAttribute($filterAttribute);
  2083. $addFilterAttribute->setCategoryPage($category);
  2084. $addFilterAttribute->setDelta($category->getFilterAttributes()->count());
  2085. $category->addFilterAttribute($addFilterAttribute);
  2086. $entityManager->persist($category);
  2087. $entityManager->flush();
  2088. $result = 'success';
  2089. }
  2090. return new JsonResponse([
  2091. 'response' => $result,
  2092. ]);
  2093. }
  2094. /**
  2095. * @Route("/update-filter-attribute-to-category", name="update_filter_attribute_to_category")
  2096. *
  2097. * @param Request $request
  2098. * @return JsonResponse
  2099. *
  2100. * FOR UPDATING FILTER ATTRIBUTES TO PRODUCT CATEGORY
  2101. */
  2102. public function updateFilterAttributeToCategoryAction(Request $request): JsonResponse
  2103. {
  2104. $entityManager = $this->getEntityManager();
  2105. $categoryId = (int)$request->request->get('categoryId');
  2106. $filterAttributes = explode(',', $request->request->get('filterAttributes'));
  2107. $result = 'error';
  2108. /**
  2109. * @var CategoryPage $category
  2110. */
  2111. if (!empty($filterAttributes)) {
  2112. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  2113. if ($category) {
  2114. $category->clearFilterAttribute();
  2115. foreach ($filterAttributes as $delta => $filterAttributeId) {
  2116. $filterAttribute = $entityManager->getRepository(Attribute::class)->find($filterAttributeId);
  2117. if ($filterAttribute) {
  2118. $addFilterAttribute = new CategoryPageFilterAttribute();
  2119. $addFilterAttribute->setAttribute($filterAttribute);
  2120. $addFilterAttribute->setCategoryPage($category);
  2121. $addFilterAttribute->setDelta($delta);
  2122. $category->addFilterAttribute($addFilterAttribute);
  2123. $entityManager->flush();
  2124. }
  2125. }
  2126. $entityManager->refresh($category);
  2127. $entityManager->flush();
  2128. $result = 'success';
  2129. }
  2130. }
  2131. return new JsonResponse([
  2132. 'response' => $result,
  2133. ]);
  2134. }
  2135. /**
  2136. * @Route("/remove-filter-attribute-to-category", name="remove_filter_attribute_to_category")
  2137. *
  2138. * @param Request $request
  2139. * @return JsonResponse
  2140. *
  2141. * FOR REMOVING FILTER ATTRIBUTES TO PRODUCT CATEGORY
  2142. */
  2143. public function removeFilterAttributeToCategoryAction(Request $request): JsonResponse
  2144. {
  2145. $entityManager = $this->getEntityManager();
  2146. $categoryId = $request->request->get('categoryId');
  2147. $filterAttributeId = $request->request->get('filterAttributeId');
  2148. $result = 'error';
  2149. /**
  2150. * @var CategoryPage $category
  2151. */
  2152. if (is_numeric($categoryId) && is_numeric($filterAttributeId)) {
  2153. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  2154. $filterAttribute = $entityManager->getRepository(Attribute::class)->find($filterAttributeId);
  2155. if ($category && $filterAttribute) {
  2156. $category->removeFilterAttribute($filterAttribute);
  2157. $entityManager->persist($category);
  2158. $entityManager->flush();
  2159. $result = 'success';
  2160. }
  2161. }
  2162. return new JsonResponse([
  2163. 'response' => $result,
  2164. ]);
  2165. }
  2166. /**
  2167. * @Route("/add-remove-badge-from-category", name="add_remove_badge_from_category")
  2168. *
  2169. * @param Request $request
  2170. * @return JsonResponse
  2171. *
  2172. * FOR ADDING AND REMOVING BADGES FROM PRODUCT CATEGORY
  2173. */
  2174. public function badgeToCategoryAction(Request $request): JsonResponse
  2175. {
  2176. $entityManager = $this->getEntityManager();
  2177. $categoryId = $request->request->get('categoryId');
  2178. $badge = $request->request->get('badge');
  2179. $badgeValue = $request->request->get('badgeValue');
  2180. $result = 'error';
  2181. /**
  2182. * @var CategoryPage $category
  2183. */
  2184. if (is_numeric($categoryId) && $badge != '' && $badgeValue != '' && in_array($badge, Product::getBadgesChoices())) {
  2185. $category = $entityManager->getRepository(CategoryPage::class)->find($categoryId);
  2186. if ($category) {
  2187. $currentBadges = json_decode($category->getBadges(), true);
  2188. if ($badgeValue == 0) {
  2189. foreach ($currentBadges as $key => $currentBadge) {
  2190. if ($currentBadge == $badge) {
  2191. unset($currentBadges[$key]);
  2192. }
  2193. }
  2194. } else {
  2195. $currentBadges[] = $badge;
  2196. }
  2197. $category->setBadges(json_encode($currentBadges));
  2198. $entityManager->flush();
  2199. $result = 'success';
  2200. }
  2201. }
  2202. return new JsonResponse([
  2203. 'response' => $result,
  2204. ]);
  2205. }
  2206. /**
  2207. * @Route("/centralis-replay/{year}", name="atech_net_core_year_stats")
  2208. *
  2209. * @return Response
  2210. */
  2211. public function yearStatsAction(Request $request, int $year): Response
  2212. {
  2213. $data = [];
  2214. $entityManager = $this->getEntityManager();
  2215. $user = $this->getUser();
  2216. $dateFrom = (new \DateTime())->setDate($year, 1, 1)->setTime(0, 0);
  2217. $dateFromLiteral = $dateFrom->format('Y-m-d H:i:s');
  2218. $dateTo = (new \DateTime())->setDate($year + 1, 1, 1)->setTime(0, 0);
  2219. $dateToLiteral = $dateTo->format('Y-m-d H:i:s');
  2220. $conn = $entityManager->getConnection();
  2221. $data['username'] = $user->getNickname();
  2222. $data['domains'] = [
  2223. Domain::DOMAIN_ID_RT_SK => 'RT SK',
  2224. Domain::DOMAIN_ID_WS_SK => 'WS SK',
  2225. Domain::DOMAIN_ID_RT_HU => 'RT HU',
  2226. Domain::DOMAIN_ID_WS_HU => 'WS HU',
  2227. Domain::DOMAIN_ID_WS_CZ => 'WS CZ',
  2228. Domain::DOMAIN_ID_WS_EU => 'WS EU',
  2229. Domain::DOMAIN_ID_B2C_EU => 'B2C EU',
  2230. Domain::DOMAIN_ID_RT_CZ => 'RT CZ',
  2231. ];
  2232. $data['months'] = [
  2233. 1 => 'Január',
  2234. 2 => 'Február',
  2235. 3 => 'Március',
  2236. 4 => 'Április',
  2237. 5 => 'Május',
  2238. 6 => 'Június',
  2239. 7 => 'Július',
  2240. 8 => 'Augusztus',
  2241. 9 => 'Szeptember',
  2242. 10 => 'Október',
  2243. 11 => 'November',
  2244. 12 => 'December',
  2245. ];
  2246. $data['userCount'] = count($entityManager->getRepository(User::class)->findBy([
  2247. 'isActive' => 1,
  2248. ]));
  2249. $userAbsences = $entityManager->createQuery("SELECT COUNT(ua.id) AS cnt FROM AtechNetCoreBundle:UserAbsence ua WHERE ua.created > :dateFrom AND ua.created < :dateTo AND ua.user = :user")
  2250. ->setParameters([
  2251. 'dateFrom' => $dateFrom,
  2252. 'dateTo' => $dateTo,
  2253. 'user' => $user,
  2254. ])
  2255. ->getResult();
  2256. $data['user']['absences'] = $userAbsences[0]['cnt'];
  2257. $userMeals = $entityManager->createQuery("SELECT COUNT(m.id) AS cnt, SUM(m.price) AS cnt_price FROM AtechNetCoreBundle:Meal m WHERE m.created > :dateFrom AND m.created < :dateTo AND m.createdBy = :user ")
  2258. ->setParameters([
  2259. 'dateFrom' => $dateFrom,
  2260. 'dateTo' => $dateTo,
  2261. 'user' => $user,
  2262. ])
  2263. ->getResult();
  2264. $data['user']['meals'] = $userMeals[0]['cnt'];
  2265. $data['user']['meals_price'] = $userMeals[0]['cnt_price'];
  2266. $userCreatedTasks = $entityManager->createQuery("SELECT COUNT(m.id) AS cnt FROM AtechNetCoreBundle:Task m WHERE m.created > :dateFrom AND m.created < :dateTo AND m.creator = :user")
  2267. ->setParameters([
  2268. 'dateFrom' => $dateFrom,
  2269. 'dateTo' => $dateTo,
  2270. 'user' => $user,
  2271. ])
  2272. ->getResult();
  2273. $data['user']['createdTasks'] = $userCreatedTasks[0]['cnt'];
  2274. $userAssignedTasks = $entityManager->createQuery("SELECT COUNT(m.id) AS cnt FROM AtechNetCoreBundle:TaskAssignedTo m WHERE m.created > :dateFrom AND m.created < :dateTo AND m.user = :user")
  2275. ->setParameters([
  2276. 'dateFrom' => $dateFrom,
  2277. 'dateTo' => $dateTo,
  2278. 'user' => $user,
  2279. ])
  2280. ->getResult();
  2281. $data['user']['assignedTasks'] = $userAssignedTasks[0]['cnt'];
  2282. $userCreatedOrders = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
  2283. ->setParameters([
  2284. 'dateFrom' => $dateFrom,
  2285. 'dateTo' => $dateTo,
  2286. 'user' => $user,
  2287. ])
  2288. ->getResult();
  2289. $data['user']['createdOrders'] = $userCreatedOrders[0]['cnt'];
  2290. $userUpdatedOrders = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
  2291. ->setParameters([
  2292. 'dateFrom' => $dateFrom,
  2293. 'dateTo' => $dateTo,
  2294. 'user' => $user,
  2295. ])
  2296. ->getResult();
  2297. $data['user']['updatedOrders'] = $userUpdatedOrders[0]['cnt'];
  2298. $userCreatedDocuments = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Document o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
  2299. ->setParameters([
  2300. 'dateFrom' => $dateFrom,
  2301. 'dateTo' => $dateTo,
  2302. 'user' => $user,
  2303. ])
  2304. ->getResult();
  2305. $data['user']['createdDocuments'] = $userCreatedDocuments[0]['cnt'];
  2306. $userUpdatedDocuments = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Document o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
  2307. ->setParameters([
  2308. 'dateFrom' => $dateFrom,
  2309. 'dateTo' => $dateTo,
  2310. 'user' => $user,
  2311. ])
  2312. ->getResult();
  2313. $data['user']['updatedDocuments'] = $userUpdatedDocuments[0]['cnt'];
  2314. $userCreatedMovements = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:StockMovement o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
  2315. ->setParameters([
  2316. 'dateFrom' => $dateFrom,
  2317. 'dateTo' => $dateTo,
  2318. 'user' => $user,
  2319. ])
  2320. ->getResult();
  2321. $data['user']['createdMovements'] = $userCreatedMovements[0]['cnt'];
  2322. $userUpdatedMovements = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:StockMovement o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
  2323. ->setParameters([
  2324. 'dateFrom' => $dateFrom,
  2325. 'dateTo' => $dateTo,
  2326. 'user' => $user,
  2327. ])
  2328. ->getResult();
  2329. $data['user']['updatedMovements'] = $userUpdatedMovements[0]['cnt'];
  2330. $userCreatedCustomers = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
  2331. ->setParameters([
  2332. 'dateFrom' => $dateFrom,
  2333. 'dateTo' => $dateTo,
  2334. 'user' => $user,
  2335. ])
  2336. ->getResult();
  2337. $data['user']['createdCustomers'] = $userCreatedCustomers[0]['cnt'];
  2338. $userUpdatedCustomers = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Order o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
  2339. ->setParameters([
  2340. 'dateFrom' => $dateFrom,
  2341. 'dateTo' => $dateTo,
  2342. 'user' => $user,
  2343. ])
  2344. ->getResult();
  2345. $data['user']['updatedCustomers'] = $userUpdatedCustomers[0]['cnt'];
  2346. $userCreatedProducts = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Product o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.createdBy = :user")
  2347. ->setParameters([
  2348. 'dateFrom' => $dateFrom,
  2349. 'dateTo' => $dateTo,
  2350. 'user' => $user,
  2351. ])
  2352. ->getResult();
  2353. $data['user']['createdProducts'] = $userCreatedProducts[0]['cnt'];
  2354. $userUpdatedProducts = $entityManager->createQuery("SELECT COUNT(o.id) AS cnt FROM AtechNetCoreBundle:Product o WHERE o.created > :dateFrom AND o.created < :dateTo AND o.updatedBy = :user")
  2355. ->setParameters([
  2356. 'dateFrom' => $dateFrom,
  2357. 'dateTo' => $dateTo,
  2358. 'user' => $user,
  2359. ])
  2360. ->getResult();
  2361. $data['user']['updatedProducts'] = $userUpdatedProducts[0]['cnt'];
  2362. $cacheItem = $this->cache->getItem("centralis-replay-current-year");
  2363. if ($cacheItem->isHit()) {
  2364. $data = array_merge($data, $cacheItem->get());
  2365. } else {
  2366. $items = [];
  2367. $items['all']['orders']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
  2368. $items['all']['packages']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, SUM(o.box_count) AS sm FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
  2369. $items['all']['absences']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM users_absence o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2370. $items['all']['documents']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM documents o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2371. $items['all']['documents_billingo']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM customers__billingo_data o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2372. $items['all']['stockMovements']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM stock_movements o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2373. $items['all']['stockItems']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM stock_items o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2374. $items['all']['claim']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM claims o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2375. $items['all']['meal']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt, SUM(o.price) AS cnt_price FROM meal o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2376. $items['all']['customers']['byMonth'] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM customers o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2377. $items['all']['orders']['byHour'] = $conn->fetchAllAssociative("SELECT HOUR(o.created) AS hour, COUNT(o.id) AS cnt FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY HOUR(o.created)");
  2378. $cacheItem->set($items);
  2379. $cacheItem->expiresAfter(self::CACHE_LIFETIME_1_DAY);
  2380. $this->cache->save($cacheItem);
  2381. $data = array_merge($data, $items);
  2382. }
  2383. $data['all']['meal']['favouriteRestaurant']['id'] = $conn->fetchAllAssociative("SELECT m.restaurant FROM meal m WHERE m.created >= '" . $dateFromLiteral . "' AND m.created <= '" . $dateToLiteral . "' GROUP BY m.restaurant ORDER BY COUNT(m.restaurant) DESC LIMIT 1")[0]['restaurant'];
  2384. $data['all']['meal']['favouriteRestaurant']['title'] = Meal::getRestaurantName($data['all']['meal']['favouriteRestaurant']['id']);
  2385. $data['all']['meal']['favouriteRestaurant']['orderCount'] = $conn->fetchAllAssociative("SELECT COUNT(m.id) AS orderCount FROM meal m WHERE m.created >= '" . $dateFromLiteral . "' AND m.created <= '" . $dateToLiteral . "' AND m.restaurant = " . $data['all']['meal']['favouriteRestaurant']['id'])[0]['orderCount'];
  2386. $data['all']['meal']['favouriteRestaurant']['orderValue'] = $conn->fetchAllAssociative("SELECT SUM(m.price) AS orderValue FROM meal m WHERE m.created >= '" . $dateFromLiteral . "' AND m.created <= '" . $dateToLiteral . "' AND m.restaurant = " . $data['all']['meal']['favouriteRestaurant']['id'])[0]['orderValue'];
  2387. $cacheItem = $this->cache->getItem("centralis-replay-previous-year");
  2388. if ($cacheItem->isHit()) {
  2389. $data = array_merge($data, $cacheItem->get());
  2390. } else {
  2391. $items = [];
  2392. for ($i = $year - 1; $i > 2011; $i--) {
  2393. $dateFrom = (new \DateTime())->setDate($i, 1, 1)->setTime(0, 0);
  2394. $dateFromLiteral = $dateFrom->format('Y-m-d H:i:s');
  2395. $dateTo = (new \DateTime())->setDate($i + 1, 1, 1)->setTime(0, 0);
  2396. $dateToLiteral = $dateTo->format('Y-m-d H:i:s');
  2397. $items['previousYear']['orders']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
  2398. $items['previousYear']['packages']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, SUM(o.box_count) AS sm FROM orders o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' AND o.status = 60 GROUP BY MONTH(o.created)");
  2399. $items['previousYear']['documents']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM documents o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2400. $items['previousYear']['stockItems']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM stock_items o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2401. $items['previousYear']['claim']['byYears'][$i] = $conn->fetchAllAssociative("SELECT MONTH(o.created) AS month, COUNT(o.id) AS cnt FROM claims o WHERE o.created > '" . $dateFromLiteral . "' AND o.created < '" . $dateToLiteral . "' GROUP BY MONTH(o.created)");
  2402. }
  2403. $cacheItem->set($items);
  2404. $cacheItem->expiresAfter(self::CACHE_LIFETIME_7_DAYS);
  2405. $this->cache->save($cacheItem);
  2406. $data = array_merge($data, $items);
  2407. }
  2408. $data['all']['orders']['all'] = 0;
  2409. foreach ($data['all']['orders']['byMonth'] as $month) {
  2410. $data['all']['orders']['all'] += $month['cnt'];
  2411. }
  2412. $data['all']['packages']['all'] = 0;
  2413. foreach ($data['all']['packages']['byMonth'] as $month) {
  2414. $data['all']['packages']['all'] += $month['sm'];
  2415. }
  2416. $data['all']['absences']['all'] = 0;
  2417. foreach ($data['all']['absences']['byMonth'] as $month) {
  2418. $data['all']['absences']['all'] += $month['cnt'];
  2419. }
  2420. $data['all']['documents']['all'] = 0;
  2421. foreach ($data['all']['documents']['byMonth'] as $month) {
  2422. $data['all']['documents']['all'] += $month['cnt'];
  2423. }
  2424. foreach ($data['all']['documents_billingo']['byMonth'] as $month) {
  2425. $data['all']['documents']['all'] += $month['cnt'];
  2426. }
  2427. $data['all']['stockMovements']['all'] = 0;
  2428. foreach ($data['all']['stockMovements']['byMonth'] as $month) {
  2429. $data['all']['stockMovements']['all'] += $month['cnt'];
  2430. }
  2431. $data['all']['stockItems']['all'] = 0;
  2432. foreach ($data['all']['stockItems']['byMonth'] as $month) {
  2433. $data['all']['stockItems']['all'] += $month['cnt'];
  2434. }
  2435. $data['all']['claim']['all'] = 0;
  2436. foreach ($data['all']['claim']['byMonth'] as $month) {
  2437. $data['all']['claim']['all'] += $month['cnt'];
  2438. }
  2439. $data['all']['meal']['all'] = 0;
  2440. $data['all']['meal']['all_price'] = 0;
  2441. foreach ($data['all']['meal']['byMonth'] as $month) {
  2442. $data['all']['meal']['all'] += $month['cnt'];
  2443. $data['all']['meal']['all_price'] += $month['cnt_price'];
  2444. }
  2445. $data['all']['customers']['all'] = 0;
  2446. foreach ($data['all']['customers']['byMonth'] as $month) {
  2447. $data['all']['customers']['all'] += $month['cnt'];
  2448. }
  2449. $data['year'] = $year;
  2450. return $this->render('AtechNetCoreBundle/Default/yearStats.html.twig', $data);
  2451. }
  2452. /**
  2453. * @Route("/cdn/image/product/{image}-{width}-{height}.{extension}", name="image_cdn")
  2454. * @param Request $request
  2455. * @param string $image
  2456. * @param int $width
  2457. * @param int $height
  2458. * @param string $extension
  2459. *
  2460. * @return Response
  2461. * @throws NotFoundException
  2462. */
  2463. public function cdnAction(Request $request, string $image, int $width, int $height, string $extension): Response
  2464. {
  2465. $photoId = (int)substr($image, 0, (strlen($image) - 32));
  2466. $photo = $this->getEntityManager()->getRepository(Photo::class)->find($photoId);
  2467. /**
  2468. * @var Photo $photo
  2469. */
  2470. if ($photo) {
  2471. // Validate Salt
  2472. if ($photo->getSalt() == str_replace($photoId, '', $image)) {
  2473. // Variant
  2474. $variant = Image::determineCloudflareVariant($width, $height);
  2475. if (!is_null($variant)) {
  2476. // Cloudflare
  2477. if (!is_null($photo->getCloudflareId())) {
  2478. $url = $photo->getCdnUrl($variant);
  2479. // Image Mime Type
  2480. switch ($extension) {
  2481. case 'jpg':
  2482. case 'jpeg':
  2483. $headerAccept = 'image/jpeg';
  2484. break;
  2485. case 'gif':
  2486. $headerAccept = 'image/gif';
  2487. break;
  2488. case 'webp':
  2489. $headerAccept = 'image/webp';
  2490. break;
  2491. case 'png':
  2492. $headerAccept = 'image/png';
  2493. break;
  2494. default:
  2495. $headerAccept = $request->server->get('HTTP_ACCEPT');
  2496. break;
  2497. }
  2498. $userAgent = $request->server->get('HTTP_USER_AGENT');
  2499. // Response Header
  2500. $headers = [];
  2501. // Get Image
  2502. $ch = curl_init();
  2503. curl_setopt($ch, CURLOPT_HEADER, false);
  2504. curl_setopt($ch, CURLOPT_VERBOSE, false);
  2505. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2506. curl_setopt($ch, CURLOPT_URL, $url);
  2507. curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
  2508. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  2509. 'Accept' => $headerAccept,
  2510. ]);
  2511. curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$headers) {
  2512. $length = strlen($header);
  2513. // Parse Header
  2514. $header = explode(':', $header, 2);
  2515. // Ignore invalid Header
  2516. if (count($header) < 2) {
  2517. return $length;
  2518. }
  2519. $headers[strtolower(trim($header[0]))][] = trim($header[1]);
  2520. return $length;
  2521. });
  2522. $response = curl_exec($ch);
  2523. // HTTP OK
  2524. if ((int)curl_getinfo($ch, CURLINFO_HTTP_CODE) == Response::HTTP_OK) {
  2525. $contentType = false;
  2526. if (isset($headers['content-type'])) {
  2527. $contentType = array_pop($headers['content-type']);
  2528. }
  2529. $contentLength = false;
  2530. if (isset($headers['content-length'])) {
  2531. $contentLength = array_pop($headers['content-length']);
  2532. }
  2533. if ($contentType && $contentLength) {
  2534. return new Response($response, Response::HTTP_OK, [
  2535. 'Cache-Control' => 'public',
  2536. 'Content-Type' => $contentType,
  2537. 'Content-Length' => $contentLength,
  2538. 'Content-Disposition' => 'inline; filename="' . $photo->getOriginalName() . '-' . $width . '-' . $height . '.' . $extension . '"',
  2539. ]);
  2540. }
  2541. }
  2542. }
  2543. // Use system photo generation
  2544. if ($photo->getAlbum()) {
  2545. // Product
  2546. $product = $this->getEntityManager()->getRepository(Product::class)->findOneByAlbum($photo->getAlbum());
  2547. if ($product) {
  2548. $image = $this->getImage($photo, 'product/' . $product->getCode(), false)->resize($width, $height);
  2549. $imageContent = file_get_contents(str_replace(' ', '%20', $image));
  2550. return new Response($imageContent, Response::HTTP_OK, [
  2551. 'Cache-Control' => 'public',
  2552. 'Content-Type' => $photo->getMimeType(),
  2553. 'Content-Length' => strlen($imageContent),
  2554. 'Content-Disposition' => 'inline; filename="' . basename($image) . '"',
  2555. ]);
  2556. }
  2557. }
  2558. }
  2559. }
  2560. }
  2561. throw new NotFoundException('Photo not found!');
  2562. }
  2563. /**
  2564. * @Route("/update-entity-items-settings", name="atech_net_core_update_entity_items_settings")
  2565. * @param Request $request
  2566. * @return JsonResponse
  2567. */
  2568. public function updateEntityItemsSettingsAction(Request $request): JsonResponse
  2569. {
  2570. $entityName = $request->get('entityName');
  2571. $entityColumnName = $request->get('entityColumnName');
  2572. $entityIds = $request->get('entityIds');
  2573. $columnValue = (bool) $request->get('columnValue');
  2574. $entityManager = $this->getEntityManager();
  2575. switch ($entityName) {
  2576. case 'stockItem':
  2577. $entityManager->getRepository(StockItem::class)->updateStockItems(
  2578. $entityColumnName,
  2579. explode(',', $entityIds),
  2580. $columnValue
  2581. );
  2582. break;
  2583. }
  2584. return new JsonResponse([]);
  2585. }
  2586. /**
  2587. * @Route("/digitalocean-object/{scope}/{id}", name="atech_net_core_digitalocean_object")
  2588. *
  2589. * @param Request $request
  2590. * @return Response
  2591. */
  2592. public function digitalOceanObject(Request $request, string $scope, int $id): Response
  2593. {
  2594. // Entity Manager
  2595. $entityManager = $this->getEntityManager();
  2596. // Digital Ocean Space
  2597. $digitalOcean = $this->getDigitalOceanSpace();
  2598. // Response
  2599. $response = new Response();
  2600. switch ($scope) {
  2601. case 'claim':
  2602. $claimMedia = $entityManager->getRepository(ClaimMedia::class)->find($id);
  2603. if ($claimMedia) {
  2604. $result = $digitalOcean->claimMedia($claimMedia, 'download');
  2605. if (!empty($result['body'])) {
  2606. $response->headers->set('Content-Type', $claimMedia->getMimeType());
  2607. $response->headers->set('Content-Disposition', 'attachment;filename="' . $claimMedia->getFilename());
  2608. $response->setContent($result['body']);
  2609. }
  2610. }
  2611. break;
  2612. case 'user-avatar':
  2613. $user = $entityManager->getRepository(User::class)->find($id);
  2614. if ($user) {
  2615. $result = $digitalOcean->userAvatar($user, null, 'download');
  2616. if (!empty($result['body'])) {
  2617. // Extension
  2618. $extension = pathinfo($user->getAvatar(), PATHINFO_EXTENSION);
  2619. // Mime Type
  2620. switch ($extension) {
  2621. case 'jpg':
  2622. case 'jpeg':
  2623. $mimeType = 'image/jpeg';
  2624. break;
  2625. case 'gif':
  2626. $mimeType = 'image/gif';
  2627. break;
  2628. case 'webp':
  2629. $mimeType = 'image/webp';
  2630. break;
  2631. case 'png':
  2632. $mimeType = 'image/png';
  2633. break;
  2634. default:
  2635. // Temporary File
  2636. $tmp = tempnam(DigitalOceanSpaces::getUploadDirectory() . 'digitalocean/user-avatar/', 'frb_') . '_' . $user->getAvatar();
  2637. file_put_contents($tmp, $result['body']);
  2638. $mimeType = MimeTypes::getDefault()->guessMimeType($tmp);
  2639. @unlink($tmp);
  2640. break;
  2641. }
  2642. $response->headers->set('Content-Type', $mimeType);
  2643. $response->headers->set('Content-Disposition', 'attachment;filename="' . $user->getAvatar());
  2644. $response->setContent($result['body']);
  2645. }
  2646. }
  2647. break;
  2648. }
  2649. return $response;
  2650. }
  2651. }