custom/plugins/SystemIntegration/src/Services/VirginUser/VirginUser.php line 1161

Open in your IDE?
  1. <?php
  2. namespace Virgin\SystemIntegration\Services\VirginUser;
  3. use phpDocumentor\Reflection\Types\This;
  4. use Shopware\Core\Checkout\Customer\CustomerEntity;
  5. use Shopware\Core\Checkout\Customer\SalesChannel\AbstractLoginRoute;
  6. use Shopware\Core\Checkout\Customer\SalesChannel\AccountService;
  7. use Shopware\Core\Framework\Context;
  8. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  11. use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
  12. use Shopware\Core\System\SalesChannel\ContextTokenResponse;
  13. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  14. use Symfony\Component\HttpFoundation\Cookie;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Session\Session;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use Virgin\GDPRPlugin\Service\PrivacyService;
  19. use Virgin\LeadManager\Utils\Services\LeadGenerationService;
  20. use Virgin\ProductModelExtension\Custom\Club\ClubEntity;
  21. use Virgin\SystemIntegration\Exception\VirginApiException;
  22. use Virgin\SystemIntegration\Services\RestApiClient;
  23. use Shopware\Core\Framework\Validation\DataValidator;
  24. use Shopware\Core\Framework\Validation\DataValidationDefinition;
  25. use Symfony\Component\Validator\Constraints\Email;
  26. use Shopware\Core\System\SystemConfig\SystemConfigService;
  27. use Virgin\SystemIntegration\Services\Selling\Subscription;
  28. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  29. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  30. use Shopware\Core\Checkout\Customer\Exception\InactiveCustomerException;
  31. use Virgin\VirginCustomElement\Service\LandingPageService;
  32. class VirginUser
  33. {
  34. const CONTACT_LEADPURO = 100;
  35. // COSTANTI PER LA GESTIONE DEL TIPO DI UTILIZZATORE //
  36. const PERSONTYPE_LEAD = 0;
  37. const PERSONTYPE_SOCIO = 1;
  38. const PERSONTYPE_EXSOCIO = 2;
  39. const PERSONTYPE_INSOLUTO = 3;
  40. const PERSONTYPE_BLACKLIST = 4;
  41. const PERSONTYPE_DROPECCEZ = 5;
  42. const PERSONTYPE_NN = 6;
  43. const PERSONTYPE_LEADLAYER = 7;
  44. const PERSONDESC_LEAD = 'Lead';
  45. const PERSONDESC_SOCIO = 'Socio';
  46. const PERSONDESC_EXSOCIO = 'ExSocio';
  47. const PERSONDESC_INSOLUTO = 'Insoluto';
  48. const PERSONDESC_BLACKLIST = 'BlackList';
  49. const PERSONDESC_DROPECCEZ = 'Drop Eccezione'; //drop eccezione รจ una cancellazione anticipata rispetto alla naturale data di scadenza del'abbonamento es. motivi di salute
  50. const PERSONDESC_LEADLAYER = 'Lead Layer';
  51. const PERSONDESC_NN = 'Non Disponibile';
  52. // COSTANTI PER GESTIONE TIPO DI APPUNTAMENTO //
  53. const APP_INFO = 1;
  54. const APP_TRY = 2;
  55. // -------------------------------------//
  56. const ERROR_PSW_VAIGLOBAL_WRONG = 'VAPI API Error Forbidden';
  57. const HOME_TRAINING_CLUB_CODE = 233;
  58. private $personDesc;
  59. private $personType;
  60. /** @var GlobalUser */
  61. private $globalUser;
  62. /** @var ExerpUser */
  63. private $exerp_User;
  64. /** @var PartnerUser */
  65. private $partner_User;
  66. /** @var LeadLayerUser $leadLayer_User */
  67. private $leadLayer_User;
  68. private $errorCode;
  69. private $errorDesc;
  70. /** @var EntityRepository */
  71. private $customerRepository;
  72. private $partnerGroup;
  73. /** @var LeadGenerationService */
  74. private $leadService;
  75. /** @var RestApiClient */
  76. private $restApiClient;
  77. private $clubRepository;
  78. /** @var SystemConfigService
  79. */
  80. private SystemConfigService $systemConfigService;
  81. /** @var DataValidator
  82. */
  83. private $dataValidator;
  84. /** @var PrivacyService */
  85. private $privacyService;
  86. private $isInLeadLayer;
  87. private $customerGroupRepository;
  88. /** @var AccountService */
  89. private $accountService;
  90. /** @var TranslatorInterface */
  91. private $translator;
  92. /**
  93. * @var AbstractLoginRoute
  94. */
  95. private $loginRoute;
  96. /**
  97. * @var ClubEntity
  98. */
  99. private $clubEntity;
  100. /**
  101. * @var CustomerEntity|null
  102. */
  103. private $customerEntity;
  104. /**
  105. * @var Session
  106. */
  107. private $session;
  108. public function __construct(
  109. $customerRepository,
  110. $leadService,
  111. $restApiClient,
  112. $clubRepository,
  113. $systemConfigService,
  114. $dataValidator,
  115. $privacyService,
  116. $customerGroupRepository,
  117. $accountService,
  118. $translator,
  119. AbstractLoginRoute $loginRoute,
  120. Session $session
  121. )
  122. {
  123. $this->customerRepository = $customerRepository;
  124. $this->leadService = $leadService;
  125. $this->restApiClient = $restApiClient;
  126. $this->clubRepository = $clubRepository;
  127. $this->systemConfigService = $systemConfigService;
  128. $this->dataValidator = $dataValidator;
  129. $this->privacyService = $privacyService;
  130. $this->customerGroupRepository = $customerGroupRepository;
  131. $this->accountService = $accountService;
  132. $this->translator = $translator;
  133. $this->loginRoute = $loginRoute;
  134. $this->session = $session;
  135. }
  136. public function checkPersonFull($email, $password, $codFisc)
  137. {
  138. $response = $this->restApiClient->checkPerson($email, $password, $codFisc);
  139. if ($response!=""){
  140. $this->mapResponseToObject($response);
  141. $this->DetectPersonType();
  142. $this->GetSubscription();
  143. }
  144. return json_decode($response, true);
  145. }
  146. public function checkPerson($email, $codFisc = null)
  147. {
  148. $response = $this->restApiClient->checkPerson($email, null, $codFisc);
  149. // var_dump($response);
  150. if ($response!=""){
  151. $this->mapResponseToObject($response);
  152. $this->DetectPersonType();
  153. $this->GetSubscription();
  154. }
  155. return $response;
  156. }
  157. public function checkPersonByExerpInfo($exerpId, $campaignCode)
  158. {
  159. $response = $this->restApiClient->checkPersonByExerpInfo($exerpId, $campaignCode);
  160. if ($response!=""){
  161. $this->mapResponseToObject($response);
  162. $this->DetectPersonType();
  163. $this->GetSubscription();
  164. }
  165. return $response;
  166. }
  167. public function mapResponseToObject($response): VirginUser
  168. {
  169. $this->personType = self::PERSONTYPE_NN;
  170. $response = json_decode($response);
  171. $this->personDesc = $response->personDesc;
  172. $this->errorCode = $response->errorCode;
  173. $this->errorDesc = $response->errorDesc;
  174. $this->exerp_User = null;
  175. $this->globalUser = null;
  176. $this->leadLayer_User = null;
  177. $this->isInLeadLayer = false;
  178. $this->partner_User = null;
  179. if (isset($response->exerp_User)) {
  180. $this->exerp_User = new ExerpUser();
  181. $this->exerp_User->setErrorCode($response->exerp_User->errorCode);
  182. $this->exerp_User->setErrorDesc($response->exerp_User->errorDesc);
  183. $this->exerp_User->setId($response->exerp_User->id);
  184. $this->exerp_User->setCenterId($response->exerp_User->centerId);
  185. $this->exerp_User->setExternalId($response->exerp_User->externalId);
  186. $this->exerp_User->setEmail($response->email);
  187. $this->exerp_User->setCustomerGroup($response->customerGroup);
  188. }
  189. if (isset($response->exerp_Person)) {
  190. if(is_array($response->exerp_Person)){
  191. $key = array_search('ACTIVE',array_column($response->exerp_Person,'status'));
  192. if($key === false) {
  193. $this->personType = self::PERSONTYPE_EXSOCIO;
  194. } else {
  195. $this->personType = self::PERSONTYPE_SOCIO;
  196. }
  197. if($key>0){
  198. $response->exerp_Person=$response->exerp_Person[$key];
  199. }else{
  200. $response->exerp_Person= reset($response->exerp_Person);
  201. }
  202. }
  203. $user = $response->exerp_Person;
  204. $this->exerp_User = new ExerpUser();
  205. $this->exerp_User->setCenterId($user->personId->center);
  206. $this->exerp_User->setId($user->personId->id);
  207. $this->exerp_User->setExternalId($user->personId->externalId);
  208. $this->exerp_User->setPersonStatus($user->status);
  209. $this->exerp_User->setGender($user->gender);
  210. $this->exerp_User->setLastName($user->lastName);
  211. $this->exerp_User->setFirstName($user->firstName);
  212. $this->exerp_User->setCodFisc($user->codFisc);
  213. $this->exerp_User->setPersonType($user->personType);
  214. $this->exerp_User->setEmail($response->email);
  215. $this->exerp_User->setCustomerGroup($response->customerGroup);
  216. //var_dump($this->exerp_User );
  217. }
  218. if (isset($response->global_User)) {
  219. $this->globalUser = new GlobalUser(
  220. $response->global_User->userId,
  221. $response->global_User->firstName,
  222. $response->global_User->lastName,
  223. $response->global_User->email,
  224. $response->global_User->gender,
  225. $response->global_User->dateOfBirth,
  226. $response->global_User->externalId,
  227. $response->global_User->claims,
  228. $response->global_User->error,
  229. $response->global_User->token,
  230. $response->global_User->refreshToken
  231. );
  232. if ($this->getGlobalUser()->getToken() !=null && $this->session->get('tokenGlobal') != $this->getGlobalUser()->getToken()){
  233. $this->session->set('refreshTokenGlobal', $this->getGlobalUser()->getRefreshToken());
  234. $this->session->set('tokenGlobal', $this->getGlobalUser()->getToken());
  235. $this->session->set('tokenGlobalTimestamp', new \DateTime());
  236. }
  237. }
  238. if (isset($response->leadLayer_User)) {
  239. $this->isInLeadLayer = true;
  240. $this->leadLayer_User = new LeadLayerUser();
  241. $this->leadLayer_User->setNome($response->leadLayer_User->nome);
  242. $this->leadLayer_User->setCognome($response->leadLayer_User->cognome);
  243. $this->leadLayer_User->setCanale($response->leadLayer_User->canale);
  244. $this->leadLayer_User->setGuidLead($response->leadLayer_User->guid_lead);
  245. $this->leadLayer_User->setGiornoPredefinito($response->leadLayer_User->giorno_predefinito);
  246. $this->leadLayer_User->setOrarioPredefinito($response->leadLayer_User->orario_predefinito);
  247. $this->leadLayer_User->setClubDescrizione($response->leadLayer_User->club_Descrizione);
  248. $this->leadLayer_User->setGuidClub($response->leadLayer_User->guid_Club);
  249. $this->leadLayer_User->setTelefono($response->leadLayer_User->telefono);
  250. $this->leadLayer_User->setEmail($response->leadLayer_User->email);
  251. $this->leadLayer_User->setCanale($response->leadLayer_User->canale);
  252. $this->leadLayer_User->setPrivacy($response->leadLayer_User->privacy);
  253. }
  254. if (isset($response->partnerUser)) {
  255. $this->partner_User = new PartnerUser();
  256. $this->partner_User->setEmail($response->partnerUser->email ?? null);
  257. $this->partner_User->setUserName($response->partnerUser->userName ?? null);
  258. $this->partner_User->setSurnameName($response->partnerUser->surnameName ?? null);
  259. $this->partner_User->setBirthdate($response->partnerUser->birthdate ?? null);
  260. $this->partner_User->setBirthPlace($response->partnerUser->birthPlace ?? null);
  261. $this->partner_User->setFiscalCode($response->partnerUser->fiscalCode ?? null);
  262. $this->partner_User->setCustomerGroup($response->partnerUser->customerGroup ?? null);
  263. $this->partner_User->setItalian($response->partnerUser->italian ?? null);
  264. $this->partner_User->setNation($response->partnerUser->nation ?? null);
  265. $this->partner_User->setPhoneNumber($response->partnerUser->phoneNumber ?? null);
  266. $this->partner_User->setResidentAddress($response->partnerUser->residentAddress ?? null);
  267. $this->partner_User->setResidentCity($response->partnerUser->residentCity ?? null);
  268. $this->partner_User->setClubId($response->partnerUser->clubId ?? null);
  269. $this->setPartnerGroup($response->partnerUser->customerGroup ?? null);
  270. }
  271. return $this;
  272. }
  273. private function DetectPersonType()
  274. {
  275. $personType = $this->personType;
  276. $inExerp = isset($this->exerp_User) ? true : false;
  277. $inLeadLayer = isset($this->leadLayer_User) ? true : false;
  278. if ($inExerp) {
  279. // Socio da verificarne il tipo
  280. $externalId = $this->exerp_User->getExternalId();
  281. $personDetails = $this->restApiClient->getPersonDetail($externalId);
  282. if (isset($personDetails)) {
  283. $personDetailsArray = json_decode($personDetails,true);
  284. $personDetails = json_decode($personDetails);
  285. $this->exerp_User->setPersonType($personDetails->person->personType);
  286. $this->exerp_User->setPersonStatus($personDetails->person->status);
  287. $this->exerp_User->setCodFisc($personDetails->person->codFisc);
  288. $this->exerp_User->setSuspended($personDetails->personTypeAndStatus->suspended);
  289. $this->exerp_User->setBlackListed($personDetails->personTypeAndStatus->blacklisted);
  290. $this->exerp_User->setSubscriptions($personDetails->subscriptions);
  291. $this->exerp_User->setFirstName($personDetails->person->firstName);
  292. $this->exerp_User->setLastName($personDetails->person->lastName);
  293. $this->exerp_User->setCenterId($personDetails->person->personId->center);
  294. if($personDetailsArray['person']['status'] == 'TEMPORARYINACTIVE'
  295. || $personDetailsArray['person']['status'] == 'INACTIVE') {
  296. $key = array_search('ACTIVE',array_column($personDetailsArray['subscriptions'],'state'));
  297. if($key===false){
  298. // Sub Appena acquistata ma non attiva quindi sono TEMPORARYINACTIVE ma sub non ancora attiva
  299. $key = array_search('CREATED',array_column($personDetailsArray['subscriptions'],'state'));
  300. }
  301. if($key===false){
  302. // Sub in stato freeze
  303. $key = array_search('FROZEN',array_column($personDetailsArray['subscriptions'],'state'));
  304. }
  305. if($key===false){
  306. // se non รจ attivo cerco per sub appena creato
  307. $personType = self::PERSONTYPE_EXSOCIO;
  308. }else{
  309. $personType = self::PERSONTYPE_SOCIO;
  310. }
  311. } else {
  312. if($personDetailsArray['person']['status'] =='ACTIVE'){
  313. $key = array_search('ACTIVE',array_column($personDetailsArray['subscriptions'],'state'));
  314. if($key===false){
  315. $key = array_search('CREATED',array_column($personDetailsArray['subscriptions'],'state'));
  316. }
  317. if($key===false){
  318. $key = array_search('FROZEN',array_column($personDetailsArray['subscriptions'],'state'));
  319. }
  320. if($key===false){
  321. $key = array_search('CREATED',array_column($personDetailsArray['subscriptions'],'state'));
  322. }
  323. //var_dump($key);
  324. if($key === false) {
  325. $personType = self::PERSONTYPE_EXSOCIO;
  326. } else {
  327. $personType = self::PERSONTYPE_SOCIO;
  328. }
  329. }else{
  330. $personType = self::PERSONTYPE_EXSOCIO;
  331. }
  332. }
  333. };
  334. $balance = $this->restApiClient->getBalance($externalId);
  335. if (isset($balance)) {
  336. $this->exerp_User->setBalance($balance["totalPayableDebt"]);
  337. }
  338. if ($this->exerp_User->getBalance() > 0) {
  339. $personType = self::PERSONTYPE_INSOLUTO;
  340. }
  341. if ($this->exerp_User->getBlackListed()) {
  342. $personType = self::PERSONTYPE_BLACKLIST;
  343. }
  344. //var_dump($this->exerp_User->getPersonStatus());
  345. if($this->exerp_User->getPersonStatus() =='LEAD'){
  346. $personType = self::PERSONTYPE_LEAD;
  347. }
  348. }else{
  349. $personType = self::PERSONTYPE_LEAD;
  350. if ($inLeadLayer) {
  351. $personType = self::PERSONTYPE_LEADLAYER;
  352. }
  353. }
  354. $this->personType = $personType;
  355. $this->PersonTypeDesc();
  356. // var_dump($this->personType );
  357. }
  358. private function PersonTypeDesc()
  359. {
  360. switch ($this->personType) {
  361. case self::PERSONTYPE_LEAD:
  362. $this->personDesc = self::PERSONDESC_LEAD;
  363. break;
  364. case self::PERSONTYPE_EXSOCIO:
  365. $this->personDesc = self::PERSONDESC_EXSOCIO;
  366. break;
  367. case self::PERSONTYPE_INSOLUTO:
  368. $this->personDesc = self::PERSONDESC_INSOLUTO;
  369. break;
  370. case self::PERSONTYPE_BLACKLIST:
  371. $this->personDesc = self::PERSONDESC_BLACKLIST;
  372. break;
  373. case self::PERSONTYPE_SOCIO:
  374. $this->personDesc = self::PERSONDESC_SOCIO;
  375. break;
  376. case self::PERSONTYPE_DROPECCEZ:
  377. $this->personDesc = self::PERSONDESC_DROPECCEZ;
  378. break;
  379. case self::PERSONTYPE_LEADLAYER:
  380. $this->personDesc = self::PERSONDESC_LEADLAYER;
  381. break;
  382. case self::PERSONDESC_NN:
  383. $this->personDesc = self::PERSONDESC_NN;
  384. }
  385. }
  386. public function GetSubscription()
  387. {
  388. if (isset($this->exerp_User)) {
  389. $exerpId=null;
  390. $exrpCenterId=null;
  391. if($this->exerp_User->getId() != '' || $this->exerp_User->getId() != null){
  392. $exerpId = $this ->exerp_User->getId();
  393. $exrpCenterId=$this ->exerp_User->getCenterId();
  394. }
  395. if ($exerpId!=null) {
  396. $response = $this->restApiClient->getPersonSubscriptions($exerpId ,$exrpCenterId);
  397. if (isset($response)) {
  398. $subJson = json_decode($response,true);
  399. if($subJson['item'] != null) {
  400. $item = array_search('ACTIVE',array_column($subJson['item'],'state'));
  401. if($item !== false){
  402. $sub = new Subscription();
  403. $sub->setName($subJson['item'][$item]['product']['name']);
  404. $sub->setPeriodLength($subJson['item'][$item]['product']['periodLength']);
  405. $sub->setPeriodUnit($subJson['item'][$item]['product']['periodUnit']);
  406. $sub->setType($subJson['item'][$item]['product']['type']);
  407. $sub->setStartDate($subJson['item'][$item]['startDate']);
  408. $sub->setEndDate($subJson['item'][$item]['endDate']);
  409. $sub->setSubscriptionId($subJson['item'][$item]['subscriptionId']['center']. 'ss' .$subJson['item'][$item]['subscriptionId']['id']);
  410. $sub->setState($subJson['item'][$item]['state']);
  411. $sub->setSubState($subJson['item'][$item]['subState']);
  412. $this->exerp_User->setSubscriptions($sub);
  413. }
  414. }
  415. }
  416. }
  417. }
  418. }
  419. /**
  420. * @param RequestDataBag $data
  421. * @return string|null
  422. */
  423. public function CheckFormParamsToStorefront(RequestDataBag $data): ?string
  424. {
  425. $firstname = $data->get('name');
  426. $lastname = $data->get('lastname');
  427. $phone = $data->get('phone');
  428. $phonePrefix = $data->get('intlPrefix');
  429. $email = $data->get('email');
  430. $privacy = $data->get('privacy');
  431. $club = $data->get('club');
  432. $zipcode = $data->get('zipcode');
  433. $validation = new DataValidationDefinition('customer.email');
  434. $validation->add('email', new Email());
  435. if (empty($firstname) || empty($lastname) || empty($phone) || empty($email) || empty($club)) {
  436. return 'lead-manager.form.message.errorMessage';
  437. }
  438. $response = $this->leadService->getCaptchaResponse($_POST['g-recaptcha-response'], $this->systemConfigService->get('LeadManager.config.secretKey'));
  439. if (!$response->success) {
  440. return 'lead-manager.form.message.invalidCaptcha';
  441. }
  442. if (!preg_match($this->systemConfigService->get('LeadManager.config.textRegex'), $firstname) || !preg_match($this->systemConfigService->get('LeadManager.config.textRegex'), $lastname) || !preg_match($this->systemConfigService->get('LeadManager.config.numberRegex'), $phone)) {
  443. return 'lead-manager.form.message.errorRegexFields';
  444. }
  445. try {
  446. $this->dataValidator->validate(['email' => $email], $validation);
  447. } catch (\Exception $e) {
  448. return $e->getMessage();
  449. }
  450. return null;
  451. }
  452. /**
  453. * @param array $formParams
  454. * @param SalesChannelContext $context
  455. * @return string|null
  456. */
  457. public function handlePerson(array $formParams, SalesChannelContext $context): ?string
  458. {
  459. $privacy = $formParams['privacy'] ?? false;
  460. if (!empty($_SESSION['utm_params'])) {
  461. $this->restApiClient->insertUtmParams($_SESSION['utm_params'], $formParams['email'], $formParams['firstName'], $formParams['lastName']);
  462. unset($_SESSION['utm_params']);
  463. }
  464. if ($this->getPersonType()!=self::PERSONTYPE_LEAD && $this->getPersonType()!=self::PERSONTYPE_LEADLAYER){
  465. return 'lead-manager.form.message.userRegistered';
  466. }
  467. if ($this->getErrorDesc()){
  468. return 'lead-manager.account.genericErrorLogin';
  469. }
  470. try {
  471. $this->saveCurrentLead(
  472. null,
  473. $formParams['email'],
  474. $formParams['firstName'],
  475. $formParams['lastName'],
  476. $formParams['phone'],
  477. $formParams['club'],
  478. $privacy,
  479. null,
  480. $context
  481. );
  482. } catch (VirginApiException $e) {
  483. } catch (\Exception $e) {
  484. return 'lead-manager.form.message.errorRegistration';
  485. }
  486. return null;
  487. }
  488. /**
  489. * @param array $formParams
  490. * @param string|null $guid
  491. * @return void
  492. * @throws VirginApiException
  493. * @throws \Exception
  494. */
  495. private function upsertLeadToLayer(array $formParams, string $guid=null): void
  496. {
  497. if ($guid){
  498. $lead = $this->restApiClient->getLead(['guid' => $guid]);
  499. } else {
  500. $lead = $this->restApiClient->getLead(['email' => $formParams['email']]);
  501. }
  502. if ($lead != []) {
  503. $this->restApiClient->updateLeadAndAppointment($formParams);
  504. } else {
  505. $this->restApiClient->insertLeadAndAppointment($formParams);
  506. }
  507. }
  508. /**
  509. * @param array $customerData
  510. * @param SalesChannelContext $context
  511. * @return false|void
  512. */
  513. public function updateLead(array $customerData, SalesChannelContext $context)
  514. {
  515. if (empty($customerData)) {
  516. return false;
  517. }
  518. try {
  519. $currentLead = $this->getCurrentLead();
  520. if (
  521. $currentLead['firstName'] != $customerData['name'] ||
  522. $currentLead['lastName'] != $customerData['surname'] ||
  523. $currentLead['phoneNumber'] != $customerData['phone'] ||
  524. $currentLead['email'] != $customerData['email'] ||
  525. $currentLead['clubId'] != $customerData['clubId']
  526. ) {
  527. $this->saveCurrentLead(
  528. $currentLead['guid_lead'],
  529. $customerData['email'],
  530. $customerData['name'],
  531. $customerData['surname'],
  532. $customerData['phone'],
  533. $currentLead['clubId'],
  534. $currentLead['privacy'],
  535. $currentLead['timestamp'],
  536. $context
  537. );
  538. }
  539. } catch (\Exception $e) {
  540. return false;
  541. }
  542. }
  543. public function getCustomerGroupIdByVirginUserTypeCode($userTypeCode)
  544. {
  545. $customerGroupEntity = $this->customerGroupRepository->search(
  546. (new Criteria())->addFilter(new EqualsFilter('customFields.virgin_user_type_code', $userTypeCode))
  547. , Context::createDefaultContext())->first();
  548. return $customerGroupEntity->getId();
  549. }
  550. public function getCustomerGroupIdByName($customerGroupName)
  551. {
  552. $customerGroupEntity = $this->customerGroupRepository->search(
  553. (new Criteria())->addFilter(new EqualsFilter('name', $customerGroupName))
  554. , Context::createDefaultContext())->first();
  555. return $customerGroupEntity->getId();
  556. }
  557. public function writeCookies($formParams)
  558. {
  559. $params = [
  560. 'name' => $formParams['firstName'],
  561. 'lastname' => $formParams['lastName'],
  562. 'phone' => $formParams['phone'],
  563. 'email' => $formParams['email'],
  564. 'userType' => '', // handle CRM user type
  565. ];
  566. $this->leadService->createCookie($params);
  567. }
  568. /**
  569. * @param $data
  570. * @param SalesChannelContext $context
  571. * @return array
  572. */
  573. public function LoginManager($data, SalesChannelContext $context): array
  574. {
  575. $email = $data->get('username');
  576. $password = $data->get('password');
  577. $checkPersonResponse = $this->checkPersonFull($email , $password,null);
  578. if (!$checkPersonResponse || $this->errorCode == 500) {
  579. return [
  580. 'login' => false,
  581. 'errorMessage' => $this->translator->trans('lead-manager.form.message.checkpersonFail')
  582. ];
  583. }
  584. $this->setCustomerEntity($this->getCustomerByEmail($email, $context));
  585. $this->setClub($context);
  586. if ($checkPersonResponse['personDesc'] == "LEAD" || $checkPersonResponse['personDesc'] == "LEADLAYER") {
  587. return [
  588. 'login' => false,
  589. 'errorMessage' => $this->translator->trans('lead-manager.form.message.accountLoginOldLead'),
  590. 'personType' => $this->getPersonType()
  591. ];
  592. }
  593. if ($this->errorDesc == self::ERROR_PSW_VAIGLOBAL_WRONG) {
  594. return [
  595. 'login' => false,
  596. 'errorMessage' => $this->translator->trans('lead-manager.form.message.accountLogin'),
  597. 'personType' => $this->getPersonType()
  598. ];
  599. }
  600. if (!empty($this->errorDesc)) {
  601. return [
  602. 'login' => false,
  603. 'errorMessage' => $this->translator->trans('lead-manager.account.genericErrorLogin'),
  604. 'personType' => $this->getPersonType()
  605. ];
  606. }
  607. if ($this->getGlobalUser() == null || $this->getExerpUser() == null){
  608. return [
  609. 'login' => false,
  610. 'errorMessage' => $this->translator->trans('lead-manager.form.message.checkpersonFail')
  611. ];
  612. }
  613. //user is not on shopware, implicit registration
  614. if (!$this->getCustomerEntity()) {
  615. $this->setCustomerEntity($this->registerFromGlobal($context, $email, $password));
  616. if (!$this->getCustomerEntity()){
  617. return [
  618. 'login' => false,
  619. 'errorMessage' => $this->translator->trans('lead-manager.form.message.checkpersonFail'),
  620. ];
  621. }
  622. }
  623. $customerUpdateArray = $this->getUpdateShopwareFields($password);
  624. $customFields = [
  625. 'lead_implicit_registration' => false,
  626. 'privacy_consent' => null,
  627. 'home_training' => $this->getIsHomeTraining(),
  628. ];
  629. if ($this->getPartnerUser()) {
  630. $customFields = array_merge($customFields, $this->getPartnerUser()->getObjectVars());
  631. }
  632. $customerUpdateArray['id'] = $this->getCustomerEntity()->getId();
  633. $customerUpdateArray['customFields'] = $customFields;
  634. if (!empty($_SESSION['utm_params'])) {
  635. $this->restApiClient->insertUtmParams($_SESSION['utm_params'], $email, $this->getCustomerEntity()->getFirstName(), $this->getCustomerEntity()->getLastName(), 'LOGIN');
  636. unset($_SESSION['utm_params']);
  637. }
  638. if ($this->leadLayer_User){
  639. $customerUpdateArray['customFields']['virgin_guid'] = $this->leadLayer_User->getGuidLead();
  640. } else {
  641. error_log("LoginManager - no leadLayer_user for ".$email);
  642. }
  643. try {
  644. if ($this->getPersonType() != VirginUser::PERSONTYPE_BLACKLIST) {
  645. $this->customerRepository->update([$customerUpdateArray], $context->getContext());
  646. $this->loginRoute->login($data, $context);
  647. if ($this->getCustomerEntity()->getCustomFields() &&
  648. isset($this->getCustomerEntity()->getCustomFields()['unsolved_under_evaluation']) &&
  649. $this->getCustomerEntity()->getCustomFields()['unsolved_under_evaluation']
  650. ) {
  651. $this->customerRepository->update([
  652. [
  653. 'id' => $this->getCustomerEntity()->getId(),
  654. 'customFields' => [
  655. 'unsolved_under_evaluation' => false,
  656. ],
  657. ],
  658. ], $context->getContext());
  659. }
  660. }
  661. $this->session->set('personType', $this->getPersonType());
  662. $response = [
  663. 'login' => true,
  664. 'personType' => $this->getPersonType(),
  665. 'customerEntity' => $this->getCustomerEntity()
  666. ];
  667. } catch (BadCredentialsException|UnauthorizedHttpException|InactiveCustomerException $e) {
  668. //login ko
  669. switch ($e) {
  670. case $e instanceof UnauthorizedHttpException:
  671. case $e instanceof BadCredentialsException:
  672. default:
  673. $errorMessage = $this->translator->trans('lead-manager.form.message.accountLogin');
  674. }
  675. $response = [
  676. 'login' => false,
  677. 'errorMessage' => $errorMessage,
  678. 'personType' => $this->getPersonType(),
  679. 'customerEntity' => $this->getCustomerEntity()
  680. ];
  681. }
  682. return $response;
  683. }
  684. /**
  685. * @param string $email
  686. * @param SalesChannelContext $salesChannelContext
  687. * @return CustomerEntity | null
  688. */
  689. private function getCustomerByEmail(string $email, SalesChannelContext $salesChannelContext): ?CustomerEntity
  690. {
  691. $criteria = new Criteria();
  692. $criteria->addFilter(new EqualsFilter('customer.email', $email));
  693. /** @var CustomerEntity $customerEntity */
  694. return $this->customerRepository->search($criteria, $salesChannelContext->getContext())->first();
  695. }
  696. /**
  697. * @param string $urlLogin
  698. * @param string $urlCourses
  699. * @return string
  700. * @throws VirginApiException
  701. */
  702. public function getURL_TO_PersonalAreaCMS(string $urlLogin, string $urlCourses ): string
  703. {
  704. $token = $this->getGlobalToken();
  705. if (!$token){
  706. return "#";
  707. }
  708. return $urlLogin.'?token='.$token.'&landingurl='.$urlCourses;
  709. }
  710. /**
  711. * @return mixed|null
  712. * @throws VirginApiException
  713. */
  714. public function getGlobalToken()
  715. {
  716. if ($this->session->get('tokenGlobalTimestamp') &&
  717. (new \DateTime())->diff($this->session->get('tokenGlobalTimestamp'))->m < 120
  718. ){
  719. return $this->session->get('tokenGlobal');
  720. }
  721. $tokenData = $this->restApiClient->GlobalRefreshToken($this->session->get('refreshTokenGlobal'));
  722. if (!$tokenData){
  723. return null;
  724. }
  725. $this->session->set('refreshTokenGlobal', $tokenData['token']);
  726. $this->session->set('tokenGlobal', $tokenData['oneTimeToken']);
  727. $this->session->set('tokenGlobalTimestamp', new \DateTime());
  728. return $tokenData['oneTimeToken'];
  729. }
  730. /**
  731. * @return mixed
  732. */
  733. public function getPersonDesc()
  734. {
  735. return $this->personDesc;
  736. }
  737. /**
  738. * @param mixed $personDesc
  739. */
  740. public function setPersonDesc($personDesc): void
  741. {
  742. $this->personDesc = $personDesc;
  743. }
  744. /**
  745. * @return mixed
  746. */
  747. public function getPersonType()
  748. {
  749. return $this->personType;
  750. }
  751. /**
  752. * @param GlobalUser $globalUser
  753. */
  754. public function setGlobalUser(GlobalUser $globalUser): void
  755. {
  756. $this->globalUser = $globalUser;
  757. }
  758. /**
  759. * @return GlobalUser | null
  760. */
  761. public function getGlobalUser(): ?GlobalUser
  762. {
  763. return $this->globalUser ?? null;
  764. }
  765. /**
  766. * @return ExerpUser | null
  767. */
  768. public function getExerpUser(): ?ExerpUser
  769. {
  770. return $this->exerp_User ?? null;
  771. }
  772. /**
  773. * @param ExerpUser $exerp_User
  774. */
  775. public function setExerpUser(ExerpUser $exerp_User): void
  776. {
  777. $this->exerp_User = $exerp_User;
  778. }
  779. /**
  780. * @return mixed
  781. */
  782. public function getErrorCode()
  783. {
  784. return $this->errorCode;
  785. }
  786. /**
  787. * @param mixed $errorCode
  788. */
  789. public function setErrorCode($errorCode): void
  790. {
  791. $this->errorCode = $errorCode;
  792. }
  793. /**
  794. * @return mixed
  795. */
  796. public function getErrorDesc()
  797. {
  798. return $this->errorDesc;
  799. }
  800. /**
  801. * @param mixed $errorDesc
  802. */
  803. public function setErrorDesc($errorDesc): void
  804. {
  805. $this->errorDesc = $errorDesc;
  806. }
  807. /**
  808. * @return LeadLayerUser
  809. */
  810. public function getLeadLayerUser(): ?LeadLayerUser
  811. {
  812. return $this->leadLayer_User;
  813. }
  814. /**
  815. * @param LeadLayerUser $leadLayer_User
  816. */
  817. public function setLeadLayerUser(LeadLayerUser $leadLayer_User): void
  818. {
  819. $this->leadLayer_User = $leadLayer_User;
  820. }
  821. /**
  822. * @return mixed
  823. */
  824. public function getIsInLeadLayer()
  825. {
  826. return $this->isInLeadLayer;
  827. }
  828. /**
  829. * @param mixed $isInLeadLayer
  830. */
  831. public function setIsInLeadLayer($isInLeadLayer): void
  832. {
  833. $this->isInLeadLayer = $isInLeadLayer;
  834. }
  835. /**
  836. * @return mixed
  837. */
  838. public function getPartnerGroup()
  839. {
  840. return $this->partnerGroup;
  841. }
  842. /**
  843. * @param mixed $partnerGroup
  844. */
  845. public function setPartnerGroup($partnerGroup): void
  846. {
  847. $customerGroups = explode(",", $partnerGroup);
  848. if(count($customerGroups) > 1) {
  849. $this->partnerGroup = $customerGroups[1];
  850. } else {
  851. $this->partnerGroup = $customerGroups[0];
  852. }
  853. }
  854. /**
  855. * @return PartnerUser
  856. */
  857. public function getPartnerUser():? PartnerUser
  858. {
  859. return $this->partner_User;
  860. }
  861. /**
  862. * @param PartnerUser $partner_User
  863. */
  864. public function setPartnerUser(PartnerUser $partner_User)
  865. {
  866. $this->partner_User = $partner_User;
  867. }
  868. /**
  869. * @return mixed
  870. */
  871. public function getCustomerGroupId()
  872. {
  873. if($this->getExerpUser() != null && !empty($this->getExerpUser()->getCustomerGroup())) {
  874. $customerGroupId = $this->getCustomerGroupIdByName($this->getExerpUser()->getCustomerGroup());
  875. } else {
  876. if(!empty($this->getPartnerGroup())) {
  877. $customerGroupId = $this->getCustomerGroupIdByName($this->getPartnerGroup());
  878. if(empty($customerGroupId)) {
  879. $customerGroupId = $this->getCustomerGroupIdByVirginUserTypeCode($this->getPersonType());
  880. }
  881. } else {
  882. $customerGroupId = $this->getCustomerGroupIdByVirginUserTypeCode($this->getPersonType());
  883. }
  884. }
  885. return $customerGroupId;
  886. }
  887. private function registerFromGlobal(SalesChannelContext $context, $email, $password): CustomerEntity
  888. {
  889. $shopwareUserBasicData = [
  890. 'firstName' => $this->getGlobalUser()->getFirstName(),
  891. 'lastName' => $this->getGlobalUser()->getLastName(),
  892. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  893. 'email' => $email,
  894. 'password' => $password,
  895. ];
  896. //registrazione implicita
  897. return $this->leadService->prepareRegistrationData($context, $shopwareUserBasicData, false);
  898. }
  899. /**
  900. * @param string|null $password
  901. * @return array|null
  902. */
  903. private function getUpdateShopwareFields(string $password=null): ?array
  904. {
  905. if (!$this->getCustomerEntity()){
  906. return null;
  907. }
  908. //clubentity
  909. $updateArray = [
  910. 'active' => true,
  911. 'group' => [
  912. 'id' => $this->getCustomerGroupId()
  913. ],
  914. 'extensions' => ['preferredClubId' => $this->getClubEntity() ? $this->getClubEntity()->getId() : null],
  915. ];
  916. if ($this->getCustomerEntity()->getFirstName() != $this->getGlobalUser()->getFirstName()) {
  917. $updateArray['firstName'] = $this->getGlobalUser()->getFirstName();
  918. }
  919. if ($this->getCustomerEntity()->getLastName() != $this->getGlobalUser()->getLastName()) {
  920. $updateArray['lastName'] = $this->getGlobalUser()->getLastName();
  921. }
  922. if ($password && !password_verify($password, $this->customerEntity->getPassword())){
  923. $updateArray['password'] = $password;
  924. }
  925. return $updateArray;
  926. }
  927. /**
  928. * @param SalesChannelContext $context
  929. * @return void
  930. */
  931. private function setClub(SalesChannelContext $context)
  932. {
  933. if ($this->getExerpUser()) {
  934. $criteria = new Criteria();
  935. $criteria->addFilter(new EqualsFilter('club.centerId', $this->getExerpUser()->getCenterId()));
  936. /** @var ClubEntity $clubEntity */
  937. $this->clubEntity = $this->clubRepository->search($criteria, $context->getContext())->first();
  938. }
  939. }
  940. /**
  941. * @return ClubEntity|null
  942. */
  943. public function getClubEntity(): ? ClubEntity
  944. {
  945. return $this->clubEntity;
  946. }
  947. /**
  948. * @return bool
  949. */
  950. private function getIsHomeTraining(): bool
  951. {
  952. return $this->getExerpUser()->getCenterId() == $this::HOME_TRAINING_CLUB_CODE;
  953. }
  954. private function isImplicit()
  955. {
  956. return $this->customerEntity->getCustomFields()['lead_implicit_registration'] ?? false;
  957. }
  958. /**
  959. * @return CustomerEntity|null
  960. */
  961. public function getCustomerEntity(): ?CustomerEntity
  962. {
  963. return $this->customerEntity;
  964. }
  965. /**
  966. * @param CustomerEntity|null $customerEntity
  967. * @return void
  968. */
  969. private function setCustomerEntity(?CustomerEntity $customerEntity)
  970. {
  971. $this->customerEntity = $customerEntity;
  972. }
  973. /**
  974. * @throws \Exception
  975. */
  976. public function getCurrentLead(){
  977. if (
  978. $this->session->get('leadUser') &&
  979. (new \DateTime())->diff(
  980. (new \DateTime())->setTimestamp($this->session->get('leadUser')['timestamp'])
  981. )->days > 30
  982. ) {
  983. $this->session->set('leadUser', null);
  984. throw new \Exception('Expired Lead');
  985. }
  986. if (isset($_COOKIE['leadUser'])){
  987. $this->session->set('leadUser', json_decode($_COOKIE['leadUser'], true));
  988. }
  989. return $this->session->get('leadUser');
  990. }
  991. /**
  992. * @param string|null $guid
  993. * @param string $email
  994. * @param string $firstName
  995. * @param string $lastName
  996. * @param string $phoneNumber
  997. * @param string $clubId
  998. * @param bool $privacy
  999. * @param string|null $timestamp
  1000. * @param SalesChannelContext $context
  1001. * @throws VirginApiException
  1002. */
  1003. public function saveCurrentLead(
  1004. ?string $guid,
  1005. string $email,
  1006. string $firstName,
  1007. string $lastName,
  1008. string $phoneNumber,
  1009. string $clubId,
  1010. bool $privacy,
  1011. ?string $timestamp,
  1012. SalesChannelContext $context,
  1013. bool $skipUpsertLeadToLayer= false
  1014. ): void
  1015. {
  1016. $update = true;
  1017. if (!$guid){
  1018. $dateTime = new \DateTime();
  1019. $guid = $dateTime->getTimestamp() . $email;
  1020. $timestamp = $dateTime->getTimestamp();
  1021. $update = false;
  1022. }
  1023. $user = [
  1024. 'guid_lead' => $guid,
  1025. 'firstName' => $firstName,
  1026. 'lastName' => $lastName,
  1027. 'email' => $email,
  1028. 'phoneNumber' => $phoneNumber,
  1029. 'clubId' => $clubId,
  1030. 'privacy' => $privacy,
  1031. 'timestamp' => $timestamp,
  1032. ];
  1033. $this->session->set('leadUser', $user);
  1034. //todo
  1035. $privacyText = "";
  1036. if ($privacyText) {
  1037. $user['privacyJson'] = $privacyText;
  1038. }
  1039. if ($clubId == 'digital'){
  1040. return;
  1041. } else {
  1042. $criteria = new Criteria();
  1043. $criteria->addFilter(new EqualsFilter('club.id', $clubId));
  1044. /** @var ClubEntity $clubEntity */
  1045. $clubEntity = $this->clubRepository->search($criteria, $context->getContext())->first();
  1046. $user['guid_club'] = $clubEntity->getGuidVirgin();
  1047. $user['clubName'] = $clubEntity->getName();
  1048. }
  1049. if (!$skipUpsertLeadToLayer) {
  1050. $this->upsertLeadToLayer($user, $update ? $guid : null);
  1051. }
  1052. }
  1053. /**
  1054. * @param string|null $email
  1055. * @return bool
  1056. */
  1057. public function canBuy(string $email = null): bool
  1058. {
  1059. if ($email){
  1060. $this->checkPerson($email);
  1061. }
  1062. return match ($this->getPersonType()) {
  1063. $this::PERSONTYPE_LEAD,
  1064. $this::PERSONTYPE_LEADLAYER,
  1065. $this::PERSONTYPE_DROPECCEZ,
  1066. $this::PERSONTYPE_EXSOCIO => true,
  1067. default => false,
  1068. };
  1069. }
  1070. }