src/Controller/Common/CommonController.php line 250

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Common;
  3. use App\Annotation\Exportable;
  4. use App\Annotation\ExportableEntity;
  5. use App\Annotation\ExportableMethod;
  6. use App\Constants\Platform;
  7. use App\Constants\UserExtension;
  8. use App\Entity\CustomerProduct;
  9. use App\Entity\Parameter;
  10. use App\Entity\PointTransaction;
  11. use App\Entity\PointTransactionType;
  12. use App\Entity\Purchase;
  13. use App\Entity\PurchaseProduct;
  14. use App\Entity\PurchaseProductItem;
  15. use App\Entity\Regate;
  16. use App\Entity\SaleOrder;
  17. use App\Entity\Setting;
  18. use App\Entity\User;
  19. use App\Entity\UserBusinessResult;
  20. use App\Exception\CatalogueException;
  21. use App\Exception\PurchaseDeclarationException;
  22. use App\Factory\Platform\MailerFactory;
  23. use App\Services\Common\Point\UserPointService;
  24. use App\Model\Period;
  25. use App\Services\Back\RegateService;
  26. use App\Services\Common\Email\MailTypes;
  27. use App\Services\Common\MailerService;
  28. use App\Services\Common\PlatformService;
  29. use App\Services\Common\Point\UserPointServiceInterface;
  30. use App\Services\Common\SettingStatusService;
  31. use App\Services\Common\UserService;
  32. use App\Services\CommonServices;
  33. use App\Services\ConfigService;
  34. use App\Services\DTV\MailService;
  35. use App\Services\DTV\YamlConfig\YamlReader;
  36. use App\Services\Front\Catalogue\JsonCatalogueService;
  37. use App\Services\Front\UserFrontService;
  38. use App\Services\HighlightService;
  39. use DateTime;
  40. use Doctrine\Common\Annotations\Reader;
  41. use Doctrine\DBAL\Connection;
  42. use Doctrine\ORM\EntityManagerInterface;
  43. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  44. use Doctrine\ORM\NonUniqueResultException;
  45. use Exception;
  46. use Hautelook\Phpass\PasswordHash;
  47. use ReflectionClass;
  48. use ReflectionException;
  49. use RuntimeException;
  50. use Symfony\Bundle\FrameworkBundle\Console\Application;
  51. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  52. use Symfony\Component\Console\Input\ArrayInput;
  53. use Symfony\Component\Console\Output\BufferedOutput;
  54. use Symfony\Component\Finder\Finder;
  55. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  56. use Symfony\Component\HttpFoundation\JsonResponse;
  57. use Symfony\Component\HttpFoundation\RedirectResponse;
  58. use Symfony\Component\HttpFoundation\Request;
  59. use Symfony\Component\HttpFoundation\Response;
  60. use Symfony\Component\HttpKernel\KernelInterface;
  61. use Symfony\Component\Routing\Annotation\Route;
  62. use Symfony\Component\Stopwatch\Stopwatch;
  63. use Symfony\Component\Yaml\Yaml;
  64. use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
  65. use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
  66. use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
  67. use Symfony\Contracts\HttpClient\HttpClientInterface;
  68. use Symfony\Contracts\Translation\TranslatorInterface;
  69. class CommonController extends AbstractController
  70. {
  71. private KernelInterface $kernel;
  72. private EntityManagerInterface $em;
  73. private ConfigService $configService;
  74. private PlatformService $platformService;
  75. private YamlReader $yamlReader;
  76. private UserPointServiceInterface $userPointService;
  77. private JsonCatalogueService $jsonCatalogueService;
  78. private RegateService $regateService;
  79. private UserFrontService $userFrontService;
  80. private string $projectDir;
  81. private SettingStatusService $settingStatusService;
  82. private MailService $mailService;
  83. private CommonServices $commonServices;
  84. private HttpClientInterface $client;
  85. private HighlightService $highlightService;
  86. private UserService $userService;
  87. /**
  88. * @param KernelInterface $kernel
  89. * @param EntityManagerInterface $em
  90. * @param ConfigService $configService
  91. * @param PlatformService $platformService
  92. * @param YamlReader $yamlReader
  93. * @param UserPointService $userPointService
  94. * @param JsonCatalogueService $jsonCatalogueService
  95. * @param RegateService $regateService
  96. * @param UserFrontService $userFrontService
  97. * @param SettingStatusService $settingStatusService
  98. * @param MailService $mailService
  99. * @param CommonServices $commonServices
  100. * @param HttpClientInterface $client
  101. * @param HighlightService $highlightService
  102. * @param string $projectDir
  103. * @param UserService $userService
  104. *
  105. * @throws Exception
  106. */
  107. public function __construct(KernelInterface $kernel, EntityManagerInterface $em, ConfigService $configService, PlatformService $platformService, YamlReader $yamlReader, UserPointService $userPointService, JsonCatalogueService $jsonCatalogueService, RegateService $regateService, UserFrontService $userFrontService, SettingStatusService $settingStatusService, MailService $mailService, CommonServices $commonServices, HttpClientInterface $client, HighlightService $highlightService, string $projectDir, UserService $userService)
  108. {
  109. $this->kernel = $kernel;
  110. $this->em = $em;
  111. $this->configService = $configService;
  112. $this->platformService = $platformService;
  113. $this->yamlReader = $yamlReader;
  114. $this->userPointService = $userPointService;
  115. $this->jsonCatalogueService = $jsonCatalogueService;
  116. $this->regateService = $regateService;
  117. $this->userFrontService = $userFrontService;
  118. $this->projectDir = $projectDir;
  119. $this->settingStatusService = $settingStatusService;
  120. $this->commonServices = $commonServices;
  121. $this->mailService = $mailService;
  122. $this->client = $client;
  123. $this->highlightService = $highlightService;
  124. $this->userService = $userService;
  125. }
  126. /**
  127. * @return RedirectResponse
  128. */
  129. public function backRedirection(): RedirectResponse
  130. {
  131. return $this->redirectToRoute('back_dashboard');
  132. }
  133. /**
  134. * @param string $folder
  135. * @param string $fileName
  136. *
  137. * @return BinaryFileResponse
  138. *
  139. * @throws Exception
  140. */
  141. public function exposeFolderFile(string $folder, string $fileName): BinaryFileResponse
  142. {
  143. $path = $this->getParameter('kernel.project_dir') . '/medias/' . $this->platformService->getDomain() . '/' . $folder . '/';
  144. $file = $path . $fileName;
  145. if(!file_exists($file))
  146. {
  147. throw $this->createNotFoundException("Cette ressource n'existe pas");
  148. }
  149. return $this->file($file);
  150. }
  151. /**
  152. * @param string $fileName
  153. *
  154. * @return object|BinaryFileResponse
  155. *
  156. * @throws Exception
  157. */
  158. public function exposeProjectFile(string $fileName, string $prefix = null)
  159. {
  160. $folder = $this->platformService->getDomain() . '/';
  161. $path = $this->getParameter('kernel.project_dir') . '/medias/' . $folder;
  162. $file = $path . ($prefix ? '/' . $prefix . '/' : '') . $fileName;
  163. if(!file_exists($file))
  164. {
  165. throw $this->createNotFoundException('La ressource n\'existe pas');
  166. }
  167. return $this->file($file);
  168. }
  169. /**
  170. * Route qui ne sert qu'à évaluer le temps nécessaire à fournir l'image
  171. *
  172. * @param string $fileName
  173. *
  174. * @return Response
  175. *
  176. * @throws Exception
  177. */
  178. public function exposeProjectFileBody(string $fileName): Response
  179. {
  180. $folder = $this->platformService->getDomain() . '/';
  181. $path = $this->getParameter('kernel.project_dir') . '/medias/' . $folder;
  182. $file = $path . $fileName;
  183. if(!file_exists($file))
  184. {
  185. throw $this->createNotFoundException('La ressource n\'existe pas');
  186. }
  187. return new Response('<body>' . $file . '</body>');
  188. }
  189. /**
  190. * @param string $file
  191. * @param $size
  192. *
  193. * @return BinaryFileResponse
  194. */
  195. public function getPicture(string $file, $size): BinaryFileResponse
  196. {
  197. $src = "http://bo.37deux.com/pictures/$size/$file";
  198. $dir = $this->getParameter('kernel.project_dir') . "/medias/$size";
  199. $dest = "$dir/$file";
  200. if(!is_dir($dir) && !mkdir($dir, 0755) && !is_dir($dir))
  201. {
  202. throw new RuntimeException(sprintf('Directory "%s" was not created', $dir));
  203. }
  204. if(!file_exists($dest))
  205. {
  206. $data = $this->get_content($src);
  207. file_put_contents($dest, $data);
  208. }
  209. return $this->file($file);
  210. }
  211. /**
  212. * @param string $URL
  213. *
  214. * @return bool|string
  215. */
  216. private function get_content(string $URL)
  217. {
  218. $ch = curl_init();
  219. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  220. curl_setopt($ch, CURLOPT_URL, $URL);
  221. $data = curl_exec($ch);
  222. curl_close($ch);
  223. return $data;
  224. }
  225. /**
  226. * @param string $slug
  227. *
  228. * @return Response
  229. */
  230. public function getDocument(string $slug): Response
  231. {
  232. $document = $this->em->getRepository(Parameter::class)->findOneBy([
  233. 'slug' => $slug,
  234. ],);
  235. if(empty($document))
  236. {
  237. throw $this->createNotFoundException("Ce document n'existe pas");
  238. }
  239. // on vérifie si le document est public
  240. if(!$document->isPublic() && $this->getUser() === NULL)
  241. {
  242. $this->addFlash('info', "Vous n'avez pas le droit d'accéder à ce document");
  243. throw $this->createAccessDeniedException("Vous n'avez pas le droit de consulter ce document");
  244. }
  245. if($document->getFileName() !== NULL)
  246. {
  247. return $this->redirectToRoute('static_file_folder', [
  248. 'folder' => $this->getParameter('app.path.general_documents'),
  249. 'fileName' => $document->getFileName(),
  250. ]);
  251. }
  252. return $this->render($this->configService->getTemplateDependingDomain('front/common/document.html.twig'), [
  253. 'document' => $document,
  254. ]);
  255. }
  256. /**
  257. * @TODO: check si toujours utilisée
  258. *
  259. * @param string $slug
  260. *
  261. * @return JsonResponse
  262. */
  263. public function getAjaxDocumentHtml(string $slug): JsonResponse
  264. {
  265. /** @var Parameter $document */
  266. $document = $this->em->getRepository(Parameter::class)->findOneBy([
  267. 'slug' => $slug,
  268. ],);
  269. if($document instanceof Parameter && $document->getValue() !== NULL)
  270. {
  271. $html = $this->renderView('front/common/document-panel.html.twig', [
  272. 'document' => $document,
  273. ]);
  274. $redirect = FALSE;
  275. }
  276. else
  277. {
  278. $html = '';
  279. $redirect = TRUE;
  280. }
  281. return new JsonResponse([
  282. 'redirect' => $redirect,
  283. 'html' => $html,
  284. 'title' => $document->getTitle(),
  285. ],);
  286. }
  287. /**
  288. * @return Response
  289. *
  290. * @throws Exception
  291. */
  292. public function BddUp(): Response
  293. {
  294. $application = new Application($this->kernel);
  295. $application->setAutoExit(FALSE);
  296. $input = new ArrayInput([
  297. 'command' => 'dtv:bdd-update',
  298. // (optional) define the value of command arguments
  299. 'project' => $this->yamlReader->getGlobal()['subdomain'],
  300. ],);
  301. // You can use NullOutput() if you don't need the output
  302. $output = new BufferedOutput();
  303. $application->run($input, $output);
  304. // return the output, don't use if you used NullOutput()
  305. $content = $output->fetch();
  306. $content .= '<a href="/">retour au site</a>';
  307. // return new Response(""), if you used NullOutput()
  308. return new Response('<pre>' . $content . '</pre>');
  309. }
  310. /**
  311. * Crée un compte Developer
  312. *
  313. * @param Request $request
  314. *
  315. * @return Response
  316. */
  317. public function CreateDeveloper(Request $request): Response
  318. {
  319. $email = $request->query->get('email');
  320. $user = $this->em->getRepository(User::class)->findOneBy([
  321. 'email' => $email,
  322. ],);
  323. if($user instanceof User)
  324. {
  325. return new Response("Developer $email already exists");
  326. }
  327. if(is_null($email))
  328. {
  329. return new Response("Email is required");
  330. }
  331. $passwordHash = new PasswordHash(8, FALSE);
  332. $password = $passwordHash->HashPassword('pass1234');
  333. $user = ($this->userService->initUser())
  334. ->setEmail($email)
  335. ->setPassword($password)
  336. ->setRoles(['ROLE_DEVELOPER'])
  337. ->setFirstname('Developer')
  338. ->setLastname($email)
  339. ->setStatus('enabled')
  340. ->setCguAt(new DateTime())
  341. ->setCreatedAt(new DateTime())
  342. ->setUpdatedAt(new DateTime())
  343. ;
  344. $this->em->persist($user);
  345. $this->em->flush();
  346. return new Response("Developer $email created with password pass1234");
  347. }
  348. /**
  349. * @param Request $request
  350. *
  351. * @return Response
  352. */
  353. public function showUserStatusDaikin(Request $request): Response
  354. {
  355. /** @var User $currentUser */
  356. $currentUser = $this->getUser();
  357. if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
  358. {
  359. return new Response('Page non trouvée', 404);
  360. }
  361. $thisYear = (new DateTime())->format('Y') * 1;
  362. $lastYear = $thisYear - 1;
  363. $nextYear = $thisYear + 1;
  364. $period = new Period("$thisYear/01/01 00:00:00", "$thisYear/12/31 23:59:59");
  365. $newUser = $request->request->get('newUser', FALSE);
  366. $pointThisYear = $request->request->get('pointThisYear', 0);
  367. $pointLastYear = $request->request->get('pointLastYear', 0);
  368. if($pointLastYear >= 1000)
  369. {
  370. $levelLastYear = 2;
  371. }
  372. elseif($pointLastYear >= 500)
  373. {
  374. $levelLastYear = 1;
  375. }
  376. else
  377. {
  378. $levelLastYear = 0;
  379. }
  380. if($pointThisYear >= 1000)
  381. {
  382. $levelThisYear = 2;
  383. }
  384. elseif($pointThisYear >= 500)
  385. {
  386. $levelThisYear = 1;
  387. }
  388. else
  389. {
  390. $levelThisYear = 0;
  391. }
  392. $data = [
  393. 'thisYear' => $thisYear,
  394. 'lastYear' => $lastYear,
  395. 'nextYear' => $nextYear,
  396. 'period' => $period,
  397. 'pointThisYear' => $pointThisYear,
  398. 'pointLastYear' => $pointLastYear,
  399. 'newUser' => $newUser,
  400. 'levelLastYear' => $levelLastYear,
  401. 'levelThisYear' => $levelThisYear,
  402. ];
  403. $data['data'] = $this->userPointService->getUserStatusDaikinFormatted($data);
  404. return $this->render('front/common/test-user-status.html.twig', $data);
  405. }
  406. /**
  407. * @return Response
  408. *
  409. * @throws Exception
  410. */
  411. public function getUsersDaikin(): Response
  412. {
  413. /** @var User $currentUser */
  414. $currentUser = $this->getUser();
  415. if(!$currentUser->isDeveloper())
  416. {
  417. return new Response('Page non trouvée', 404);
  418. }
  419. set_time_limit(0);
  420. $users = $this->em->getRepository(User::class)->findAll();
  421. $countUsers = [];
  422. $response = '<table>';
  423. for($year = 2021; $year <= 2022; $year++)
  424. {
  425. for($month = 1; $month <= 12; $month++)
  426. {
  427. $fin = date("Ymt", strtotime($year . '-' . $month . '-1'));
  428. $formattedDate = (new DateTime($year . '-' . $month . '-1'))->format('M Y');
  429. /**
  430. * @var $index
  431. * @var User $user
  432. */
  433. foreach($users as $user)
  434. {
  435. if(!$user->isInstaller())
  436. {
  437. continue;
  438. }
  439. if($user->getCguAt() == NULL)
  440. {
  441. continue;
  442. }
  443. if($user->isDeleted())
  444. {
  445. continue;
  446. }
  447. $created_at = $user->getCreatedAt()->format('Ymd');
  448. if($created_at > $fin)
  449. {
  450. continue;
  451. }
  452. if($user->getArchivedAt() !== NULL)
  453. {
  454. $archived_at = $user->getArchivedAt()->format('Ymd');
  455. if($archived_at <= $fin)
  456. {
  457. continue;
  458. }
  459. }
  460. $countUsers[$formattedDate]['total'] = ($countUsers[$formattedDate]['total'] ?? 0) + 1;
  461. $cgu_at = $user->getCguAt()->format('Ymd');
  462. if($cgu_at <= $fin)
  463. {
  464. $purchases = $this->em
  465. ->getRepository(Purchase::class)->getPurchaseUserAtDate($user->getId(), $fin)
  466. ;
  467. if(!empty($purchases))
  468. {
  469. $countUsers[$formattedDate]['actif'] = ($countUsers[$formattedDate]['actif'] ?? 0) + 1;
  470. }
  471. }
  472. }
  473. $response .= '<tr>';
  474. $response .= '<td>' . $countUsers[$formattedDate]['total'] . '</td>';
  475. $response .= '<td>' . $countUsers[$formattedDate]['actif'] . '</td>';
  476. $response .= '</tr>';
  477. }
  478. }
  479. $response .= '</table>';
  480. return new Response($response);
  481. }
  482. /**
  483. * @param Request $request
  484. *
  485. * @return Response
  486. *
  487. * @throws PurchaseDeclarationException
  488. */
  489. public function getStatusAndPointsOfUser(Request $request): Response
  490. {
  491. /** @var User $currentUser */
  492. $currentUser = $this->getUser();
  493. if(!$currentUser->isDeveloper())
  494. {
  495. return new Response('Page non trouvée', 404);
  496. }
  497. $id = $request->query->get('id', '0');
  498. $email = $request->query->get('email', '');
  499. $force = $request->query->get('force', TRUE);
  500. $force = strtolower($force) !== 'false';
  501. $user = $this->em->getRepository(User::class)->find($id);
  502. if(is_null($user))
  503. {
  504. $user = $this->em->getRepository(User::class)->findOneByEmail($email);
  505. }
  506. if(is_null($user))
  507. {
  508. return new Response('User ' . $email . ' not found !');
  509. }
  510. $period = new Period('2010-01-01', '2023-01-01 00:00:00');
  511. $userPoints = $this->userPointService->getPointsOfUser($user, NULL, $force);
  512. $newPoints = $this->userPointService->getAvailablePoints($user);
  513. if(!is_null($request->get('update')))
  514. {
  515. if($newPoints < 0)
  516. {
  517. $corrections = $this->em->getRepository(PointTransaction::class)->findBy([
  518. 'label' => [
  519. 'Balance de points pour la nouvelle version du site',
  520. 'Balance de points période précédente',
  521. 'Balance de points après expiration',
  522. ],
  523. 'user' => $user,
  524. ],);
  525. if(!empty($corrections))
  526. {
  527. foreach($corrections as $correction)
  528. {
  529. $this->em->remove($correction);
  530. }
  531. $this->em->flush();
  532. }
  533. $userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
  534. $newPoints = $userPoints['availablePoints'];
  535. /** @var PointTransaction $firstPointTransaction */
  536. $firstPointTransaction = $this->em->getRepository(PointTransaction::class)->findOneBy([
  537. 'user' => $user,
  538. ], [
  539. 'createdAt' => 'ASC',
  540. ],);
  541. $date = $firstPointTransaction->getCreatedAt()->modify('-1 day');
  542. $ptt = $this->em->getRepository(PointTransactionType::class)->findOneBy([
  543. 'slug' => PointTransactionType::EXCEPTIONAL,
  544. ],);
  545. $newPt = (new PointTransaction())
  546. ->setCreatedAt($date)
  547. ->setUpdatedAt($date)
  548. ->setEffectiveAt($date)
  549. ->setUser($user)
  550. ->setValue(abs($newPoints))
  551. ->setLabel('Balance de points période précédente')
  552. ->setExpiredAt(NULL)
  553. ->setTransactionType($ptt)
  554. ;
  555. $this->em->persist($newPt);
  556. $this->em->flush();
  557. $userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
  558. $newPoints = $userPoints['availablePoints'];
  559. if($newPoints < 0)
  560. {
  561. $date = new DateTime('2021-07-01 00:00:00');
  562. $newPt = (new PointTransaction())
  563. ->setCreatedAt($date)
  564. ->setUpdatedAt($date)
  565. ->setEffectiveAt($date)
  566. ->setUser($user)
  567. ->setValue(abs($newPoints))
  568. ->setLabel('Balance de points après expiration')
  569. ->setExpiredAt(NULL)
  570. ->setTransactionType($ptt)
  571. ;
  572. $this->em->persist($newPt);
  573. $this->em->flush();
  574. $userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
  575. $newPoints = $userPoints['availablePoints'];
  576. if($newPoints < 0)
  577. {
  578. return new Response('erreur : $newPoints < 0');
  579. }
  580. }
  581. }
  582. $userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
  583. }
  584. $levels = [
  585. 'Level le 01/01/20 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2019/01/01')),
  586. 'Level le 31/12/20 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2019/12/31')),
  587. 'Level le 01/01/21 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2020/01/01')),
  588. 'Level le 01/04/21 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2020/12/31')),
  589. 'Level le 01/01/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2021/01/01')),
  590. 'Level le 01/02/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2021/12/31')),
  591. 'Level le 01/04/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2022/01/01')),
  592. 'Level le 01/06/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2022/12/31')),
  593. ];
  594. $labelLevel = [
  595. 0 => '',
  596. 1 => 'vip',
  597. 2 => 'ambassadeur',
  598. ];
  599. return $this->render('front/common/test-user-point-2.html.twig', [
  600. 'rows' => $userPoints,
  601. 'user_labels' => $labelLevel,
  602. 'user' => $user,
  603. 'levels' => $levels,
  604. 'version ' => $this->userPointService->getVersion(),
  605. ]);
  606. }
  607. /**
  608. * Retourne la version de la plateforme DTV et les infos du user connectés (le cas échéant))
  609. *
  610. * @return Response
  611. */
  612. public function getVersion(): Response
  613. {
  614. $maintenance = $this->platformService->maintenanceMode();
  615. $saleOrders = $this->em->getRepository(SaleOrder::class)->findBy([
  616. 'status' => \App\Constants\SaleOrder::ALL_PENDING_STATUS,
  617. 'isManagedByCustomer' => FALSE,
  618. ],);
  619. if(count($saleOrders) > 0)
  620. {
  621. /** @var SaleOrder $saleOrder */
  622. foreach($saleOrders as $index => $saleOrder)
  623. {
  624. if(count($saleOrder->getItems()) === 0)
  625. {
  626. unset($saleOrders[$index]);
  627. }
  628. }
  629. }
  630. /**
  631. * @var User $currentUser
  632. */
  633. $currentUser = $this->getUser();
  634. if(!is_null($currentUser))
  635. {
  636. $user_status = $currentUser->getStatus();
  637. }
  638. else
  639. {
  640. $user_status = 'not_connected';
  641. }
  642. return new JsonResponse([
  643. 'version' => $this->yamlReader->getVersion(),
  644. 'type' => Platform::MODULES[$this->yamlReader->getType()] ?? 'N/C',
  645. 'mailer' => $this->yamlReader->getMailer()['intercept_emails'] ?? FALSE,
  646. 'glady' => $this->yamlReader->getGlady()['enabled'] ?? FALSE,
  647. 'maintenance' => $maintenance['enabled'] ?? FALSE,
  648. 'admin_confirmation' => $this->settingStatusService->isOrderValidationEnabled($currentUser),
  649. 'saleOrders' => count($saleOrders),
  650. 'user_status' => $user_status,
  651. ],);
  652. }
  653. /**
  654. * @return Response
  655. */
  656. public function customerProductJson(): Response
  657. {
  658. /** @var User $currentUser */
  659. $currentUser = $this->getUser();
  660. if(!$currentUser->isDeveloper())
  661. {
  662. return new Response('Page non trouvée', 404);
  663. }
  664. return new Response('<html lang="fr"><body>' . $this->em
  665. ->getRepository(CustomerProduct::class)->getAllEnabledJson() . '</body></html>',);
  666. }
  667. /**
  668. * Route pour tester l'envoi d'email
  669. *
  670. * @param MailerService $mailerService
  671. *
  672. * @return Response
  673. * @throws ReflectionException
  674. * @throws ClientExceptionInterface
  675. * @throws RedirectionExceptionInterface
  676. * @throws ServerExceptionInterface
  677. * @throws Exception
  678. */
  679. public function testEmail(MailerService $mailerService): Response
  680. {
  681. /** @var User $currentUser */
  682. $currentUser = $this->getUser();
  683. if(!$currentUser->isDeveloper())
  684. {
  685. return new Response('Page non trouvée', 404);
  686. }
  687. $mailerService
  688. ->createApiMailRequest(MailTypes::UPDATE_POINTS)
  689. ->addRecipientToRequest($currentUser, MailerFactory::buildUpdatePoints(100))
  690. ->send()
  691. ;
  692. return new Response("<html><body></body></html>");
  693. }
  694. /**
  695. * Route pour tester la traduction
  696. *
  697. * @param TranslatorInterface $translator
  698. *
  699. * @return Response
  700. *
  701. * @throws Exception
  702. */
  703. public function testTranslation(TranslatorInterface $translator): Response
  704. {
  705. /** @var User $currentUser */
  706. $currentUser = $this->getUser();
  707. if(!$currentUser->isDeveloper())
  708. {
  709. return new Response('Page non trouvée', 404);
  710. }
  711. // Calcul des performances
  712. $stopwatch = new Stopwatch();
  713. $stopwatch->start('first_translation');
  714. $translator->trans('bienvenue');
  715. $stopwatch->stop('first_translation');
  716. $stopwatch->start('second_translation');
  717. $translator->trans('mes informations');
  718. $stopwatch->stop('second_translation');
  719. $stopwatch->start('third_translation');
  720. $stopwatch->stop('third_translation');
  721. return $this->render('test/trans.html.twig');
  722. }
  723. /**
  724. * @return Response
  725. */
  726. public function compareTwoYaml(): Response
  727. {
  728. /** @var User $currentUser */
  729. $currentUser = $this->getUser();
  730. if(!$currentUser->isDeveloper())
  731. {
  732. return new Response('Page non trouvée', 404);
  733. }
  734. $url1 = $this->getParameter('kernel.project_dir') . '/config/platform.loc/animation-lpm.dtv.loc.yaml';
  735. $url2 = $this->getParameter('kernel.project_dir') . '/config/platform.loc/lecercledaikin.dtv.loc.yaml';
  736. $file1 = Yaml::parseFile($url1);
  737. $file2 = Yaml::parseFile($url2);
  738. $diff = [];
  739. $diff = $this->compareKeysHtml($file1, $file2, $diff);
  740. $response = '';
  741. if(!empty($diff))
  742. {
  743. $response = "<ul>" . implode('', $diff) . "</ul>";
  744. }
  745. return new Response($response);
  746. }
  747. /** @param $file1
  748. * @param $file2
  749. * @param array $diff
  750. * @param int $level
  751. *
  752. * @return mixed
  753. */
  754. private function compareKeysHtml($file1, $file2, array $diff, int $level = 1)
  755. {
  756. $keys_diff = array_diff_key($file1, $file2);
  757. $keys_added = array_diff_key($file2, $file1);
  758. $keys_identical = array_intersect_key($file1, $file2);
  759. if(!empty($keys_diff))
  760. {
  761. foreach($keys_diff as $key => $value)
  762. {
  763. if(is_array($value) && isset($file1[$key]) && isset($file2[$key]))
  764. {
  765. $diff[] = "<li style='color:red;'> $key: <ul>";
  766. $diff = $this->compareKeysHtml($file1[$key], $file2[$key], $diff, $level + 1);
  767. $diff[] = '</ul></li>';
  768. }
  769. else
  770. {
  771. $diff[] = "<li style='color:red;'> $key: " . json_encode($value) . " </li>";
  772. }
  773. }
  774. }
  775. if(!empty($keys_added))
  776. {
  777. foreach($keys_added as $key => $value)
  778. {
  779. if(is_array($value) && isset($file1[$key]) && isset($file2[$key]))
  780. {
  781. $diff[] = "<li style='color:green;'> $key: <ul>";
  782. $diff = $this->compareKeysHtml($file1[$key], $file2[$key], $diff, $level + 1);
  783. $diff[] = '</ul></li>';
  784. }
  785. else
  786. {
  787. $diff[] = "<li style='color:green;'> $key:" . json_encode($value) . " </li>";
  788. }
  789. }
  790. }
  791. if(!empty($keys_identical))
  792. {
  793. foreach($keys_identical as $key => $value)
  794. {
  795. if(is_array($value) && isset($file1[$key]) && isset($file2[$key]))
  796. {
  797. $diff[] = "<li style='color:black;'> $key: <ul>";
  798. $diff = $this->compareKeysHtml($file1[$key], $file2[$key], $diff, $level + 1);
  799. $diff[] = '</ul></li>';
  800. }
  801. else
  802. {
  803. $diff[] = "<li style='color:black;'> $key: " . json_encode($value) . " </li>";
  804. }
  805. }
  806. }
  807. return $diff;
  808. }
  809. /**
  810. * @return Response
  811. */
  812. public function closedPlatform(): Response
  813. {
  814. $messageCloturePlatform = $this->em->getRepository(Setting::class)
  815. ->findOneByCached(['name' => 'GENERAL_MESSAGE_SITE_CLOSED'])
  816. ;
  817. $message = $messageCloturePlatform->getValue();
  818. return $this->render('common/closed/default.html.twig', [
  819. 'closeSiteMessage' => $message,
  820. ]);
  821. }
  822. /**
  823. * Méthode qui permet de vérifier les prix des commandes et les corriger si besoin
  824. *
  825. * @return Response|void
  826. *
  827. * @throws CatalogueException
  828. */
  829. public function checkSaleOrderPrices()
  830. {
  831. /** @var User $currentUser */
  832. $currentUser = $this->getUser();
  833. if(!$currentUser->isDeveloper())
  834. {
  835. return new Response('Page non trouvée', 404);
  836. }
  837. $global = $this->yamlReader->getGlobal();
  838. $rate = $global['point']['rate'];
  839. $saleOrders = $this->em->getRepository(SaleOrder::class)->findAll();
  840. /** @var SaleOrder $saleOrder */
  841. foreach($saleOrders as $saleOrder)
  842. {
  843. echo '<br>' . ($saleOrder->getTotal() / $rate) . '<br>';
  844. $total = 0;
  845. foreach($saleOrder->getItems() as $item)
  846. {
  847. $sku = $item->getSku();
  848. $gamme = $item->getGamme();
  849. $product = $this->jsonCatalogueService->getProductBySkuFromCatalogue($sku, $gamme);
  850. if(!is_null($product))
  851. {
  852. $price = $product->getSalePrice();
  853. echo $saleOrder->getId() . ' --- ' . $sku . ' - ' . $gamme . ' ' . $item->getName() . ' : ' . $item->getPriceHT() . ' vs ' . $price . '<br>';
  854. $item->setPriceHT($price);
  855. $total += $price * $item->getQuantity();
  856. }
  857. else
  858. {
  859. echo $sku . ' non présent dans le catalogue<br>';
  860. }
  861. }
  862. $saleOrder
  863. ->setTotal($total)->setOrderRate($rate)
  864. ;
  865. }
  866. $this->em->flush();
  867. die();
  868. }
  869. /**
  870. * @return RedirectResponse|Response
  871. *
  872. * @throws NonUniqueResultException
  873. */
  874. public function purchaseProductToBooster()
  875. {
  876. $purchaseProducts = $this->em->getRepository(PurchaseProduct::class)->findPurchaseProductsWithOldBoost();
  877. $purchaseProductItems = $this->em->getRepository(PurchaseProductItem::class)->findBy([
  878. 'purchase' => NULL,
  879. ],);
  880. if(count($purchaseProductItems) > 0)
  881. {
  882. foreach($purchaseProductItems as $purchaseProductItem)
  883. {
  884. $this->em->remove($purchaseProductItem);
  885. }
  886. $this->em->flush();
  887. }
  888. $total = 0;
  889. $formattedProducts = [];
  890. /** @var PurchaseProduct $purchaseProduct */
  891. foreach($purchaseProducts as $purchaseProduct)
  892. {
  893. $reference = $name = '';
  894. $referenceExplode = explode(' Boost', $purchaseProduct->getReference());
  895. if(count($referenceExplode) > 1)
  896. {
  897. $reference = $referenceExplode[0];
  898. }
  899. $nameExplode = explode('- Booster', $purchaseProduct->getName());
  900. if(count($nameExplode) > 1)
  901. {
  902. $reference = $purchaseProduct->getReference();
  903. $name = $nameExplode[array_key_last($nameExplode)];
  904. }
  905. $nameExplode = explode('Boost ', $purchaseProduct->getName());
  906. if(count($nameExplode) > 1)
  907. {
  908. $reference = $purchaseProduct->getReference();
  909. $name = $nameExplode[array_key_last($nameExplode)];
  910. }
  911. switch($name)
  912. {
  913. case 'DKN ALT 3 H HT_UExt 14kW 1ph':
  914. $name = 'DKN ALTHERMA 3 H HT_UExt   14kW 1ph';
  915. break;
  916. case 'DKN ALT 3 H HT_UExt 16kW 1ph':
  917. $name = 'DKN ALTHERMA 3 H HT_UExt   16kW 1ph';
  918. break;
  919. case 'DKN ALT 3 H HT_UExt 18kW 1ph':
  920. $name = 'DKN ALTHERMA 3 H HT_UExt   18kW 1ph';
  921. break;
  922. case 'DKN ALT 3 H HT_UExt 14kW 3ph':
  923. $name = 'DKN ALTHERMA 3 H HT_UExt   14kW 3ph';
  924. break;
  925. case 'DKN ALT 3 H HT_UExt 16kW 3ph':
  926. $name = 'DKN ALTHERMA 3 H HT_UExt   16kW 3ph';
  927. break;
  928. case 'DKN ALT 3 H HT_UExt 18kW 3ph':
  929. $name = 'DKN ALTHERMA 3 H HT_UExt   18kW 3ph';
  930. break;
  931. }
  932. /** @var PurchaseProduct $parent */
  933. $parent = $this->em->getRepository(PurchaseProduct::class)->findOneBy([
  934. 'reference' => $reference,
  935. 'name' => $name,
  936. ],);
  937. if(!$parent instanceof PurchaseProduct)
  938. {
  939. $parentTpms = $this->em->getRepository(PurchaseProduct::class)->findBy([
  940. 'reference' => $reference,
  941. ], [
  942. 'value' => 'asc',
  943. ],);
  944. $parent = $parentTpms[0];
  945. }
  946. $qb = $this->em
  947. ->createQueryBuilder()
  948. ->from(PurchaseProductItem::class, 'ppi')
  949. ->select('ppi')
  950. ->leftJoin('ppi.product', 'p')
  951. ->leftJoin('ppi.purchase', 'pu')
  952. ->andWhere('p.id = :pId')
  953. ->setParameter('pId', $purchaseProduct->getId())
  954. ->orderBy('pu.invoiceDate', 'ASC')
  955. ->setFirstResult(0)
  956. ->setMaxResults(1)
  957. ;
  958. $qb->orderBy('pu.invoiceDate', 'DESC');
  959. $qb
  960. ->select('ppi.id')->setMaxResults(NULL)
  961. ;
  962. $ids = $qb->getQuery()->getArrayResult();
  963. if(count($ids) > 0)
  964. {
  965. $formattedProducts[$parent->getId()] = $ids;
  966. $total += count($ids);
  967. if($total > 200)
  968. {
  969. break;
  970. }
  971. }
  972. }
  973. foreach($formattedProducts as $ppiId => $ppiIDs)
  974. {
  975. $qb = $this->em->createQueryBuilder();
  976. $qb
  977. ->from(PurchaseProductItem::class, 'ppi')
  978. ->select('ppi')
  979. ->andWhere('ppi.id IN (:ppiIDs)')
  980. ->setParameter('ppiIDs', $ppiIDs)
  981. ->setMaxResults(10)
  982. ;
  983. $ppis = $qb->getQuery()->getResult();
  984. $product = $this->em->getRepository(PurchaseProduct::class)->find($ppiId);
  985. /** @var PurchaseProductItem $ppi */
  986. foreach($ppis as $ppi)
  987. {
  988. $ppi->setProduct($product);
  989. }
  990. }
  991. if(count($formattedProducts) > 0)
  992. {
  993. $this->em->flush();
  994. return $this->redirectToRoute('test_purchase_products_to_booster');
  995. }
  996. /** @var PurchaseProduct $purchaseProduct */
  997. foreach($purchaseProducts as $purchaseProduct)
  998. {
  999. if(count($this->em
  1000. ->getRepository(PurchaseProductItem::class)->findBy(['product' => $purchaseProduct]),) > 0)
  1001. {
  1002. return new Response(' PurchaseProductItem.length > 0');
  1003. }
  1004. $this->em->remove($purchaseProduct);
  1005. }
  1006. $this->em->flush();
  1007. return new Response(TRUE);
  1008. }
  1009. /**
  1010. * @return Response
  1011. *
  1012. * @throws ClientExceptionInterface
  1013. * @throws RedirectionExceptionInterface
  1014. * @throws ServerExceptionInterface
  1015. */
  1016. public function getSaleOrderItemFees(): Response
  1017. {
  1018. /** @var User $currentUser */
  1019. $currentUser = $this->getUser();
  1020. if(!$currentUser->isDeveloper())
  1021. {
  1022. return new Response('Page non trouvée', 404);
  1023. }
  1024. return new Response("<html><body></body></html>");
  1025. }
  1026. /**
  1027. * @Route("/get-user-point-at/657sqd9f46q8sf4/{date}", name="getUserPointAt")
  1028. *
  1029. * @param $date
  1030. *
  1031. * @return JsonResponse
  1032. *
  1033. * @throws PurchaseDeclarationException
  1034. * @throws Exception
  1035. */
  1036. public function getUserPointAt($date): JsonResponse
  1037. {
  1038. $date = new DateTime($date);
  1039. $period = new Period('2010-01-01 00:00:00', $date);
  1040. $users = $this->em->getRepository(User::class)->findAll();
  1041. $finalUsers = [];
  1042. /** @var User $user */
  1043. foreach($users as $user)
  1044. {
  1045. if($user->isInstaller())
  1046. {
  1047. $finalUsers[] = [
  1048. 'email' => $user->getEmail(),
  1049. 'id' => $user->getId(),
  1050. 'points' => $this->userPointService->getAvailablePoints($user, $period),
  1051. 'level' => $this->userPointService->getLevelOneDate($user, $date),
  1052. ];
  1053. }
  1054. }
  1055. return new JsonResponse($finalUsers,);
  1056. }
  1057. /**
  1058. * Tableau de diagnostic sur les régates
  1059. * Code régate en double ou boucle de relation
  1060. *
  1061. * @return Response
  1062. */
  1063. public function checkRegate(): Response
  1064. {
  1065. /** @var User $currentUser */
  1066. $currentUser = $this->getUser();
  1067. if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
  1068. {
  1069. return new Response('Page non trouvée', 404);
  1070. }
  1071. $global = $this->yamlReader->getGlobal();
  1072. if(!$global['regate'])
  1073. {
  1074. return new Response('Les régates ne sont pas active sur cette plateforme');
  1075. }
  1076. $sameAffectation = $this->em->getRepository(Regate::class)->findSameAffectation();
  1077. $inLoop = $this->em->getRepository(Regate::class)->findCircularReferences();
  1078. return $this->render('front/common/check-regate.html.twig', [
  1079. 'sameAffectation' => $sameAffectation,
  1080. 'inLoop' => $inLoop,
  1081. ]);
  1082. }
  1083. /**
  1084. * @return Response
  1085. */
  1086. public function checkUsersRelation(): Response
  1087. {
  1088. /** @var User $currentUser */
  1089. $currentUser = $this->getUser();
  1090. if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
  1091. {
  1092. return new Response('Page non trouvée', 404);
  1093. }
  1094. $users = $this->em->getRepository(User::class)->findAll();
  1095. $relateToSelf = [];
  1096. /** @var User $user */
  1097. foreach($users as $user)
  1098. {
  1099. $child = $user->getChildren()->toArray();
  1100. if(in_array($user, $child, FALSE))
  1101. {
  1102. $relateToSelf[] = $user;
  1103. }
  1104. }
  1105. return $this->render('front/common/check-user-relation.html.twig', [
  1106. 'relateToSelf' => $relateToSelf,
  1107. ]);
  1108. }
  1109. public function checkUsersRelationRemove()
  1110. {
  1111. /** @var User $currentUser */
  1112. $currentUser = $this->getUser();
  1113. if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
  1114. {
  1115. return new Response('Page non trouvée', 404);
  1116. }
  1117. $users = $this->em->getRepository(User::class)->findAll();
  1118. /** @var User $user */
  1119. foreach($users as $user)
  1120. {
  1121. $child = $user->getChildren()->toArray();
  1122. if(in_array($user, $child, FALSE))
  1123. {
  1124. $user->removeChild($user);
  1125. }
  1126. }
  1127. $this->em->flush();
  1128. return $this->redirectToRoute('check_users_relation');
  1129. }
  1130. /**
  1131. * @Route("/getDatatable", name="/getDatatable")
  1132. *
  1133. * @param Request $request
  1134. *
  1135. * @return Response
  1136. */
  1137. public function getDataTableCustomQuery(Request $request): Response
  1138. {
  1139. $version = 2;
  1140. $config = Yaml::parseFile($this->getParameter('kernel.project_dir') . '/config/datatable/lecercledaikin/back_community_installer_list.yaml');
  1141. $config = $config[0];
  1142. $queryBuilder = $this->em->createQueryBuilder();
  1143. // Construction de la requête SELECT
  1144. $select = [];
  1145. foreach($config['queryBuilder']['customQuery']['select'] as $alias => $field)
  1146. {
  1147. $select[] = "$field AS $alias";
  1148. }
  1149. $queryBuilder->select(implode(', ', $select));
  1150. // Construction de la requête FROM
  1151. switch($version)
  1152. {
  1153. case 2:
  1154. $entityName = 'App\Entity\\' . $config['queryBuilder']['entityName'];
  1155. break;
  1156. default:
  1157. $entityName = $config['queryBuilder']['entityName'];
  1158. break;
  1159. }
  1160. $queryBuilder->from($entityName, 'user');
  1161. // Construction des jointures LEFT JOIN
  1162. foreach($config['queryBuilder']['customQuery']['leftJoin'] as $alias => $join)
  1163. {
  1164. $queryBuilder->leftJoin("$join", $alias);
  1165. }
  1166. // Appliquer les filtres de recherche
  1167. $queryBuilder = $this->applyFilters($queryBuilder, $config['searches'], $request->query->get('query', []));
  1168. $whereConditions = [];
  1169. foreach($config['queryBuilder']['preRequires'] as $index => $preRequire)
  1170. {
  1171. $condition = NULL;
  1172. if(isset($preRequire['fields']))
  1173. {
  1174. // Traitement des conditions basées sur des champs
  1175. $fields = [];
  1176. foreach($preRequire['fields'] as $field)
  1177. {
  1178. $fieldName = "field$index"; // Créez un nom de paramètre unique
  1179. $comparison = strtoupper($preRequire['comparison']);
  1180. $fieldExpression = "user.$field $comparison :$fieldName";
  1181. $fields[] = "($fieldExpression)";
  1182. $default = $preRequire['default'];
  1183. $default = $this->getGlobalValueIfExist($default);
  1184. $queryBuilder->setParameter($fieldName, $default);
  1185. }
  1186. $condition = '(' . implode(' AND ', $fields) . ')';
  1187. }
  1188. elseif(isset($preRequire['conditions']))
  1189. {
  1190. // Traitement des autres types de conditions (par exemple, in_array)
  1191. $conditions = [];
  1192. foreach($preRequire['conditions'] as $subCondition)
  1193. {
  1194. if($subCondition['type'] === 'in_array')
  1195. {
  1196. $field = "user." . $subCondition['fields'][0];
  1197. $needle = $subCondition['needle'];
  1198. $conditions[] = "$field IN (:needles)";
  1199. $queryBuilder->setParameter('needles', [$needle], Connection::PARAM_STR_ARRAY);
  1200. }
  1201. }
  1202. if(!empty($conditions))
  1203. {
  1204. $condition = '(' . implode(' AND ', $conditions) . ')';
  1205. }
  1206. }
  1207. if($condition)
  1208. {
  1209. $whereConditions[] = $condition;
  1210. }
  1211. }
  1212. if(!empty($whereConditions))
  1213. {
  1214. $queryBuilder->andWhere(implode(' OR ', $whereConditions));
  1215. }
  1216. // Ajouter d'autres parties de la requête ici, comme GROUP BY, ORDER BY, etc.
  1217. $query = $queryBuilder->getQuery();
  1218. $results = $query->getResult();
  1219. return new Response('<html><body>généré : ' . count($results) . '</body></html>');
  1220. }
  1221. /**
  1222. * Méthode pour appliquer les filtres de recherche
  1223. *
  1224. * @param $queryBuilder
  1225. * @param $filters
  1226. * @param array $searches
  1227. *
  1228. * @return mixed
  1229. */
  1230. private function applyFilters($queryBuilder, $filters, array $searches = [])
  1231. {
  1232. foreach($filters as $index => $filter)
  1233. {
  1234. if(array_key_exists("datatable_search_$index", $searches))
  1235. {
  1236. $filter['default'] = $searches["datatable_search_$index"];
  1237. }
  1238. switch($filter['type'])
  1239. {
  1240. case 'input':
  1241. $fieldName = "user." . $filter['query']['fields'][0];
  1242. $parameterName = ":{$filter['query']['fields'][0]}";
  1243. // Assurez-vous que la clé 'comparison' est définie dans le tableau $filter
  1244. $comparison = $filter['comparison'] ?? 'LIKE';
  1245. // Assurez-vous que la clé 'default' est définie dans le tableau $filter
  1246. $defaultValue = $filter['default'] ?? NULL;
  1247. if($defaultValue !== NULL)
  1248. {
  1249. $queryBuilder->andWhere("$fieldName $comparison $parameterName");
  1250. $queryBuilder->setParameter($parameterName, "%$defaultValue%");
  1251. }
  1252. break;
  1253. case 'select':
  1254. $fieldName = "user." . $filter['query']['fields'][0];
  1255. $parameterName = ":{$filter['query']['fields'][0]}";
  1256. // Assurez-vous que la clé 'default' est définie dans le tableau $filter
  1257. $defaultValue = $filter['default'] ?? '*';
  1258. $value = $this->getGlobalValueIfExist($defaultValue); // Utilisez la fonction pour obtenir la valeur dynamique
  1259. if($defaultValue !== '*' && $value !== NULL)
  1260. {
  1261. if(count($value) > 1)
  1262. {
  1263. $queryBuilder->andWhere("$fieldName IN ($parameterName)");
  1264. }
  1265. else
  1266. {
  1267. $queryBuilder->andWhere("$fieldName = $parameterName");
  1268. }
  1269. $queryBuilder->setParameter($parameterName, $value);
  1270. }
  1271. break;
  1272. // Ajouter d'autres types de filtres selon vos besoins
  1273. }
  1274. }
  1275. return $queryBuilder;
  1276. }
  1277. /**
  1278. * @param $val
  1279. * @param array $context
  1280. *
  1281. * @return User|array|int|mixed|string|string[]|null
  1282. */
  1283. private function getGlobalValueIfExist($val, array $context = [])
  1284. {
  1285. /** @var User $user */
  1286. $user = $this->getUser();
  1287. if(is_string($val) && array_key_exists($val, $context))
  1288. {
  1289. return $context[$val];
  1290. }
  1291. switch($val)
  1292. {
  1293. case '__currentUserRoles__':
  1294. return $user->getRoles();
  1295. case '__currentUserStatus__':
  1296. return $user->getStatus();
  1297. case '__currentUser__':
  1298. return $user;
  1299. case '__currentUserId__':
  1300. return $user->getId();
  1301. case '__currentUserAgencyId__':
  1302. if($user->getAgency() === NULL)
  1303. {
  1304. return NULL;
  1305. }
  1306. return $user->getAgency()->getId();
  1307. case '__currentUserRegateAffectation__':
  1308. if($user->getRegate() === NULL)
  1309. {
  1310. return NULL;
  1311. }
  1312. return ($user->getRegate())->getAffectation();
  1313. case '__currentUserRegateChildren__':
  1314. if($user->getRegate() === NULL)
  1315. {
  1316. return NULL;
  1317. }
  1318. return $this->regateService->getRegateIdTreeListFlat($user->getRegate(), FALSE);
  1319. case '__currentDomain__':
  1320. return $_SERVER['HTTP_HOST'];
  1321. case '__currentUserJob__':
  1322. return $user->getJob();
  1323. case '__currentUserRolesAndJob__':
  1324. $job = $user->getJob() ? [$user->getJob()] : [];
  1325. return array_merge($user->getRoles(), $job);
  1326. case '__currentUserExtensionPointSystem__':
  1327. return [$user->getExtensionBySlug(UserExtension::POINT_SYSTEM) ?? 'point'];
  1328. case '__currentUserParentOf__':
  1329. $userChildren = $this->userFrontService->getUserChildrenAtRoleAndJob($user);
  1330. $childrenId = [];
  1331. /** @var User $child */
  1332. foreach($userChildren as $child)
  1333. {
  1334. $childrenId[] = $child->getId();
  1335. }
  1336. return $childrenId;
  1337. default:
  1338. return $val;
  1339. }
  1340. }
  1341. /**
  1342. * @throws ReflectionException
  1343. */
  1344. public function getExportable(Reader $reader)
  1345. {
  1346. $finder = new Finder();
  1347. $finder->files()->in($this->projectDir . '/src/Entity')->depth(0)->name('*.php');
  1348. $traitFinder = new Finder();
  1349. $traitFinder->files()->in($this->projectDir . '/src/Traits')->depth(0)->name('*.php');
  1350. $exportableEntities = [];
  1351. $processedEntities = [];
  1352. // 1. Récupérer tous les traits et leurs propriétés @Exportable
  1353. $traitProperties = [];
  1354. foreach($traitFinder as $traitFile)
  1355. {
  1356. $traitName = 'App\\Traits\\' . $traitFile->getBasename('.php');
  1357. $reflectionTrait = new ReflectionClass($traitName);
  1358. if($reflectionTrait->isTrait())
  1359. {
  1360. foreach($reflectionTrait->getProperties() as $property)
  1361. {
  1362. if($reader->getPropertyAnnotation($property, Exportable::class))
  1363. {
  1364. $traitProperties[$reflectionTrait->getName()][] = $property->getName();
  1365. }
  1366. }
  1367. }
  1368. }
  1369. foreach($finder as $file)
  1370. {
  1371. $className = 'App\\Entity\\' . $file->getBasename('.php');
  1372. $reflectionClass = new ReflectionClass($className);
  1373. if($reflectionClass->isTrait())
  1374. {
  1375. foreach($reflectionClass->getProperties() as $property)
  1376. {
  1377. if($reader->getPropertyAnnotation($property, Exportable::class))
  1378. {
  1379. $traitProperties[$reflectionClass->getName()][] = $property->getName();
  1380. }
  1381. }
  1382. }
  1383. }
  1384. foreach($finder as $file)
  1385. {
  1386. $entityClass = 'App\\Entity\\' . $file->getBasename('.php');
  1387. $reflectionClass = new ReflectionClass($entityClass);
  1388. if($reflectionClass->isAbstract() || $reflectionClass->isInterface() || $reflectionClass->isTrait())
  1389. {
  1390. continue;
  1391. }
  1392. if($reader->getClassAnnotation($reflectionClass, ExportableEntity::class))
  1393. {
  1394. $exportableFields = [];
  1395. // Vérifier si l'entité utilise l'un des traits et récupérer ses propriétés
  1396. foreach($reflectionClass->getTraitNames() as $usedTrait)
  1397. {
  1398. if(array_key_exists($usedTrait, $traitProperties))
  1399. {
  1400. foreach($traitProperties[$usedTrait] as $traitProperty)
  1401. {
  1402. $exportableFields[] = $traitProperty;
  1403. }
  1404. }
  1405. }
  1406. $metadata = $this->em->getClassMetadata($entityClass);
  1407. foreach($reflectionClass->getProperties() as $property)
  1408. {
  1409. if($reader->getPropertyAnnotation($property, Exportable::class))
  1410. {
  1411. $propertyName = $property->getName();
  1412. // Pour la relation OneToMany ou OneToOne
  1413. if(isset($metadata->associationMappings[$propertyName]))
  1414. {
  1415. $associationType = $metadata->associationMappings[$propertyName]['type'];
  1416. if($associationType === ClassMetadataInfo::ONE_TO_MANY || $associationType === ClassMetadataInfo::ONE_TO_ONE)
  1417. {
  1418. $associatedEntityClass = $metadata->associationMappings[$propertyName]['targetEntity'];
  1419. // Si l'entité associée n'a pas déjà été traitée
  1420. if(!in_array($associatedEntityClass, $processedEntities))
  1421. {
  1422. $associatedReflectionClass = new ReflectionClass($associatedEntityClass);
  1423. $associatedExportableFields = [];
  1424. foreach($associatedReflectionClass->getProperties() as $associatedProperty)
  1425. {
  1426. if($reader->getPropertyAnnotation($associatedProperty, Exportable::class))
  1427. {
  1428. $associatedExportableFields[] = $associatedProperty->getName();
  1429. }
  1430. }
  1431. $exportableFields[$associatedEntityClass] = $associatedExportableFields;
  1432. $processedEntities[] = $associatedEntityClass;
  1433. }
  1434. }
  1435. }
  1436. else
  1437. {
  1438. $exportableFields[] = $propertyName;
  1439. }
  1440. }
  1441. }
  1442. foreach($reflectionClass->getMethods() as $method)
  1443. {
  1444. if($reader->getMethodAnnotation($method, ExportableMethod::class) || $reader->getMethodAnnotation($method, Exportable::class))
  1445. {
  1446. $exportableFields[] = $method->getName();
  1447. }
  1448. }
  1449. $exportableEntities[$entityClass] = $exportableFields;
  1450. }
  1451. }
  1452. // Filtrer les entités qui ont déjà été traitées comme des entités associées
  1453. foreach($processedEntities as $processedEntity)
  1454. {
  1455. unset($exportableEntities[$processedEntity]);
  1456. }
  1457. return new Response('<html><body>généré : ' . count($exportableEntities) . '</body></html>');
  1458. }
  1459. /**
  1460. * @return JsonResponse
  1461. * @throws Exception
  1462. */
  1463. public function MailwizzCustomerCreate(): JsonResponse
  1464. {
  1465. $response = [];
  1466. $subDomain = $this->yamlReader->getSubdomain();
  1467. $email = 'admin@' . $subDomain;
  1468. // supprimer un adminCustomer s'il existe
  1469. $this->mailService->removeCustomerOnMailwizzDB($email);
  1470. // crée un nouvel adminCustomer
  1471. $customerPlainPassword = $this->commonServices->generatePassword(8);
  1472. $passwordHasher = new PasswordHash(13, TRUE);
  1473. $customerPassword = $passwordHasher->HashPassword($customerPlainPassword);
  1474. $customer = [
  1475. 'customer_id' => NULL,
  1476. 'customer_uid' => $this->mailService->uniqid(),
  1477. 'parent_id' => NULL,
  1478. 'group_id' => NULL,
  1479. 'language_id' => NULL,
  1480. 'first_name' => 'DTV',
  1481. 'last_name' => $subDomain,
  1482. 'email' => $email,
  1483. 'password' => $customerPassword,
  1484. 'timezone' => 'Europe/Paris',
  1485. 'avatar' => NULL,
  1486. 'hourly_quota' => 0,
  1487. 'removable' => 'yes',
  1488. 'confirmation_key' => NULL,
  1489. 'oauth_uid' => NULL,
  1490. 'oauth_provider' => NULL,
  1491. 'status' => 'active',
  1492. 'birth_date' => (new DateTime())->modify('-20 years')->format('Y-m-d'),
  1493. 'phone' => NULL,
  1494. 'twofa_enabled' => 'no',
  1495. 'twofa_secret' => '',
  1496. 'twofa_timestamp' => '0',
  1497. 'date_added' => (new DateTime())->modify('-1 day')->format('Y-m-d'),
  1498. 'last_login' => (new DateTime())->format('Y-m-d'),
  1499. 'inactive_at' => NULL,
  1500. ];
  1501. $customer = $this->mailService->createCustomer($customer);
  1502. $apiKey = $this->mailService->createCustomerApiKey($email);
  1503. $response['customerAdmin'] = $customer;
  1504. $response['customerApiKey'] = $apiKey;
  1505. // création de sender mailWizz
  1506. $response['deliveryServer'] = $this->mailService->createMailwizzDeliveryServer($customer);
  1507. return new JsonResponse($response);
  1508. }
  1509. /**
  1510. * @Route ("/test-communcation-between-child-and-portail", name="test_communication_between_child_and_portail")
  1511. * @return Response
  1512. */
  1513. public function testCommunicationBetweenPortailAndChild(): Response
  1514. {
  1515. /** @var User $currentUser */
  1516. $currentUser = $this->getUser();
  1517. if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
  1518. {
  1519. return new Response('Page non trouvée', 404);
  1520. }
  1521. try
  1522. {
  1523. // Request to child http://stellantis.fs-clubelite.dtv.loc/test-communcation-between-child-and-portail
  1524. $response = $this->client->request('GET', 'http://stellantis.fs-clubelite.dtv.loc/api/test-communcation-between-portail-and-child', [], [], [
  1525. 'HTTP_X-Auth-Token' => '123456789',
  1526. ],);
  1527. $statusCode = $response->getStatusCode();
  1528. $content = json_decode($response->getContent(), TRUE);
  1529. } catch(Exception $e)
  1530. {
  1531. return new Response($e->getMessage());
  1532. }
  1533. return new JsonResponse($content, $statusCode);
  1534. }
  1535. /**
  1536. * @Route ("/test-account-id-constraint", name="test_account_id_constraint")
  1537. * @return Response
  1538. */
  1539. public function testAccountIdConstraint(): Response
  1540. {
  1541. /** @var User $currentUser */
  1542. $currentUser = $this->getUser();
  1543. if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
  1544. {
  1545. return new Response('Page non trouvée', 404);
  1546. }
  1547. // $token = md5(uniqid(rand(), TRUE));
  1548. $token = 'TEST55';
  1549. // $user = $this->userService->initUser();
  1550. // $user->setFirstName('test')
  1551. // ->setLastName('test')
  1552. // ->setEmail($token.'@test.fr')
  1553. // ->setPassword('test');
  1554. // $this->em->persist($user);
  1555. // $user2 = $this->userService->initUser();
  1556. // $user2->setFirstName('test')
  1557. // ->setLastName('test')
  1558. // ->setEmail($token.'@test.fr')
  1559. // ->setPassword('test');
  1560. // $this->em->persist($user2);
  1561. // $this->em->flush();
  1562. return new JsonResponse('OK', 200);
  1563. }
  1564. /**
  1565. * @Route ("/api/test-communcation-between-portail-and-child", name="test_communication_between_portail_and_child")
  1566. * @return JsonResponse
  1567. */
  1568. public function testCommunicationBetweenChildAndPortail(): JsonResponse
  1569. {
  1570. return new JsonResponse([
  1571. 'status' => 'success',
  1572. 'message' => 'Hello',
  1573. ], 200);
  1574. }
  1575. /**
  1576. * @Route ("/test-ubr", name="test_ubr")
  1577. */
  1578. public function testUserBusinessResult(): Response
  1579. {
  1580. $stepsData = $this->highlightService->getHighlightActiveSteps();
  1581. $pointsByStep = [];
  1582. // Remplir $pointsByStep avec les points correspondant à chaque étape
  1583. foreach($stepsData as $step => $data)
  1584. {
  1585. // S'assurer que 'max' est défini, sinon utiliser une valeur par défaut élevée
  1586. $max = $data['max'] !== NULL ? $data['max'] : $data['min'];
  1587. for($i = $data['min']; $i <= $max; $i++)
  1588. {
  1589. $pointsByStep[$i] = $data['points'];
  1590. }
  1591. }
  1592. $globalMin = min(array_keys($pointsByStep));
  1593. $globalMax = max(array_keys($pointsByStep));
  1594. $ubrs = $this->em->getRepository(UserBusinessResult::class)->findByUniqueAccountId(null, false, false, true);
  1595. foreach($ubrs as $key => $ubr)
  1596. {
  1597. if($ubr['totalSale'] > $globalMax)
  1598. {
  1599. $ubrs[$key] ['total'] = $pointsByStep[$globalMax];
  1600. }
  1601. elseif($ubr['totalSale'] < $globalMin)
  1602. {
  1603. $ubrs[$key] ['total'] = $pointsByStep[$globalMin];
  1604. }
  1605. else
  1606. {
  1607. $ubrs[$key] ['total'] = $pointsByStep[$ubr['totalSale']];
  1608. }
  1609. }
  1610. $users = $this->em
  1611. ->createQueryBuilder()->from(User::class, 'u', 'u.id')->select('u')->getQuery()->getResult()
  1612. ;
  1613. $transactionType = $this->em->getRepository(PointTransactionType::class)->findOneBy([
  1614. 'slug' => PointTransactionType::FIDELITY,
  1615. ],);
  1616. $currentHighlight = $this->highlightService->getHighlight();
  1617. foreach($ubrs as $ubr)
  1618. {
  1619. $pointTransaction = (new PointTransaction())
  1620. ->setUser($users[$ubr['userId']])
  1621. ->setValue(abs($ubr['total']))
  1622. ->setLabel('Conversion des résultats du temps fort ' . $currentHighlight['name'] . ' en points')
  1623. ->setTransactionType($transactionType)
  1624. ->setCreatedAt(new DateTime())
  1625. ->setSubtype(PointTransaction::TRANSACTION_HIGHLIGHT)
  1626. ;
  1627. $this->em->persist($pointTransaction);
  1628. }
  1629. $this->em->flush();
  1630. $this->em
  1631. ->createQuery('UPDATE ' . UserBusinessResult::class . ' ubr SET ubr.highlight = :highlight WHERE ubr.highlight IS NULL')
  1632. ->setParameter('highlight', $currentHighlight['number'])
  1633. ->execute()
  1634. ;
  1635. return new Response('<body></body>');
  1636. }
  1637. /**
  1638. * @Route ("/test-ubr-2", name="test_ubr_2")
  1639. */
  1640. public function testUserBusinessResult2(): Response
  1641. {
  1642. $stepsData = $this->highlightService->getHighlightActiveSteps();
  1643. $pointsByStep = [];
  1644. // Remplir $pointsByStep avec les points correspondant à chaque étape
  1645. foreach($stepsData as $step => $data)
  1646. {
  1647. // S'assurer que 'max' est défini, sinon utiliser une valeur par défaut élevée
  1648. $max = $data['max'] !== NULL ? $data['max'] : $data['min'];
  1649. for($i = $data['min']; $i <= $max; $i++)
  1650. {
  1651. $pointsByStep[$i] = $data['points'];
  1652. }
  1653. }
  1654. $globalMin = min(array_keys($pointsByStep));
  1655. $globalMax = max(array_keys($pointsByStep));
  1656. $ubrs = $this->em->getRepository(UserBusinessResult::class)->findByUniqueAccountIdForCurrent_2();
  1657. $userIds = [];
  1658. foreach($ubrs as $key => $ubr)
  1659. {
  1660. if($ubr['totalSale'] > $globalMax)
  1661. {
  1662. $ubrs[$key] ['total'] = $pointsByStep[$globalMax];
  1663. }
  1664. elseif($ubr['totalSale'] < $globalMin)
  1665. {
  1666. $ubrs[$key] ['total'] = $pointsByStep[$globalMin];
  1667. }
  1668. else
  1669. {
  1670. $ubrs[$key] ['total'] = $pointsByStep[$ubr['totalSale']];
  1671. }
  1672. $userIds[] = $ubr['userId'];
  1673. }
  1674. $userIds = array_unique($userIds);
  1675. $users = $this->em->getRepository(User::class)->getUserByIds($userIds, TRUE);
  1676. $transactionType = $this->em->getRepository(PointTransactionType::class)
  1677. ->findOneBySlug(PointTransactionType::FIDELITY)
  1678. ;
  1679. $currentHighlight = $this->highlightService->getHighlight();
  1680. foreach($ubrs as $key => $ubr)
  1681. {
  1682. $pts = $ubr['total'];
  1683. $pointTransaction = new PointTransaction();
  1684. $pointTransaction
  1685. ->setValue($pts)
  1686. ->setUser($users[$ubr['userId']])
  1687. ->setLabel('Conversion des résultats du temps fort ' . $currentHighlight['name'] . ' en points')
  1688. ->setTransactionType($transactionType)
  1689. ->setSubtype(PointTransaction::TRANSACTION_HIGHLIGHT)
  1690. ;
  1691. $this->em->persist($pointTransaction);
  1692. }
  1693. $this->em->flush(); // Persist objects that did not make up an entire batch
  1694. return new Response('<body></body>');
  1695. }
  1696. /**
  1697. * @Route ("/test-update-user/{id}", name="test_update_user")
  1698. */
  1699. public function testUpdateUser(string $id): Response
  1700. {
  1701. /** @var User $currentUser */
  1702. $currentUser = $this->getUser();
  1703. if(!$currentUser->isDeveloper())
  1704. {
  1705. return new Response('Page non trouvée', 404);
  1706. }
  1707. $user = $this->em->getRepository(User::class)->find($id);
  1708. $user
  1709. ->setFirstName('test')->setLastName('test')->setLastActivity(new DateTime())
  1710. ;
  1711. $this->em->flush();
  1712. return new JsonResponse('OK', 200);
  1713. }
  1714. }