src/Controller/Common/CommonController.php line 269

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