Newsletter.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. <?php
  2. namespace Dotdigitalgroup\Email\Controller\Customer;
  3. use Magento\Customer\Api\CustomerRepositoryInterface as CustomerRepository;
  4. use Magento\Newsletter\Model\Subscriber;
  5. class Newsletter extends \Magento\Framework\App\Action\Action
  6. {
  7. /**
  8. * @var \Dotdigitalgroup\Email\Helper\Data
  9. */
  10. private $helper;
  11. /**
  12. * @var \Magento\Customer\Model\Session
  13. */
  14. private $customerSession;
  15. /**
  16. * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
  17. */
  18. private $localeDate;
  19. /**
  20. * @var \Dotdigitalgroup\Email\Model\ConsentFactory
  21. */
  22. private $consentFactory;
  23. /**
  24. * @var \Magento\Framework\Data\Form\FormKey\Validator
  25. */
  26. private $formKeyValidator;
  27. /**
  28. * @var CustomerRepository
  29. */
  30. protected $customerRepository;
  31. /**
  32. * @var \Magento\Newsletter\Model\SubscriberFactory
  33. */
  34. protected $subscriberFactory;
  35. /**
  36. * Newsletter constructor.
  37. *
  38. * @param \Dotdigitalgroup\Email\Helper\Data $helper
  39. * @param \Magento\Customer\Model\Session $session
  40. * @param \Dotdigitalgroup\Email\Model\ConsentFactory $consentFactory
  41. * @param \Magento\Framework\App\Action\Context $context
  42. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  43. * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
  44. * @param CustomerRepository $customerRepository
  45. * @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
  46. */
  47. public function __construct(
  48. \Dotdigitalgroup\Email\Helper\Data $helper,
  49. \Magento\Customer\Model\Session $session,
  50. \Dotdigitalgroup\Email\Model\ConsentFactory $consentFactory,
  51. \Magento\Framework\App\Action\Context $context,
  52. \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
  53. \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
  54. CustomerRepository $customerRepository,
  55. \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
  56. ) {
  57. $this->helper = $helper;
  58. $this->customerSession = $session;
  59. $this->localeDate = $localeDate;
  60. $this->consentFactory = $consentFactory;
  61. $this->formKeyValidator = $formKeyValidator;
  62. $this->customerRepository = $customerRepository;
  63. $this->subscriberFactory = $subscriberFactory;
  64. parent::__construct($context);
  65. }
  66. /**
  67. * @return \Magento\Framework\App\ResponseInterface
  68. */
  69. public function execute()
  70. {
  71. if (! $this->formKeyValidator->validate($this->getRequest())) {
  72. return $this->_redirect('customer/account/');
  73. }
  74. $this->processGeneralSubscription();
  75. $website = $this->customerSession->getCustomer()->getStore()->getWebsite();
  76. //if enabled
  77. if ($this->helper->isEnabled($website)) {
  78. $customerEmail = $this->customerSession->getCustomer()->getEmail();
  79. $contactFromTable = $this->helper->getContactByEmail($customerEmail, $website->getId());
  80. $contactId = $this->getContactId($contactFromTable);
  81. $client = $this->helper->getWebsiteApiClient($website);
  82. $contact = isset($contactId) ? $client->getContactById($contactId) :
  83. $this->createContact($client, $customerEmail, $website, $contactFromTable);
  84. if (isset($contact->id)) {
  85. $additionalSubscriptionsSuccess = $this->processAdditionalSubscriptions(
  86. $contact,
  87. $client,
  88. $website
  89. );
  90. $contactDataFieldsSuccess = $this->processContactDataFields(
  91. $customerEmail,
  92. $client,
  93. $website
  94. );
  95. $contactPreferencesSuccess = $this->processContactPreferences($client, $contact);
  96. if (! $contactDataFieldsSuccess || ! $additionalSubscriptionsSuccess || ! $contactPreferencesSuccess) {
  97. $this->messageManager->addErrorMessage(
  98. __(
  99. 'An error occurred while saving your subscription preferences.'
  100. )
  101. );
  102. } else {
  103. $this->messageManager->addSuccessMessage(
  104. __('The subscription preferences has been saved.')
  105. );
  106. }
  107. } else {
  108. $this->messageManager->addErrorMessage(
  109. __(
  110. 'An error occurred while saving your subscription preferences.'
  111. )
  112. );
  113. }
  114. }
  115. return $this->_redirect('connector/customer/index/');
  116. }
  117. /**
  118. * @param $apiClient
  119. * @param string $customerEmail
  120. * @param $website
  121. * @param $contactFromTable
  122. *
  123. * @return object
  124. */
  125. private function createContact($apiClient, $customerEmail, $website, $contactFromTable)
  126. {
  127. $consentModel = $this->consentFactory->create();
  128. $consentData = $consentModel->getFormattedConsentDataByContactForApi(
  129. $website->getId(),
  130. $customerEmail
  131. );
  132. if (empty(! $consentData)) {
  133. $needToConfirm = $this->helper->getWebsiteConfig(
  134. \Magento\Newsletter\Model\Subscriber::XML_PATH_CONFIRMATION_FLAG,
  135. $website->getId()
  136. );
  137. $optInType = ($needToConfirm)? 'Double' : 'Single';
  138. $contactData = [
  139. 'Email' => $customerEmail,
  140. 'EmailType' => 'Html',
  141. 'OptInType' => $optInType,
  142. ];
  143. $contact = $apiClient->postContactWithConsent(
  144. $contactData,
  145. $consentData
  146. );
  147. } else {
  148. $contact = $apiClient->postContacts(
  149. $customerEmail
  150. );
  151. }
  152. if (isset($contact->id)) {
  153. $contactFromTable->setContactId($contact->id);
  154. $this->helper->saveContact($contactFromTable);
  155. }
  156. return $contact;
  157. }
  158. /**
  159. * @param Object $contact
  160. * @param \Dotdigitalgroup\Email\Model\Apiconnector\Client $client
  161. * @param \Magento\Store\Model\Website $website
  162. *
  163. * @return bool
  164. */
  165. private function processAdditionalSubscriptions($contact, $client, $website)
  166. {
  167. $additionalFromConfig = $this->helper->getAddressBookIdsToShow($website);
  168. if (!$this->helper->getCanShowAdditionalSubscriptions($website) ||
  169. empty($additionalFromConfig)) {
  170. return true;
  171. }
  172. $success = true;
  173. $additionalSubscriptions = $this->getRequest()->getParam('additional_subscriptions', []);
  174. foreach ($additionalFromConfig as $bookId) {
  175. if (in_array($bookId, $additionalSubscriptions)) {
  176. $bookResponse = $client->postAddressBookContacts(
  177. $bookId,
  178. $contact
  179. );
  180. if (isset($bookResponse->message)) {
  181. $success = false;
  182. }
  183. }
  184. }
  185. foreach ($additionalFromConfig as $bookId) {
  186. if (!in_array($bookId, $additionalSubscriptions)) {
  187. $client->deleteAddressBookContact(
  188. $bookId,
  189. $contact->id
  190. );
  191. }
  192. }
  193. return $success;
  194. }
  195. /**
  196. * @param string $customerEmail
  197. * @param \Dotdigitalgroup\Email\Model\Apiconnector\Client $client
  198. * @param \Magento\Store\Model\Website $website
  199. *
  200. * @return bool - success
  201. */
  202. private function processContactDataFields($customerEmail, $client, $website)
  203. {
  204. $paramDataFields = $this->getRequest()->getParam('data_fields', []);
  205. if (!$this->helper->getCanShowDataFields($website) ||
  206. empty($paramDataFields)) {
  207. return true;
  208. }
  209. $data = $this->getDataFields($client, $paramDataFields);
  210. $contactResponse = $client->updateContactDatafieldsByEmail(
  211. $customerEmail,
  212. $data
  213. );
  214. return !isset($contactResponse->message);
  215. }
  216. /**
  217. * @param \Dotdigitalgroup\Email\Model\Apiconnector\Client $client
  218. * @param array $paramDataFields
  219. * @return array
  220. */
  221. private function getDataFields($client, $paramDataFields)
  222. {
  223. $data = [];
  224. $dataFields = $client->getDataFields();
  225. $processedFields = [];
  226. foreach ($dataFields as $dataField) {
  227. $processedFields[$dataField->name] = $dataField->type;
  228. }
  229. foreach ($paramDataFields as $key => $value) {
  230. if (isset($processedFields[$key]) && $value) {
  231. if ($processedFields[$key] == 'Numeric') {
  232. $paramDataFields[$key] = (int)$value;
  233. }
  234. if ($processedFields[$key] == 'String') {
  235. $paramDataFields[$key] = (string)$value;
  236. }
  237. if ($processedFields[$key] == 'Date') {
  238. $paramDataFields[$key] = $this->localeDate->date($value)->format(\Zend_Date::ISO_8601);
  239. }
  240. $data[] = [
  241. 'Key' => $key,
  242. 'Value' => $paramDataFields[$key],
  243. ];
  244. }
  245. }
  246. return $data;
  247. }
  248. /**
  249. * @param \Dotdigitalgroup\Email\Model\Apiconnector\Client $client
  250. * @param Object $contact
  251. * @return bool
  252. */
  253. private function processContactPreferences($client, $contact)
  254. {
  255. $preferences = [];
  256. $paramPreferences = $this->getRequest()->getParam('preferences', []);
  257. $preferencesFromSession = $this->customerSession->getDmContactPreferences();
  258. if (empty($paramPreferences) || empty($preferencesFromSession)) {
  259. return true;
  260. }
  261. $preferences = $this->processParamPreferences($paramPreferences, $preferences);
  262. $preferences = $this->processPreferencesFromSession($preferencesFromSession, $preferences);
  263. foreach ($preferences as $id => $preference) {
  264. if (isset($preference["preferences"])) {
  265. $preferences[$id]["preferences"] = array_values($preference["preferences"]);
  266. }
  267. }
  268. $response = $client->setPreferencesForContact($contact->id, array_values($preferences));
  269. return !isset($response->message);
  270. }
  271. /**
  272. * @param array $paramPreferences
  273. * @param array $data
  274. * @return array
  275. */
  276. private function processParamPreferences($paramPreferences, $data)
  277. {
  278. foreach ($paramPreferences as $paramPreference) {
  279. $idsArray = explode(',', $paramPreference);
  280. if (count($idsArray) == 2) {
  281. if (isset($data[$idsArray[0]])) {
  282. $catPref = [
  283. "id" => $idsArray[1],
  284. "isPreference" => true,
  285. "isOptedIn" => true
  286. ];
  287. $data[$idsArray[0]]['preferences'][$idsArray[1]] = $catPref;
  288. } else {
  289. $data[$idsArray[0]] = [
  290. "id" => $idsArray[0],
  291. "isPreference" => false,
  292. "preferences" => [$idsArray[1] =>
  293. [
  294. "id" => $idsArray[1],
  295. "isPreference" => true,
  296. "isOptedIn" => true
  297. ]
  298. ]
  299. ];
  300. }
  301. } else {
  302. $data[$idsArray[0]] = [
  303. "id" => $idsArray[0],
  304. "isPreference" => true,
  305. "isOptedIn" => true
  306. ];
  307. }
  308. }
  309. return $data;
  310. }
  311. /**
  312. * @param array $preferencesFromSession
  313. * @param array $data
  314. *
  315. * @return array
  316. */
  317. private function processPreferencesFromSession($preferencesFromSession, $data)
  318. {
  319. foreach ($preferencesFromSession as $id => $preferenceFromSession) {
  320. if ($preferenceFromSession['isPreference'] && !isset($data[$id])) {
  321. $data[$id] = [
  322. "id" => $id,
  323. "isPreference" => true,
  324. "isOptedIn" => false
  325. ];
  326. } elseif (!$preferenceFromSession['isPreference']) {
  327. foreach ($preferenceFromSession["catPreferences"] as $catPrefId => $catPreference) {
  328. if (!isset($data[$id]["preferences"][$catPrefId])) {
  329. $data[$id]["preferences"][$catPrefId] = [
  330. "id" => $catPrefId,
  331. "isPreference" => true,
  332. "isOptedIn" => false
  333. ];
  334. }
  335. }
  336. }
  337. }
  338. return $data;
  339. }
  340. /**
  341. * @param $contactFromTable
  342. * @return mixed
  343. */
  344. private function getContactId($contactFromTable)
  345. {
  346. $contactId = null;
  347. if (!$this->customerSession->getConnectorContactId()) {
  348. $contactId = $this->customerSession->getConnectorContactId();
  349. } elseif ($contactFromTable->getContactId()) {
  350. $contactId = $contactFromTable->getContactId();
  351. }
  352. return $contactId;
  353. }
  354. /**
  355. * Process general subscription
  356. */
  357. private function processGeneralSubscription()
  358. {
  359. $customerId = $this->customerSession->getCustomerId();
  360. if ($customerId === null) {
  361. $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
  362. } else {
  363. try {
  364. $customer = $this->customerRepository->getById($customerId);
  365. $storeId = $this->helper->storeManager->getStore()->getId();
  366. $customer->setStoreId($storeId);
  367. $isSubscribedState = $customer->getExtensionAttributes()
  368. ->getIsSubscribed();
  369. $isSubscribedParam = (boolean)$this->getRequest()
  370. ->getParam('is_subscribed', false);
  371. if ($isSubscribedParam !== $isSubscribedState) {
  372. $this->customerRepository->save($customer);
  373. if ($isSubscribedParam) {
  374. $subscribeModel = $this->subscriberFactory->create()
  375. ->subscribeCustomerById($customerId);
  376. $subscribeStatus = $subscribeModel->getStatus();
  377. if ($subscribeStatus == Subscriber::STATUS_SUBSCRIBED) {
  378. $this->messageManager->addSuccess(__('We have saved your subscription.'));
  379. } else {
  380. $this->messageManager->addSuccess(__('A confirmation request has been sent.'));
  381. }
  382. } else {
  383. $this->subscriberFactory->create()
  384. ->unsubscribeCustomerById($customerId);
  385. $this->messageManager->addSuccess(__('We have removed your newsletter subscription.'));
  386. }
  387. } else {
  388. $this->messageManager->addSuccess(__('We have updated your subscription.'));
  389. }
  390. } catch (\Exception $e) {
  391. $this->messageManager->addError(__('Something went wrong while saving your subscription.'));
  392. }
  393. }
  394. }
  395. }