<?php
/******************************************************************************
* Copyright (c) Echo-numeric 2020-2023. *
******************************************************************************/
namespace App\Controller\Common;
use App\Constants\Platform;
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\SaleOrder;
use App\Entity\Setting;
use App\Entity\User;
use App\Exception\CatalogueException;
use App\Exception\PurchaseDeclarationException;
use App\Factory\Platform\MailerFactory;
use App\Factory\PointFactory;
use App\Model\Period;
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\SaleOrderService;
use App\Services\ConfigService;
use App\Services\DTV\YamlConfig\YamlReader;
use App\Services\Front\Catalogue\JsonCatalogueService;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Exception;
use Psr\Log\LoggerInterface;
use ReflectionException;
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\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\Exception\TransportExceptionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class CommonController extends AbstractController
{
private KernelInterface $kernel;
private LoggerInterface $logger;
private EntityManagerInterface $em;
private ConfigService $configService;
private PlatformService $platformService;
private YamlReader $yamlReader;
private UserPointServiceInterface $userPointService;
private JsonCatalogueService $jsonCatalogueService;
private SaleOrderService $saleOrderService;
/**
* @throws Exception
*/
public function __construct(
KernelInterface $kernel,
LoggerInterface $logger,
EntityManagerInterface $em,
ConfigService $configService,
PlatformService $platformService,
YamlReader $yamlReader,
PointFactory $pointFactory,
JsonCatalogueService $jsonCatalogueService,
SaleOrderService $saleOrderService
) {
$this->kernel = $kernel;
$this->logger = $logger;
$this->em = $em;
$this->configService = $configService;
$this->platformService = $platformService;
$this->yamlReader = $yamlReader;
$this->userPointService = $pointFactory->getUserPointService();
$this->jsonCatalogueService = $jsonCatalogueService;
$this->saleOrderService = $saleOrderService;
}
/**
* @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 new BinaryFileResponse($file, 200);
}
/**
* @param string $fileName
*
* @return object|BinaryFileResponse
*
* @throws Exception
*/
public function exposeProjectFile(string $fileName)
{
$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 BinaryFileResponse($file, 200);
}
/**
* 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);
}
if (!file_exists($dest)) {
$data = $this->get_content($src);
file_put_contents($dest, $data);
}
return new BinaryFileResponse($dest, 200);
}
/**
* @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 (!empty($document) && NULL !== $document->getValue()) {
$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>');
}
/**
* @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;
if ( TRUE ) {
$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;
}
}
} elseif ($user->isEnabled()) {
$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)->findOneBy(
[
'email' => $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(),
]);
}
/**
* @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 ]);
}
}
}
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->yamlReader->getCheckout()[ 'admin_confirmation' ][ 'enabled' ] ?? FALSE,
'saleOrders' => count($saleOrders),
]
);
}
/**
* @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 TransportExceptionInterface
* @throws Exception
*/
public function testEmail(MailerService $mailerService): Response
{
$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');
$trad1 = $translator->trans('bienvenue');
$event1 = $stopwatch->stop('first_translation');
$stopwatch->start('second_translation');
$trad2 = $translator->trans('mes informations');
$event2 = $stopwatch->stop('second_translation');
$stopwatch->start('third_translation');
$trad3 = $translator->trans('point.expire', ['count' => 2, 'date' => '01/01/2021', 'point' => 2]);
$event3 = $stopwatch->stop('third_translation');
$results = [
'bienvenue' => $event1->getDuration().' ms',
'mes informations' => $event2->getDuration().' ms',
'point.expire' => $event3->getDuration().' ms',
'CGU' => $translator->trans("je donne mon consentement et j'accepte les cgu", [
"path" => 'https://www.google.com/',
"foo" => 'bla',
]),
'bienvenue dans votre espace' => $translator->trans("bienvenue dans votre espace", ["name" => 'Yop']),
];
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 = [];
/**
* @param $file1
* @param $file2
* @param array $diff
* @param int $level
*
* @return mixed
*/
function compare_keys_html($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 = compare_keys_html($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 = compare_keys_html($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 = compare_keys_html($file1[ $key ], $file2[ $key ], $diff, $level + 1);
$diff[] = '</ul></li>';
} else {
$diff[] = "<li style='color:black;'> $key: ".json_encode($value)." </li>";
}
}
}
return $diff;
}
$diff = compare_keys_html($file1, $file2, $diff);
$response = '';
if (!empty($diff)) {
$response = "<ul>".implode('', $diff)."</ul>";
}
return new Response($response);
}
/**
* @return Response
*/
public function closedPlatform(): Response
{
return $this->redirectToRoute();
$messageCloturePlateform = $this->em->getRepository(Setting::class)->findOneBy(['name' => 'CLOSE_SITE_MESSAGE']
);
$message = $messageCloturePlateform->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
);
}
}