src/Controller/Common/CommonController.php line 263

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