<?php
namespace Virgin\LeadManager\Storefront\Controller;
use Monolog\Logger;
use RuntimeException;
use Shopware\Core\Checkout\Customer\SalesChannel\AbstractSendPasswordRecoveryMailRoute;
use Shopware\Core\Checkout\Customer\SalesChannel\AbstractResetPasswordRoute;
use Shopware\Core\Checkout\Customer\SalesChannel\AbstractLogoutRoute;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Checkout\Customer\Exception\CustomerNotFoundByHashException;
use Shopware\Core\Checkout\Customer\Exception\CustomerNotFoundException;
use Shopware\Core\Checkout\Customer\Exception\CustomerRecoveryHashExpiredException;
use Shopware\Core\Checkout\Customer\SalesChannel\AccountService;
use Shopware\Core\Content\Category\Exception\CategoryNotFoundException;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Shopware\Core\Framework\Routing\Exception\MissingRequestParameterException;
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
use Shopware\Core\Framework\Validation\DataValidationDefinition;
use Shopware\Core\Framework\Validation\DataValidator;
use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
use Shopware\Core\System\SalesChannel\Context\SalesChannelContextPersister;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Controller\StorefrontController;
use Shopware\Storefront\Page\Account\Login\AccountLoginPageLoader;
use Shopware\Storefront\Page\Navigation\Error\ErrorPageLoader;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Virgin\GDPRPlugin\Service\PrivacyService;
use Virgin\LeadManager\Custom\Autologin\AutologinRequestDefinition;
use Virgin\LeadManager\Service\AccountRegistrationServiceDecorator;
use Virgin\LeadManager\Storefront\Page\Contact\ContactPageLoader;
use Virgin\LeadManager\Utils\Services\LeadGenerationService;
use Virgin\ProductModelExtension\Custom\Club\ClubEntity;
use Virgin\ProductModelExtension\Services\ClubService;
use Virgin\SubscriptionsConfigurator\Utils\Services\SubscriptionsConfiguratorService;
use Virgin\SystemIntegration\Exception\VirginApiException;
use Virgin\SystemIntegration\Services\RestApiClient;
use Virgin\SystemIntegration\Services\VirginUser\VirginUser;
use Shopware\Core\Framework\Uuid\Uuid;
use DateTime;
use DateTimeZone;
/**
* @RouteScope(scopes={"storefront"})
*/
class LeadManagerController extends StorefrontController
{
const CALL = '1';
const APPOINTMENT = '2';
const REVOLUTION_CENTER_ID = 233;
/**
* @var AccountService
*/
private $accountService;
/**
* @var AccountRegistrationServiceDecorator
*/
private $accountRegistrationService;
/**
* @var SalesChannelContextPersister
*/
private $contextPersister;
/**
* @var LeadGenerationService
*/
private $leadService;
/**
* @var EntityRepositoryInterface
*/
private $customerRepository;
/**
* @var DataValidator
*/
private $validator;
/**
* @var Logger
*/
private $logger;
/**
* @var ContactPageLoader
*/
private $contactPageLoader;
/**
* @var EntityRepositoryInterface
*/
private $contactRepository;
/**
* @var EntityRepositoryInterface
*/
private $contactTypeRepository;
/**
* @var EntityRepositoryInterface
*/
private $virginUserTypeRepository;
/**
* @var EntityRepositoryInterface
*/
private $clubRepository;
/**
* @var ClubService
*/
private $clubService;
/**
* @var RestApiClient
*/
private $restApiClient;
/**
* @var PrivacyService
*/
private $privacyService;
/**
* @var SystemConfigService
*/
private $systemConfigService;
/**
* @var AccountLoginPageLoader
*/
private $loginPageLoader;
/**
* @var VirginUser
*/
private $virginUser;
/**
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/** @var SubscriptionsConfiguratorService */
private $configuratorService;
/**
* @var EntityRepositoryInterface
*/
private $autologinRequestRepository;
/**
* @var ErrorPageLoader
*/
private $errorPageLoader;
/**
* @var AbstractLogoutRoute
*/
private $logoutRoute;
/**
* @var AbstractSendPasswordRecoveryMailRoute
*/
private $sendPasswordRecoveryMailRoute;
/**
* @var AbstractResetPasswordRoute
*/
private $resetPasswordRoute;
/**
* @var EntityRepositoryInterface
*/
private $customerRecoveryRepository;
/**
* @var SessionInterface
*/
private $session;
const TYPE_CALLCENTER = 1;
const TYPE_ONSITE = 2;
public function __construct(
AccountService $accountService,
AccountRegistrationServiceDecorator $accountRegistrationService,
SalesChannelContextPersister $contextPersister,
LeadGenerationService $leadService,
EntityRepositoryInterface $customerRepository,
DataValidator $validator,
Logger $logger,
ContactPageLoader $contactPageLoader,
EntityRepositoryInterface $contactRepository,
EntityRepositoryInterface $contactTypeRepository,
EntityRepositoryInterface $virginUserTypeRepository,
EntityRepositoryInterface $clubRepository,
ClubService $clubService,
RestApiClient $restApiClient,
PrivacyService $privacyService,
SystemConfigService $systemConfigService,
AccountLoginPageLoader $loginPageLoader,
VirginUser $virginUser,
EventDispatcherInterface $eventDispatcher,
SubscriptionsConfiguratorService $configuratorService,
EntityRepositoryInterface $autologinRequestRepository,
ErrorPageLoader $errorPageLoader,
AbstractLogoutRoute $logoutRoute,
AbstractSendPasswordRecoveryMailRoute $sendPasswordRecoveryMailRoute,
AbstractResetPasswordRoute $resetPasswordRoute,
EntityRepositoryInterface $customerRecoveryRepository,
SessionInterface $session
)
{
$this->accountService = $accountService;
$this->accountRegistrationService = $accountRegistrationService;
$this->contextPersister = $contextPersister;
$this->leadService = $leadService;
$this->customerRepository = $customerRepository;
$this->validator = $validator;
$this->logger = $logger;
$this->contactPageLoader = $contactPageLoader;
$this->contactRepository = $contactRepository;
$this->contactTypeRepository = $contactTypeRepository;
$this->virginUserTypeRepository = $virginUserTypeRepository;
$this->clubRepository = $clubRepository;
$this->clubService = $clubService;
$this->restApiClient = $restApiClient;
$this->privacyService = $privacyService;
$this->systemConfigService = $systemConfigService;
$this->loginPageLoader = $loginPageLoader;
$this->virginUser = $virginUser;
$this->eventDispatcher = $eventDispatcher;
$this->configuratorService = $configuratorService;
$this->autologinRequestRepository = $autologinRequestRepository;
$this->errorPageLoader = $errorPageLoader;
$this->logoutRoute = $logoutRoute;
$this->sendPasswordRecoveryMailRoute = $sendPasswordRecoveryMailRoute;
$this->resetPasswordRoute = $resetPasswordRoute;
$this->customerRecoveryRepository = $customerRecoveryRepository;
$this->session = $session;
}
/**
* @Route("/contact", name="frontend.contact", options={"seo" = "false"}, methods={"GET"})
*/
public function showContactForm(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
// Remove this redirect to enable contact form
return $this->redirectToRoute('frontend.account.login.page');
$this->logger->log(Logger::DEBUG, 'Contact form request - print data');
if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
return $this->redirectToRoute('frontend.home.page');
}
$loginError = $request->query->get('loginError');
if ($context->getCustomer()) {
$club = $context->getCustomer()->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
}
$page = $this->contactPageLoader->load($request, $context);
return $this->renderStorefront('@Storefront/storefront/page/contact/index.html.twig', [
'page' => $page,
'loginError' => isset($loginError) ? (bool)$loginError : false,
'loginSnippet' => $request->query->get('errorSnippet'),
]);
}
//DEPRECATED
// /**
// * @Route("/contact/create", name="frontend.contact.create", options={"seo" = "false"}, methods={"POST"})
// */
// public function createContact(Request $request, RequestDataBag $data, SalesChannelContext $context)
// {
// if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
// return $this->redirectToRoute('frontend.home.page');
// }
//
// $this->logger->log(Logger::DEBUG, 'Contact form submit data: ' . serialize($data));
// $page = $this->contactPageLoader->load($request, $context);
//
// $redirectObject = $this->virginUser->CheckFormParamsToStorefront($data, $page, '@Storefront/storefront/page/contact/index.html.twig');
//
// $firstname = $data->get('name');
// $lastname = $data->get('lastname');
// $phone = $data->get('phone');
// $phonePrefix = $data->get('intlPrefix');
// $email = $data->get('email');
// $club = $data->get('club');
// $zipcode = $data->get('zipcode');
//
// if ($club == 'home_training') {
// $club = null;
// $homeTraining = true;
// } else {
// $homeTraining = null;
// }
//
// // form params
// $contactFormParams = [
// 'firstName' => $firstname,
// 'lastName' => $lastname,
// //'phone' => "+" . $phonePrefix . $phone,
// 'phone' => $phone,
// 'email' => $email,
// 'club' => $club,
// 'zipcode' => $zipcode,
// 'privacy' => true,
// 'page' => $page,
// 'home_training' => $homeTraining,
// ];
//
// //////// checkPerson
// $this->virginUser->checkPerson($email);
// // preparazione per il salvataggio della privacy
// $contactFormParams['route'] = $route = $request->getPathInfo();
//
// $redirectObject = $this->virginUser->handlePerson($contactFormParams, $context, VirginUser::FORM_CONTACT);
//
// $redirectObject['params']['home_training'] = $homeTraining;
//
// if ($redirectObject['errorSnippet'] != '') {
// $redirectObject['params']['errorSnippet'] = $this->trans($redirectObject['errorSnippet']);
// }
// $redirectObject['params']['club'] = $club;
// if ($redirectObject['renderStorefront']) {
// return $this->renderStorefront($redirectObject['route'], $redirectObject['params']);
// } else {
// return $this->redirectToRoute($redirectObject['route'], $redirectObject['params']);
// }
// }
/**
* @Route("/contact/methods", name="frontend.contact.methods", options={"seo" = "false"}, methods={"GET"})
*/
public function showContactMethodsPage(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$this->logger->log(Logger::DEBUG, 'Contact methods form request' . serialize($data));
$userLogged = ($context->getCustomer()) ? true : false;
$page = $this->contactPageLoader->load($request, $context);
if (isset($_COOKIE['ecommerce-va'])) {
$decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
}
if ($context->getCustomer()) {
$email = $context->getCustomer()->getEmail();
} elseif (isset($decodedCookie)) {
$email = $decodedCookie->email;
} else {
return $this->redirectToRoute('frontend.contact');
}
$contactId = $this->contactRepository->searchIds(
(new Criteria())->addFilter(new EqualsFilter('email', $email)),
Context::createDefaultContext()
)->firstId();
if ($contactId) {
return $this->redirectToRoute('frontend.home.page');
}
$home_training = false;
if ($context->getCustomer() != null
&& array_key_exists('home_training', $context->getCustomer()->getCustomFields())
&& !empty($context->getCustomer()->getCustomFields()['home_training'])
) {
$home_training = true;
}
return $this->renderStorefront('@Storefront/storefront/page/contact/methods.html.twig',
[
'userLogged' => $userLogged,
'page' => $page,
'email' => $email,
'preselectedClub' => $request->get('club'),
'home_training'=> $home_training
]
);
}
/**
* @Route("/appointment-new", name="frontend.appointment.new", options={"seo" = "false"}, methods={"POST"})
* @throws \Exception
*/
public function createAppointmentNew(Request $request, RequestDataBag $data, SalesChannelContext $salesChannelContext)
{
if (!$salesChannelContext->getCustomer()){
return;
}
if ($data->get("appointmentType") == self::TYPE_ONSITE){
$dateTimeObj = new DateTime($data->get("date")." ".$data->get("hour"));
} else {
$dateTimeObj = new DateTime("now");
}
/** @var ClubEntity $club */
$club = $this->clubService->getClubById($data->get("clubId"), $salesChannelContext);
$formParams = [
'guid_lead' => $salesChannelContext->getCustomer()->getCustomFields()['virgin_guid'],
'guid_club' => $club->getGuidVirgin(),
'app_type' => $data->get("appointmentType"),
'app_date' => $dateTimeObj->format(DateTime::ATOM),
'note' => "Inserito da ecommerce",
];
$resp = $this->restApiClient->insertAppointment($formParams);
return new Response($resp['message'], $resp['code']);
}
/**
* @Route("/contact/appointment", name="frontend.contact.appointment", options={"seo" = "false"}, methods={"POST"})
*/
public function saveAppointment(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$this->logger->log(Logger::DEBUG, 'Appointment form request' . serialize($data));
$date = $data->get('data-appointment');
$time = $data->get('time-appointment');
$email = $data->get('email');
$club = $data->get('club');
$page = $this->contactPageLoader->load($request, $context);
if (empty($date) || empty($time) || empty($email) || empty($club)) {
return $this->redirectToRoute('frontend.contact.methods', [
'error' => true,
'errorSnippet' => $this->trans('lead-manager.form.message.errorMessage'),
'page' => $page,
]);
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $email ));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
/// Create Appountment
$contactTypeId = $this->contactTypeRepository->searchIds(
(new Criteria())->addFilter(new EqualsFilter('identifier', self::APPOINTMENT)),
Context::createDefaultContext()
)->firstId();
//echo 'Appuntamente in ShopWare';
$appId = Uuid::randomHex();
$App = $this->contactRepository->create(
[
[
'id' => $appId,
'firstname' => $customerEntity->getFirstName(),
'lastname' => $customerEntity->getLastName(),
'phone' => $customerEntity->getCustomFields()['phone_number'],
'email' => $email,
'time' => $time,
'date' => $date,
'contactTypeId' => $contactTypeId,
'preferredClubId' => $club,
'customerId' => $customerEntity->getId()
],
],
$context->getContext()
);
$contactEntity = $this->contactRepository->search(
(new Criteria())->addFilter(new EqualsFilter('id', $appId)),
Context::createDefaultContext()
)->first();
// dispatch email event
//$emailEvent = new AppointmentConfirmationEvent($context, $customerEntity, $contactEntity, $clubEntity);
//$this->eventDispatcher->dispatch($emailEvent);
$clubCriteria = new Criteria();
$clubCriteria->addFilter(new EqualsFilter('id', $club));
$clubEntity = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
if(isset($clubEntity)){
$clubGuidId = $clubEntity->getGuidVirgin();
} else {
$clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
$clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
}
$formParams = [
'guid_lead' => $customerEntity->getId(),
'guid_club' => $clubGuidId,
'app_type' => VirginUser::APP_INFO,
'app_date' => $date . 'T' . $time . 'Z',
'note' => 'Inserito da ecommerce'
];
$this->restApiClient->insertAppointment($formParams);
return $this->renderStorefront('@Storefront/storefront/page/contact/methods.html.twig', [
'successAppointmentPopup' => true,
'successSnippet' => $this->trans('lead-manager.form.message.successRegistration'),
'home_training' => $customerEntity->getCustomFields()['home_training']
]);
}
/**
* @Route("/contact/call", name="frontend.contact.call", options={"seo" = "false"}, methods={"POST"})
*/
public function saveCall(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$this->logger->log(Logger::DEBUG, 'Call form request' . serialize($data));
$date = $data->get('date-call');
$time = $data->get('time-call');
$page = $this->contactPageLoader->load($request, $context);
if (empty($date) || empty($time)) {
return $this->redirectToRoute('frontend.contact.methods', [
'error' => true,
'errorSnippet' => $this->trans('lead-manager.form.message.errorMessage'),
]);
}
if (isset($_COOKIE['ecommerce-va'])) {
$decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
if (isset($customerEntity)) {
$contactTypeId = $this->contactTypeRepository->searchIds(
(new Criteria())->addFilter(new EqualsFilter('identifier', self::CALL)),
Context::createDefaultContext()
)->firstId();
$this->contactRepository->create(
[
[
'firstname' => $decodedCookie->name,
'lastname' => $decodedCookie->lastname,
'phone' => $decodedCookie->phone,
'email' => $decodedCookie->email,
'time' => $time,
'date' => $date,
'contactTypeId' => $contactTypeId,
'customerId' => $customerEntity->getId()
],
],
$context->getContext()
);
if(isset($customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'])){
$clubCriteria = new Criteria();
$clubCriteria->addFilter(new EqualsFilter('id', $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId']));
$clubEntity = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
}else{
$clubEntity = $this->configuratorService->getClubByZipcode( $customerEntity->getCustomFields()['zipcode']);
if(!isset($clubEntity)){
$clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
$clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
}
}
$formParams = [
'guid_lead' => $customerEntity->getId(),
'firstName' => $decodedCookie->name,
'lastName' => $decodedCookie->lastname,
'phone' => $decodedCookie->phone,
'email' => $decodedCookie->email,
'page' => $page,
'privacy' => $customerEntity->getCustomFields()['privacy_consent'],
'clubGuidId' => isset($clubEntity) ? $clubEntity->getGuidVirgin() : $clubGuidId,
'clubName' => isset($clubEntity) ? $clubEntity->getName() : $clubName ,
'giorno_predefinito' => $date,
'orario_predefinito' => $time,
'channel' => VirginUser:: FORM_CONTACT,
'cap' => $customerEntity->getCustomFields()['zipcode'],
'isExplicitRegistration' => !$customerEntity->getCustomFields()['lead_implicit_registration'],
];
$privacyText = $this->privacyService->getPrivacyConsent($context->getContext(), VirginUser:: FORM_CONTACT);
if(isset($privacyText)){
$formParams['privacyJson']= $privacyText;
}
$this->virginUser->insertLeadToLayerQuick($formParams, $customerEntity, $context);
}
} else {
return $this->redirectToRoute('frontend.contact.methods', [
'error' => true,
'errorSnippet' => $this->trans('lead-manager.form.message.errorCookie'),
]);
}
return $this->renderStorefront('@Storefront/storefront/page/contact/methods.html.twig', [
'successCallPopup' => true,
'email' => $decodedCookie->email,
'page' => $this->contactPageLoader->load($request, $context),
'successSnippet' => $this->trans('lead-manager.form.message.successBook'),
'home_training'=> $context->getCustomer()->getCustomFields()['home_training']
]);
}
/**
* @Route("/contact/registration", name="frontend.register.contact", options={"seo" = "false"}, methods={"GET"})
*/
public function contactRegisterForm(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
if(array_key_exists('lead_implicit_registration', $context->getCustomer()->getCustomFields()) && $context->getCustomer()->getCustomFields()['lead_implicit_registration'] === false) {
$club = $context->getCustomer()->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
}
$page = $this->contactPageLoader->load($request, $context);
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'page' => $page,
'email' => $context->getCustomer()->getEmail(),
'loginError' => isset($loginError) ? (bool)$loginError : false,
'loginSnippet' => $request->query->get('errorSnippet'),
]);
}
/**
* @Route("/purchase", name="frontend.purchase", options={"seo" = "false"}, methods={"GET"})
*/
public function purchaseForm(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$this->logger->log(Logger::DEBUG, 'purchase form request - print data');
$page = $this->contactPageLoader->load($request, $context);
if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
return $this->redirectToRoute('frontend.home.page');
}
if ($context->getCustomer()) {
$club = $context->getCustomer()->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
}
return $this->redirectToRoute('frontend.account.login.page');
}
//DEPRECATED
// /**
// * @Route("/purchase/create", name="frontend.purchase.create", options={"seo" = "false"}, methods={"POST"})
// */
// public function purchaseCreateUser(Request $request, RequestDataBag $data, SalesChannelContext $context)
// {
// return $this->redirectToRoute('frontend.account.login.page');
//
// if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
// return $this->redirectToRoute('frontend.home.page');
// }
//
// $this->logger->log(Logger::DEBUG, 'Purchase form request - send data');
// $page = $this->contactPageLoader->load($request, $context);
//
// // spostata tutta la validazione in una funzione
// $redirectObject = $this->virginUser->CheckFormParamsToStorefront($data, $page, '@Storefront/storefront/page/purchase/index.html.twig');
//
// if ($redirectObject != null) {
// return $this->renderStorefront($redirectObject['route'],
// [
// 'loginError' => $redirectObject['loginError'],
// 'errorSnippet' => $this->trans($redirectObject['errorSnippet']),
// 'page' => $page,
// ]);
// }
//
// $firstname = $data->get('name');
// $lastname = $data->get('lastname');
// $phone = $data->get('phone');
// $phonePrefix = $data->get('intlPrefix');
// $email = $data->get('email');
// $privacy = $data->get('privacy');
// $club = $data->get('club');
// $zipcode = $data->get('zipcode');
//
// if ($club == 'home_training') {
// $club = null;
// $homeTraining = true;
// } else {
// $homeTraining = null;
// }
//
// $this->virginUser->checkPerson($email);
//
// // preparazione per il salvataggio della privacy
// $contactFormParams['route'] = $request->getPathInfo();
// $contactFormParams['email'] = $email;
// $contactFormParams['firstName'] = $firstname;
// $contactFormParams['lastName'] = $lastname;
// //$contactFormParams['phone'] = "+" . $phonePrefix . $phone;
// $contactFormParams['phone'] = $phone;
// $contactFormParams['privacy'] = $privacy;
// $contactFormParams['club'] = $club;
// $contactFormParams['page'] = $page;
// $contactFormParams['home_training'] = $homeTraining;
// $contactFormParams['zipcode'] = $zipcode;
//
// $redirectObject = $this->virginUser->handlePerson($contactFormParams, $context, VirginUser::FORM_PURCHASE);
//
// $redirectObject['params']['home_training'] = $homeTraining;
//
// if ($redirectObject['errorSnippet'] != '') {
// $redirectObject['params']['errorSnippet'] = $this->trans($redirectObject['errorSnippet']);
// }
//
// if ($redirectObject['renderStorefront'] == true) {
// return $this->renderStorefront($redirectObject['route'], $redirectObject['params']);
// } else {
// return $this->redirectToRoute($redirectObject['route'], $redirectObject['params']);
// }
// }
/**
* @Route("/purchase/register", name="frontend.purchase.register", options={"seo" = "false"}, methods={"POST"})
*/
public function registerCustomer(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
return $this->redirectToRoute('frontend.account.login.page');
$this->logger->log(Logger::DEBUG, 'Register methods form request' . serialize($data));
$page = $this->contactPageLoader->load($request, $context);
$email = $data->get('email');
$password = $data->get('password');
$privacy = $data->get('privacy');
$route = $request->getPathInfo();
$decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
if (empty($email) || empty($password)) {
return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
'loginError' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
$validation = new DataValidationDefinition('customer.email');
$validation->add('email', new Email());
try {
$this->validator->validate(['email' => $email], $validation);
} catch (ConstraintViolationException $e) {
$this->logger->log(Logger::ERROR, $e->getMessage());
return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
'loginError' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
$criteria = new Criteria();
$this->virginUser->checkPerson($email);
if ($decodedCookie->email !== $email) {
$criteria->addFilter(new EqualsFilter('customer.email', $email));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
if($this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEADLAYER ||
$this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEAD ) {
// passo solo se sono lead o solo sul lead layer
if(!isset($customerEntity)){
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
}elseif (!$customerEntity->getCustomFields()['lead_implicit_registration']){
return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
'loginError' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
}
else{
$this->logoutRoute->logout($context);
return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
'loginError' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
} else {
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
}
if (isset($customerEntity)) {
// email is just on shopware system at this point must check if is the same person or not
if($this->virginUser->getIsInLeadLayer()){
$leadLayerUser = $this->virginUser->getLeadLayerUser();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
$criteria->addAssociation('salutation');
$customerEntityCookie = $this->customerRepository->search($criteria, $context->getContext())->first();
// search on the lead Layer the same email, and check if name and surname are the same
if(!($leadLayerUser->getNome() == $customerEntityCookie->getFirstName() && $leadLayerUser->getCognome() == $customerEntityCookie->getLastName())){
// Name and Surname are the same on Lead Layer system, -> error for User Just Registered
$this->logoutRoute->logout($context);
if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
}
return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
'loginError' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
}
// User in Lead Layer or on the same Name and Surname
if ($customerEntity->getCustomFields()['lead_implicit_registration']) {
/** @var EntityRepositoryInterface $productRepository */
$customerRepository = $this->container->get('customer.repository');
$partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
$customFields = [
'lead_implicit_registration' => false,
'privacy_consent' => (isset($privacy)) ? (bool)$privacy : null,
];
if (!empty($partnerUser)) {
$customFields = array_merge($customFields, $partnerUser);
}
$customerRepository->update(
[
[
'id' => $customerEntity->getId(),
'email' => $email,
'password' => $password,
'customFields' => $customFields,
],
],
\Shopware\Core\Framework\Context::createDefaultContext()
);
$this->logoutRoute->logout($context);
if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
}
$this->accountService->login($email, $context);
$customerEntity->setEmail($email);
$this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
if(isset($customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'])){
$clubCriteria = new Criteria();
$clubCriteria->addFilter(new EqualsFilter('id', $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId']));
$club = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
}else{
$club = $this->configuratorService->getClubByZipcode( $customerEntity->getCustomFields()['zipcode']);
if(!isset($club)){
$clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
$clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
}
}
$leadToUpdate = [
'firstName' => $customerEntity->getFirstName(),
'lastName' => $customerEntity->getLastName(),
'clubGuidId' => isset($club) ? $club->getGuidVirgin(): $clubGuidId,
'clubName' => isset($club) ? $club->getName(): $clubName,
'phone' => $customerEntity->getCustomFields()['phone_number'],
'email' => $email,
'channel' => VirginUser::FORM_REGISTER,
'privacy' => (isset($privacy)) ? (bool)$privacy : null,
'cap' => $customerEntity->getCustomFields()['zipcode'],
'isExplicitRegistration' => !$customerEntity->getCustomFields()['lead_implicit_registration'],
];
$privacyText = $this->privacyService->getPrivacyConsent($context->getContext(), VirginUser:: FORM_REGISTER);
if(isset($privacyText)){
$leadToUpdate['privacyJson']= $privacyText;
}
if($this->virginUser->getIsInLeadLayer()){
$leadToUpdate['guid_lead'] = $customerEntity->getCustomFields()['virgin_guid'];
$this->restApiClient->UpdateLead($leadToUpdate);
}else{
$leadToUpdate['guid_lead'] = $customerEntity->getId();
$this->restApiClient->InsertLead($leadToUpdate);
}
$club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
}
$club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
} else {
// Error they never been reatched
$this->logoutRoute->logout($context);
if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
}
return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
'loginError' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
return $this->redirectToRoute('frontend.configurator');
}
/**
* @Route("/walkin", name="frontend.walkin", options={"seo" = "false"}, methods={"GET"})
*/
public function handleLeadLoadingPage(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$page = $this->loginPageLoader->load($request, $context);
return $this->renderStorefront('@Storefront/storefront/page/loading/walkin_loading.html.twig', [
'page' => $page,
]);
}
/**
* @Route("/walkinTA", name="frontend.walkinta", options={"seo" = "false"}, methods={"GET"})
*/
public function handleLead(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$this->logger->log(Logger::DEBUG, 'Walkin request: ' . serialize($data));
$leadInfo = $request->get('l');
$decodedLeadInfo = json_decode(base64_decode($leadInfo));
if(isset($decodedLeadInfo->mc_ExerpCode)){
$_SESSION['mc_code'] = $decodedLeadInfo->mc_ExerpCode;
}
$leadCrm_Guid = str_replace ("}", "", str_replace ("{", "", $decodedLeadInfo->leadCrm_Guid));
$club_Guid = str_replace ("}", "", str_replace ("{", "", $decodedLeadInfo->club_Guid));
$this->logger->log(Logger::DEBUG, 'Walkin decoded request: ' . serialize($data));
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedLeadInfo->email));
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
$user = [
'firstName' => $decodedLeadInfo->nome,
'lastName' => $decodedLeadInfo->cognome,
'salutationId' => $this->leadService->getDefaultSalutation($context),
'email' => $decodedLeadInfo->email,
'password' => '12345678',
"storefrontUrl" => $context->getSalesChannel()->getDomains()->first()->getUrl(),
];
$this->virginUser->checkPerson($decodedLeadInfo->email);
$partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
$isEmptyPartnerUser = empty($partnerUser);
if (isset($customerEntity)) {
$this->accountService->login($decodedLeadInfo->email, $context);
$customFields = [
'lead_implicit_registration' => false,
'mc_code_customer' => $decodedLeadInfo->mc_ExerpCode,
'id_richiesta' => $leadCrm_Guid,
'data_richiesta_mc' => (new DateTime('now', new DateTimeZone("Europe/Rome")))->format('Ymd')
];
if (!$isEmptyPartnerUser) {
$customFields = array_merge($customFields, $partnerUser);
}
$this->customerRepository->update([
[
'id' => $customerEntity->getId(),
'customFields' => $customFields,
'group' => [
'id' => $this->virginUser->getCustomerGroupId()
],
],
], $context->getContext());
} else {
$customerEntity = $this->leadService->prepareRegistrationData($context, $user);
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.guidVirgin', $club_Guid));
$club = $this->clubRepository->search($criteria, $context->getContext())->first();
$customFields = [
'lead_implicit_registration' => false,
'phone_number' => $decodedLeadInfo->telefono,
'privacy_consent' => null,
'mc_code_customer' => $decodedLeadInfo->mc_ExerpCode,
'id_richiesta' => $leadCrm_Guid,
'data_richiesta_mc' => (new DateTime('now', new DateTimeZone("Europe/Rome")))->format('Ymd')
];
if (!$isEmptyPartnerUser) {
$customFields = array_merge($customFields, $partnerUser);
}
$this->customerRepository->update([
[
'id' => $customerEntity->getId(),
'customFields' => $customFields,
'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
'group' => [
'id' => $this->virginUser->getCustomerGroupId()
],
],
], $context->getContext());
$this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
//$userData = new RequestDataBag($user);
//$this->sendPasswordRecoveryMailRoute->sendRecoveryMail($userData->toRequestDataBag(), $context);
}
$userData = new RequestDataBag($user);
// $validateStorefrontUrl is bugged up to v6.5.1 - it isn't taken into account - always true - added storefrontUrl in $user to fix it
$this->sendPasswordRecoveryMailRoute->sendRecoveryMail($userData->toRequestDataBag(), $context, false);
if(isset($decodedLeadInfo->redirectTo)) {
switch ($decodedLeadInfo->redirectTo) {
// In current situation the only case and the default case are returning the same value
// so those cases must be handled properly, otherwise switch is not needed
case '/configurator':
return $this->redirectToRoute('frontend.configurator');
default:
return $this->redirectToRoute('frontend.configurator');
}
}else{
return $this->redirectToRoute('frontend.configurator');
}
}
/**
* @Route("/contact-chatbot", name="frontend.contact.chatbot", defaults={"csrf_protected"=false}, options={"seo" = "false"}, methods={"GET"})
*/
public function contactChatbot(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$leadInfo = $request->get('token');
$decodedLeadInfo = json_decode(base64_decode($leadInfo));
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedLeadInfo->email));
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.centerId', $decodedLeadInfo->club));
$club = $this->clubRepository->search($criteria, $context->getContext())->first();
$user = [
'firstName' => $decodedLeadInfo->nome,
'lastName' => $decodedLeadInfo->cognome,
'salutationId' => $this->leadService->getDefaultSalutation($context),
'email' => $decodedLeadInfo->email,
'password' => '12345678',
"storefrontUrl" => $context->getSalesChannel()->getDomains()->first()->getUrl(),
];
$this->virginUser->checkPerson($decodedLeadInfo->email);
$partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
$isEmptyPartnerUser = empty($partnerUser);
if (isset($customerEntity)) {
$this->accountService->login($decodedLeadInfo->email, $context);
$customFields = [
'lead_implicit_registration' => false,
];
if (!$isEmptyPartnerUser) {
$customFields = array_merge($customFields, $partnerUser);
}
$this->customerRepository->update([
[
'id' => $customerEntity->getId(),
'customFields' => $customFields,
'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
'group' => [
'id' => $this->virginUser->getCustomerGroupId()
],
],
], $context->getContext());
} else {
$customerEntity = $this->leadService->prepareRegistrationData($context, $user);
$customFields = [
'lead_implicit_registration' => false,
'phone_number' => $decodedLeadInfo->telefono,
'privacy_consent' => null,
];
if (!$isEmptyPartnerUser) {
$customFields = array_merge($customFields, $partnerUser);
}
$this->customerRepository->update([
[
'id' => $customerEntity->getId(),
'customFields' => $customFields,
'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
'group' => [
'id' => $this->virginUser->getCustomerGroupId()
],
],
], $context->getContext());
$this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
}
$userData = new RequestDataBag($user);
// $validateStorefrontUrl is bugged up to v6.5.1 - it isn't taken into account - always true - added storefrontUrl in $user to fix it
$this->sendPasswordRecoveryMailRoute->sendRecoveryMail($userData->toRequestDataBag(), $context, false);
$navigationId = $this->leadService->getNavigationIdByTag("promo_chatbot", $context);
$this->session->set('clubId', isset($club) ? $club->getId() : null);
if($navigationId) {
return $this->redirectToRoute(
"frontend.navigation.page",
[
"navigationId" => $navigationId,
]
);
}
else {
return $this->redirectToRoute('frontend.configurator');
}
}
/**
* @Route("/contact/register", name="frontend.contact.register", methods={"POST"})
*/
public function register(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$this->logger->log(Logger::DEBUG, 'Register methods form request' . serialize($data));
$page = $this->contactPageLoader->load($request, $context);
$email = $data->get('username');
$password = $data->get('password');
$decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
$leadLayerUser=null;
if (empty($email) || empty($password)) {
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'error' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]);
}
$validation = new DataValidationDefinition('customer.email');
$validation->add('email', new Email());
try {
$this->validator->validate(['email' => $email], $validation);
} catch (ConstraintViolationException $e) {
$this->logger->log(Logger::ERROR, $e->getMessage());
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'error' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
'page' => $this->contactPageLoader->load($request, $context),
]);
}
$criteria = new Criteria();
// CheckPerson on Sysytem if
$this->virginUser->checkPerson($email);
if ($decodedCookie->email !== $email) {
$criteria->addFilter(new EqualsFilter('customer.email', $email));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
if($this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEADLAYER ||
$this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEAD ) {
// passo solo se sono lead o solo sul lead layer
if(!isset($customerEntity)){
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
}elseif (!$customerEntity->getCustomFields()['lead_implicit_registration']){
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'error' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
'page' => $this->contactPageLoader->load($request, $context),
]);
}
}
else{
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'error' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
'page' => $this->contactPageLoader->load($request, $context),
]);
}
} else {
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
}
if (isset($customerEntity)) {
// email is just on shopware system at this point must check if is the same person or not
if($this->virginUser->getIsInLeadLayer()){
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
$criteria->addAssociation('salutation');
$customerEntityCookie = $this->customerRepository->search($criteria, $context->getContext())->first();
$leadLayerUser = $this->virginUser->getLeadLayerUser();
// search on the lead Layer the same email, and check if name and surname are the same
if(!($leadLayerUser->getNome() == $customerEntityCookie->getFirstName() && $leadLayerUser->getCognome() == $customerEntityCookie->getLastName())){
// Name and Surname are the same on Lead Layer system, -> error for User Just Registered
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'error' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
'page' => $this->contactPageLoader->load($request, $context),
]);
}
}
$isImplicitRegistration = $customerEntity->getCustomFields()['lead_implicit_registration'];
// User in Lead Layer or on the same Name and Surname
if ($isImplicitRegistration) {
/** @var EntityRepositoryInterface $productRepository */
$customerRepository = $this->container->get('customer.repository');
$partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
$customFields = ['lead_implicit_registration' => false];
if (!empty($partnerUser)) {
$customFields = array_merge($customFields, $partnerUser);
}
$customerRepository->update(
[
[
'id' => $customerEntity->getId(),
'email' => $email,
'password' => $password,
'customFields' => $customFields,
],
],
\Shopware\Core\Framework\Context::createDefaultContext()
);
$this->logoutRoute->logout($context);
if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
}
$this->accountService->login($email, $context);
$customerEntity->setEmail($email);
$this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
if(isset($customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'])){
$clubCriteria = new Criteria();
$clubCriteria->addFilter(new EqualsFilter('id', $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId']));
$club = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
}else{
/* @var ClubEntity $club */
$club = $this->configuratorService->getClubByZipcode( $customerEntity->getCustomFields()['zipcode']);
if(!isset($club)){
$clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
$clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
}
}
$leadToUpdate = [
'firstName' => $customerEntity->getFirstName(),
'lastName' => $customerEntity->getLastName(),
'clubGuidId' => isset($club) ? $club->getGuidVirgin(): $clubGuidId,
'clubName' => isset($club) ? $club->getName(): $clubName,
'phone' => $customerEntity->getCustomFields()['phone_number'],
'email' => $email,
'channel' => VirginUser::FORM_CONTACT,
'privacy' => $customerEntity->getCustomFields()['privacy_consent'],
'cap' => $customerEntity->getCustomFields()['zipcode'],
'isExplicitRegistration' => !$isImplicitRegistration,
];
if($this->virginUser->getIsInLeadLayer()){
$leadToUpdate['guid_lead'] = $customerEntity->getCustomFields()['virgin_guid'];
$this->restApiClient->UpdateLead($leadToUpdate);
}else{
$leadToUpdate['guid_lead'] = $customerEntity->getId();
$this->restApiClient->InsertLead($leadToUpdate);
}
$club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
}
$club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
if(isset($club)) {
return $this->redirectToRoute('frontend.configurator');
} else {
$navigationId = $this->leadService->getRevolutionDigitaleId($context);
return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
}
} else {
// Error they never been reatched
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
'error' => true,
'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
'page' => $this->contactPageLoader->load($request, $context),
]);
}
return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', ['page' => $page]);
}
/**
* @Route("/account/recover", name="frontend.account.recover.page", methods={"GET"})
*
* @throws CategoryNotFoundException
* @throws InconsistentCriteriaIdsException
* @throws MissingRequestParameterException
*/
public function recoverAccountForm(Request $request, SalesChannelContext $context): Response
{
$page = $this->loginPageLoader->load($request, $context);
return $this->renderStorefront('@Storefront/storefront/page/recover-password.html.twig', [
'page' => $page,
]);
}
/**
* @Route("/account/recover", name="frontend.account.recover.request", methods={"POST"})
* @throws VirginApiException
*/
public function generateAccountRecovery(Request $request, RequestDataBag $data, SalesChannelContext $context): Response
{
$email = $data->all()['email']['email'];
$this->virginUser->checkPerson($email);
if ($this->virginUser->getPersonType()==$this->virginUser::PERSONTYPE_LEAD || $this->virginUser->getPersonType()==$this->virginUser::PERSONTYPE_LEADLAYER){
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $email));
$criteria->addFilter(new EqualsFilter('customer.guest', 0));
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
if (!$customerEntity) {
$this->addFlash('danger', $this->trans('lead-manager.account.emailIsNotRegistered'));
return $this->redirectToRoute('frontend.account.login.page');
}
try {
$data->get('email')->set('storefrontUrl', $request->attributes->get('sw-sales-channel-absolute-base-url'));
$this->sendPasswordRecoveryMailRoute->sendRecoveryMail($data->get('email')->toRequestDataBag(), $context);
$this->addFlash('success', $this->trans('account.recoveryMailSend'));
} catch (CustomerNotFoundException $e) {
$this->addFlash('success', $this->trans('account.recoveryMailSend'));
} catch (InconsistentCriteriaIdsException $e) {
$this->addFlash('danger', $this->trans('error.message-default'));
}
return $this->redirectToRoute('frontend.account.recover.page');
} else {
$this->restApiClient->requestGlobalPasswordReset($email);
$this->session->set("recovery-email", $email);
$this->session->set("recovery-timestamp", (new DateTime())->getTimestamp());
return $this->redirectToRoute('frontend.account.recover.password.global');
}
}
private function checkHash(string $hash, Context $context): bool
{
$criteria = new Criteria();
$criteria->addFilter(
new EqualsFilter('hash', $hash)
);
$recovery = $this->customerRecoveryRepository->search($criteria, $context)->first();
$validDateTime = (new \DateTime())->sub(new \DateInterval('PT2H'));
return $recovery && $validDateTime < $recovery->getCreatedAt();
}
/**
* @Route("/account/recover/password", name="frontend.account.recover.password.page", methods={"GET"})
*
* @throws CategoryNotFoundException
* @throws InconsistentCriteriaIdsException
* @throws MissingRequestParameterException
*/
public function resetPasswordForm(Request $request, SalesChannelContext $context): Response
{
$page = $this->loginPageLoader->load($request, $context);
$hash = $request->get('hash');
if (!$hash) {
$this->addFlash('danger', $this->trans('account.passwordHashNotFound'));
return $this->redirectToRoute('frontend.account.recover.request');
}
$customerHashCriteria = new Criteria();
$customerHashCriteria->addFilter(new EqualsFilter('hash', $hash));
$customerRecovery = $this->customerRecoveryRepository->search($customerHashCriteria, $context->getContext())->first();
if ($customerRecovery === null) {
$this->addFlash('danger', $this->trans('account.passwordHashNotFound'));
return $this->redirectToRoute('frontend.account.recover.request');
}
if (!$this->checkHash($hash, $context->getContext())) {
$this->addFlash('danger', $this->trans('account.passwordHashExpired'));
return $this->redirectToRoute('frontend.account.recover.request');
}
return $this->renderStorefront('@Storefront/storefront/page/reset-password.html.twig', [
'page' => $page,
'hash' => $hash,
'formViolations' => $request->get('formViolations'),
]);
}
/**
* @Route("/account/recover/password/global", name="frontend.account.recover.password.global", methods={"GET"})
* */
public function resetPasswordGlobalPage(Request $request, SalesChannelContext $context): Response
{
$email = $this->session->get("recovery-email");
$timestamp = $this->session->get("recovery-timestamp");
if (!$email || !$timestamp){
$this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
return $this->redirectToRoute('frontend.account.recover.request');
}
try {
if ((new DateTime())->diff(new DateTime("@".$timestamp))->h > 24){
$this->addFlash('danger', $this->trans('lead-manager.account.recovery.invalidTimestamp'));
return $this->redirectToRoute('frontend.account.recover.request');
}
} catch (\Exception $e){
$this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
return $this->redirectToRoute('frontend.account.recover.request');
}
return $this->renderStorefront('@Storefront/storefront/page/reset-password.html.twig', [
'isGlobal' => true,
'email' => $email,
]);
}
/**
* @Route("/account/recover/password", name="frontend.account.recover.password.reset", methods={"POST"})
*
* @throws InconsistentCriteriaIdsException
*/
public function resetPassword(RequestDataBag $data, SalesChannelContext $context): Response
{
$hash = $data->get('password')->get('hash');
try {
if (!preg_match($this->restApiClient::PASSWORD_REGEX, $data->get('password')->get('newPassword'))){
$this->addFlash('danger', $this->trans('account.passwordChangeNoSuccess'));
return $this->forwardToRoute(
'frontend.account.recover.password.page',
['hash' => $hash, 'formViolations' => "Password not matching requirements", 'passwordFormViolation' => true]
);
}
$customerHashCriteria = new Criteria();
$customerHashCriteria->addFilter(new EqualsFilter('hash', $hash));
$customerHashCriteria->addAssociation('customer');
$customerRecovery = $this->customerRecoveryRepository->search($customerHashCriteria, $context->getContext())->first();
$this->resetPasswordRoute->resetPassword($data->get('password')->toRequestDataBag(), $context);
/** @var CustomerEntity $customer */
$customer = $customerRecovery->getCustomer();
$customerEmail = $customer->getEmail();
$newPassword = $data->get('password')->get('newPassword');
$checkPersonResp = $this->virginUser->checkPerson($customerEmail);
$customFields = [
'lead_implicit_registration' => false
];
$this->customerRepository->update([
[
'id' => $customer->getId(),
'customFields' => $customFields,
'active' => true
],
], $context->getContext());
} catch (ConstraintViolationException $formViolations) {
$this->addFlash('danger', $this->trans('account.passwordChangeNoSuccess'));
return $this->forwardToRoute(
'frontend.account.recover.password.page',
['hash' => $hash, 'formViolations' => $formViolations, 'passwordFormViolation' => true]
);
} catch (CustomerNotFoundByHashException $e) {
$this->addFlash('danger', $this->trans('account.passwordChangeNoSuccess'));
return $this->forwardToRoute('frontend.account.recover.request');
} catch (CustomerRecoveryHashExpiredException $e) {
$this->addFlash('danger', $this->trans('account.passwordHashExpired'));
return $this->forwardToRoute('frontend.account.recover.request');
}
return $this->redirectToRoute('frontend.account.login.page');
}
/**
* @Route("/account/recover/password/global", name="frontend.account.recover.password.reset.global", methods={"POST"})
*
* @throws VirginApiException
*/
public function resetPasswordGlobal(RequestDataBag $data, SalesChannelContext $context): Response
{
$email = $data->get("email");
$token = $data->get("token");
$newPassword = $data->get("password")->get("newPassword");
$this->virginUser->checkPerson($email);
if ($this->virginUser->getPersonType()==$this->virginUser::PERSONTYPE_LEAD){
$this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
return $this->redirectToRoute('frontend.account.recover.request');
}
$response = $this->restApiClient->sendGlobalPasswordReset($email, $newPassword, $token);
if (!$response['success']){
$this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
return $this->redirectToRoute('frontend.account.recover.request');
}
$this->addFlash('success', $this->trans('lead-manager.account.recovery.success'));
return $this->redirectToRoute('frontend.account.login.page');
}
/**
* @Route("/continueCheckout", name="frontend.continue.checkout", options={"seo" = "false"}, methods={"GET"})
*/
public function continueCheckout(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$token = $request->get('t');
$criteria = new Criteria([$token]);
/** @var CustomerEntity $order */
$customer = $this->customerRepository->search($criteria, $context->getContext())->first();
$this->accountService->login($customer->getEmail(), $context);
return $this->redirectToRoute('frontend.checkout.confirm.page');
}
/**
* @Route("/dem", name="frontend.exerp.dem", options={"seo" = "false"}, methods={"GET"})
*/
public function autologinByExerpId(Request $request, RequestDataBag $data, SalesChannelContext $context)
{
$exerpCampaignCode = $request->get('g');
$exerpId = $request->get('e');
if(empty($exerpCampaignCode) || empty($exerpId)) {
$errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.ErrorPage404');
return $this->renderStorefront(
'@Storefront/storefront/page/content/index.html.twig',
['page' => $errorPage]
);
}
$this->virginUser->checkPersonByExerpInfo($exerpId, $exerpCampaignCode);
if($this->virginUser->getExerpUser()) {
if(empty($this->virginUser->getExerpUser()->getEmail())) {
$errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.ErrorPage404');
return $this->renderStorefront(
'@Storefront/storefront/page/content/index.html.twig',
['page' => $errorPage]
);
} else {
if($this->virginUser->getExerpUser()->getCustomerGroup() != $exerpCampaignCode || $this->virginUser->getExerpUser()->getCustomerGroup() == null) {
$errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.InvalidPromotion404');
return $this->renderStorefront(
'@Storefront/storefront/page/content/index.html.twig',
['page' => $errorPage]
);
}
if($this->virginUser->getExerpUser()->getCenterId()) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.centerId', $this->virginUser->getExerpUser()->getCenterId()));
} else {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.default', true));
}
$club = $this->clubRepository->search($criteria, $context->getContext())->first();
if($club == null) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.default', true));
$club = $this->clubRepository->search($criteria, $context->getContext())->first();
}
$email = $this->virginUser->getExerpUser()->getEmail();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $email));
$criteria->addAssociation('salutation');
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
if($customerEntity !== null) {
$this->customerRepository->update([
[
'id' => $customerEntity->getId(),
'customFields' => [
'lead_implicit_registration' => false,
'home_training' => false
],
'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
'group' => [
'id' => $this->virginUser->getCustomerGroupId()
],
],
], $context->getContext());
} else {
$user = [
'firstName' => $this->virginUser->getExerpUser()->getFirstName(),
'lastName' => $this->virginUser->getExerpUser()->getLastName(),
'salutationId' => $this->leadService->getDefaultSalutation($context),
'email' => $email,
'password' => '12345678a',
];
$customerEntity = $this->leadService->prepareRegistrationData($context, $user);
$this->customerRepository->update([
[
'id' => $customerEntity->getId(),
'customFields' => [
'lead_implicit_registration' => false,
'privacy_consent' => false,
'home_training' => false,
],
'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
'group' => [
'id' => $this->virginUser->getCustomerGroupId()
],
],
], $context->getContext());
}
$this->accountService->login($email, $context);
}
} else {
$errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.ErrorPage404');
return $this->renderStorefront(
'@Storefront/storefront/page/content/index.html.twig',
['page' => $errorPage]
);
}
return $this->redirectToRoute('frontend.configurator');
}
/**
* @Route("/clan-landing", name="frontend.clan.landing", options={"seo" = "false"}, methods={"GET"})
*/
public function clanImplicitAutologinToConfigurator(Request $request, SalesChannelContext $context)
{
try {
$clanToken = $request->get('token');
if (empty($clanToken)) {
throw new RuntimeException($this->trans('lead-manager.profiling.parameterTokenEmpty'));
}
$decodedClanTokenInfo = $this->restApiClient->getDecodedLeadTokenInfo($clanToken);
if (empty($decodedClanTokenInfo)) {
throw new RuntimeException($this->trans('lead-manager.profiling.tokenEmpty'));
}
foreach ($decodedClanTokenInfo as $key => $value) {
if (empty($value)) {
throw new RuntimeException($key . " " . $this->trans('lead-manager.profiling.cantBeEmpty'));
}
}
$clanEmail = $decodedClanTokenInfo['email'];
//////// checkPerson
$this->virginUser->checkPerson($clanEmail);
$personType = $this->virginUser->getPersonType();
if ($personType === VirginUser::PERSONTYPE_LEAD || $personType === VirginUser::PERSONTYPE_LEADLAYER) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.centerId', $decodedClanTokenInfo['club_center_id']));
$clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
if (!$clubId) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.default', true));
$clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $clanEmail));
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
// no user in Shopware
if ($customerEntity === null) {
// user not registered ->
$shopwareUserBasicData = [
'firstName' => $decodedClanTokenInfo['nome'],
'lastName' => $decodedClanTokenInfo['cognome'],
'salutationId' => $this->leadService->getDefaultSalutation($context),
'email' => $clanEmail,
'password' => bin2hex(openssl_random_pseudo_bytes(4)),
];
// implicit registration
$shopwareCustomerEntity = $this->leadService->prepareRegistrationData($context, $shopwareUserBasicData);
// update custom fields
$customFields = [
'lead_implicit_registration' => true,
'phone_number' => $decodedClanTokenInfo['telefono'],
'privacy_consent' => true,
];
$this->customerRepository->update([
[
'id' => $shopwareCustomerEntity->getId(),
'customFields' => $customFields,
'extensions' => ['preferredClubId' => $clubId],
],
], $context->getContext());
} else {
// User in Shopware Update Data
if (
$customerEntity->getFirstName() === $decodedClanTokenInfo['nome']
&& $customerEntity->getLastName() === $decodedClanTokenInfo['cognome']
) {
// Firstname and Lastname match
// Update user phone and club
$updateUserInfo = [
'id' => $customerEntity->getId(),
'customFields' => ['phone_number' => $decodedClanTokenInfo['telefono']],
'extensions' => ['preferredClubId' => $clubId],
];
$this->customerRepository->update([$updateUserInfo], $context->getContext());
$this->accountService->login($clanEmail, $context);
} else {
return $this->redirectToRoute('frontend.account.login.page',
[
'loginError' => true,
'errorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
]
);
}
}
return $this->redirectToRoute('frontend.configurator');
}
throw new RuntimeException($this->trans('lead-manager.profiling.onlyLeadUsers'));
} catch (\Exception $e) {
throw $e;
}
}
/**
* @Route("/contact-landing", name="frontend.contact.landing", options={"seo" = "false"}, methods={"GET"})
*/
public function contactLanding(Request $request, SalesChannelContext $context): RedirectResponse
{
try {
$contactToken = $request->get('token');
if (empty($contactToken)) {
throw new RuntimeException($this->trans('lead-manager.contactLanding.parameterTokenEmpty'));
}
$decodedContactTokenInfo = $this->restApiClient->getDecodedLeadTokenInfo($contactToken);
if (empty($decodedContactTokenInfo)) {
throw new RuntimeException($this->trans('lead-manager.contactLanding.tokenEmpty'));
}
foreach ($decodedContactTokenInfo as $key => $value) {
if (empty($value)) {
throw new RuntimeException($key . " " . $this->trans('lead-manager.contactLanding.cantBeEmpty'));
}
}
$contactEmail = $decodedContactTokenInfo['email'];
//////// checkPerson
$this->virginUser->checkPerson($contactEmail);
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.centerId', $decodedContactTokenInfo['club_center_id']));
$clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
if (!$clubId) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('club.default', true));
$clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
}
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customer.email', $contactEmail));
/** @var CustomerEntity $customerEntity */
$customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
$decodedContactFirstname = $decodedContactTokenInfo['nome'];
$decodedContactLastname = $decodedContactTokenInfo['cognome'];
$decodedContactPhoneNumber = $decodedContactTokenInfo['telefono'];
// no user in Shopware
if ($customerEntity === null) {
// user not registered ->
$shopwareUserBasicData = [
'firstName' => $decodedContactFirstname,
'lastName' => $decodedContactLastname,
'salutationId' => $this->leadService->getDefaultSalutation($context),
'email' => $contactEmail,
'password' => bin2hex(openssl_random_pseudo_bytes(4)),
];
// implicit registration
$shopwareCustomerEntity = $this->leadService->prepareRegistrationData($context, $shopwareUserBasicData);
// update custom fields
$customFields = [
'lead_implicit_registration' => true,
'phone_number' => $decodedContactPhoneNumber,
'privacy_consent' => true,
];
$this->customerRepository->update([
[
'id' => $shopwareCustomerEntity->getId(),
'customFields' => $customFields,
'extensions' => ['preferredClubId' => $clubId],
'active' => false,
],
], $context->getContext());
} else {
// User in Shopware Update Data
if ($customerEntity->getCustomFields()['lead_implicit_registration']) {
$updateUserInfo = [
'id' => $customerEntity->getId(),
'firstName' => $decodedContactFirstname,
'lastName' => $decodedContactLastname,
'customFields' => ['phone_number' => $decodedContactPhoneNumber],
'extensions' => ['preferredClubId' => $clubId],
];
$this->customerRepository->update([$updateUserInfo], $context->getContext());
$this->accountService->login($contactEmail, $context);
} else {
return $this->redirectToRoute('frontend.account.login.page',
[
'loginError' => true,
'errorSnippet' => $this->trans('lead-manager.contactLanding.explicitUserAlreadyExistsLoginWithYourCredentials')
]
);
}
}
return $this->redirectToRoute('frontend.configurator');
} catch (\Exception $e) {
throw $e;
}
}
private function URLIsValid($url)
{
$exists = true;
$router = $this->get('router');
try {
$route = $router->match($url);
if (!$route) {
$exists = false;
}
} catch (\Exception $e) {
$exists = false;
}
return $exists;
}
private function getErrorPage(Request $request, SalesChannelContext $context, $page)
{
$salesChannelId = $context->getSalesChannel()->getId();
$cmsErrorLayoutId = $this->systemConfigService->get($page, $salesChannelId);
return $this->errorPageLoader->load((string) $cmsErrorLayoutId, $request, $context);
}
}