src/Controller/Common/CommonController.php line 659

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