<?php
namespace App\Controller\Common;
use App\Annotation\Exportable;
use App\Annotation\ExportableEntity;
use App\Annotation\ExportableMethod;
use App\Constants\Platform;
use App\Constants\UserExtension;
use App\Entity\CustomerProduct;
use App\Entity\Parameter;
use App\Entity\PointTransaction;
use App\Entity\PointTransactionType;
use App\Entity\Purchase;
use App\Entity\PurchaseProduct;
use App\Entity\PurchaseProductItem;
use App\Entity\Regate;
use App\Entity\SaleOrder;
use App\Entity\Setting;
use App\Entity\User;
use App\Entity\UserBusinessResult;
use App\Exception\CatalogueException;
use App\Exception\PurchaseDeclarationException;
use App\Factory\Platform\MailerFactory;
use App\Services\Common\Point\UserPointService;
use App\Model\Period;
use App\Services\Back\RegateService;
use App\Services\Common\Email\MailTypes;
use App\Services\Common\MailerService;
use App\Services\Common\PlatformService;
use App\Services\Common\Point\UserPointServiceInterface;
use App\Services\Common\SettingStatusService;
use App\Services\Common\UserService;
use App\Services\CommonServices;
use App\Services\ConfigService;
use App\Services\DTV\MailService;
use App\Services\DTV\YamlConfig\YamlReader;
use App\Services\Front\Catalogue\JsonCatalogueService;
use App\Services\Front\UserFrontService;
use App\Services\HighlightService;
use DateTime;
use Doctrine\Common\Annotations\Reader;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\NonUniqueResultException;
use Exception;
use Hautelook\Phpass\PasswordHash;
use ReflectionClass;
use ReflectionException;
use RuntimeException;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Yaml\Yaml;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class CommonController extends AbstractController
{
private KernelInterface $kernel;
private EntityManagerInterface $em;
private ConfigService $configService;
private PlatformService $platformService;
private YamlReader $yamlReader;
private UserPointServiceInterface $userPointService;
private JsonCatalogueService $jsonCatalogueService;
private RegateService $regateService;
private UserFrontService $userFrontService;
private string $projectDir;
private SettingStatusService $settingStatusService;
private MailService $mailService;
private CommonServices $commonServices;
private HttpClientInterface $client;
private HighlightService $highlightService;
private UserService $userService;
/**
* @param KernelInterface $kernel
* @param EntityManagerInterface $em
* @param ConfigService $configService
* @param PlatformService $platformService
* @param YamlReader $yamlReader
* @param UserPointService $userPointService
* @param JsonCatalogueService $jsonCatalogueService
* @param RegateService $regateService
* @param UserFrontService $userFrontService
* @param SettingStatusService $settingStatusService
* @param MailService $mailService
* @param CommonServices $commonServices
* @param HttpClientInterface $client
* @param HighlightService $highlightService
* @param string $projectDir
* @param UserService $userService
*
* @throws Exception
*/
public function __construct(KernelInterface $kernel, EntityManagerInterface $em, ConfigService $configService, PlatformService $platformService, YamlReader $yamlReader, UserPointService $userPointService, JsonCatalogueService $jsonCatalogueService, RegateService $regateService, UserFrontService $userFrontService, SettingStatusService $settingStatusService, MailService $mailService, CommonServices $commonServices, HttpClientInterface $client, HighlightService $highlightService, string $projectDir, UserService $userService)
{
$this->kernel = $kernel;
$this->em = $em;
$this->configService = $configService;
$this->platformService = $platformService;
$this->yamlReader = $yamlReader;
$this->userPointService = $userPointService;
$this->jsonCatalogueService = $jsonCatalogueService;
$this->regateService = $regateService;
$this->userFrontService = $userFrontService;
$this->projectDir = $projectDir;
$this->settingStatusService = $settingStatusService;
$this->commonServices = $commonServices;
$this->mailService = $mailService;
$this->client = $client;
$this->highlightService = $highlightService;
$this->userService = $userService;
}
/**
* @return RedirectResponse
*/
public function backRedirection(): RedirectResponse
{
return $this->redirectToRoute('back_dashboard');
}
/**
* @param string $folder
* @param string $fileName
*
* @return BinaryFileResponse
*
* @throws Exception
*/
public function exposeFolderFile(string $folder, string $fileName): BinaryFileResponse
{
$path = $this->getParameter('kernel.project_dir') . '/medias/' . $this->platformService->getDomain() . '/' . $folder . '/';
$file = $path . $fileName;
if(!file_exists($file))
{
throw $this->createNotFoundException("Cette ressource n'existe pas");
}
return $this->file($file);
}
/**
* @param string $fileName
*
* @return object|BinaryFileResponse
*
* @throws Exception
*/
public function exposeProjectFile(string $fileName, string $prefix = null)
{
$folder = $this->platformService->getDomain() . '/';
$path = $this->getParameter('kernel.project_dir') . '/medias/' . $folder;
$file = $path . ($prefix ? '/' . $prefix . '/' : '') . $fileName;
if(!file_exists($file))
{
throw $this->createNotFoundException('La ressource n\'existe pas');
}
return $this->file($file);
}
/**
* Route qui ne sert qu'à évaluer le temps nécessaire à fournir l'image
*
* @param string $fileName
*
* @return Response
*
* @throws Exception
*/
public function exposeProjectFileBody(string $fileName): Response
{
$folder = $this->platformService->getDomain() . '/';
$path = $this->getParameter('kernel.project_dir') . '/medias/' . $folder;
$file = $path . $fileName;
if(!file_exists($file))
{
throw $this->createNotFoundException('La ressource n\'existe pas');
}
return new Response('<body>' . $file . '</body>');
}
/**
* @param string $file
* @param $size
*
* @return BinaryFileResponse
*/
public function getPicture(string $file, $size): BinaryFileResponse
{
$src = "http://bo.37deux.com/pictures/$size/$file";
$dir = $this->getParameter('kernel.project_dir') . "/medias/$size";
$dest = "$dir/$file";
if(!is_dir($dir) && !mkdir($dir, 0755) && !is_dir($dir))
{
throw new RuntimeException(sprintf('Directory "%s" was not created', $dir));
}
if(!file_exists($dest))
{
$data = $this->get_content($src);
file_put_contents($dest, $data);
}
return $this->file($file);
}
/**
* @param string $URL
*
* @return bool|string
*/
private function get_content(string $URL)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* @param string $slug
*
* @return Response
*/
public function getDocument(string $slug): Response
{
$document = $this->em->getRepository(Parameter::class)->findOneBy([
'slug' => $slug,
],);
if(empty($document))
{
throw $this->createNotFoundException("Ce document n'existe pas");
}
// on vérifie si le document est public
if(!$document->isPublic() && $this->getUser() === NULL)
{
$this->addFlash('info', "Vous n'avez pas le droit d'accéder à ce document");
throw $this->createAccessDeniedException("Vous n'avez pas le droit de consulter ce document");
}
if($document->getFileName() !== NULL)
{
return $this->redirectToRoute('static_file_folder', [
'folder' => $this->getParameter('app.path.general_documents'),
'fileName' => $document->getFileName(),
]);
}
return $this->render($this->configService->getTemplateDependingDomain('front/common/document.html.twig'), [
'document' => $document,
]);
}
/**
* @TODO: check si toujours utilisée
*
* @param string $slug
*
* @return JsonResponse
*/
public function getAjaxDocumentHtml(string $slug): JsonResponse
{
/** @var Parameter $document */
$document = $this->em->getRepository(Parameter::class)->findOneBy([
'slug' => $slug,
],);
if($document instanceof Parameter && $document->getValue() !== NULL)
{
$html = $this->renderView('front/common/document-panel.html.twig', [
'document' => $document,
]);
$redirect = FALSE;
}
else
{
$html = '';
$redirect = TRUE;
}
return new JsonResponse([
'redirect' => $redirect,
'html' => $html,
'title' => $document->getTitle(),
],);
}
/**
* @return Response
*
* @throws Exception
*/
public function BddUp(): Response
{
$application = new Application($this->kernel);
$application->setAutoExit(FALSE);
$input = new ArrayInput([
'command' => 'dtv:bdd-update',
// (optional) define the value of command arguments
'project' => $this->yamlReader->getGlobal()['subdomain'],
],);
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
$content .= '<a href="/">retour au site</a>';
// return new Response(""), if you used NullOutput()
return new Response('<pre>' . $content . '</pre>');
}
/**
* Crée un compte Developer
*
* @param Request $request
*
* @return Response
*/
public function CreateDeveloper(Request $request): Response
{
$email = $request->query->get('email');
$user = $this->em->getRepository(User::class)->findOneBy([
'email' => $email,
],);
if($user instanceof User)
{
return new Response("Developer $email already exists");
}
if(is_null($email))
{
return new Response("Email is required");
}
$passwordHash = new PasswordHash(8, FALSE);
$password = $passwordHash->HashPassword('pass1234');
$user = ($this->userService->initUser())
->setEmail($email)
->setPassword($password)
->setRoles(['ROLE_DEVELOPER'])
->setFirstname('Developer')
->setLastname($email)
->setStatus('enabled')
->setCguAt(new DateTime())
->setCreatedAt(new DateTime())
->setUpdatedAt(new DateTime())
;
$this->em->persist($user);
$this->em->flush();
return new Response("Developer $email created with password pass1234");
}
/**
* @param Request $request
*
* @return Response
*/
public function showUserStatusDaikin(Request $request): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
{
return new Response('Page non trouvée', 404);
}
$thisYear = (new DateTime())->format('Y') * 1;
$lastYear = $thisYear - 1;
$nextYear = $thisYear + 1;
$period = new Period("$thisYear/01/01 00:00:00", "$thisYear/12/31 23:59:59");
$newUser = $request->request->get('newUser', FALSE);
$pointThisYear = $request->request->get('pointThisYear', 0);
$pointLastYear = $request->request->get('pointLastYear', 0);
if($pointLastYear >= 1000)
{
$levelLastYear = 2;
}
elseif($pointLastYear >= 500)
{
$levelLastYear = 1;
}
else
{
$levelLastYear = 0;
}
if($pointThisYear >= 1000)
{
$levelThisYear = 2;
}
elseif($pointThisYear >= 500)
{
$levelThisYear = 1;
}
else
{
$levelThisYear = 0;
}
$data = [
'thisYear' => $thisYear,
'lastYear' => $lastYear,
'nextYear' => $nextYear,
'period' => $period,
'pointThisYear' => $pointThisYear,
'pointLastYear' => $pointLastYear,
'newUser' => $newUser,
'levelLastYear' => $levelLastYear,
'levelThisYear' => $levelThisYear,
];
$data['data'] = $this->userPointService->getUserStatusDaikinFormatted($data);
return $this->render('front/common/test-user-status.html.twig', $data);
}
/**
* @return Response
*
* @throws Exception
*/
public function getUsersDaikin(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
set_time_limit(0);
$users = $this->em->getRepository(User::class)->findAll();
$countUsers = [];
$response = '<table>';
for($year = 2021; $year <= 2022; $year++)
{
for($month = 1; $month <= 12; $month++)
{
$fin = date("Ymt", strtotime($year . '-' . $month . '-1'));
$formattedDate = (new DateTime($year . '-' . $month . '-1'))->format('M Y');
/**
* @var $index
* @var User $user
*/
foreach($users as $user)
{
if(!$user->isInstaller())
{
continue;
}
if($user->getCguAt() == NULL)
{
continue;
}
if($user->isDeleted())
{
continue;
}
$created_at = $user->getCreatedAt()->format('Ymd');
if($created_at > $fin)
{
continue;
}
if($user->getArchivedAt() !== NULL)
{
$archived_at = $user->getArchivedAt()->format('Ymd');
if($archived_at <= $fin)
{
continue;
}
}
$countUsers[$formattedDate]['total'] = ($countUsers[$formattedDate]['total'] ?? 0) + 1;
$cgu_at = $user->getCguAt()->format('Ymd');
if($cgu_at <= $fin)
{
$purchases = $this->em
->getRepository(Purchase::class)->getPurchaseUserAtDate($user->getId(), $fin)
;
if(!empty($purchases))
{
$countUsers[$formattedDate]['actif'] = ($countUsers[$formattedDate]['actif'] ?? 0) + 1;
}
}
}
$response .= '<tr>';
$response .= '<td>' . $countUsers[$formattedDate]['total'] . '</td>';
$response .= '<td>' . $countUsers[$formattedDate]['actif'] . '</td>';
$response .= '</tr>';
}
}
$response .= '</table>';
return new Response($response);
}
/**
* @param Request $request
*
* @return Response
*
* @throws PurchaseDeclarationException
*/
public function getStatusAndPointsOfUser(Request $request): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
$id = $request->query->get('id', '0');
$email = $request->query->get('email', '');
$force = $request->query->get('force', TRUE);
$force = strtolower($force) !== 'false';
$user = $this->em->getRepository(User::class)->find($id);
if(is_null($user))
{
$user = $this->em->getRepository(User::class)->findOneByEmail($email);
}
if(is_null($user))
{
return new Response('User ' . $email . ' not found !');
}
$period = new Period('2010-01-01', '2023-01-01 00:00:00');
$userPoints = $this->userPointService->getPointsOfUser($user, NULL, $force);
$newPoints = $this->userPointService->getAvailablePoints($user);
if(!is_null($request->get('update')))
{
if($newPoints < 0)
{
$corrections = $this->em->getRepository(PointTransaction::class)->findBy([
'label' => [
'Balance de points pour la nouvelle version du site',
'Balance de points période précédente',
'Balance de points après expiration',
],
'user' => $user,
],);
if(!empty($corrections))
{
foreach($corrections as $correction)
{
$this->em->remove($correction);
}
$this->em->flush();
}
$userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
$newPoints = $userPoints['availablePoints'];
/** @var PointTransaction $firstPointTransaction */
$firstPointTransaction = $this->em->getRepository(PointTransaction::class)->findOneBy([
'user' => $user,
], [
'createdAt' => 'ASC',
],);
$date = $firstPointTransaction->getCreatedAt()->modify('-1 day');
$ptt = $this->em->getRepository(PointTransactionType::class)->findOneBy([
'slug' => PointTransactionType::EXCEPTIONAL,
],);
$newPt = (new PointTransaction())
->setCreatedAt($date)
->setUpdatedAt($date)
->setEffectiveAt($date)
->setUser($user)
->setValue(abs($newPoints))
->setLabel('Balance de points période précédente')
->setExpiredAt(NULL)
->setTransactionType($ptt)
;
$this->em->persist($newPt);
$this->em->flush();
$userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
$newPoints = $userPoints['availablePoints'];
if($newPoints < 0)
{
$date = new DateTime('2021-07-01 00:00:00');
$newPt = (new PointTransaction())
->setCreatedAt($date)
->setUpdatedAt($date)
->setEffectiveAt($date)
->setUser($user)
->setValue(abs($newPoints))
->setLabel('Balance de points après expiration')
->setExpiredAt(NULL)
->setTransactionType($ptt)
;
$this->em->persist($newPt);
$this->em->flush();
$userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
$newPoints = $userPoints['availablePoints'];
if($newPoints < 0)
{
return new Response('erreur : $newPoints < 0');
}
}
}
$userPoints = $this->userPointService->getPointsOfUser($user, $period, $force);
}
$levels = [
'Level le 01/01/20 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2019/01/01')),
'Level le 31/12/20 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2019/12/31')),
'Level le 01/01/21 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2020/01/01')),
'Level le 01/04/21 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2020/12/31')),
'Level le 01/01/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2021/01/01')),
'Level le 01/02/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2021/12/31')),
'Level le 01/04/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2022/01/01')),
'Level le 01/06/22 : ' . $this->userPointService->getLevelOneDate($user, new DateTime('2022/12/31')),
];
$labelLevel = [
0 => '',
1 => 'vip',
2 => 'ambassadeur',
];
return $this->render('front/common/test-user-point-2.html.twig', [
'rows' => $userPoints,
'user_labels' => $labelLevel,
'user' => $user,
'levels' => $levels,
'version ' => $this->userPointService->getVersion(),
]);
}
/**
* Retourne la version de la plateforme DTV et les infos du user connectés (le cas échéant))
*
* @return Response
*/
public function getVersion(): Response
{
$maintenance = $this->platformService->maintenanceMode();
$saleOrders = $this->em->getRepository(SaleOrder::class)->findBy([
'status' => \App\Constants\SaleOrder::ALL_PENDING_STATUS,
'isManagedByCustomer' => FALSE,
],);
if(count($saleOrders) > 0)
{
/** @var SaleOrder $saleOrder */
foreach($saleOrders as $index => $saleOrder)
{
if(count($saleOrder->getItems()) === 0)
{
unset($saleOrders[$index]);
}
}
}
/**
* @var User $currentUser
*/
$currentUser = $this->getUser();
if(!is_null($currentUser))
{
$user_status = $currentUser->getStatus();
}
else
{
$user_status = 'not_connected';
}
return new JsonResponse([
'version' => $this->yamlReader->getVersion(),
'type' => Platform::MODULES[$this->yamlReader->getType()] ?? 'N/C',
'mailer' => $this->yamlReader->getMailer()['intercept_emails'] ?? FALSE,
'glady' => $this->yamlReader->getGlady()['enabled'] ?? FALSE,
'maintenance' => $maintenance['enabled'] ?? FALSE,
'admin_confirmation' => $this->settingStatusService->isOrderValidationEnabled($currentUser),
'saleOrders' => count($saleOrders),
'user_status' => $user_status,
],);
}
/**
* @return Response
*/
public function customerProductJson(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
return new Response('<html lang="fr"><body>' . $this->em
->getRepository(CustomerProduct::class)->getAllEnabledJson() . '</body></html>',);
}
/**
* Route pour tester l'envoi d'email
*
* @param MailerService $mailerService
*
* @return Response
* @throws ReflectionException
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
* @throws Exception
*/
public function testEmail(MailerService $mailerService): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
$mailerService
->createApiMailRequest(MailTypes::UPDATE_POINTS)
->addRecipientToRequest($currentUser, MailerFactory::buildUpdatePoints(100))
->send()
;
return new Response("<html><body></body></html>");
}
/**
* Route pour tester la traduction
*
* @param TranslatorInterface $translator
*
* @return Response
*
* @throws Exception
*/
public function testTranslation(TranslatorInterface $translator): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
// Calcul des performances
$stopwatch = new Stopwatch();
$stopwatch->start('first_translation');
$translator->trans('bienvenue');
$stopwatch->stop('first_translation');
$stopwatch->start('second_translation');
$translator->trans('mes informations');
$stopwatch->stop('second_translation');
$stopwatch->start('third_translation');
$stopwatch->stop('third_translation');
return $this->render('test/trans.html.twig');
}
/**
* @return Response
*/
public function compareTwoYaml(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
$url1 = $this->getParameter('kernel.project_dir') . '/config/platform.loc/animation-lpm.dtv.loc.yaml';
$url2 = $this->getParameter('kernel.project_dir') . '/config/platform.loc/lecercledaikin.dtv.loc.yaml';
$file1 = Yaml::parseFile($url1);
$file2 = Yaml::parseFile($url2);
$diff = [];
$diff = $this->compareKeysHtml($file1, $file2, $diff);
$response = '';
if(!empty($diff))
{
$response = "<ul>" . implode('', $diff) . "</ul>";
}
return new Response($response);
}
/** @param $file1
* @param $file2
* @param array $diff
* @param int $level
*
* @return mixed
*/
private function compareKeysHtml($file1, $file2, array $diff, int $level = 1)
{
$keys_diff = array_diff_key($file1, $file2);
$keys_added = array_diff_key($file2, $file1);
$keys_identical = array_intersect_key($file1, $file2);
if(!empty($keys_diff))
{
foreach($keys_diff as $key => $value)
{
if(is_array($value) && isset($file1[$key]) && isset($file2[$key]))
{
$diff[] = "<li style='color:red;'> $key: <ul>";
$diff = $this->compareKeysHtml($file1[$key], $file2[$key], $diff, $level + 1);
$diff[] = '</ul></li>';
}
else
{
$diff[] = "<li style='color:red;'> $key: " . json_encode($value) . " </li>";
}
}
}
if(!empty($keys_added))
{
foreach($keys_added as $key => $value)
{
if(is_array($value) && isset($file1[$key]) && isset($file2[$key]))
{
$diff[] = "<li style='color:green;'> $key: <ul>";
$diff = $this->compareKeysHtml($file1[$key], $file2[$key], $diff, $level + 1);
$diff[] = '</ul></li>';
}
else
{
$diff[] = "<li style='color:green;'> $key:" . json_encode($value) . " </li>";
}
}
}
if(!empty($keys_identical))
{
foreach($keys_identical as $key => $value)
{
if(is_array($value) && isset($file1[$key]) && isset($file2[$key]))
{
$diff[] = "<li style='color:black;'> $key: <ul>";
$diff = $this->compareKeysHtml($file1[$key], $file2[$key], $diff, $level + 1);
$diff[] = '</ul></li>';
}
else
{
$diff[] = "<li style='color:black;'> $key: " . json_encode($value) . " </li>";
}
}
}
return $diff;
}
/**
* @return Response
*/
public function closedPlatform(): Response
{
$messageCloturePlatform = $this->em->getRepository(Setting::class)
->findOneByCached(['name' => 'GENERAL_MESSAGE_SITE_CLOSED'])
;
$message = $messageCloturePlatform->getValue();
return $this->render('common/closed/default.html.twig', [
'closeSiteMessage' => $message,
]);
}
/**
* Méthode qui permet de vérifier les prix des commandes et les corriger si besoin
*
* @return Response|void
*
* @throws CatalogueException
*/
public function checkSaleOrderPrices()
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
$global = $this->yamlReader->getGlobal();
$rate = $global['point']['rate'];
$saleOrders = $this->em->getRepository(SaleOrder::class)->findAll();
/** @var SaleOrder $saleOrder */
foreach($saleOrders as $saleOrder)
{
echo '<br>' . ($saleOrder->getTotal() / $rate) . '<br>';
$total = 0;
foreach($saleOrder->getItems() as $item)
{
$sku = $item->getSku();
$gamme = $item->getGamme();
$product = $this->jsonCatalogueService->getProductBySkuFromCatalogue($sku, $gamme);
if(!is_null($product))
{
$price = $product->getSalePrice();
echo $saleOrder->getId() . ' --- ' . $sku . ' - ' . $gamme . ' ' . $item->getName() . ' : ' . $item->getPriceHT() . ' vs ' . $price . '<br>';
$item->setPriceHT($price);
$total += $price * $item->getQuantity();
}
else
{
echo $sku . ' non présent dans le catalogue<br>';
}
}
$saleOrder
->setTotal($total)->setOrderRate($rate)
;
}
$this->em->flush();
die();
}
/**
* @return RedirectResponse|Response
*
* @throws NonUniqueResultException
*/
public function purchaseProductToBooster()
{
$purchaseProducts = $this->em->getRepository(PurchaseProduct::class)->findPurchaseProductsWithOldBoost();
$purchaseProductItems = $this->em->getRepository(PurchaseProductItem::class)->findBy([
'purchase' => NULL,
],);
if(count($purchaseProductItems) > 0)
{
foreach($purchaseProductItems as $purchaseProductItem)
{
$this->em->remove($purchaseProductItem);
}
$this->em->flush();
}
$total = 0;
$formattedProducts = [];
/** @var PurchaseProduct $purchaseProduct */
foreach($purchaseProducts as $purchaseProduct)
{
$reference = $name = '';
$referenceExplode = explode(' Boost', $purchaseProduct->getReference());
if(count($referenceExplode) > 1)
{
$reference = $referenceExplode[0];
}
$nameExplode = explode('- Booster', $purchaseProduct->getName());
if(count($nameExplode) > 1)
{
$reference = $purchaseProduct->getReference();
$name = $nameExplode[array_key_last($nameExplode)];
}
$nameExplode = explode('Boost ', $purchaseProduct->getName());
if(count($nameExplode) > 1)
{
$reference = $purchaseProduct->getReference();
$name = $nameExplode[array_key_last($nameExplode)];
}
switch($name)
{
case 'DKN ALT 3 H HT_UExt 14kW 1ph':
$name = 'DKN ALTHERMA 3 H HT_UExt 14kW 1ph';
break;
case 'DKN ALT 3 H HT_UExt 16kW 1ph':
$name = 'DKN ALTHERMA 3 H HT_UExt 16kW 1ph';
break;
case 'DKN ALT 3 H HT_UExt 18kW 1ph':
$name = 'DKN ALTHERMA 3 H HT_UExt 18kW 1ph';
break;
case 'DKN ALT 3 H HT_UExt 14kW 3ph':
$name = 'DKN ALTHERMA 3 H HT_UExt 14kW 3ph';
break;
case 'DKN ALT 3 H HT_UExt 16kW 3ph':
$name = 'DKN ALTHERMA 3 H HT_UExt 16kW 3ph';
break;
case 'DKN ALT 3 H HT_UExt 18kW 3ph':
$name = 'DKN ALTHERMA 3 H HT_UExt 18kW 3ph';
break;
}
/** @var PurchaseProduct $parent */
$parent = $this->em->getRepository(PurchaseProduct::class)->findOneBy([
'reference' => $reference,
'name' => $name,
],);
if(!$parent instanceof PurchaseProduct)
{
$parentTpms = $this->em->getRepository(PurchaseProduct::class)->findBy([
'reference' => $reference,
], [
'value' => 'asc',
],);
$parent = $parentTpms[0];
}
$qb = $this->em
->createQueryBuilder()
->from(PurchaseProductItem::class, 'ppi')
->select('ppi')
->leftJoin('ppi.product', 'p')
->leftJoin('ppi.purchase', 'pu')
->andWhere('p.id = :pId')
->setParameter('pId', $purchaseProduct->getId())
->orderBy('pu.invoiceDate', 'ASC')
->setFirstResult(0)
->setMaxResults(1)
;
$qb->orderBy('pu.invoiceDate', 'DESC');
$qb
->select('ppi.id')->setMaxResults(NULL)
;
$ids = $qb->getQuery()->getArrayResult();
if(count($ids) > 0)
{
$formattedProducts[$parent->getId()] = $ids;
$total += count($ids);
if($total > 200)
{
break;
}
}
}
foreach($formattedProducts as $ppiId => $ppiIDs)
{
$qb = $this->em->createQueryBuilder();
$qb
->from(PurchaseProductItem::class, 'ppi')
->select('ppi')
->andWhere('ppi.id IN (:ppiIDs)')
->setParameter('ppiIDs', $ppiIDs)
->setMaxResults(10)
;
$ppis = $qb->getQuery()->getResult();
$product = $this->em->getRepository(PurchaseProduct::class)->find($ppiId);
/** @var PurchaseProductItem $ppi */
foreach($ppis as $ppi)
{
$ppi->setProduct($product);
}
}
if(count($formattedProducts) > 0)
{
$this->em->flush();
return $this->redirectToRoute('test_purchase_products_to_booster');
}
/** @var PurchaseProduct $purchaseProduct */
foreach($purchaseProducts as $purchaseProduct)
{
if(count($this->em
->getRepository(PurchaseProductItem::class)->findBy(['product' => $purchaseProduct]),) > 0)
{
return new Response(' PurchaseProductItem.length > 0');
}
$this->em->remove($purchaseProduct);
}
$this->em->flush();
return new Response(TRUE);
}
/**
* @return Response
*
* @throws ClientExceptionInterface
* @throws RedirectionExceptionInterface
* @throws ServerExceptionInterface
*/
public function getSaleOrderItemFees(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
return new Response("<html><body></body></html>");
}
/**
* @Route("/get-user-point-at/657sqd9f46q8sf4/{date}", name="getUserPointAt")
*
* @param $date
*
* @return JsonResponse
*
* @throws PurchaseDeclarationException
* @throws Exception
*/
public function getUserPointAt($date): JsonResponse
{
$date = new DateTime($date);
$period = new Period('2010-01-01 00:00:00', $date);
$users = $this->em->getRepository(User::class)->findAll();
$finalUsers = [];
/** @var User $user */
foreach($users as $user)
{
if($user->isInstaller())
{
$finalUsers[] = [
'email' => $user->getEmail(),
'id' => $user->getId(),
'points' => $this->userPointService->getAvailablePoints($user, $period),
'level' => $this->userPointService->getLevelOneDate($user, $date),
];
}
}
return new JsonResponse($finalUsers,);
}
/**
* Tableau de diagnostic sur les régates
* Code régate en double ou boucle de relation
*
* @return Response
*/
public function checkRegate(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
{
return new Response('Page non trouvée', 404);
}
$global = $this->yamlReader->getGlobal();
if(!$global['regate'])
{
return new Response('Les régates ne sont pas active sur cette plateforme');
}
$sameAffectation = $this->em->getRepository(Regate::class)->findSameAffectation();
$inLoop = $this->em->getRepository(Regate::class)->findCircularReferences();
return $this->render('front/common/check-regate.html.twig', [
'sameAffectation' => $sameAffectation,
'inLoop' => $inLoop,
]);
}
/**
* @return Response
*/
public function checkUsersRelation(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
{
return new Response('Page non trouvée', 404);
}
$users = $this->em->getRepository(User::class)->findAll();
$relateToSelf = [];
/** @var User $user */
foreach($users as $user)
{
$child = $user->getChildren()->toArray();
if(in_array($user, $child, FALSE))
{
$relateToSelf[] = $user;
}
}
return $this->render('front/common/check-user-relation.html.twig', [
'relateToSelf' => $relateToSelf,
]);
}
public function checkUsersRelationRemove()
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
{
return new Response('Page non trouvée', 404);
}
$users = $this->em->getRepository(User::class)->findAll();
/** @var User $user */
foreach($users as $user)
{
$child = $user->getChildren()->toArray();
if(in_array($user, $child, FALSE))
{
$user->removeChild($user);
}
}
$this->em->flush();
return $this->redirectToRoute('check_users_relation');
}
/**
* @Route("/getDatatable", name="/getDatatable")
*
* @param Request $request
*
* @return Response
*/
public function getDataTableCustomQuery(Request $request): Response
{
$version = 2;
$config = Yaml::parseFile($this->getParameter('kernel.project_dir') . '/config/datatable/lecercledaikin/back_community_installer_list.yaml');
$config = $config[0];
$queryBuilder = $this->em->createQueryBuilder();
// Construction de la requête SELECT
$select = [];
foreach($config['queryBuilder']['customQuery']['select'] as $alias => $field)
{
$select[] = "$field AS $alias";
}
$queryBuilder->select(implode(', ', $select));
// Construction de la requête FROM
switch($version)
{
case 2:
$entityName = 'App\Entity\\' . $config['queryBuilder']['entityName'];
break;
default:
$entityName = $config['queryBuilder']['entityName'];
break;
}
$queryBuilder->from($entityName, 'user');
// Construction des jointures LEFT JOIN
foreach($config['queryBuilder']['customQuery']['leftJoin'] as $alias => $join)
{
$queryBuilder->leftJoin("$join", $alias);
}
// Appliquer les filtres de recherche
$queryBuilder = $this->applyFilters($queryBuilder, $config['searches'], $request->query->get('query', []));
$whereConditions = [];
foreach($config['queryBuilder']['preRequires'] as $index => $preRequire)
{
$condition = NULL;
if(isset($preRequire['fields']))
{
// Traitement des conditions basées sur des champs
$fields = [];
foreach($preRequire['fields'] as $field)
{
$fieldName = "field$index"; // Créez un nom de paramètre unique
$comparison = strtoupper($preRequire['comparison']);
$fieldExpression = "user.$field $comparison :$fieldName";
$fields[] = "($fieldExpression)";
$default = $preRequire['default'];
$default = $this->getGlobalValueIfExist($default);
$queryBuilder->setParameter($fieldName, $default);
}
$condition = '(' . implode(' AND ', $fields) . ')';
}
elseif(isset($preRequire['conditions']))
{
// Traitement des autres types de conditions (par exemple, in_array)
$conditions = [];
foreach($preRequire['conditions'] as $subCondition)
{
if($subCondition['type'] === 'in_array')
{
$field = "user." . $subCondition['fields'][0];
$needle = $subCondition['needle'];
$conditions[] = "$field IN (:needles)";
$queryBuilder->setParameter('needles', [$needle], Connection::PARAM_STR_ARRAY);
}
}
if(!empty($conditions))
{
$condition = '(' . implode(' AND ', $conditions) . ')';
}
}
if($condition)
{
$whereConditions[] = $condition;
}
}
if(!empty($whereConditions))
{
$queryBuilder->andWhere(implode(' OR ', $whereConditions));
}
// Ajouter d'autres parties de la requête ici, comme GROUP BY, ORDER BY, etc.
$query = $queryBuilder->getQuery();
$results = $query->getResult();
return new Response('<html><body>généré : ' . count($results) . '</body></html>');
}
/**
* Méthode pour appliquer les filtres de recherche
*
* @param $queryBuilder
* @param $filters
* @param array $searches
*
* @return mixed
*/
private function applyFilters($queryBuilder, $filters, array $searches = [])
{
foreach($filters as $index => $filter)
{
if(array_key_exists("datatable_search_$index", $searches))
{
$filter['default'] = $searches["datatable_search_$index"];
}
switch($filter['type'])
{
case 'input':
$fieldName = "user." . $filter['query']['fields'][0];
$parameterName = ":{$filter['query']['fields'][0]}";
// Assurez-vous que la clé 'comparison' est définie dans le tableau $filter
$comparison = $filter['comparison'] ?? 'LIKE';
// Assurez-vous que la clé 'default' est définie dans le tableau $filter
$defaultValue = $filter['default'] ?? NULL;
if($defaultValue !== NULL)
{
$queryBuilder->andWhere("$fieldName $comparison $parameterName");
$queryBuilder->setParameter($parameterName, "%$defaultValue%");
}
break;
case 'select':
$fieldName = "user." . $filter['query']['fields'][0];
$parameterName = ":{$filter['query']['fields'][0]}";
// Assurez-vous que la clé 'default' est définie dans le tableau $filter
$defaultValue = $filter['default'] ?? '*';
$value = $this->getGlobalValueIfExist($defaultValue); // Utilisez la fonction pour obtenir la valeur dynamique
if($defaultValue !== '*' && $value !== NULL)
{
if(count($value) > 1)
{
$queryBuilder->andWhere("$fieldName IN ($parameterName)");
}
else
{
$queryBuilder->andWhere("$fieldName = $parameterName");
}
$queryBuilder->setParameter($parameterName, $value);
}
break;
// Ajouter d'autres types de filtres selon vos besoins
}
}
return $queryBuilder;
}
/**
* @param $val
* @param array $context
*
* @return User|array|int|mixed|string|string[]|null
*/
private function getGlobalValueIfExist($val, array $context = [])
{
/** @var User $user */
$user = $this->getUser();
if(is_string($val) && array_key_exists($val, $context))
{
return $context[$val];
}
switch($val)
{
case '__currentUserRoles__':
return $user->getRoles();
case '__currentUserStatus__':
return $user->getStatus();
case '__currentUser__':
return $user;
case '__currentUserId__':
return $user->getId();
case '__currentUserAgencyId__':
if($user->getAgency() === NULL)
{
return NULL;
}
return $user->getAgency()->getId();
case '__currentUserRegateAffectation__':
if($user->getRegate() === NULL)
{
return NULL;
}
return ($user->getRegate())->getAffectation();
case '__currentUserRegateChildren__':
if($user->getRegate() === NULL)
{
return NULL;
}
return $this->regateService->getRegateIdTreeListFlat($user->getRegate(), FALSE);
case '__currentDomain__':
return $_SERVER['HTTP_HOST'];
case '__currentUserJob__':
return $user->getJob();
case '__currentUserRolesAndJob__':
$job = $user->getJob() ? [$user->getJob()] : [];
return array_merge($user->getRoles(), $job);
case '__currentUserExtensionPointSystem__':
return [$user->getExtensionBySlug(UserExtension::POINT_SYSTEM) ?? 'point'];
case '__currentUserParentOf__':
$userChildren = $this->userFrontService->getUserChildrenAtRoleAndJob($user);
$childrenId = [];
/** @var User $child */
foreach($userChildren as $child)
{
$childrenId[] = $child->getId();
}
return $childrenId;
default:
return $val;
}
}
/**
* @throws ReflectionException
*/
public function getExportable(Reader $reader)
{
$finder = new Finder();
$finder->files()->in($this->projectDir . '/src/Entity')->depth(0)->name('*.php');
$traitFinder = new Finder();
$traitFinder->files()->in($this->projectDir . '/src/Traits')->depth(0)->name('*.php');
$exportableEntities = [];
$processedEntities = [];
// 1. Récupérer tous les traits et leurs propriétés @Exportable
$traitProperties = [];
foreach($traitFinder as $traitFile)
{
$traitName = 'App\\Traits\\' . $traitFile->getBasename('.php');
$reflectionTrait = new ReflectionClass($traitName);
if($reflectionTrait->isTrait())
{
foreach($reflectionTrait->getProperties() as $property)
{
if($reader->getPropertyAnnotation($property, Exportable::class))
{
$traitProperties[$reflectionTrait->getName()][] = $property->getName();
}
}
}
}
foreach($finder as $file)
{
$className = 'App\\Entity\\' . $file->getBasename('.php');
$reflectionClass = new ReflectionClass($className);
if($reflectionClass->isTrait())
{
foreach($reflectionClass->getProperties() as $property)
{
if($reader->getPropertyAnnotation($property, Exportable::class))
{
$traitProperties[$reflectionClass->getName()][] = $property->getName();
}
}
}
}
foreach($finder as $file)
{
$entityClass = 'App\\Entity\\' . $file->getBasename('.php');
$reflectionClass = new ReflectionClass($entityClass);
if($reflectionClass->isAbstract() || $reflectionClass->isInterface() || $reflectionClass->isTrait())
{
continue;
}
if($reader->getClassAnnotation($reflectionClass, ExportableEntity::class))
{
$exportableFields = [];
// Vérifier si l'entité utilise l'un des traits et récupérer ses propriétés
foreach($reflectionClass->getTraitNames() as $usedTrait)
{
if(array_key_exists($usedTrait, $traitProperties))
{
foreach($traitProperties[$usedTrait] as $traitProperty)
{
$exportableFields[] = $traitProperty;
}
}
}
$metadata = $this->em->getClassMetadata($entityClass);
foreach($reflectionClass->getProperties() as $property)
{
if($reader->getPropertyAnnotation($property, Exportable::class))
{
$propertyName = $property->getName();
// Pour la relation OneToMany ou OneToOne
if(isset($metadata->associationMappings[$propertyName]))
{
$associationType = $metadata->associationMappings[$propertyName]['type'];
if($associationType === ClassMetadataInfo::ONE_TO_MANY || $associationType === ClassMetadataInfo::ONE_TO_ONE)
{
$associatedEntityClass = $metadata->associationMappings[$propertyName]['targetEntity'];
// Si l'entité associée n'a pas déjà été traitée
if(!in_array($associatedEntityClass, $processedEntities))
{
$associatedReflectionClass = new ReflectionClass($associatedEntityClass);
$associatedExportableFields = [];
foreach($associatedReflectionClass->getProperties() as $associatedProperty)
{
if($reader->getPropertyAnnotation($associatedProperty, Exportable::class))
{
$associatedExportableFields[] = $associatedProperty->getName();
}
}
$exportableFields[$associatedEntityClass] = $associatedExportableFields;
$processedEntities[] = $associatedEntityClass;
}
}
}
else
{
$exportableFields[] = $propertyName;
}
}
}
foreach($reflectionClass->getMethods() as $method)
{
if($reader->getMethodAnnotation($method, ExportableMethod::class) || $reader->getMethodAnnotation($method, Exportable::class))
{
$exportableFields[] = $method->getName();
}
}
$exportableEntities[$entityClass] = $exportableFields;
}
}
// Filtrer les entités qui ont déjà été traitées comme des entités associées
foreach($processedEntities as $processedEntity)
{
unset($exportableEntities[$processedEntity]);
}
return new Response('<html><body>généré : ' . count($exportableEntities) . '</body></html>');
}
/**
* @return JsonResponse
* @throws Exception
*/
public function MailwizzCustomerCreate(): JsonResponse
{
$response = [];
$subDomain = $this->yamlReader->getSubdomain();
$email = 'admin@' . $subDomain;
// supprimer un adminCustomer s'il existe
$this->mailService->removeCustomerOnMailwizzDB($email);
// crée un nouvel adminCustomer
$customerPlainPassword = $this->commonServices->generatePassword(8);
$passwordHasher = new PasswordHash(13, TRUE);
$customerPassword = $passwordHasher->HashPassword($customerPlainPassword);
$customer = [
'customer_id' => NULL,
'customer_uid' => $this->mailService->uniqid(),
'parent_id' => NULL,
'group_id' => NULL,
'language_id' => NULL,
'first_name' => 'DTV',
'last_name' => $subDomain,
'email' => $email,
'password' => $customerPassword,
'timezone' => 'Europe/Paris',
'avatar' => NULL,
'hourly_quota' => 0,
'removable' => 'yes',
'confirmation_key' => NULL,
'oauth_uid' => NULL,
'oauth_provider' => NULL,
'status' => 'active',
'birth_date' => (new DateTime())->modify('-20 years')->format('Y-m-d'),
'phone' => NULL,
'twofa_enabled' => 'no',
'twofa_secret' => '',
'twofa_timestamp' => '0',
'date_added' => (new DateTime())->modify('-1 day')->format('Y-m-d'),
'last_login' => (new DateTime())->format('Y-m-d'),
'inactive_at' => NULL,
];
$customer = $this->mailService->createCustomer($customer);
$apiKey = $this->mailService->createCustomerApiKey($email);
$response['customerAdmin'] = $customer;
$response['customerApiKey'] = $apiKey;
// création de sender mailWizz
$response['deliveryServer'] = $this->mailService->createMailwizzDeliveryServer($customer);
return new JsonResponse($response);
}
/**
* @Route ("/test-communcation-between-child-and-portail", name="test_communication_between_child_and_portail")
* @return Response
*/
public function testCommunicationBetweenPortailAndChild(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
{
return new Response('Page non trouvée', 404);
}
try
{
// Request to child http://stellantis.fs-clubelite.dtv.loc/test-communcation-between-child-and-portail
$response = $this->client->request('GET', 'http://stellantis.fs-clubelite.dtv.loc/api/test-communcation-between-portail-and-child', [], [], [
'HTTP_X-Auth-Token' => '123456789',
],);
$statusCode = $response->getStatusCode();
$content = json_decode($response->getContent(), TRUE);
} catch(Exception $e)
{
return new Response($e->getMessage());
}
return new JsonResponse($content, $statusCode);
}
/**
* @Route ("/test-account-id-constraint", name="test_account_id_constraint")
* @return Response
*/
public function testAccountIdConstraint(): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper() && !$currentUser->isSuperAdmin() && !$currentUser->isAdmin())
{
return new Response('Page non trouvée', 404);
}
// $token = md5(uniqid(rand(), TRUE));
$token = 'TEST55';
// $user = $this->userService->initUser();
// $user->setFirstName('test')
// ->setLastName('test')
// ->setEmail($token.'@test.fr')
// ->setPassword('test');
// $this->em->persist($user);
// $user2 = $this->userService->initUser();
// $user2->setFirstName('test')
// ->setLastName('test')
// ->setEmail($token.'@test.fr')
// ->setPassword('test');
// $this->em->persist($user2);
// $this->em->flush();
return new JsonResponse('OK', 200);
}
/**
* @Route ("/api/test-communcation-between-portail-and-child", name="test_communication_between_portail_and_child")
* @return JsonResponse
*/
public function testCommunicationBetweenChildAndPortail(): JsonResponse
{
return new JsonResponse([
'status' => 'success',
'message' => 'Hello',
], 200);
}
/**
* @Route ("/test-ubr", name="test_ubr")
*/
public function testUserBusinessResult(): Response
{
$stepsData = $this->highlightService->getHighlightActiveSteps();
$pointsByStep = [];
// Remplir $pointsByStep avec les points correspondant à chaque étape
foreach($stepsData as $step => $data)
{
// S'assurer que 'max' est défini, sinon utiliser une valeur par défaut élevée
$max = $data['max'] !== NULL ? $data['max'] : $data['min'];
for($i = $data['min']; $i <= $max; $i++)
{
$pointsByStep[$i] = $data['points'];
}
}
$globalMin = min(array_keys($pointsByStep));
$globalMax = max(array_keys($pointsByStep));
$ubrs = $this->em->getRepository(UserBusinessResult::class)->findByUniqueAccountId(null, false, false, true);
foreach($ubrs as $key => $ubr)
{
if($ubr['totalSale'] > $globalMax)
{
$ubrs[$key] ['total'] = $pointsByStep[$globalMax];
}
elseif($ubr['totalSale'] < $globalMin)
{
$ubrs[$key] ['total'] = $pointsByStep[$globalMin];
}
else
{
$ubrs[$key] ['total'] = $pointsByStep[$ubr['totalSale']];
}
}
$users = $this->em
->createQueryBuilder()->from(User::class, 'u', 'u.id')->select('u')->getQuery()->getResult()
;
$transactionType = $this->em->getRepository(PointTransactionType::class)->findOneBy([
'slug' => PointTransactionType::FIDELITY,
],);
$currentHighlight = $this->highlightService->getHighlight();
foreach($ubrs as $ubr)
{
$pointTransaction = (new PointTransaction())
->setUser($users[$ubr['userId']])
->setValue(abs($ubr['total']))
->setLabel('Conversion des résultats du temps fort ' . $currentHighlight['name'] . ' en points')
->setTransactionType($transactionType)
->setCreatedAt(new DateTime())
->setSubtype(PointTransaction::TRANSACTION_HIGHLIGHT)
;
$this->em->persist($pointTransaction);
}
$this->em->flush();
$this->em
->createQuery('UPDATE ' . UserBusinessResult::class . ' ubr SET ubr.highlight = :highlight WHERE ubr.highlight IS NULL')
->setParameter('highlight', $currentHighlight['number'])
->execute()
;
return new Response('<body></body>');
}
/**
* @Route ("/test-ubr-2", name="test_ubr_2")
*/
public function testUserBusinessResult2(): Response
{
$stepsData = $this->highlightService->getHighlightActiveSteps();
$pointsByStep = [];
// Remplir $pointsByStep avec les points correspondant à chaque étape
foreach($stepsData as $step => $data)
{
// S'assurer que 'max' est défini, sinon utiliser une valeur par défaut élevée
$max = $data['max'] !== NULL ? $data['max'] : $data['min'];
for($i = $data['min']; $i <= $max; $i++)
{
$pointsByStep[$i] = $data['points'];
}
}
$globalMin = min(array_keys($pointsByStep));
$globalMax = max(array_keys($pointsByStep));
$ubrs = $this->em->getRepository(UserBusinessResult::class)->findByUniqueAccountIdForCurrent_2();
$userIds = [];
foreach($ubrs as $key => $ubr)
{
if($ubr['totalSale'] > $globalMax)
{
$ubrs[$key] ['total'] = $pointsByStep[$globalMax];
}
elseif($ubr['totalSale'] < $globalMin)
{
$ubrs[$key] ['total'] = $pointsByStep[$globalMin];
}
else
{
$ubrs[$key] ['total'] = $pointsByStep[$ubr['totalSale']];
}
$userIds[] = $ubr['userId'];
}
$userIds = array_unique($userIds);
$users = $this->em->getRepository(User::class)->getUserByIds($userIds, TRUE);
$transactionType = $this->em->getRepository(PointTransactionType::class)
->findOneBySlug(PointTransactionType::FIDELITY)
;
$currentHighlight = $this->highlightService->getHighlight();
foreach($ubrs as $key => $ubr)
{
$pts = $ubr['total'];
$pointTransaction = new PointTransaction();
$pointTransaction
->setValue($pts)
->setUser($users[$ubr['userId']])
->setLabel('Conversion des résultats du temps fort ' . $currentHighlight['name'] . ' en points')
->setTransactionType($transactionType)
->setSubtype(PointTransaction::TRANSACTION_HIGHLIGHT)
;
$this->em->persist($pointTransaction);
}
$this->em->flush(); // Persist objects that did not make up an entire batch
return new Response('<body></body>');
}
/**
* @Route ("/test-update-user/{id}", name="test_update_user")
*/
public function testUpdateUser(string $id): Response
{
/** @var User $currentUser */
$currentUser = $this->getUser();
if(!$currentUser->isDeveloper())
{
return new Response('Page non trouvée', 404);
}
$user = $this->em->getRepository(User::class)->find($id);
$user
->setFirstName('test')->setLastName('test')->setLastActivity(new DateTime())
;
$this->em->flush();
return new JsonResponse('OK', 200);
}
}