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

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. try {
  468. $this->saveCurrentLead(
  469. null,
  470. $formParams['email'],
  471. $formParams['firstName'],
  472. $formParams['lastName'],
  473. $formParams['phone'],
  474. $formParams['club'],
  475. $privacy,
  476. null,
  477. $context
  478. );
  479. } catch (VirginApiException $e) {
  480. } catch (\Exception $e) {
  481. return 'lead-manager.form.message.errorRegistration';
  482. }
  483. return null;
  484. }
  485. /**
  486. * @param array $formParams
  487. * @param string|null $guid
  488. * @return void
  489. * @throws VirginApiException
  490. * @throws \Exception
  491. */
  492. private function upsertLeadToLayer(array $formParams, string $guid=null): void
  493. {
  494. if ($guid){
  495. $lead = $this->restApiClient->getLead(['guid' => $guid]);
  496. } else {
  497. $lead = $this->restApiClient->getLead(['email' => $formParams['email']]);
  498. }
  499. if ($lead != []) {
  500. $this->restApiClient->updateLeadAndAppointment($formParams);
  501. } else {
  502. $this->restApiClient->insertLeadAndAppointment($formParams);
  503. }
  504. }
  505. /**
  506. * @param array $customerData
  507. * @param SalesChannelContext $context
  508. * @return false|void
  509. */
  510. public function updateLead(array $customerData, SalesChannelContext $context)
  511. {
  512. if (empty($customerData)) {
  513. return false;
  514. }
  515. try {
  516. $currentLead = $this->getCurrentLead();
  517. if (
  518. $currentLead['firstName'] != $customerData['name'] ||
  519. $currentLead['lastName'] != $customerData['surname'] ||
  520. $currentLead['phoneNumber'] != $customerData['phone'] ||
  521. $currentLead['email'] != $customerData['email'] ||
  522. $currentLead['clubId'] != $customerData['clubId']
  523. ) {
  524. $this->saveCurrentLead(
  525. $currentLead['guid_lead'],
  526. $customerData['email'],
  527. $customerData['name'],
  528. $customerData['surname'],
  529. $customerData['phone'],
  530. $currentLead['clubId'],
  531. $currentLead['privacy'],
  532. $currentLead['timestamp'],
  533. $context
  534. );
  535. }
  536. } catch (\Exception $e) {
  537. return false;
  538. }
  539. }
  540. public function getCustomerGroupIdByVirginUserTypeCode($userTypeCode)
  541. {
  542. $customerGroupEntity = $this->customerGroupRepository->search(
  543. (new Criteria())->addFilter(new EqualsFilter('customFields.virgin_user_type_code', $userTypeCode))
  544. , Context::createDefaultContext())->first();
  545. return $customerGroupEntity->getId();
  546. }
  547. public function getCustomerGroupIdByName($customerGroupName)
  548. {
  549. $customerGroupEntity = $this->customerGroupRepository->search(
  550. (new Criteria())->addFilter(new EqualsFilter('name', $customerGroupName))
  551. , Context::createDefaultContext())->first();
  552. return $customerGroupEntity->getId();
  553. }
  554. public function writeCookies($formParams)
  555. {
  556. $params = [
  557. 'name' => $formParams['firstName'],
  558. 'lastname' => $formParams['lastName'],
  559. 'phone' => $formParams['phone'],
  560. 'email' => $formParams['email'],
  561. 'userType' => '', // handle CRM user type
  562. ];
  563. $this->leadService->createCookie($params);
  564. }
  565. /**
  566. * @param $data
  567. * @param SalesChannelContext $context
  568. * @return array
  569. */
  570. public function LoginManager($data, SalesChannelContext $context): array
  571. {
  572. $email = $data->get('username');
  573. $password = $data->get('password');
  574. $checkPersonResponse = $this->checkPersonFull($email , $password,null);
  575. if (!$checkPersonResponse || $this->errorCode == 500) {
  576. return [
  577. 'login' => false,
  578. 'errorMessage' => $this->translator->trans('lead-manager.form.message.checkpersonFail')
  579. ];
  580. }
  581. $this->setCustomerEntity($this->getCustomerByEmail($email, $context));
  582. $this->setClub($context);
  583. if ($checkPersonResponse['personDesc'] == "LEAD" || $checkPersonResponse['personDesc'] == "LEADLAYER") {
  584. return [
  585. 'login' => false,
  586. 'errorMessage' => $this->translator->trans('lead-manager.form.message.accountLoginOldLead'),
  587. 'personType' => $this->getPersonType()
  588. ];
  589. }
  590. if ($this->errorDesc == self::ERROR_PSW_VAIGLOBAL_WRONG) {
  591. return [
  592. 'login' => false,
  593. 'errorMessage' => $this->translator->trans('lead-manager.form.message.accountLogin'),
  594. 'personType' => $this->getPersonType()
  595. ];
  596. }
  597. if ($this->getGlobalUser() == null || $this->getExerpUser() == null){
  598. return [
  599. 'login' => false,
  600. 'errorMessage' => $this->translator->trans('lead-manager.form.message.checkpersonFail')
  601. ];
  602. }
  603. //user is not on shopware, implicit registration
  604. if (!$this->getCustomerEntity()) {
  605. $this->setCustomerEntity($this->registerFromGlobal($context, $email, $password));
  606. if (!$this->getCustomerEntity()){
  607. return [
  608. 'login' => false,
  609. 'errorMessage' => $this->translator->trans('lead-manager.form.message.checkpersonFail'),
  610. ];
  611. }
  612. }
  613. $customerUpdateArray = $this->getUpdateShopwareFields($password);
  614. $customFields = [
  615. 'lead_implicit_registration' => false,
  616. 'privacy_consent' => null,
  617. 'home_training' => $this->getIsHomeTraining(),
  618. ];
  619. if ($this->getPartnerUser()) {
  620. $customFields = array_merge($customFields, $this->getPartnerUser()->getObjectVars());
  621. }
  622. $customerUpdateArray['id'] = $this->getCustomerEntity()->getId();
  623. $customerUpdateArray['customFields'] = $customFields;
  624. if (!empty($_SESSION['utm_params'])) {
  625. $this->restApiClient->insertUtmParams($_SESSION['utm_params'], $email, $this->getCustomerEntity()->getFirstName(), $this->getCustomerEntity()->getLastName(), 'LOGIN');
  626. unset($_SESSION['utm_params']);
  627. }
  628. if ($this->leadLayer_User){
  629. $customerUpdateArray['customFields']['virgin_guid'] = $this->leadLayer_User->getGuidLead();
  630. } else {
  631. error_log("LoginManager - no leadLayer_user for ".$email);
  632. }
  633. try {
  634. if ($this->getPersonType() != VirginUser::PERSONTYPE_BLACKLIST) {
  635. $this->customerRepository->update([$customerUpdateArray], $context->getContext());
  636. $this->loginRoute->login($data, $context);
  637. if ($this->getCustomerEntity()->getCustomFields() &&
  638. isset($this->getCustomerEntity()->getCustomFields()['unsolved_under_evaluation']) &&
  639. $this->getCustomerEntity()->getCustomFields()['unsolved_under_evaluation']
  640. ) {
  641. $this->customerRepository->update([
  642. [
  643. 'id' => $this->getCustomerEntity()->getId(),
  644. 'customFields' => [
  645. 'unsolved_under_evaluation' => false,
  646. ],
  647. ],
  648. ], $context->getContext());
  649. }
  650. }
  651. $response = [
  652. 'login' => true,
  653. 'personType' => $this->getPersonType(),
  654. 'customerEntity' => $this->getCustomerEntity()
  655. ];
  656. } catch (BadCredentialsException|UnauthorizedHttpException|InactiveCustomerException $e) {
  657. //login ko
  658. switch ($e) {
  659. case $e instanceof UnauthorizedHttpException:
  660. case $e instanceof BadCredentialsException:
  661. default:
  662. $errorMessage = $this->translator->trans('lead-manager.form.message.accountLogin');
  663. }
  664. $response = [
  665. 'login' => false,
  666. 'errorMessage' => $errorMessage,
  667. 'personType' => $this->getPersonType(),
  668. 'customerEntity' => $this->getCustomerEntity()
  669. ];
  670. }
  671. return $response;
  672. }
  673. /**
  674. * @param string $email
  675. * @param SalesChannelContext $salesChannelContext
  676. * @return CustomerEntity | null
  677. */
  678. private function getCustomerByEmail(string $email, SalesChannelContext $salesChannelContext): ?CustomerEntity
  679. {
  680. $criteria = new Criteria();
  681. $criteria->addFilter(new EqualsFilter('customer.email', $email));
  682. /** @var CustomerEntity $customerEntity */
  683. return $this->customerRepository->search($criteria, $salesChannelContext->getContext())->first();
  684. }
  685. /**
  686. * @param string $urlCMS
  687. * @param string $urlLanding
  688. * @return string
  689. * @throws VirginApiException
  690. */
  691. public function getURL_TO_PersonalAreaCMS(string $urlCMS, string $urlLanding ): string
  692. {
  693. $token = $this->getGlobalToken();
  694. if (!$token){
  695. return "#";
  696. }
  697. return $urlCMS.'?token='.$token.'&landingurl='.$urlLanding;
  698. }
  699. /**
  700. * @return mixed|null
  701. * @throws VirginApiException
  702. */
  703. public function getGlobalToken()
  704. {
  705. if ($this->session->get('tokenGlobalTimestamp') &&
  706. (new \DateTime())->diff($this->session->get('tokenGlobalTimestamp'))->m < 120
  707. ){
  708. return $this->session->get('tokenGlobal');
  709. }
  710. $tokenData = $this->restApiClient->GlobalRefreshToken($this->session->get('refreshTokenGlobal'));
  711. if (!$tokenData){
  712. return null;
  713. }
  714. $this->session->set('refreshTokenGlobal', $tokenData['token']);
  715. $this->session->set('tokenGlobal', $tokenData['oneTimeToken']);
  716. $this->session->set('tokenGlobalTimestamp', new \DateTime());
  717. return $tokenData['oneTimeToken'];
  718. }
  719. /**
  720. * @return mixed
  721. */
  722. public function getPersonDesc()
  723. {
  724. return $this->personDesc;
  725. }
  726. /**
  727. * @param mixed $personDesc
  728. */
  729. public function setPersonDesc($personDesc): void
  730. {
  731. $this->personDesc = $personDesc;
  732. }
  733. /**
  734. * @return mixed
  735. */
  736. public function getPersonType()
  737. {
  738. return $this->personType;
  739. }
  740. /**
  741. * @param GlobalUser $globalUser
  742. */
  743. public function setGlobalUser(GlobalUser $globalUser): void
  744. {
  745. $this->globalUser = $globalUser;
  746. }
  747. /**
  748. * @return GlobalUser | null
  749. */
  750. public function getGlobalUser(): ?GlobalUser
  751. {
  752. return $this->globalUser ?? null;
  753. }
  754. /**
  755. * @return ExerpUser | null
  756. */
  757. public function getExerpUser(): ?ExerpUser
  758. {
  759. return $this->exerp_User ?? null;
  760. }
  761. /**
  762. * @param ExerpUser $exerp_User
  763. */
  764. public function setExerpUser(ExerpUser $exerp_User): void
  765. {
  766. $this->exerp_User = $exerp_User;
  767. }
  768. /**
  769. * @return mixed
  770. */
  771. public function getErrorCode()
  772. {
  773. return $this->errorCode;
  774. }
  775. /**
  776. * @param mixed $errorCode
  777. */
  778. public function setErrorCode($errorCode): void
  779. {
  780. $this->errorCode = $errorCode;
  781. }
  782. /**
  783. * @return mixed
  784. */
  785. public function getErrorDesc()
  786. {
  787. return $this->errorDesc;
  788. }
  789. /**
  790. * @param mixed $errorDesc
  791. */
  792. public function setErrorDesc($errorDesc): void
  793. {
  794. $this->errorDesc = $errorDesc;
  795. }
  796. /**
  797. * @return LeadLayerUser
  798. */
  799. public function getLeadLayerUser(): ?LeadLayerUser
  800. {
  801. return $this->leadLayer_User;
  802. }
  803. /**
  804. * @param LeadLayerUser $leadLayer_User
  805. */
  806. public function setLeadLayerUser(LeadLayerUser $leadLayer_User): void
  807. {
  808. $this->leadLayer_User = $leadLayer_User;
  809. }
  810. /**
  811. * @return mixed
  812. */
  813. public function getIsInLeadLayer()
  814. {
  815. return $this->isInLeadLayer;
  816. }
  817. /**
  818. * @param mixed $isInLeadLayer
  819. */
  820. public function setIsInLeadLayer($isInLeadLayer): void
  821. {
  822. $this->isInLeadLayer = $isInLeadLayer;
  823. }
  824. /**
  825. * @return mixed
  826. */
  827. public function getPartnerGroup()
  828. {
  829. return $this->partnerGroup;
  830. }
  831. /**
  832. * @param mixed $partnerGroup
  833. */
  834. public function setPartnerGroup($partnerGroup): void
  835. {
  836. $customerGroups = explode(",", $partnerGroup);
  837. if(count($customerGroups) > 1) {
  838. $this->partnerGroup = $customerGroups[1];
  839. } else {
  840. $this->partnerGroup = $customerGroups[0];
  841. }
  842. }
  843. /**
  844. * @return PartnerUser
  845. */
  846. public function getPartnerUser():? PartnerUser
  847. {
  848. return $this->partner_User;
  849. }
  850. /**
  851. * @param PartnerUser $partner_User
  852. */
  853. public function setPartnerUser(PartnerUser $partner_User)
  854. {
  855. $this->partner_User = $partner_User;
  856. }
  857. /**
  858. * @return mixed
  859. */
  860. public function getCustomerGroupId()
  861. {
  862. if($this->getExerpUser() != null && !empty($this->getExerpUser()->getCustomerGroup())) {
  863. $customerGroupId = $this->getCustomerGroupIdByName($this->getExerpUser()->getCustomerGroup());
  864. } else {
  865. if(!empty($this->getPartnerGroup())) {
  866. $customerGroupId = $this->getCustomerGroupIdByName($this->getPartnerGroup());
  867. if(empty($customerGroupId)) {
  868. $customerGroupId = $this->getCustomerGroupIdByVirginUserTypeCode($this->getPersonType());
  869. }
  870. } else {
  871. $customerGroupId = $this->getCustomerGroupIdByVirginUserTypeCode($this->getPersonType());
  872. }
  873. }
  874. return $customerGroupId;
  875. }
  876. private function registerFromGlobal(SalesChannelContext $context, $email, $password): CustomerEntity
  877. {
  878. $shopwareUserBasicData = [
  879. 'firstName' => $this->getGlobalUser()->getFirstName(),
  880. 'lastName' => $this->getGlobalUser()->getLastName(),
  881. 'salutationId' => $this->leadService->getDefaultSalutation($context),
  882. 'email' => $email,
  883. 'password' => $password,
  884. ];
  885. //registrazione implicita
  886. return $this->leadService->prepareRegistrationData($context, $shopwareUserBasicData, false);
  887. }
  888. /**
  889. * @param string|null $password
  890. * @return array|null
  891. */
  892. private function getUpdateShopwareFields(string $password=null): ?array
  893. {
  894. if (!$this->getCustomerEntity()){
  895. return null;
  896. }
  897. //clubentity
  898. $updateArray = [
  899. 'active' => true,
  900. 'group' => [
  901. 'id' => $this->getCustomerGroupId()
  902. ],
  903. 'extensions' => ['preferredClubId' => $this->getClubEntity() ? $this->getClubEntity()->getId() : null],
  904. ];
  905. if ($this->getCustomerEntity()->getFirstName() != $this->getGlobalUser()->getFirstName()) {
  906. $updateArray['firstName'] = $this->getGlobalUser()->getFirstName();
  907. }
  908. if ($this->getCustomerEntity()->getLastName() != $this->getGlobalUser()->getLastName()) {
  909. $updateArray['lastName'] = $this->getGlobalUser()->getLastName();
  910. }
  911. if ($password && !password_verify($password, $this->customerEntity->getPassword())){
  912. $updateArray['password'] = $password;
  913. }
  914. return $updateArray;
  915. }
  916. /**
  917. * @param SalesChannelContext $context
  918. * @return void
  919. */
  920. private function setClub(SalesChannelContext $context)
  921. {
  922. if ($this->getExerpUser()) {
  923. $criteria = new Criteria();
  924. $criteria->addFilter(new EqualsFilter('club.centerId', $this->getExerpUser()->getCenterId()));
  925. /** @var ClubEntity $clubEntity */
  926. $this->clubEntity = $this->clubRepository->search($criteria, $context->getContext())->first();
  927. }
  928. }
  929. /**
  930. * @return ClubEntity|null
  931. */
  932. public function getClubEntity(): ? ClubEntity
  933. {
  934. return $this->clubEntity;
  935. }
  936. /**
  937. * @return bool
  938. */
  939. private function getIsHomeTraining(): bool
  940. {
  941. return $this->getExerpUser()->getCenterId() == $this::HOME_TRAINING_CLUB_CODE;
  942. }
  943. private function isImplicit()
  944. {
  945. return $this->customerEntity->getCustomFields()['lead_implicit_registration'] ?? false;
  946. }
  947. /**
  948. * @return CustomerEntity|null
  949. */
  950. public function getCustomerEntity(): ?CustomerEntity
  951. {
  952. return $this->customerEntity;
  953. }
  954. /**
  955. * @param CustomerEntity|null $customerEntity
  956. * @return void
  957. */
  958. private function setCustomerEntity(?CustomerEntity $customerEntity)
  959. {
  960. $this->customerEntity = $customerEntity;
  961. }
  962. /**
  963. * @throws \Exception
  964. */
  965. public function getCurrentLead(){
  966. if (
  967. $this->session->get('leadUser') &&
  968. (new \DateTime())->diff(
  969. (new \DateTime())->setTimestamp($this->session->get('leadUser')['timestamp'])
  970. )->days > 30
  971. ) {
  972. $this->session->set('leadUser', null);
  973. throw new \Exception('Expired Lead');
  974. }
  975. if (isset($_COOKIE['leadUser'])){
  976. $this->session->set('leadUser', json_decode($_COOKIE['leadUser'], true));
  977. }
  978. return $this->session->get('leadUser');
  979. }
  980. /**
  981. * @param string|null $guid
  982. * @param string $email
  983. * @param string $firstName
  984. * @param string $lastName
  985. * @param string $phoneNumber
  986. * @param string $clubId
  987. * @param bool $privacy
  988. * @param string|null $timestamp
  989. * @param SalesChannelContext $context
  990. * @throws VirginApiException
  991. */
  992. public function saveCurrentLead(
  993. ?string $guid,
  994. string $email,
  995. string $firstName,
  996. string $lastName,
  997. string $phoneNumber,
  998. string $clubId,
  999. bool $privacy,
  1000. ?string $timestamp,
  1001. SalesChannelContext $context,
  1002. bool $skipUpsertLeadToLayer= false
  1003. ): void
  1004. {
  1005. $update = true;
  1006. if (!$guid){
  1007. $dateTime = new \DateTime();
  1008. $guid = $dateTime->getTimestamp() . $email;
  1009. $timestamp = $dateTime->getTimestamp();
  1010. $update = false;
  1011. }
  1012. $user = [
  1013. 'guid_lead' => $guid,
  1014. 'firstName' => $firstName,
  1015. 'lastName' => $lastName,
  1016. 'email' => $email,
  1017. 'phoneNumber' => $phoneNumber,
  1018. 'clubId' => $clubId,
  1019. 'privacy' => $privacy,
  1020. 'timestamp' => $timestamp,
  1021. ];
  1022. $this->session->set('leadUser', $user);
  1023. //todo
  1024. $privacyText = "";
  1025. if ($privacyText) {
  1026. $user['privacyJson'] = $privacyText;
  1027. }
  1028. if ($clubId == 'digital'){
  1029. return;
  1030. } else {
  1031. $criteria = new Criteria();
  1032. $criteria->addFilter(new EqualsFilter('club.id', $clubId));
  1033. /** @var ClubEntity $clubEntity */
  1034. $clubEntity = $this->clubRepository->search($criteria, $context->getContext())->first();
  1035. $user['guid_club'] = $clubEntity->getGuidVirgin();
  1036. $user['clubName'] = $clubEntity->getName();
  1037. }
  1038. if (!$skipUpsertLeadToLayer) {
  1039. $this->upsertLeadToLayer($user, $update ? $guid : null);
  1040. }
  1041. }
  1042. }