custom/plugins/LeadManager/src/Storefront/Controller/LeadManagerController.php line 1388

Open in your IDE?
  1. <?php
  2. namespace Virgin\LeadManager\Storefront\Controller;
  3. use Monolog\Logger;
  4. use RuntimeException;
  5. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractSendPasswordRecoveryMailRoute;
  6. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractResetPasswordRoute;
  7. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractLogoutRoute;
  8. use Shopware\Core\Checkout\Customer\CustomerEntity;
  9. use Shopware\Core\Checkout\Customer\Exception\CustomerNotFoundByHashException;
  10. use Shopware\Core\Checkout\Customer\Exception\CustomerNotFoundException;
  11. use Shopware\Core\Checkout\Customer\Exception\CustomerRecoveryHashExpiredException;
  12. use Shopware\Core\Checkout\Customer\SalesChannel\AccountService;
  13. use Shopware\Core\Content\Category\Exception\CategoryNotFoundException;
  14. use Shopware\Core\Framework\Context;
  15. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException;
  17. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  19. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  20. use Shopware\Core\Framework\Routing\Exception\MissingRequestParameterException;
  21. use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
  22. use Shopware\Core\Framework\Validation\DataValidationDefinition;
  23. use Shopware\Core\Framework\Validation\DataValidator;
  24. use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
  25. use Shopware\Core\System\SalesChannel\Context\SalesChannelContextPersister;
  26. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  27. use Shopware\Core\System\SystemConfig\SystemConfigService;
  28. use Shopware\Storefront\Controller\StorefrontController;
  29. use Shopware\Storefront\Page\Account\Login\AccountLoginPageLoader;
  30. use Shopware\Storefront\Page\Navigation\Error\ErrorPageLoader;
  31. use Symfony\Component\HttpFoundation\RedirectResponse;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpFoundation\Response;
  34. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use Symfony\Component\Validator\Constraints\Email;
  37. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  38. use Virgin\GDPRPlugin\Service\PrivacyService;
  39. use Virgin\LeadManager\Custom\Autologin\AutologinRequestDefinition;
  40. use Virgin\LeadManager\Service\AccountRegistrationServiceDecorator;
  41. use Virgin\LeadManager\Storefront\Page\Contact\ContactPageLoader;
  42. use Virgin\LeadManager\Utils\Services\LeadGenerationService;
  43. use Virgin\ProductModelExtension\Custom\Club\ClubEntity;
  44. use Virgin\ProductModelExtension\Services\ClubService;
  45. use Virgin\SubscriptionsConfigurator\Utils\Services\SubscriptionsConfiguratorService;
  46. use Virgin\SystemIntegration\Exception\VirginApiException;
  47. use Virgin\SystemIntegration\Services\RestApiClient;
  48. use Virgin\SystemIntegration\Services\VirginUser\VirginUser;
  49. use Shopware\Core\Framework\Uuid\Uuid;
  50. use DateTime;
  51. use DateTimeZone;
  52. /**
  53. * @RouteScope(scopes={"storefront"})
  54. */
  55. class LeadManagerController extends StorefrontController
  56. {
  57. const CALL = '1';
  58. const APPOINTMENT = '2';
  59. const REVOLUTION_CENTER_ID = 233;
  60. /**
  61. * @var AccountService
  62. */
  63. private $accountService;
  64. /**
  65. * @var AccountRegistrationServiceDecorator
  66. */
  67. private $accountRegistrationService;
  68. /**
  69. * @var SalesChannelContextPersister
  70. */
  71. private $contextPersister;
  72. /**
  73. * @var LeadGenerationService
  74. */
  75. private $leadService;
  76. /**
  77. * @var EntityRepositoryInterface
  78. */
  79. private $customerRepository;
  80. /**
  81. * @var DataValidator
  82. */
  83. private $validator;
  84. /**
  85. * @var Logger
  86. */
  87. private $logger;
  88. /**
  89. * @var ContactPageLoader
  90. */
  91. private $contactPageLoader;
  92. /**
  93. * @var EntityRepositoryInterface
  94. */
  95. private $contactRepository;
  96. /**
  97. * @var EntityRepositoryInterface
  98. */
  99. private $contactTypeRepository;
  100. /**
  101. * @var EntityRepositoryInterface
  102. */
  103. private $virginUserTypeRepository;
  104. /**
  105. * @var EntityRepositoryInterface
  106. */
  107. private $clubRepository;
  108. /**
  109. * @var ClubService
  110. */
  111. private $clubService;
  112. /**
  113. * @var RestApiClient
  114. */
  115. private $restApiClient;
  116. /**
  117. * @var PrivacyService
  118. */
  119. private $privacyService;
  120. /**
  121. * @var SystemConfigService
  122. */
  123. private $systemConfigService;
  124. /**
  125. * @var AccountLoginPageLoader
  126. */
  127. private $loginPageLoader;
  128. /**
  129. * @var VirginUser
  130. */
  131. private $virginUser;
  132. /**
  133. * @var EventDispatcherInterface
  134. */
  135. private $eventDispatcher;
  136. /** @var SubscriptionsConfiguratorService */
  137. private $configuratorService;
  138. /**
  139. * @var EntityRepositoryInterface
  140. */
  141. private $autologinRequestRepository;
  142. /**
  143. * @var ErrorPageLoader
  144. */
  145. private $errorPageLoader;
  146. /**
  147. * @var AbstractLogoutRoute
  148. */
  149. private $logoutRoute;
  150. /**
  151. * @var AbstractSendPasswordRecoveryMailRoute
  152. */
  153. private $sendPasswordRecoveryMailRoute;
  154. /**
  155. * @var AbstractResetPasswordRoute
  156. */
  157. private $resetPasswordRoute;
  158. /**
  159. * @var EntityRepositoryInterface
  160. */
  161. private $customerRecoveryRepository;
  162. /**
  163. * @var SessionInterface
  164. */
  165. private $session;
  166. const TYPE_CALLCENTER = 1;
  167. const TYPE_ONSITE = 2;
  168. public function __construct(
  169. AccountService $accountService,
  170. AccountRegistrationServiceDecorator $accountRegistrationService,
  171. SalesChannelContextPersister $contextPersister,
  172. LeadGenerationService $leadService,
  173. EntityRepositoryInterface $customerRepository,
  174. DataValidator $validator,
  175. Logger $logger,
  176. ContactPageLoader $contactPageLoader,
  177. EntityRepositoryInterface $contactRepository,
  178. EntityRepositoryInterface $contactTypeRepository,
  179. EntityRepositoryInterface $virginUserTypeRepository,
  180. EntityRepositoryInterface $clubRepository,
  181. ClubService $clubService,
  182. RestApiClient $restApiClient,
  183. PrivacyService $privacyService,
  184. SystemConfigService $systemConfigService,
  185. AccountLoginPageLoader $loginPageLoader,
  186. VirginUser $virginUser,
  187. EventDispatcherInterface $eventDispatcher,
  188. SubscriptionsConfiguratorService $configuratorService,
  189. EntityRepositoryInterface $autologinRequestRepository,
  190. ErrorPageLoader $errorPageLoader,
  191. AbstractLogoutRoute $logoutRoute,
  192. AbstractSendPasswordRecoveryMailRoute $sendPasswordRecoveryMailRoute,
  193. AbstractResetPasswordRoute $resetPasswordRoute,
  194. EntityRepositoryInterface $customerRecoveryRepository,
  195. SessionInterface $session
  196. )
  197. {
  198. $this->accountService = $accountService;
  199. $this->accountRegistrationService = $accountRegistrationService;
  200. $this->contextPersister = $contextPersister;
  201. $this->leadService = $leadService;
  202. $this->customerRepository = $customerRepository;
  203. $this->validator = $validator;
  204. $this->logger = $logger;
  205. $this->contactPageLoader = $contactPageLoader;
  206. $this->contactRepository = $contactRepository;
  207. $this->contactTypeRepository = $contactTypeRepository;
  208. $this->virginUserTypeRepository = $virginUserTypeRepository;
  209. $this->clubRepository = $clubRepository;
  210. $this->clubService = $clubService;
  211. $this->restApiClient = $restApiClient;
  212. $this->privacyService = $privacyService;
  213. $this->systemConfigService = $systemConfigService;
  214. $this->loginPageLoader = $loginPageLoader;
  215. $this->virginUser = $virginUser;
  216. $this->eventDispatcher = $eventDispatcher;
  217. $this->configuratorService = $configuratorService;
  218. $this->autologinRequestRepository = $autologinRequestRepository;
  219. $this->errorPageLoader = $errorPageLoader;
  220. $this->logoutRoute = $logoutRoute;
  221. $this->sendPasswordRecoveryMailRoute = $sendPasswordRecoveryMailRoute;
  222. $this->resetPasswordRoute = $resetPasswordRoute;
  223. $this->customerRecoveryRepository = $customerRecoveryRepository;
  224. $this->session = $session;
  225. }
  226. /**
  227. * @Route("/contact", name="frontend.contact", options={"seo" = "false"}, methods={"GET"})
  228. */
  229. public function showContactForm(Request $request, RequestDataBag $data, SalesChannelContext $context)
  230. {
  231. // Remove this redirect to enable contact form
  232. return $this->redirectToRoute('frontend.account.login.page');
  233. $this->logger->log(Logger::DEBUG, 'Contact form request - print data');
  234. if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  235. return $this->redirectToRoute('frontend.home.page');
  236. }
  237. $loginError = $request->query->get('loginError');
  238. if ($context->getCustomer()) {
  239. $club = $context->getCustomer()->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  240. if(isset($club)) {
  241. return $this->redirectToRoute('frontend.configurator');
  242. } else {
  243. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  244. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  245. }
  246. }
  247. $page = $this->contactPageLoader->load($request, $context);
  248. return $this->renderStorefront('@Storefront/storefront/page/contact/index.html.twig', [
  249. 'page' => $page,
  250. 'loginError' => isset($loginError) ? (bool)$loginError : false,
  251. 'loginSnippet' => $request->query->get('errorSnippet'),
  252. ]);
  253. }
  254. //DEPRECATED
  255. // /**
  256. // * @Route("/contact/create", name="frontend.contact.create", options={"seo" = "false"}, methods={"POST"})
  257. // */
  258. // public function createContact(Request $request, RequestDataBag $data, SalesChannelContext $context)
  259. // {
  260. // if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  261. // return $this->redirectToRoute('frontend.home.page');
  262. // }
  263. //
  264. // $this->logger->log(Logger::DEBUG, 'Contact form submit data: ' . serialize($data));
  265. // $page = $this->contactPageLoader->load($request, $context);
  266. //
  267. // $redirectObject = $this->virginUser->CheckFormParamsToStorefront($data, $page, '@Storefront/storefront/page/contact/index.html.twig');
  268. //
  269. // $firstname = $data->get('name');
  270. // $lastname = $data->get('lastname');
  271. // $phone = $data->get('phone');
  272. // $phonePrefix = $data->get('intlPrefix');
  273. // $email = $data->get('email');
  274. // $club = $data->get('club');
  275. // $zipcode = $data->get('zipcode');
  276. //
  277. // if ($club == 'home_training') {
  278. // $club = null;
  279. // $homeTraining = true;
  280. // } else {
  281. // $homeTraining = null;
  282. // }
  283. //
  284. // // form params
  285. // $contactFormParams = [
  286. // 'firstName' => $firstname,
  287. // 'lastName' => $lastname,
  288. // //'phone' => "+" . $phonePrefix . $phone,
  289. // 'phone' => $phone,
  290. // 'email' => $email,
  291. // 'club' => $club,
  292. // 'zipcode' => $zipcode,
  293. // 'privacy' => true,
  294. // 'page' => $page,
  295. // 'home_training' => $homeTraining,
  296. // ];
  297. //
  298. // //////// checkPerson
  299. // $this->virginUser->checkPerson($email);
  300. // // preparazione per il salvataggio della privacy
  301. // $contactFormParams['route'] = $route = $request->getPathInfo();
  302. //
  303. // $redirectObject = $this->virginUser->handlePerson($contactFormParams, $context, VirginUser::FORM_CONTACT);
  304. //
  305. // $redirectObject['params']['home_training'] = $homeTraining;
  306. //
  307. // if ($redirectObject['errorSnippet'] != '') {
  308. // $redirectObject['params']['errorSnippet'] = $this->trans($redirectObject['errorSnippet']);
  309. // }
  310. // $redirectObject['params']['club'] = $club;
  311. // if ($redirectObject['renderStorefront']) {
  312. // return $this->renderStorefront($redirectObject['route'], $redirectObject['params']);
  313. // } else {
  314. // return $this->redirectToRoute($redirectObject['route'], $redirectObject['params']);
  315. // }
  316. // }
  317. /**
  318. * @Route("/contact/methods", name="frontend.contact.methods", options={"seo" = "false"}, methods={"GET"})
  319. */
  320. public function showContactMethodsPage(Request $request, RequestDataBag $data, SalesChannelContext $context)
  321. {
  322. $this->logger->log(Logger::DEBUG, 'Contact methods form request' . serialize($data));
  323. $userLogged = ($context->getCustomer()) ? true : false;
  324. $page = $this->contactPageLoader->load($request, $context);
  325. if (isset($_COOKIE['ecommerce-va'])) {
  326. $decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
  327. }
  328. if ($context->getCustomer()) {
  329. $email = $context->getCustomer()->getEmail();
  330. } elseif (isset($decodedCookie)) {
  331. $email = $decodedCookie->email;
  332. } else {
  333. return $this->redirectToRoute('frontend.contact');
  334. }
  335. $contactId = $this->contactRepository->searchIds(
  336. (new Criteria())->addFilter(new EqualsFilter('email', $email)),
  337. Context::createDefaultContext()
  338. )->firstId();
  339. if ($contactId) {
  340. return $this->redirectToRoute('frontend.home.page');
  341. }
  342. $home_training = false;
  343. if ($context->getCustomer() != null
  344. && array_key_exists('home_training', $context->getCustomer()->getCustomFields())
  345. && !empty($context->getCustomer()->getCustomFields()['home_training'])
  346. ) {
  347. $home_training = true;
  348. }
  349. return $this->renderStorefront('@Storefront/storefront/page/contact/methods.html.twig',
  350. [
  351. 'userLogged' => $userLogged,
  352. 'page' => $page,
  353. 'email' => $email,
  354. 'preselectedClub' => $request->get('club'),
  355. 'home_training'=> $home_training
  356. ]
  357. );
  358. }
  359. /**
  360. * @Route("/appointment-new", name="frontend.appointment.new", options={"seo" = "false"}, methods={"POST"})
  361. * @throws \Exception
  362. */
  363. public function createAppointmentNew(Request $request, RequestDataBag $data, SalesChannelContext $salesChannelContext)
  364. {
  365. if (!$salesChannelContext->getCustomer()){
  366. return;
  367. }
  368. if ($data->get("appointmentType") == self::TYPE_ONSITE){
  369. $dateTimeObj = new DateTime($data->get("date")." ".$data->get("hour"));
  370. } else {
  371. $dateTimeObj = new DateTime("now");
  372. }
  373. /** @var ClubEntity $club */
  374. $club = $this->clubService->getClubById($data->get("clubId"), $salesChannelContext);
  375. $formParams = [
  376. 'guid_lead' => $salesChannelContext->getCustomer()->getCustomFields()['virgin_guid'],
  377. 'guid_club' => $club->getGuidVirgin(),
  378. 'app_type' => $data->get("appointmentType"),
  379. 'app_date' => $dateTimeObj->format(DateTime::ATOM),
  380. 'note' => "Inserito da ecommerce",
  381. ];
  382. $resp = $this->restApiClient->insertAppointment($formParams);
  383. return new Response($resp['message'], $resp['code']);
  384. }
  385. /**
  386. * @Route("/contact/appointment", name="frontend.contact.appointment", options={"seo" = "false"}, methods={"POST"})
  387. */
  388. public function saveAppointment(Request $request, RequestDataBag $data, SalesChannelContext $context)
  389. {
  390. $this->logger->log(Logger::DEBUG, 'Appointment form request' . serialize($data));
  391. $date = $data->get('data-appointment');
  392. $time = $data->get('time-appointment');
  393. $email = $data->get('email');
  394. $club = $data->get('club');
  395. $page = $this->contactPageLoader->load($request, $context);
  396. if (empty($date) || empty($time) || empty($email) || empty($club)) {
  397. return $this->redirectToRoute('frontend.contact.methods', [
  398. 'error' => true,
  399. 'errorSnippet' => $this->trans('lead-manager.form.message.errorMessage'),
  400. 'page' => $page,
  401. ]);
  402. }
  403. $criteria = new Criteria();
  404. $criteria->addFilter(new EqualsFilter('customer.email', $email ));
  405. $criteria->addAssociation('salutation');
  406. /** @var CustomerEntity $customerEntity */
  407. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  408. /// Create Appountment
  409. $contactTypeId = $this->contactTypeRepository->searchIds(
  410. (new Criteria())->addFilter(new EqualsFilter('identifier', self::APPOINTMENT)),
  411. Context::createDefaultContext()
  412. )->firstId();
  413. //echo 'Appuntamente in ShopWare';
  414. $appId = Uuid::randomHex();
  415. $App = $this->contactRepository->create(
  416. [
  417. [
  418. 'id' => $appId,
  419. 'firstname' => $customerEntity->getFirstName(),
  420. 'lastname' => $customerEntity->getLastName(),
  421. 'phone' => $customerEntity->getCustomFields()['phone_number'],
  422. 'email' => $email,
  423. 'time' => $time,
  424. 'date' => $date,
  425. 'contactTypeId' => $contactTypeId,
  426. 'preferredClubId' => $club,
  427. 'customerId' => $customerEntity->getId()
  428. ],
  429. ],
  430. $context->getContext()
  431. );
  432. $contactEntity = $this->contactRepository->search(
  433. (new Criteria())->addFilter(new EqualsFilter('id', $appId)),
  434. Context::createDefaultContext()
  435. )->first();
  436. // dispatch email event
  437. //$emailEvent = new AppointmentConfirmationEvent($context, $customerEntity, $contactEntity, $clubEntity);
  438. //$this->eventDispatcher->dispatch($emailEvent);
  439. $clubCriteria = new Criteria();
  440. $clubCriteria->addFilter(new EqualsFilter('id', $club));
  441. $clubEntity = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
  442. if(isset($clubEntity)){
  443. $clubGuidId = $clubEntity->getGuidVirgin();
  444. } else {
  445. $clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
  446. $clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
  447. }
  448. $formParams = [
  449. 'guid_lead' => $customerEntity->getId(),
  450. 'guid_club' => $clubGuidId,
  451. 'app_type' => VirginUser::APP_INFO,
  452. 'app_date' => $date . 'T' . $time . 'Z',
  453. 'note' => 'Inserito da ecommerce'
  454. ];
  455. $this->restApiClient->insertAppointment($formParams);
  456. return $this->renderStorefront('@Storefront/storefront/page/contact/methods.html.twig', [
  457. 'successAppointmentPopup' => true,
  458. 'successSnippet' => $this->trans('lead-manager.form.message.successRegistration'),
  459. 'home_training' => $customerEntity->getCustomFields()['home_training']
  460. ]);
  461. }
  462. /**
  463. * @Route("/contact/call", name="frontend.contact.call", options={"seo" = "false"}, methods={"POST"})
  464. */
  465. public function saveCall(Request $request, RequestDataBag $data, SalesChannelContext $context)
  466. {
  467. $this->logger->log(Logger::DEBUG, 'Call form request' . serialize($data));
  468. $date = $data->get('date-call');
  469. $time = $data->get('time-call');
  470. $page = $this->contactPageLoader->load($request, $context);
  471. if (empty($date) || empty($time)) {
  472. return $this->redirectToRoute('frontend.contact.methods', [
  473. 'error' => true,
  474. 'errorSnippet' => $this->trans('lead-manager.form.message.errorMessage'),
  475. ]);
  476. }
  477. if (isset($_COOKIE['ecommerce-va'])) {
  478. $decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
  479. $criteria = new Criteria();
  480. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email));
  481. $criteria->addAssociation('salutation');
  482. /** @var CustomerEntity $customerEntity */
  483. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  484. if (isset($customerEntity)) {
  485. $contactTypeId = $this->contactTypeRepository->searchIds(
  486. (new Criteria())->addFilter(new EqualsFilter('identifier', self::CALL)),
  487. Context::createDefaultContext()
  488. )->firstId();
  489. $this->contactRepository->create(
  490. [
  491. [
  492. 'firstname' => $decodedCookie->name,
  493. 'lastname' => $decodedCookie->lastname,
  494. 'phone' => $decodedCookie->phone,
  495. 'email' => $decodedCookie->email,
  496. 'time' => $time,
  497. 'date' => $date,
  498. 'contactTypeId' => $contactTypeId,
  499. 'customerId' => $customerEntity->getId()
  500. ],
  501. ],
  502. $context->getContext()
  503. );
  504. if(isset($customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'])){
  505. $clubCriteria = new Criteria();
  506. $clubCriteria->addFilter(new EqualsFilter('id', $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId']));
  507. $clubEntity = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
  508. }else{
  509. $clubEntity = $this->configuratorService->getClubByZipcode( $customerEntity->getCustomFields()['zipcode']);
  510. if(!isset($clubEntity)){
  511. $clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
  512. $clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
  513. }
  514. }
  515. $formParams = [
  516. 'guid_lead' => $customerEntity->getId(),
  517. 'firstName' => $decodedCookie->name,
  518. 'lastName' => $decodedCookie->lastname,
  519. 'phone' => $decodedCookie->phone,
  520. 'email' => $decodedCookie->email,
  521. 'page' => $page,
  522. 'privacy' => $customerEntity->getCustomFields()['privacy_consent'],
  523. 'clubGuidId' => isset($clubEntity) ? $clubEntity->getGuidVirgin() : $clubGuidId,
  524. 'clubName' => isset($clubEntity) ? $clubEntity->getName() : $clubName ,
  525. 'giorno_predefinito' => $date,
  526. 'orario_predefinito' => $time,
  527. 'channel' => VirginUser:: FORM_CONTACT,
  528. 'cap' => $customerEntity->getCustomFields()['zipcode'],
  529. 'isExplicitRegistration' => !$customerEntity->getCustomFields()['lead_implicit_registration'],
  530. ];
  531. $privacyText = $this->privacyService->getPrivacyConsent($context->getContext(), VirginUser:: FORM_CONTACT);
  532. if(isset($privacyText)){
  533. $formParams['privacyJson']= $privacyText;
  534. }
  535. $this->virginUser->insertLeadToLayerQuick($formParams, $customerEntity, $context);
  536. }
  537. } else {
  538. return $this->redirectToRoute('frontend.contact.methods', [
  539. 'error' => true,
  540. 'errorSnippet' => $this->trans('lead-manager.form.message.errorCookie'),
  541. ]);
  542. }
  543. return $this->renderStorefront('@Storefront/storefront/page/contact/methods.html.twig', [
  544. 'successCallPopup' => true,
  545. 'email' => $decodedCookie->email,
  546. 'page' => $this->contactPageLoader->load($request, $context),
  547. 'successSnippet' => $this->trans('lead-manager.form.message.successBook'),
  548. 'home_training'=> $context->getCustomer()->getCustomFields()['home_training']
  549. ]);
  550. }
  551. /**
  552. * @Route("/contact/registration", name="frontend.register.contact", options={"seo" = "false"}, methods={"GET"})
  553. */
  554. public function contactRegisterForm(Request $request, RequestDataBag $data, SalesChannelContext $context)
  555. {
  556. if(array_key_exists('lead_implicit_registration', $context->getCustomer()->getCustomFields()) && $context->getCustomer()->getCustomFields()['lead_implicit_registration'] === false) {
  557. $club = $context->getCustomer()->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  558. if(isset($club)) {
  559. return $this->redirectToRoute('frontend.configurator');
  560. } else {
  561. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  562. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  563. }
  564. }
  565. $page = $this->contactPageLoader->load($request, $context);
  566. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  567. 'page' => $page,
  568. 'email' => $context->getCustomer()->getEmail(),
  569. 'loginError' => isset($loginError) ? (bool)$loginError : false,
  570. 'loginSnippet' => $request->query->get('errorSnippet'),
  571. ]);
  572. }
  573. /**
  574. * @Route("/purchase", name="frontend.purchase", options={"seo" = "false"}, methods={"GET"})
  575. */
  576. public function purchaseForm(Request $request, RequestDataBag $data, SalesChannelContext $context)
  577. {
  578. $this->logger->log(Logger::DEBUG, 'purchase form request - print data');
  579. $page = $this->contactPageLoader->load($request, $context);
  580. if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  581. return $this->redirectToRoute('frontend.home.page');
  582. }
  583. if ($context->getCustomer()) {
  584. $club = $context->getCustomer()->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  585. if(isset($club)) {
  586. return $this->redirectToRoute('frontend.configurator');
  587. } else {
  588. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  589. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  590. }
  591. }
  592. return $this->redirectToRoute('frontend.account.login.page');
  593. }
  594. //DEPRECATED
  595. // /**
  596. // * @Route("/purchase/create", name="frontend.purchase.create", options={"seo" = "false"}, methods={"POST"})
  597. // */
  598. // public function purchaseCreateUser(Request $request, RequestDataBag $data, SalesChannelContext $context)
  599. // {
  600. // return $this->redirectToRoute('frontend.account.login.page');
  601. //
  602. // if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  603. // return $this->redirectToRoute('frontend.home.page');
  604. // }
  605. //
  606. // $this->logger->log(Logger::DEBUG, 'Purchase form request - send data');
  607. // $page = $this->contactPageLoader->load($request, $context);
  608. //
  609. // // spostata tutta la validazione in una funzione
  610. // $redirectObject = $this->virginUser->CheckFormParamsToStorefront($data, $page, '@Storefront/storefront/page/purchase/index.html.twig');
  611. //
  612. // if ($redirectObject != null) {
  613. // return $this->renderStorefront($redirectObject['route'],
  614. // [
  615. // 'loginError' => $redirectObject['loginError'],
  616. // 'errorSnippet' => $this->trans($redirectObject['errorSnippet']),
  617. // 'page' => $page,
  618. // ]);
  619. // }
  620. //
  621. // $firstname = $data->get('name');
  622. // $lastname = $data->get('lastname');
  623. // $phone = $data->get('phone');
  624. // $phonePrefix = $data->get('intlPrefix');
  625. // $email = $data->get('email');
  626. // $privacy = $data->get('privacy');
  627. // $club = $data->get('club');
  628. // $zipcode = $data->get('zipcode');
  629. //
  630. // if ($club == 'home_training') {
  631. // $club = null;
  632. // $homeTraining = true;
  633. // } else {
  634. // $homeTraining = null;
  635. // }
  636. //
  637. // $this->virginUser->checkPerson($email);
  638. //
  639. // // preparazione per il salvataggio della privacy
  640. // $contactFormParams['route'] = $request->getPathInfo();
  641. // $contactFormParams['email'] = $email;
  642. // $contactFormParams['firstName'] = $firstname;
  643. // $contactFormParams['lastName'] = $lastname;
  644. // //$contactFormParams['phone'] = "+" . $phonePrefix . $phone;
  645. // $contactFormParams['phone'] = $phone;
  646. // $contactFormParams['privacy'] = $privacy;
  647. // $contactFormParams['club'] = $club;
  648. // $contactFormParams['page'] = $page;
  649. // $contactFormParams['home_training'] = $homeTraining;
  650. // $contactFormParams['zipcode'] = $zipcode;
  651. //
  652. // $redirectObject = $this->virginUser->handlePerson($contactFormParams, $context, VirginUser::FORM_PURCHASE);
  653. //
  654. // $redirectObject['params']['home_training'] = $homeTraining;
  655. //
  656. // if ($redirectObject['errorSnippet'] != '') {
  657. // $redirectObject['params']['errorSnippet'] = $this->trans($redirectObject['errorSnippet']);
  658. // }
  659. //
  660. // if ($redirectObject['renderStorefront'] == true) {
  661. // return $this->renderStorefront($redirectObject['route'], $redirectObject['params']);
  662. // } else {
  663. // return $this->redirectToRoute($redirectObject['route'], $redirectObject['params']);
  664. // }
  665. // }
  666. /**
  667. * @Route("/purchase/register", name="frontend.purchase.register", options={"seo" = "false"}, methods={"POST"})
  668. */
  669. public function registerCustomer(Request $request, RequestDataBag $data, SalesChannelContext $context)
  670. {
  671. return $this->redirectToRoute('frontend.account.login.page');
  672. $this->logger->log(Logger::DEBUG, 'Register methods form request' . serialize($data));
  673. $page = $this->contactPageLoader->load($request, $context);
  674. $email = $data->get('email');
  675. $password = $data->get('password');
  676. $privacy = $data->get('privacy');
  677. $route = $request->getPathInfo();
  678. $decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
  679. if (empty($email) || empty($password)) {
  680. return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
  681. 'loginError' => true,
  682. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  683. ]);
  684. }
  685. $validation = new DataValidationDefinition('customer.email');
  686. $validation->add('email', new Email());
  687. try {
  688. $this->validator->validate(['email' => $email], $validation);
  689. } catch (ConstraintViolationException $e) {
  690. $this->logger->log(Logger::ERROR, $e->getMessage());
  691. return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
  692. 'loginError' => true,
  693. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  694. ]);
  695. }
  696. $criteria = new Criteria();
  697. $this->virginUser->checkPerson($email);
  698. if ($decodedCookie->email !== $email) {
  699. $criteria->addFilter(new EqualsFilter('customer.email', $email));
  700. $criteria->addAssociation('salutation');
  701. /** @var CustomerEntity $customerEntity */
  702. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  703. if($this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEADLAYER ||
  704. $this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEAD ) {
  705. // passo solo se sono lead o solo sul lead layer
  706. if(!isset($customerEntity)){
  707. $criteria = new Criteria();
  708. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email));
  709. $criteria->addAssociation('salutation');
  710. /** @var CustomerEntity $customerEntity */
  711. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  712. }elseif (!$customerEntity->getCustomFields()['lead_implicit_registration']){
  713. return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
  714. 'loginError' => true,
  715. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  716. ]);
  717. }
  718. }
  719. else{
  720. $this->logoutRoute->logout($context);
  721. return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
  722. 'loginError' => true,
  723. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  724. ]);
  725. }
  726. } else {
  727. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
  728. $criteria->addAssociation('salutation');
  729. /** @var CustomerEntity $customerEntity */
  730. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  731. }
  732. if (isset($customerEntity)) {
  733. // email is just on shopware system at this point must check if is the same person or not
  734. if($this->virginUser->getIsInLeadLayer()){
  735. $leadLayerUser = $this->virginUser->getLeadLayerUser();
  736. $criteria = new Criteria();
  737. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
  738. $criteria->addAssociation('salutation');
  739. $customerEntityCookie = $this->customerRepository->search($criteria, $context->getContext())->first();
  740. // search on the lead Layer the same email, and check if name and surname are the same
  741. if(!($leadLayerUser->getNome() == $customerEntityCookie->getFirstName() && $leadLayerUser->getCognome() == $customerEntityCookie->getLastName())){
  742. // Name and Surname are the same on Lead Layer system, -> error for User Just Registered
  743. $this->logoutRoute->logout($context);
  744. if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  745. unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
  746. setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
  747. }
  748. return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
  749. 'loginError' => true,
  750. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  751. ]);
  752. }
  753. }
  754. // User in Lead Layer or on the same Name and Surname
  755. if ($customerEntity->getCustomFields()['lead_implicit_registration']) {
  756. /** @var EntityRepositoryInterface $productRepository */
  757. $customerRepository = $this->container->get('customer.repository');
  758. $partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
  759. $customFields = [
  760. 'lead_implicit_registration' => false,
  761. 'privacy_consent' => (isset($privacy)) ? (bool)$privacy : null,
  762. ];
  763. if (!empty($partnerUser)) {
  764. $customFields = array_merge($customFields, $partnerUser);
  765. }
  766. $customerRepository->update(
  767. [
  768. [
  769. 'id' => $customerEntity->getId(),
  770. 'email' => $email,
  771. 'password' => $password,
  772. 'customFields' => $customFields,
  773. ],
  774. ],
  775. \Shopware\Core\Framework\Context::createDefaultContext()
  776. );
  777. $this->logoutRoute->logout($context);
  778. if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  779. unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
  780. setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
  781. }
  782. $this->accountService->login($email, $context);
  783. $customerEntity->setEmail($email);
  784. $this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
  785. if(isset($customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'])){
  786. $clubCriteria = new Criteria();
  787. $clubCriteria->addFilter(new EqualsFilter('id', $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId']));
  788. $club = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
  789. }else{
  790. $club = $this->configuratorService->getClubByZipcode( $customerEntity->getCustomFields()['zipcode']);
  791. if(!isset($club)){
  792. $clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
  793. $clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
  794. }
  795. }
  796. $leadToUpdate = [
  797. 'firstName' => $customerEntity->getFirstName(),
  798. 'lastName' => $customerEntity->getLastName(),
  799. 'clubGuidId' => isset($club) ? $club->getGuidVirgin(): $clubGuidId,
  800. 'clubName' => isset($club) ? $club->getName(): $clubName,
  801. 'phone' => $customerEntity->getCustomFields()['phone_number'],
  802. 'email' => $email,
  803. 'channel' => VirginUser::FORM_REGISTER,
  804. 'privacy' => (isset($privacy)) ? (bool)$privacy : null,
  805. 'cap' => $customerEntity->getCustomFields()['zipcode'],
  806. 'isExplicitRegistration' => !$customerEntity->getCustomFields()['lead_implicit_registration'],
  807. ];
  808. $privacyText = $this->privacyService->getPrivacyConsent($context->getContext(), VirginUser:: FORM_REGISTER);
  809. if(isset($privacyText)){
  810. $leadToUpdate['privacyJson']= $privacyText;
  811. }
  812. if($this->virginUser->getIsInLeadLayer()){
  813. $leadToUpdate['guid_lead'] = $customerEntity->getCustomFields()['virgin_guid'];
  814. $this->restApiClient->UpdateLead($leadToUpdate);
  815. }else{
  816. $leadToUpdate['guid_lead'] = $customerEntity->getId();
  817. $this->restApiClient->InsertLead($leadToUpdate);
  818. }
  819. $club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  820. if(isset($club)) {
  821. return $this->redirectToRoute('frontend.configurator');
  822. } else {
  823. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  824. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  825. }
  826. }
  827. $club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  828. if(isset($club)) {
  829. return $this->redirectToRoute('frontend.configurator');
  830. } else {
  831. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  832. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  833. }
  834. } else {
  835. // Error they never been reatched
  836. $this->logoutRoute->logout($context);
  837. if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  838. unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
  839. setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
  840. }
  841. return $this->renderStorefront('@Storefront/storefront/page/purchase/register.html.twig', [
  842. 'loginError' => true,
  843. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  844. ]);
  845. }
  846. return $this->redirectToRoute('frontend.configurator');
  847. }
  848. /**
  849. * @Route("/walkin", name="frontend.walkin", options={"seo" = "false"}, methods={"GET"})
  850. */
  851. public function handleLeadLoadingPage(Request $request, RequestDataBag $data, SalesChannelContext $context)
  852. {
  853. $page = $this->loginPageLoader->load($request, $context);
  854. return $this->renderStorefront('@Storefront/storefront/page/loading/walkin_loading.html.twig', [
  855. 'page' => $page,
  856. ]);
  857. }
  858. /**
  859. * @Route("/walkinTA", name="frontend.walkinta", options={"seo" = "false"}, methods={"GET"})
  860. */
  861. public function handleLead(Request $request, RequestDataBag $data, SalesChannelContext $context)
  862. {
  863. $this->logger->log(Logger::DEBUG, 'Walkin request: ' . serialize($data));
  864. $leadInfo = $request->get('l');
  865. $decodedLeadInfo = json_decode(base64_decode($leadInfo));
  866. if(isset($decodedLeadInfo->mc_ExerpCode)){
  867. $_SESSION['mc_code'] = $decodedLeadInfo->mc_ExerpCode;
  868. }
  869. $leadCrm_Guid = str_replace ("}", "", str_replace ("{", "", $decodedLeadInfo->leadCrm_Guid));
  870. $club_Guid = str_replace ("}", "", str_replace ("{", "", $decodedLeadInfo->club_Guid));
  871. $this->logger->log(Logger::DEBUG, 'Walkin decoded request: ' . serialize($data));
  872. $criteria = new Criteria();
  873. $criteria->addFilter(new EqualsFilter('customer.email', $decodedLeadInfo->email));
  874. /** @var CustomerEntity $customerEntity */
  875. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  876. $user = [
  877. 'firstName' => $decodedLeadInfo->nome,
  878. 'lastName' => $decodedLeadInfo->cognome,
  879. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  880. 'email' => $decodedLeadInfo->email,
  881. 'password' => '12345678',
  882. "storefrontUrl" => $context->getSalesChannel()->getDomains()->first()->getUrl(),
  883. ];
  884. $this->virginUser->checkPerson($decodedLeadInfo->email);
  885. $partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
  886. $isEmptyPartnerUser = empty($partnerUser);
  887. if (isset($customerEntity)) {
  888. $this->accountService->login($decodedLeadInfo->email, $context);
  889. $customFields = [
  890. 'lead_implicit_registration' => false,
  891. 'mc_code_customer' => $decodedLeadInfo->mc_ExerpCode,
  892. 'id_richiesta' => $leadCrm_Guid,
  893. 'data_richiesta_mc' => (new DateTime('now', new DateTimeZone("Europe/Rome")))->format('Ymd')
  894. ];
  895. if (!$isEmptyPartnerUser) {
  896. $customFields = array_merge($customFields, $partnerUser);
  897. }
  898. $this->customerRepository->update([
  899. [
  900. 'id' => $customerEntity->getId(),
  901. 'customFields' => $customFields,
  902. 'group' => [
  903. 'id' => $this->virginUser->getCustomerGroupId()
  904. ],
  905. ],
  906. ], $context->getContext());
  907. } else {
  908. $customerEntity = $this->leadService->prepareRegistrationData($context, $user);
  909. $criteria = new Criteria();
  910. $criteria->addFilter(new EqualsFilter('club.guidVirgin', $club_Guid));
  911. $club = $this->clubRepository->search($criteria, $context->getContext())->first();
  912. $customFields = [
  913. 'lead_implicit_registration' => false,
  914. 'phone_number' => $decodedLeadInfo->telefono,
  915. 'privacy_consent' => null,
  916. 'mc_code_customer' => $decodedLeadInfo->mc_ExerpCode,
  917. 'id_richiesta' => $leadCrm_Guid,
  918. 'data_richiesta_mc' => (new DateTime('now', new DateTimeZone("Europe/Rome")))->format('Ymd')
  919. ];
  920. if (!$isEmptyPartnerUser) {
  921. $customFields = array_merge($customFields, $partnerUser);
  922. }
  923. $this->customerRepository->update([
  924. [
  925. 'id' => $customerEntity->getId(),
  926. 'customFields' => $customFields,
  927. 'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
  928. 'group' => [
  929. 'id' => $this->virginUser->getCustomerGroupId()
  930. ],
  931. ],
  932. ], $context->getContext());
  933. $this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
  934. //$userData = new RequestDataBag($user);
  935. //$this->sendPasswordRecoveryMailRoute->sendRecoveryMail($userData->toRequestDataBag(), $context);
  936. }
  937. $userData = new RequestDataBag($user);
  938. // $validateStorefrontUrl is bugged up to v6.5.1 - it isn't taken into account - always true - added storefrontUrl in $user to fix it
  939. $this->sendPasswordRecoveryMailRoute->sendRecoveryMail($userData->toRequestDataBag(), $context, false);
  940. if(isset($decodedLeadInfo->redirectTo)) {
  941. switch ($decodedLeadInfo->redirectTo) {
  942. // In current situation the only case and the default case are returning the same value
  943. // so those cases must be handled properly, otherwise switch is not needed
  944. case '/configurator':
  945. return $this->redirectToRoute('frontend.configurator');
  946. default:
  947. return $this->redirectToRoute('frontend.configurator');
  948. }
  949. }else{
  950. return $this->redirectToRoute('frontend.configurator');
  951. }
  952. }
  953. /**
  954. * @Route("/contact-chatbot", name="frontend.contact.chatbot", defaults={"csrf_protected"=false}, options={"seo" = "false"}, methods={"GET"})
  955. */
  956. public function contactChatbot(Request $request, RequestDataBag $data, SalesChannelContext $context)
  957. {
  958. $leadInfo = $request->get('token');
  959. $decodedLeadInfo = json_decode(base64_decode($leadInfo));
  960. $criteria = new Criteria();
  961. $criteria->addFilter(new EqualsFilter('customer.email', $decodedLeadInfo->email));
  962. /** @var CustomerEntity $customerEntity */
  963. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  964. $criteria = new Criteria();
  965. $criteria->addFilter(new EqualsFilter('club.centerId', $decodedLeadInfo->club));
  966. $club = $this->clubRepository->search($criteria, $context->getContext())->first();
  967. $user = [
  968. 'firstName' => $decodedLeadInfo->nome,
  969. 'lastName' => $decodedLeadInfo->cognome,
  970. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  971. 'email' => $decodedLeadInfo->email,
  972. 'password' => '12345678',
  973. "storefrontUrl" => $context->getSalesChannel()->getDomains()->first()->getUrl(),
  974. ];
  975. $this->virginUser->checkPerson($decodedLeadInfo->email);
  976. $partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
  977. $isEmptyPartnerUser = empty($partnerUser);
  978. if (isset($customerEntity)) {
  979. $this->accountService->login($decodedLeadInfo->email, $context);
  980. $customFields = [
  981. 'lead_implicit_registration' => false,
  982. ];
  983. if (!$isEmptyPartnerUser) {
  984. $customFields = array_merge($customFields, $partnerUser);
  985. }
  986. $this->customerRepository->update([
  987. [
  988. 'id' => $customerEntity->getId(),
  989. 'customFields' => $customFields,
  990. 'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
  991. 'group' => [
  992. 'id' => $this->virginUser->getCustomerGroupId()
  993. ],
  994. ],
  995. ], $context->getContext());
  996. } else {
  997. $customerEntity = $this->leadService->prepareRegistrationData($context, $user);
  998. $customFields = [
  999. 'lead_implicit_registration' => false,
  1000. 'phone_number' => $decodedLeadInfo->telefono,
  1001. 'privacy_consent' => null,
  1002. ];
  1003. if (!$isEmptyPartnerUser) {
  1004. $customFields = array_merge($customFields, $partnerUser);
  1005. }
  1006. $this->customerRepository->update([
  1007. [
  1008. 'id' => $customerEntity->getId(),
  1009. 'customFields' => $customFields,
  1010. 'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
  1011. 'group' => [
  1012. 'id' => $this->virginUser->getCustomerGroupId()
  1013. ],
  1014. ],
  1015. ], $context->getContext());
  1016. $this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
  1017. }
  1018. $userData = new RequestDataBag($user);
  1019. // $validateStorefrontUrl is bugged up to v6.5.1 - it isn't taken into account - always true - added storefrontUrl in $user to fix it
  1020. $this->sendPasswordRecoveryMailRoute->sendRecoveryMail($userData->toRequestDataBag(), $context, false);
  1021. $navigationId = $this->leadService->getNavigationIdByTag("promo_chatbot", $context);
  1022. $this->session->set('clubId', isset($club) ? $club->getId() : null);
  1023. if($navigationId) {
  1024. return $this->redirectToRoute(
  1025. "frontend.navigation.page",
  1026. [
  1027. "navigationId" => $navigationId,
  1028. ]
  1029. );
  1030. }
  1031. else {
  1032. return $this->redirectToRoute('frontend.configurator');
  1033. }
  1034. }
  1035. /**
  1036. * @Route("/contact/register", name="frontend.contact.register", methods={"POST"})
  1037. */
  1038. public function register(Request $request, RequestDataBag $data, SalesChannelContext $context)
  1039. {
  1040. $this->logger->log(Logger::DEBUG, 'Register methods form request' . serialize($data));
  1041. $page = $this->contactPageLoader->load($request, $context);
  1042. $email = $data->get('username');
  1043. $password = $data->get('password');
  1044. $decodedCookie = json_decode(base64_decode($_COOKIE['ecommerce-va']));
  1045. $leadLayerUser=null;
  1046. if (empty($email) || empty($password)) {
  1047. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  1048. 'error' => true,
  1049. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  1050. ]);
  1051. }
  1052. $validation = new DataValidationDefinition('customer.email');
  1053. $validation->add('email', new Email());
  1054. try {
  1055. $this->validator->validate(['email' => $email], $validation);
  1056. } catch (ConstraintViolationException $e) {
  1057. $this->logger->log(Logger::ERROR, $e->getMessage());
  1058. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  1059. 'error' => true,
  1060. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
  1061. 'page' => $this->contactPageLoader->load($request, $context),
  1062. ]);
  1063. }
  1064. $criteria = new Criteria();
  1065. // CheckPerson on Sysytem if
  1066. $this->virginUser->checkPerson($email);
  1067. if ($decodedCookie->email !== $email) {
  1068. $criteria->addFilter(new EqualsFilter('customer.email', $email));
  1069. $criteria->addAssociation('salutation');
  1070. /** @var CustomerEntity $customerEntity */
  1071. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1072. if($this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEADLAYER ||
  1073. $this->virginUser->getPersonType() == $this->virginUser::PERSONTYPE_LEAD ) {
  1074. // passo solo se sono lead o solo sul lead layer
  1075. if(!isset($customerEntity)){
  1076. $criteria = new Criteria();
  1077. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email));
  1078. $criteria->addAssociation('salutation');
  1079. /** @var CustomerEntity $customerEntity */
  1080. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1081. }elseif (!$customerEntity->getCustomFields()['lead_implicit_registration']){
  1082. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  1083. 'error' => true,
  1084. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
  1085. 'page' => $this->contactPageLoader->load($request, $context),
  1086. ]);
  1087. }
  1088. }
  1089. else{
  1090. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  1091. 'error' => true,
  1092. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
  1093. 'page' => $this->contactPageLoader->load($request, $context),
  1094. ]);
  1095. }
  1096. } else {
  1097. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
  1098. $criteria->addAssociation('salutation');
  1099. /** @var CustomerEntity $customerEntity */
  1100. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1101. }
  1102. if (isset($customerEntity)) {
  1103. // email is just on shopware system at this point must check if is the same person or not
  1104. if($this->virginUser->getIsInLeadLayer()){
  1105. $criteria = new Criteria();
  1106. $criteria->addFilter(new EqualsFilter('customer.email', $decodedCookie->email ));
  1107. $criteria->addAssociation('salutation');
  1108. $customerEntityCookie = $this->customerRepository->search($criteria, $context->getContext())->first();
  1109. $leadLayerUser = $this->virginUser->getLeadLayerUser();
  1110. // search on the lead Layer the same email, and check if name and surname are the same
  1111. if(!($leadLayerUser->getNome() == $customerEntityCookie->getFirstName() && $leadLayerUser->getCognome() == $customerEntityCookie->getLastName())){
  1112. // Name and Surname are the same on Lead Layer system, -> error for User Just Registered
  1113. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  1114. 'error' => true,
  1115. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
  1116. 'page' => $this->contactPageLoader->load($request, $context),
  1117. ]);
  1118. }
  1119. }
  1120. $isImplicitRegistration = $customerEntity->getCustomFields()['lead_implicit_registration'];
  1121. // User in Lead Layer or on the same Name and Surname
  1122. if ($isImplicitRegistration) {
  1123. /** @var EntityRepositoryInterface $productRepository */
  1124. $customerRepository = $this->container->get('customer.repository');
  1125. $partnerUser = $this->virginUser->getPartnerUser() ? $this->virginUser->getPartnerUser()->getObjectVars() : null;
  1126. $customFields = ['lead_implicit_registration' => false];
  1127. if (!empty($partnerUser)) {
  1128. $customFields = array_merge($customFields, $partnerUser);
  1129. }
  1130. $customerRepository->update(
  1131. [
  1132. [
  1133. 'id' => $customerEntity->getId(),
  1134. 'email' => $email,
  1135. 'password' => $password,
  1136. 'customFields' => $customFields,
  1137. ],
  1138. ],
  1139. \Shopware\Core\Framework\Context::createDefaultContext()
  1140. );
  1141. $this->logoutRoute->logout($context);
  1142. if (isset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME])) {
  1143. unset($_COOKIE[LeadGenerationService::ECOMMERCE_COOKIE_NAME]);
  1144. setcookie(LeadGenerationService::ECOMMERCE_COOKIE_NAME, '', time() - 3600, '/'); // empty value and old timestamp
  1145. }
  1146. $this->accountService->login($email, $context);
  1147. $customerEntity->setEmail($email);
  1148. $this->accountRegistrationService->sendCustomerRegistrationConfirmEmail($customerEntity, $context);
  1149. if(isset($customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'])){
  1150. $clubCriteria = new Criteria();
  1151. $clubCriteria->addFilter(new EqualsFilter('id', $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId']));
  1152. $club = $this->clubRepository->search($clubCriteria, $context->getContext())->first();
  1153. }else{
  1154. /* @var ClubEntity $club */
  1155. $club = $this->configuratorService->getClubByZipcode( $customerEntity->getCustomFields()['zipcode']);
  1156. if(!isset($club)){
  1157. $clubGuidId = $this->systemConfigService->get('LeadManager.config.digitalClubGuidId');
  1158. $clubName = $this->systemConfigService->get('LeadManager.config.digitalClubName');
  1159. }
  1160. }
  1161. $leadToUpdate = [
  1162. 'firstName' => $customerEntity->getFirstName(),
  1163. 'lastName' => $customerEntity->getLastName(),
  1164. 'clubGuidId' => isset($club) ? $club->getGuidVirgin(): $clubGuidId,
  1165. 'clubName' => isset($club) ? $club->getName(): $clubName,
  1166. 'phone' => $customerEntity->getCustomFields()['phone_number'],
  1167. 'email' => $email,
  1168. 'channel' => VirginUser::FORM_CONTACT,
  1169. 'privacy' => $customerEntity->getCustomFields()['privacy_consent'],
  1170. 'cap' => $customerEntity->getCustomFields()['zipcode'],
  1171. 'isExplicitRegistration' => !$isImplicitRegistration,
  1172. ];
  1173. if($this->virginUser->getIsInLeadLayer()){
  1174. $leadToUpdate['guid_lead'] = $customerEntity->getCustomFields()['virgin_guid'];
  1175. $this->restApiClient->UpdateLead($leadToUpdate);
  1176. }else{
  1177. $leadToUpdate['guid_lead'] = $customerEntity->getId();
  1178. $this->restApiClient->InsertLead($leadToUpdate);
  1179. }
  1180. $club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  1181. if(isset($club)) {
  1182. return $this->redirectToRoute('frontend.configurator');
  1183. } else {
  1184. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  1185. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  1186. }
  1187. }
  1188. $club = $customerEntity->getExtensions()['foreignKeys']->jsonSerialize()['preferredClubId'];
  1189. if(isset($club)) {
  1190. return $this->redirectToRoute('frontend.configurator');
  1191. } else {
  1192. $navigationId = $this->leadService->getRevolutionDigitaleId($context);
  1193. return $this->redirectToRoute('frontend.navigation.page', ['navigationId' => $navigationId]);
  1194. }
  1195. } else {
  1196. // Error they never been reatched
  1197. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', [
  1198. 'error' => true,
  1199. 'ErrorSnippet' => $this->trans('lead-manager.form.message.userJustPresent'),
  1200. 'page' => $this->contactPageLoader->load($request, $context),
  1201. ]);
  1202. }
  1203. return $this->renderStorefront('@Storefront/storefront/page/contact/register.html.twig', ['page' => $page]);
  1204. }
  1205. /**
  1206. * @Route("/account/recover", name="frontend.account.recover.page", methods={"GET"})
  1207. *
  1208. * @throws CategoryNotFoundException
  1209. * @throws InconsistentCriteriaIdsException
  1210. * @throws MissingRequestParameterException
  1211. */
  1212. public function recoverAccountForm(Request $request, SalesChannelContext $context): Response
  1213. {
  1214. $page = $this->loginPageLoader->load($request, $context);
  1215. return $this->renderStorefront('@Storefront/storefront/page/recover-password.html.twig', [
  1216. 'page' => $page,
  1217. ]);
  1218. }
  1219. /**
  1220. * @Route("/account/recover", name="frontend.account.recover.request", methods={"POST"})
  1221. * @throws VirginApiException
  1222. */
  1223. public function generateAccountRecovery(Request $request, RequestDataBag $data, SalesChannelContext $context): Response
  1224. {
  1225. $email = $data->all()['email']['email'];
  1226. $this->virginUser->checkPerson($email);
  1227. if ($this->virginUser->getPersonType()==$this->virginUser::PERSONTYPE_LEAD || $this->virginUser->getPersonType()==$this->virginUser::PERSONTYPE_LEADLAYER){
  1228. $criteria = new Criteria();
  1229. $criteria->addFilter(new EqualsFilter('customer.email', $email));
  1230. $criteria->addFilter(new EqualsFilter('customer.guest', 0));
  1231. /** @var CustomerEntity $customerEntity */
  1232. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1233. if (!$customerEntity) {
  1234. $this->addFlash('danger', $this->trans('lead-manager.account.emailIsNotRegistered'));
  1235. return $this->redirectToRoute('frontend.account.login.page');
  1236. }
  1237. try {
  1238. $data->get('email')->set('storefrontUrl', $request->attributes->get('sw-sales-channel-absolute-base-url'));
  1239. $this->sendPasswordRecoveryMailRoute->sendRecoveryMail($data->get('email')->toRequestDataBag(), $context);
  1240. $this->addFlash('success', $this->trans('account.recoveryMailSend'));
  1241. } catch (CustomerNotFoundException $e) {
  1242. $this->addFlash('success', $this->trans('account.recoveryMailSend'));
  1243. } catch (InconsistentCriteriaIdsException $e) {
  1244. $this->addFlash('danger', $this->trans('error.message-default'));
  1245. }
  1246. return $this->redirectToRoute('frontend.account.recover.page');
  1247. } else {
  1248. $this->restApiClient->requestGlobalPasswordReset($email);
  1249. $this->session->set("recovery-email", $email);
  1250. $this->session->set("recovery-timestamp", (new DateTime())->getTimestamp());
  1251. return $this->redirectToRoute('frontend.account.recover.password.global');
  1252. }
  1253. }
  1254. private function checkHash(string $hash, Context $context): bool
  1255. {
  1256. $criteria = new Criteria();
  1257. $criteria->addFilter(
  1258. new EqualsFilter('hash', $hash)
  1259. );
  1260. $recovery = $this->customerRecoveryRepository->search($criteria, $context)->first();
  1261. $validDateTime = (new \DateTime())->sub(new \DateInterval('PT2H'));
  1262. return $recovery && $validDateTime < $recovery->getCreatedAt();
  1263. }
  1264. /**
  1265. * @Route("/account/recover/password", name="frontend.account.recover.password.page", methods={"GET"})
  1266. *
  1267. * @throws CategoryNotFoundException
  1268. * @throws InconsistentCriteriaIdsException
  1269. * @throws MissingRequestParameterException
  1270. */
  1271. public function resetPasswordForm(Request $request, SalesChannelContext $context): Response
  1272. {
  1273. $page = $this->loginPageLoader->load($request, $context);
  1274. $hash = $request->get('hash');
  1275. if (!$hash) {
  1276. $this->addFlash('danger', $this->trans('account.passwordHashNotFound'));
  1277. return $this->redirectToRoute('frontend.account.recover.request');
  1278. }
  1279. $customerHashCriteria = new Criteria();
  1280. $customerHashCriteria->addFilter(new EqualsFilter('hash', $hash));
  1281. $customerRecovery = $this->customerRecoveryRepository->search($customerHashCriteria, $context->getContext())->first();
  1282. if ($customerRecovery === null) {
  1283. $this->addFlash('danger', $this->trans('account.passwordHashNotFound'));
  1284. return $this->redirectToRoute('frontend.account.recover.request');
  1285. }
  1286. if (!$this->checkHash($hash, $context->getContext())) {
  1287. $this->addFlash('danger', $this->trans('account.passwordHashExpired'));
  1288. return $this->redirectToRoute('frontend.account.recover.request');
  1289. }
  1290. return $this->renderStorefront('@Storefront/storefront/page/reset-password.html.twig', [
  1291. 'page' => $page,
  1292. 'hash' => $hash,
  1293. 'formViolations' => $request->get('formViolations'),
  1294. ]);
  1295. }
  1296. /**
  1297. * @Route("/account/recover/password/global", name="frontend.account.recover.password.global", methods={"GET"})
  1298. * */
  1299. public function resetPasswordGlobalPage(Request $request, SalesChannelContext $context): Response
  1300. {
  1301. $email = $this->session->get("recovery-email");
  1302. $timestamp = $this->session->get("recovery-timestamp");
  1303. if (!$email || !$timestamp){
  1304. $this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
  1305. return $this->redirectToRoute('frontend.account.recover.request');
  1306. }
  1307. try {
  1308. if ((new DateTime())->diff(new DateTime("@".$timestamp))->h > 24){
  1309. $this->addFlash('danger', $this->trans('lead-manager.account.recovery.invalidTimestamp'));
  1310. return $this->redirectToRoute('frontend.account.recover.request');
  1311. }
  1312. } catch (\Exception $e){
  1313. $this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
  1314. return $this->redirectToRoute('frontend.account.recover.request');
  1315. }
  1316. return $this->renderStorefront('@Storefront/storefront/page/reset-password.html.twig', [
  1317. 'isGlobal' => true,
  1318. 'email' => $email,
  1319. ]);
  1320. }
  1321. /**
  1322. * @Route("/account/recover/password", name="frontend.account.recover.password.reset", methods={"POST"})
  1323. *
  1324. * @throws InconsistentCriteriaIdsException
  1325. */
  1326. public function resetPassword(RequestDataBag $data, SalesChannelContext $context): Response
  1327. {
  1328. $hash = $data->get('password')->get('hash');
  1329. try {
  1330. if (!preg_match($this->restApiClient::PASSWORD_REGEX, $data->get('password')->get('newPassword'))){
  1331. $this->addFlash('danger', $this->trans('account.passwordChangeNoSuccess'));
  1332. return $this->forwardToRoute(
  1333. 'frontend.account.recover.password.page',
  1334. ['hash' => $hash, 'formViolations' => "Password not matching requirements", 'passwordFormViolation' => true]
  1335. );
  1336. }
  1337. $customerHashCriteria = new Criteria();
  1338. $customerHashCriteria->addFilter(new EqualsFilter('hash', $hash));
  1339. $customerHashCriteria->addAssociation('customer');
  1340. $customerRecovery = $this->customerRecoveryRepository->search($customerHashCriteria, $context->getContext())->first();
  1341. $this->resetPasswordRoute->resetPassword($data->get('password')->toRequestDataBag(), $context);
  1342. /** @var CustomerEntity $customer */
  1343. $customer = $customerRecovery->getCustomer();
  1344. $customerEmail = $customer->getEmail();
  1345. $newPassword = $data->get('password')->get('newPassword');
  1346. $checkPersonResp = $this->virginUser->checkPerson($customerEmail);
  1347. $customFields = [
  1348. 'lead_implicit_registration' => false
  1349. ];
  1350. $this->customerRepository->update([
  1351. [
  1352. 'id' => $customer->getId(),
  1353. 'customFields' => $customFields,
  1354. 'active' => true
  1355. ],
  1356. ], $context->getContext());
  1357. } catch (ConstraintViolationException $formViolations) {
  1358. $this->addFlash('danger', $this->trans('account.passwordChangeNoSuccess'));
  1359. return $this->forwardToRoute(
  1360. 'frontend.account.recover.password.page',
  1361. ['hash' => $hash, 'formViolations' => $formViolations, 'passwordFormViolation' => true]
  1362. );
  1363. } catch (CustomerNotFoundByHashException $e) {
  1364. $this->addFlash('danger', $this->trans('account.passwordChangeNoSuccess'));
  1365. return $this->forwardToRoute('frontend.account.recover.request');
  1366. } catch (CustomerRecoveryHashExpiredException $e) {
  1367. $this->addFlash('danger', $this->trans('account.passwordHashExpired'));
  1368. return $this->forwardToRoute('frontend.account.recover.request');
  1369. }
  1370. return $this->redirectToRoute('frontend.account.login.page');
  1371. }
  1372. /**
  1373. * @Route("/account/recover/password/global", name="frontend.account.recover.password.reset.global", methods={"POST"})
  1374. *
  1375. * @throws VirginApiException
  1376. */
  1377. public function resetPasswordGlobal(RequestDataBag $data, SalesChannelContext $context): Response
  1378. {
  1379. $email = $data->get("email");
  1380. $token = $data->get("token");
  1381. $newPassword = $data->get("password")->get("newPassword");
  1382. $this->virginUser->checkPerson($email);
  1383. if ($this->virginUser->getPersonType()==$this->virginUser::PERSONTYPE_LEAD){
  1384. $this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
  1385. return $this->redirectToRoute('frontend.account.recover.request');
  1386. }
  1387. $response = $this->restApiClient->sendGlobalPasswordReset($email, $newPassword, $token);
  1388. if (!$response['success']){
  1389. $this->addFlash('danger', $this->trans('lead-manager.account.recovery.fail'));
  1390. return $this->redirectToRoute('frontend.account.recover.request');
  1391. }
  1392. $this->addFlash('success', $this->trans('lead-manager.account.recovery.success'));
  1393. return $this->redirectToRoute('frontend.account.login.page');
  1394. }
  1395. /**
  1396. * @Route("/continueCheckout", name="frontend.continue.checkout", options={"seo" = "false"}, methods={"GET"})
  1397. */
  1398. public function continueCheckout(Request $request, RequestDataBag $data, SalesChannelContext $context)
  1399. {
  1400. $token = $request->get('t');
  1401. $criteria = new Criteria([$token]);
  1402. /** @var CustomerEntity $order */
  1403. $customer = $this->customerRepository->search($criteria, $context->getContext())->first();
  1404. $this->accountService->login($customer->getEmail(), $context);
  1405. return $this->redirectToRoute('frontend.checkout.confirm.page');
  1406. }
  1407. /**
  1408. * @Route("/dem", name="frontend.exerp.dem", options={"seo" = "false"}, methods={"GET"})
  1409. */
  1410. public function autologinByExerpId(Request $request, RequestDataBag $data, SalesChannelContext $context)
  1411. {
  1412. $exerpCampaignCode = $request->get('g');
  1413. $exerpId = $request->get('e');
  1414. if(empty($exerpCampaignCode) || empty($exerpId)) {
  1415. $errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.ErrorPage404');
  1416. return $this->renderStorefront(
  1417. '@Storefront/storefront/page/content/index.html.twig',
  1418. ['page' => $errorPage]
  1419. );
  1420. }
  1421. $this->virginUser->checkPersonByExerpInfo($exerpId, $exerpCampaignCode);
  1422. if($this->virginUser->getExerpUser()) {
  1423. if(empty($this->virginUser->getExerpUser()->getEmail())) {
  1424. $errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.ErrorPage404');
  1425. return $this->renderStorefront(
  1426. '@Storefront/storefront/page/content/index.html.twig',
  1427. ['page' => $errorPage]
  1428. );
  1429. } else {
  1430. if($this->virginUser->getExerpUser()->getCustomerGroup() != $exerpCampaignCode || $this->virginUser->getExerpUser()->getCustomerGroup() == null) {
  1431. $errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.InvalidPromotion404');
  1432. return $this->renderStorefront(
  1433. '@Storefront/storefront/page/content/index.html.twig',
  1434. ['page' => $errorPage]
  1435. );
  1436. }
  1437. if($this->virginUser->getExerpUser()->getCenterId()) {
  1438. $criteria = new Criteria();
  1439. $criteria->addFilter(new EqualsFilter('club.centerId', $this->virginUser->getExerpUser()->getCenterId()));
  1440. } else {
  1441. $criteria = new Criteria();
  1442. $criteria->addFilter(new EqualsFilter('club.default', true));
  1443. }
  1444. $club = $this->clubRepository->search($criteria, $context->getContext())->first();
  1445. if($club == null) {
  1446. $criteria = new Criteria();
  1447. $criteria->addFilter(new EqualsFilter('club.default', true));
  1448. $club = $this->clubRepository->search($criteria, $context->getContext())->first();
  1449. }
  1450. $email = $this->virginUser->getExerpUser()->getEmail();
  1451. $criteria = new Criteria();
  1452. $criteria->addFilter(new EqualsFilter('customer.email', $email));
  1453. $criteria->addAssociation('salutation');
  1454. /** @var CustomerEntity $customerEntity */
  1455. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1456. if($customerEntity !== null) {
  1457. $this->customerRepository->update([
  1458. [
  1459. 'id' => $customerEntity->getId(),
  1460. 'customFields' => [
  1461. 'lead_implicit_registration' => false,
  1462. 'home_training' => false
  1463. ],
  1464. 'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
  1465. 'group' => [
  1466. 'id' => $this->virginUser->getCustomerGroupId()
  1467. ],
  1468. ],
  1469. ], $context->getContext());
  1470. } else {
  1471. $user = [
  1472. 'firstName' => $this->virginUser->getExerpUser()->getFirstName(),
  1473. 'lastName' => $this->virginUser->getExerpUser()->getLastName(),
  1474. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  1475. 'email' => $email,
  1476. 'password' => '12345678a',
  1477. ];
  1478. $customerEntity = $this->leadService->prepareRegistrationData($context, $user);
  1479. $this->customerRepository->update([
  1480. [
  1481. 'id' => $customerEntity->getId(),
  1482. 'customFields' => [
  1483. 'lead_implicit_registration' => false,
  1484. 'privacy_consent' => false,
  1485. 'home_training' => false,
  1486. ],
  1487. 'extensions' => ['preferredClubId' => isset($club) ? $club->getId() : null],
  1488. 'group' => [
  1489. 'id' => $this->virginUser->getCustomerGroupId()
  1490. ],
  1491. ],
  1492. ], $context->getContext());
  1493. }
  1494. $this->accountService->login($email, $context);
  1495. }
  1496. } else {
  1497. $errorPage = $this->getErrorPage($request, $context, 'LeadManager.config.ErrorPage404');
  1498. return $this->renderStorefront(
  1499. '@Storefront/storefront/page/content/index.html.twig',
  1500. ['page' => $errorPage]
  1501. );
  1502. }
  1503. return $this->redirectToRoute('frontend.configurator');
  1504. }
  1505. /**
  1506. * @Route("/clan-landing", name="frontend.clan.landing", options={"seo" = "false"}, methods={"GET"})
  1507. */
  1508. public function clanImplicitAutologinToConfigurator(Request $request, SalesChannelContext $context)
  1509. {
  1510. try {
  1511. $clanToken = $request->get('token');
  1512. if (empty($clanToken)) {
  1513. throw new RuntimeException($this->trans('lead-manager.profiling.parameterTokenEmpty'));
  1514. }
  1515. $decodedClanTokenInfo = $this->restApiClient->getDecodedLeadTokenInfo($clanToken);
  1516. if (empty($decodedClanTokenInfo)) {
  1517. throw new RuntimeException($this->trans('lead-manager.profiling.tokenEmpty'));
  1518. }
  1519. foreach ($decodedClanTokenInfo as $key => $value) {
  1520. if (empty($value)) {
  1521. throw new RuntimeException($key . " " . $this->trans('lead-manager.profiling.cantBeEmpty'));
  1522. }
  1523. }
  1524. $clanEmail = $decodedClanTokenInfo['email'];
  1525. //////// checkPerson
  1526. $this->virginUser->checkPerson($clanEmail);
  1527. $personType = $this->virginUser->getPersonType();
  1528. if ($personType === VirginUser::PERSONTYPE_LEAD || $personType === VirginUser::PERSONTYPE_LEADLAYER) {
  1529. $criteria = new Criteria();
  1530. $criteria->addFilter(new EqualsFilter('club.centerId', $decodedClanTokenInfo['club_center_id']));
  1531. $clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
  1532. if (!$clubId) {
  1533. $criteria = new Criteria();
  1534. $criteria->addFilter(new EqualsFilter('club.default', true));
  1535. $clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
  1536. }
  1537. $criteria = new Criteria();
  1538. $criteria->addFilter(new EqualsFilter('customer.email', $clanEmail));
  1539. /** @var CustomerEntity $customerEntity */
  1540. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1541. // no user in Shopware
  1542. if ($customerEntity === null) {
  1543. // user not registered ->
  1544. $shopwareUserBasicData = [
  1545. 'firstName' => $decodedClanTokenInfo['nome'],
  1546. 'lastName' => $decodedClanTokenInfo['cognome'],
  1547. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  1548. 'email' => $clanEmail,
  1549. 'password' => bin2hex(openssl_random_pseudo_bytes(4)),
  1550. ];
  1551. // implicit registration
  1552. $shopwareCustomerEntity = $this->leadService->prepareRegistrationData($context, $shopwareUserBasicData);
  1553. // update custom fields
  1554. $customFields = [
  1555. 'lead_implicit_registration' => true,
  1556. 'phone_number' => $decodedClanTokenInfo['telefono'],
  1557. 'privacy_consent' => true,
  1558. ];
  1559. $this->customerRepository->update([
  1560. [
  1561. 'id' => $shopwareCustomerEntity->getId(),
  1562. 'customFields' => $customFields,
  1563. 'extensions' => ['preferredClubId' => $clubId],
  1564. ],
  1565. ], $context->getContext());
  1566. } else {
  1567. // User in Shopware Update Data
  1568. if (
  1569. $customerEntity->getFirstName() === $decodedClanTokenInfo['nome']
  1570. && $customerEntity->getLastName() === $decodedClanTokenInfo['cognome']
  1571. ) {
  1572. // Firstname and Lastname match
  1573. // Update user phone and club
  1574. $updateUserInfo = [
  1575. 'id' => $customerEntity->getId(),
  1576. 'customFields' => ['phone_number' => $decodedClanTokenInfo['telefono']],
  1577. 'extensions' => ['preferredClubId' => $clubId],
  1578. ];
  1579. $this->customerRepository->update([$updateUserInfo], $context->getContext());
  1580. $this->accountService->login($clanEmail, $context);
  1581. } else {
  1582. return $this->redirectToRoute('frontend.account.login.page',
  1583. [
  1584. 'loginError' => true,
  1585. 'errorSnippet' => $this->trans('lead-manager.form.message.userJustPresent')
  1586. ]
  1587. );
  1588. }
  1589. }
  1590. return $this->redirectToRoute('frontend.configurator');
  1591. }
  1592. throw new RuntimeException($this->trans('lead-manager.profiling.onlyLeadUsers'));
  1593. } catch (\Exception $e) {
  1594. throw $e;
  1595. }
  1596. }
  1597. /**
  1598. * @Route("/contact-landing", name="frontend.contact.landing", options={"seo" = "false"}, methods={"GET"})
  1599. */
  1600. public function contactLanding(Request $request, SalesChannelContext $context): RedirectResponse
  1601. {
  1602. try {
  1603. $contactToken = $request->get('token');
  1604. if (empty($contactToken)) {
  1605. throw new RuntimeException($this->trans('lead-manager.contactLanding.parameterTokenEmpty'));
  1606. }
  1607. $decodedContactTokenInfo = $this->restApiClient->getDecodedLeadTokenInfo($contactToken);
  1608. if (empty($decodedContactTokenInfo)) {
  1609. throw new RuntimeException($this->trans('lead-manager.contactLanding.tokenEmpty'));
  1610. }
  1611. foreach ($decodedContactTokenInfo as $key => $value) {
  1612. if (empty($value)) {
  1613. throw new RuntimeException($key . " " . $this->trans('lead-manager.contactLanding.cantBeEmpty'));
  1614. }
  1615. }
  1616. $contactEmail = $decodedContactTokenInfo['email'];
  1617. //////// checkPerson
  1618. $this->virginUser->checkPerson($contactEmail);
  1619. $criteria = new Criteria();
  1620. $criteria->addFilter(new EqualsFilter('club.centerId', $decodedContactTokenInfo['club_center_id']));
  1621. $clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
  1622. if (!$clubId) {
  1623. $criteria = new Criteria();
  1624. $criteria->addFilter(new EqualsFilter('club.default', true));
  1625. $clubId = $this->clubRepository->searchIds($criteria, $context->getContext())->firstId();
  1626. }
  1627. $criteria = new Criteria();
  1628. $criteria->addFilter(new EqualsFilter('customer.email', $contactEmail));
  1629. /** @var CustomerEntity $customerEntity */
  1630. $customerEntity = $this->customerRepository->search($criteria, $context->getContext())->first();
  1631. $decodedContactFirstname = $decodedContactTokenInfo['nome'];
  1632. $decodedContactLastname = $decodedContactTokenInfo['cognome'];
  1633. $decodedContactPhoneNumber = $decodedContactTokenInfo['telefono'];
  1634. // no user in Shopware
  1635. if ($customerEntity === null) {
  1636. // user not registered ->
  1637. $shopwareUserBasicData = [
  1638. 'firstName' => $decodedContactFirstname,
  1639. 'lastName' => $decodedContactLastname,
  1640. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  1641. 'email' => $contactEmail,
  1642. 'password' => bin2hex(openssl_random_pseudo_bytes(4)),
  1643. ];
  1644. // implicit registration
  1645. $shopwareCustomerEntity = $this->leadService->prepareRegistrationData($context, $shopwareUserBasicData);
  1646. // update custom fields
  1647. $customFields = [
  1648. 'lead_implicit_registration' => true,
  1649. 'phone_number' => $decodedContactPhoneNumber,
  1650. 'privacy_consent' => true,
  1651. ];
  1652. $this->customerRepository->update([
  1653. [
  1654. 'id' => $shopwareCustomerEntity->getId(),
  1655. 'customFields' => $customFields,
  1656. 'extensions' => ['preferredClubId' => $clubId],
  1657. 'active' => false,
  1658. ],
  1659. ], $context->getContext());
  1660. } else {
  1661. // User in Shopware Update Data
  1662. if ($customerEntity->getCustomFields()['lead_implicit_registration']) {
  1663. $updateUserInfo = [
  1664. 'id' => $customerEntity->getId(),
  1665. 'firstName' => $decodedContactFirstname,
  1666. 'lastName' => $decodedContactLastname,
  1667. 'customFields' => ['phone_number' => $decodedContactPhoneNumber],
  1668. 'extensions' => ['preferredClubId' => $clubId],
  1669. ];
  1670. $this->customerRepository->update([$updateUserInfo], $context->getContext());
  1671. $this->accountService->login($contactEmail, $context);
  1672. } else {
  1673. return $this->redirectToRoute('frontend.account.login.page',
  1674. [
  1675. 'loginError' => true,
  1676. 'errorSnippet' => $this->trans('lead-manager.contactLanding.explicitUserAlreadyExistsLoginWithYourCredentials')
  1677. ]
  1678. );
  1679. }
  1680. }
  1681. return $this->redirectToRoute('frontend.configurator');
  1682. } catch (\Exception $e) {
  1683. throw $e;
  1684. }
  1685. }
  1686. private function URLIsValid($url)
  1687. {
  1688. $exists = true;
  1689. $router = $this->get('router');
  1690. try {
  1691. $route = $router->match($url);
  1692. if (!$route) {
  1693. $exists = false;
  1694. }
  1695. } catch (\Exception $e) {
  1696. $exists = false;
  1697. }
  1698. return $exists;
  1699. }
  1700. private function getErrorPage(Request $request, SalesChannelContext $context, $page)
  1701. {
  1702. $salesChannelId = $context->getSalesChannel()->getId();
  1703. $cmsErrorLayoutId = $this->systemConfigService->get($page, $salesChannelId);
  1704. return $this->errorPageLoader->load((string) $cmsErrorLayoutId, $request, $context);
  1705. }
  1706. }