<?php
namespace App\Controller;
use App\Api\SalesforceRest\Controllers\ApiAccountController;
use App\Api\SalesforceRest\Controllers\ApiContactController;
use App\Dto\DtoBrand;
use App\Dto\DtoNavigationContext;
use App\Dto\Enum\EnumHttpCode;
use App\Dto\Request\DtoGetNotViewedPushNotificationsRequest;
use App\Dto\Response\DtoResponse;
use App\Entity\AccountType;
use App\Entity\Article;
use App\Entity\Contact;
use App\Entity\ContactProductPrice;
use App\Entity\ContentOnDemand;
use App\Entity\InstructorRequest;
use App\Entity\Referent;
use App\Entity\SfBrand;
use App\Entity\SfProduct;
use App\Helper\ObjectConversionHelper;
use App\Helper\StringHelper;
use App\Security\ConnectAsAuthenticator;
use App\Service\LanguageManager;
use App\Service\NotificationManager;
use App\Service\NotificationService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
class EntityController extends AbstractController
{
protected EntityManagerInterface $entityManager;
protected NotificationManager $notificationManager;
protected string $language;
protected LanguageManager $languageManager;
protected array $viewData;
protected RequestStack $request;
/**
* EntityController constructor.
* @param EntityManagerInterface $entityManager
* @param NotificationManager $notificationManager
* @param RequestStack $request
* @param LanguageManager $languageManager
*/
public function __construct(EntityManagerInterface $entityManager,
NotificationManager $notificationManager,
RequestStack $requestStack,
LanguageManager $languageManager,
NotificationService $notificationService)
//<<<<<<< HEAD
// RequestStack $request,
// LanguageManager $languageManager,
// SessionInterface $session,
// NotificationService $notificationService)
//=======
// RequestStack $requestStack,
// LanguageManager $languageManager)
//>>>>>>> 92-achat-unique
{
$this->entityManager = $entityManager;
$this->notificationManager = $notificationManager;
$this->language = $this->getLanguage($requestStack);
$this->languageManager = $languageManager;
$this->currentSessionStack = $requestStack->getSession();
$this->viewData = [];
$accounts = [];
$contactCsrfToken = null;
$lightContact = null;
// Set all accounts in session then whe can get em everywhere
$currentAccount = null;
if(!is_null($contact = $this->currentSessionStack->get('contact'))){
$accounts = $contact->getAccounts();
foreach($accounts as $account) {
if($account->getSalesforceId() == $requestStack->getCurrentRequest()->get('salesforceAccountId')) {
$currentAccount = $account;
$this->viewData["accountId"] = $account->getSalesforceId();
}
}
if(isset($currentAccount) && $currentAccount->getType()->getName() == AccountType::ACCOUNT_TYPES['PersonAccount']) {
$clubsLinkedToCurrentInstructor = ApiAccountController::getAccountClubs($currentAccount->getSalesforceId());
if(empty($clubsLinkedToCurrentInstructor)) {
$instructorIsLinkedToAClub = false;
} else {
$instructorIsLinkedToAClub = true;
}
$this->viewData['instructorIsLinkedToAClub'] = $instructorIsLinkedToAClub;
}
$lightContact = $contact->cloneLightContact();
}
if(!is_null($this->currentSessionStack->get('contactCsrfToken'))){
$contactCsrfToken = $this->currentSessionStack->get('contactCsrfToken');
}
$instructorRequests = $this->entityManager->getRepository(InstructorRequest::class)->findBy([
'clubSFId' => $requestStack->getCurrentRequest()->get('salesforceAccountId')
]);
if($instructorRequests) {
$countNotification = 0;
foreach($instructorRequests as $instructorRequest) {
if($instructorRequest->getClubNotification() == true) {
$countNotification++;
}
}
$this->viewData['clubNotification'] = $countNotification;
}
if($this->language == 'it') {
$isItalian = 1;
} else {
$isItalian = 0;
}
$isHbx = false;
if($this->currentSessionStack->get('contact') != null) {
// get account access rights (for blog)
$accessLesMills = $this->currentSessionStack->get('accessLesMills');
$accessAqua = $this->currentSessionStack->get('accessAqua');
$accessHBXTT = $this->currentSessionStack->get('accessHBXTT');
$accessHBX = $this->currentSessionStack->get('accessHBX');
// set account access rights for HBX
$accessLesMills == true ? $isLesmills = true : $isLesmills = false;
$accessAqua == true ? $isAqua = true : $isAqua = false;
if($accessHBX == true || $accessHBXTT == true) {
$isHbx = true;
} else {
$isHbx = false;
}
// get articles not viewed by current contact for each article's access rights
$articlesNotViewed = $this->entityManager->getRepository(Article::class)->findArticlesNotViewed($this->entityManager, $this->currentSessionStack->get('contact')->getId(), $isItalian);
$articlesNotViewedLesmills = $this->entityManager->getRepository(Article::class)->findArticlesNotViewedLesmills($this->entityManager, $this->currentSessionStack->get('contact')->getId(), $isItalian, $isLesmills);
$articlesNotViewedHBX = $this->entityManager->getRepository(Article::class)->findArticlesNotViewedHBX($this->entityManager, $this->currentSessionStack->get('contact')->getId(), $isItalian, $isHbx);
$articlesNotViewedAqua = $this->entityManager->getRepository(Article::class)->findArticlesNotViewedAqua($this->entityManager, $this->currentSessionStack->get('contact')->getId(), $isItalian, $isAqua);
// array of array with all the article and the 3 access rights articles
$allArticles = [];
// we'll fill this array with all articles that current account can read (can contain duplicated articles)
$articlesArray = [];
// set every articles into an array
array_push($allArticles, $articlesNotViewed);
array_push($allArticles, $articlesNotViewedLesmills);
array_push($allArticles, $articlesNotViewedHBX);
array_push($allArticles, $articlesNotViewedAqua);
if(!empty($allArticles)) {
foreach ($allArticles as $articles) {
foreach($articles as $article) {
// for all articles check if account as right on them
if(($isLesmills == false && $article->getIsLesmills() == true) ||
($isAqua == false && $article->getIsAqua() == true) ||
($isHbx == false && $article->getIsHbx() == true)
) {
} else {
// if currentAccount can read an article, put it in an array
$articlesArray[] = $article;
}
}
}
}
// Récupération des alertes
$dtoGetNotViewedPushNotifications = new DtoGetNotViewedPushNotificationsRequest();
$dtoGetNotViewedPushNotifications->contactId = $contact->getId();
if ($currentAccount != null)
{
$dtoGetNotViewedPushNotifications->salesforceAccountId = $currentAccount->getSalesforceId();
}
$dtoGetNotViewedPushNotifications->isAqua = $isAqua;
$dtoGetNotViewedPushNotifications->isLesmills = $isLesmills;
$dtoGetNotViewedPushNotifications->isHbx = $isHbx;
$dtoGetNotViewedPushNotifications->languageCode = isset($this->language) ? strtoupper($this->language) : "FR";
$dtoPusNotificationResponse = $notificationService->getNotViewedPushNotifications($dtoGetNotViewedPushNotifications);
$this->viewData['notViewedPushNotifications'] = $dtoPusNotificationResponse->dtoPushNotifications;
// array of all articles that current account can read (without duplicate articles)
$allArticlesNotViewed = array_unique($articlesArray);
$this->viewData['articlesNotViewed'] = count($allArticlesNotViewed);
$this->viewData['notViewedPushNotifications'] = $dtoPusNotificationResponse->dtoPushNotifications;
$this->viewData['isHbx'] = $isHbx;
$this->viewData['isAqua'] = $isAqua;
$this->viewData['isLesmills'] = $isLesmills;
$this->viewData['isGenfit'] = $this->currentSessionStack->get('accessGenfit');
if(!is_null($requestStack->getCurrentRequest()->get('salesforceAccountId'))) {
$isHbxHub = false;
$isAquaHub = false;
$concepts = ApiContactController::getConceptsByAccount($requestStack->getCurrentRequest()->get('salesforceAccountId'));
foreach($concepts as $concept) {
if($concept->program_id == $_ENV['HBX_COACH']
||$concept->program_id == $_ENV['HBX_COACH_PRO']
||$concept->program_id == $_ENV['HBX_COACH_CLUB']
||$concept->program_id == $_ENV['HBX_COACH_CLUB_PRO']
||$concept->program_id == $_ENV['HBX_CLUB']
|| $concept->program_id == $_ENV['HBX_CLUB_PREMIUM']
|| $concept->program_id == $_ENV['HBX_CLUB_PREMIUM_PLUS']
|| $concept->program_id == in_array($concept->program_id, explode("|", $_ENV['HBX_HUB_PROGRAMS_FOR_MENU'] ))
)
{
$isHbxHub = true;
}
if($concept->program_id == $_ENV['AQUA_COACH']
||$concept->program_id == $_ENV['AQUA_COACH_PRO']
||$concept->program_id == $_ENV['AQUA_CLUB']
|| $concept->program_id == $_ENV['AQUA_CLUB_PREMIUM']
|| $concept->program_id == $_ENV['AQUA_PISCINE_PUBLIQUE']
|| $concept->program_id == $_ENV['AQUA_PISCINE_PUBLIQUE_PREMIUM']
|| $concept->program_id == in_array($concept->program_id, explode("|", $_ENV['AQUA_HUB_PROGRAMS_FOR_MENU'] ))
)
{
$isAquaHub = true;
}
}
if(!empty(ApiAccountController::getClubsWhereInstructorIsHbx($requestStack->getCurrentRequest()->get('salesforceAccountId')))) {
if(ApiAccountController::getClubsWhereInstructorIsHbx($requestStack->getCurrentRequest()->get('salesforceAccountId'))[0]->Instructeur_HBX_HUB__c == true) {
$isHbxHub = true;
}
}
if(!empty(ApiAccountController::getClubsWhereInstructorIsAqua($requestStack->getCurrentRequest()->get('salesforceAccountId')))) {
if(ApiAccountController::getClubsWhereInstructorIsAqua($requestStack->getCurrentRequest()->get('salesforceAccountId'))[0]->Instructeur_AQUA_HUB__c == true) {
$isAquaHub = true;
}
}
$contactId = $this->currentSessionStack->get('contact')->getId();
if($this->currentSessionStack->get('contact')->isHubAccess()) {
$contact = $this->entityManager->getRepository(Contact::class)->findBy([
'id' => $contactId
]);
$contactProductPrices = $this->entityManager->getRepository(ContactProductPrice::class)->findBy([
'contact' => $contact
]);
if($contactProductPrices) {
foreach($contactProductPrices as $contactProductPrice) {
if(!is_null($contactProductPrice->getContentOnDemand())) {
if($contactProductPrice->getContentOnDemand()->getSfProduct()->getBrand() &&
$contactProductPrice->getContentOnDemand()->getSfProduct()->getBrand()->getCode() == $_ENV['CODE_BRAND_HUB_HBX']) {
$isHbxHub = true;
} else if($contactProductPrice->getContentOnDemand()->getSfProduct()->getBrand() &&
$contactProductPrice->getContentOnDemand()->getSfProduct()->getBrand()->getCode() == $_ENV['CODE_BRAND_HUB_AQUA']) {
$isAquaHub = true;
}
}
}
}
}
$this->viewData['isHbxHub'] = $isHbxHub;
$this->viewData['isAquaHub'] = $isAquaHub;
}
}
// $contentOnDemand = $this->entityManager->getRepository(ContentOnDemand::class)->findOneBy([
// 'shopProductId' => '17443'
// ]);
// dump($contentOnDemand);
// $sfProduct = $this->entityManager->getRepository(SfProduct::class)->findOneBy([
// 'code' => 'FORCHBX22',
// ]);
// dump($sfProduct);
// dd($contentOnDemand->getContentOnDemandRequirements()->getValues());
// foreach($contentOnDemand->getContentOnDemandRequirements()->getValues() as $contentOnDemandRequirement) {
// if($contentOnDemandRequirement->getSfProduct() == $sfProduct) {
// dump('oui');
// }
// }
// dd('stop');
$this->viewData['isHbx'] = $isHbx;
$this->viewData['language'] = $this->language;
$this->viewData['accounts'] = $accounts;
$this->viewData['contactCsrfToken'] = $contactCsrfToken;
$this->viewData['contact'] = $lightContact;
$this->viewData['env'] = $_ENV['APP_ENV'];
$this->viewData['previousAdminUsername'] = $_SESSION["_sf2_attributes"]["previousAdminUsername"] ?? null;
}
public function getNavigationContext(Request $request, RouterInterface $router): DtoNavigationContext
{
// dump($request);
// dd($router);
$expectedUrl= $request->getPathInfo();
$dtoNavigationContext = new DtoNavigationContext();
if ($request->getSession()->get('_security.default.target_path') != null)
{
$expectedUrl = str_replace(["https://", "http://"], "", str_replace($request->getHttpHost(), "", $request->getSession()->get('_security.default.target_path')));
}
$explodeExpectedUrl = explode('/', $expectedUrl);
$explodeExpectedUrlEnd = end($explodeExpectedUrl);
$matched = [];
try {
$matched = $router->match($expectedUrl);
} catch (\Exception $e){}
if (empty($matched) == false)
{
$productCodeRaw = array_key_exists("productCode", $matched) ? $matched['productCode'] : $request->get("productCode");
//S'il y a des paramètres après le productCode, on prend le string avant le '?'
$productCode = strtok($productCodeRaw, '?');
$dbBrand = null;
if (StringHelper::isNullOrEmptyWithSpace($productCode) == false) {
$dbProduct = $this->entityManager->getRepository(SfProduct::class)->findOneBy(['code' => $productCode]);
if(!is_null($dbProduct)) {
$dbBrand = $dbProduct->getBrand();
}
}
else if ($request->get("brandCode") != null)
{
$dbBrand = $this->entityManager->getRepository(SfBrand::class)->findOneBy(['code' => $request->get("brandCode")]);
}
else if (isset($matched['brandCode']) && $matched['brandCode'] != null) {
$dbBrand = $this->entityManager->getRepository(SfBrand::class)->findOneBy(['code' => $matched['brandCode']]);
}
else if (!is_null($explodeExpectedUrlEnd)) {
$dbBrand = $this->entityManager->getRepository(SfBrand::class)->findOneBy(['code' => $explodeExpectedUrlEnd]);
}
if ($dbBrand != null) {
$dtoBrand = ObjectConversionHelper::convert($dbBrand, DtoBrand::class);
$dtoNavigationContext->dtoBrand = $dtoBrand;
}
}
return $this->viewData['context'] = $dtoNavigationContext;
}
public function refreshViewLightContactFromSession() : void
{
if(!is_null($contact = $this->session->get('contact'))){
$lightContact = $contact->cloneLightContact();
$this->viewData['contact'] = $lightContact;
}
}
/**
* @return array
*/
public function getMessages() : array
{
return $this->notificationManager::getMessages();
}
/**
* Parse all errors and messages to create flash messages
*/
protected function createFlashs() : void{
$messages = $this->getMessages();
foreach ($messages['error'] as $error){
$this->addFlash('danger', $this->languageManager->translate($error, $this->language));
}
foreach ($messages['info'] as $message){
$this->addFlash('success', $this->languageManager->translate($message, $this->language));
}
$this->notificationManager::eraseMessages();
}
/**
* Méthode permettant de convertir un DtoResponse en messages flash
* @param DtoResponse $dtoResponse
* @return void
*/
protected function createFlashsFromDtoResponse(DtoResponse $dtoResponse)
{
if ($dtoResponse->isSuccess())
{
if (empty($dtoResponse->successMessages) == false)
{
foreach ($dtoResponse->successMessages as $message){
$this->addFlash('success', $this->languageManager->translate($message, $this->language));
}
}
}
else if ($dtoResponse->isBadRequest())
{
// Création du message pour les champs obligatoires
if (empty($dtoResponse->requiredFields) == false)
{
// Gestion de la phrase d'accroche
$message = $this->languageManager->translate('REQUIRED_FIELDS_DEFAULT_MESSAGE', $this->language) . "<ul>";
// Gestion du détail des champs en erreur
foreach($dtoResponse->requiredFields as $requiredField)
{
$message .= "<li>" . $this->languageManager->translate($requiredField, $this->language) . "</li>";
}
$this->addFlash('danger', $message . "</ul>");
} // Création du message pour les champs invalides
else if (empty($dtoResponse->invalidRules) == false)
{
// Gestion de la phrase d'accroche
$message = $this->languageManager->translate('INVALID_RULES_DEFAULT_MESSAGE', $this->language) . "<ul>";
// Gestion du détail des champs en erreur
foreach($dtoResponse->invalidRules as $invalidRule)
{
$message .= "<li>" . $this->languageManager->translate($invalidRule, $this->language) . "</li>";
}
$this->addFlash('danger', $message. "</ul>");
}
}
else // Gestion des autres erreurs
{
if (empty($dtoResponse->errorMessages) == false)
{
foreach($dtoResponse->errorMessages as $errorMessage)
{
$this->addFlash('danger', $this->languageManager->translate($errorMessage, $this->language));
}
}
else // Erreur générique
{
$this->addFlash('danger', $this->languageManager->translate("Un problème est survenu", $this->language));
}
}
}
public function createJsonResponseFromDtoResponse(DtoResponse $dtoResponse, string $language) : JsonResponse
{
$response = null;
if($dtoResponse->isSuccess()) {
$response = new JsonResponse($dtoResponse, $dtoResponse->getHttpCode());
} else {
$messagesErrorKey = 'error';
$messages = [$messagesErrorKey => []];
// Création du message pour les champs obligatoires
if (empty($dtoResponse->requiredFields) == false) {
// Gestion de la phrase d'accroche
$message = $this->languageManager->translate('REQUIRED_FIELDS_DEFAULT_MESSAGE', $language) . "<ul>";
// Gestion du détail des champs en erreur
foreach ($dtoResponse->requiredFields as $requiredField) {
$message .= "<li>" . $this->languageManager->translate($requiredField, $language) . "</li>";
}
$messages[$messagesErrorKey][] = $message . '</ul>';
} // Création du message pour les champs invalides
else if (empty($dtoResponse->invalidRules) == false) {
// Gestion de la phrase d'accroche
$message = $this->languageManager->translate('INVALID_RULES_DEFAULT_MESSAGE', $language) . "<ul>";
// Gestion du détail des champs en erreur
foreach ($dtoResponse->invalidRules as $invalidRule) {
$message .= "<li>" . $this->languageManager->translate($invalidRule, $language) . "</li>";
}
$messages[$messagesErrorKey][] = $message . '</ul>';
}
else // Gestion des autres erreurs
{
if (empty($dtoResponse->errorMessages) == false) {
foreach ($dtoResponse->errorMessages as $errorMessage) {
$messages[$messagesErrorKey][] = $this->languageManager->translate($errorMessage, $language);
}
}
else if (empty($dtoResponse->errorMessage) == false)
{
$messages[$messagesErrorKey][] = $this->languageManager->translate($dtoResponse->errorMessage, $language);
}
else // Erreur générique
{
$messages[$messagesErrorKey][] = $this->languageManager->translate('Un problème est survenu.', $language);
}
}
$dtoResponse->errorSummaryMessages = $messages;
$response = new JsonResponse($dtoResponse);
$response->setStatusCode($dtoResponse->getHttpCode());
}
return $response;
}
protected function getLanguage(RequestStack $requestStack) : string{
return $requestStack->getCurrentRequest()->getLocale();
}
/**
* @param RequestStack $request
* @return Referent|null
*/
protected function getReferentFromSession(RequestStack $requestStack) : ?Referent
{
$referent = $requestStack->getSession()->get('contact', null);
if(!($referent instanceof Referent)){
$referent = null;
}
return $referent;
}
/**
* add array data in the data array
* @param string $key
* @param array $dataArray
* @return EntityController
*/
public function addViewDataArray(string $key, array $dataArray) : self
{
$this->viewData[$key] = $dataArray;
return $this;
}
/**
* add int data in the data array
* @param string $key
* @param int $dataInt
* @return EntityController
*/
public function addViewDataInt(string $key, int $dataInt) : self
{
$this->viewData[$key] = $dataInt;
return $this;
}
/**
* add string data in the data array
* @param string $key
* @param string $dataString
* @return EntityController
*/
public function addViewDataString(string $key, string $dataString) : self
{
$this->viewData[$key] = $dataString;
return $this;
}
/**
* add object data in the data array
* @param string $key
* @param object|null $dataObject
* @return EntityController
*/
public function addViewDataObject(string $key, ?object $dataObject) : self
{
$this->viewData[$key] = $dataObject;
return $this;
}
/**
* add object data in the data array
* @param string $key
* @param bool $dataBool
* @return EntityController
*/
public function addViewDataBool(string $key, bool $dataBool) : self
{
$this->viewData[$key] = $dataBool;
return $this;
}
}