diff --git a/AbandonedCart/Model/AbandonedCartSendData.php b/AbandonedCart/Model/AbandonedCartSendData.php index 32904d8..290bea6 100644 --- a/AbandonedCart/Model/AbandonedCartSendData.php +++ b/AbandonedCart/Model/AbandonedCartSendData.php @@ -31,6 +31,7 @@ use Magento\Store\Model\App\Emulation as AppEmulation; use Magento\Store\Model\StoreManagerInterface; use Psr\Log\LoggerInterface; +use ActiveCampaign\Customer\Model\Customer; class AbandonedCartSendData extends AbstractModel { @@ -121,6 +122,11 @@ class AbandonedCartSendData extends AbstractModel */ private $quoteRepository; + /** + * @var Customer + */ + protected $customer; + /** * @var UrlInterface */ @@ -129,7 +135,6 @@ class AbandonedCartSendData extends AbstractModel private $customerId; - /** * AbandonedCartSendData constructor. * @param CustomerRepositoryInterface $customerRepository @@ -154,6 +159,7 @@ class AbandonedCartSendData extends AbstractModel * @param TimezoneInterface $dateTime * @param CartRepositoryInterface $quoteRepository * @param UrlInterface $urlBuilder + * @param Customer $customer */ public function __construct( CustomerRepositoryInterface $customerRepository, @@ -177,7 +183,8 @@ public function __construct( CustomerModel $customerModel, TimezoneInterface $dateTime, CartRepositoryInterface $quoteRepository, - UrlInterface $urlBuilder + UrlInterface $urlBuilder, + Customer $customer ) { $this->urlBuilder = $urlBuilder; @@ -202,6 +209,7 @@ public function __construct( $this->customerModel = $customerModel; $this->dateTime = $dateTime; $this->quoteRepository = $quoteRepository; + $this->customer = $customer; } /** @@ -236,89 +244,46 @@ public function sendAbandonedCartData($quoteId = null): array $abandonedCarts->getSelect()->join(array('address' => $abandonedCarts->getResource()->getTable('quote_address')), 'main_table.entity_id = address.quote_id') ->where("address.address_type='billing' and (main_table.customer_email is not null or address.email is not null)"); foreach ($abandonedCarts as $abandonedCart) { - $connectionId = $this->coreHelper->getConnectionId($abandonedCart->getStoreId()); - $customerId = $abandonedCart->getCustomerId(); + $connectionId = $this->coreHelper->getConnectionId($abandonedCart->getStoreId()); $quote = $this->quoteRepository->get($abandonedCart->getEntityId()); - + $AcCustomer = NULL; if ($this->isGuest($quote)) { $customerEmail = $quote->getBillingAddress()->getEmail(); - if (!$customerEmail) { $result['error'] = __('Customer Email does not exist.'); continue; } - - if (!$this->isGuest($quote)) { - $websiteId = $this->storeManager->getStore($abandonedCart->getStoreId())->getWebsiteId(); - $customerModel = $this->customerModel; - $customerModel->setWebsiteId($websiteId); - $customerModel->loadByEmail($customerEmail); - if ($customerModel->getId()) { - $this->customerId = $customerModel->getId(); - } else { - $this->customerId = $customerEmail; - } - } else { - $this->customerId = $customerEmail; - } - - $this->createEcomCustomer($this->customerId, $quote); - - if (!$this->isGuest($quote)) { - $customerModel = $this->customerFactory->create(); - $this->customerResource->load($customerModel, $this->customerId); - - if ($customerModel->getAcCustomerId()) { - $this->customerId = $customerModel->getAcCustomerId(); - } else { - if ($quote->getAcTempCustomerId()) { - $this->customerId = $quote->getAcTempCustomerId(); - } else { - $AcCustomer = $this->curl->listAllCustomers( - self::GET_METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $customerEmail - ); - foreach ($AcCustomer['data']['ecomCustomers'] as $Ac) { - if ($Ac['connectionid'] === $connectionId) { - $this->customerId = $Ac['id']; - } - } - } - } - } - - if ($this->isGuest($quote)) { - $this->customerId = $quote->getAcTempCustomerId(); - } + $contact['email'] = $quote->getBillingAddress()->getEmail(); + $contact['firstName'] = $quote->getBillingAddress()->getFirstname(); + $contact['lastName'] = $quote->getBillingAddress()->getLastname(); + $contact['phone'] = $quote->getBillingAddress()->getTelephone(); + $contact['fieldValues'] = []; + $AcCustomer = $this->customer->createGuestCustomer($contact,$quote->getStoreId()); } else { - $this->createEcomCustomer($abandonedCart->getCustomerId(), $quote); - $customerEmail = $abandonedCart->getCustomerEmail(); - $customerModel = $this->customerFactory->create(); - $this->customerResource->load($customerModel, $customerId); - if ($customerModel->getAcCustomerId()) { - $this->customerId = $customerModel->getAcCustomerId(); - } + $AcCustomer = $this->customer->updateCustomer($this->getCustomer($abandonedCart->getCustomerId())); } + $this->customerId = $AcCustomer['ac_customer_id']; + $this->saveCustomerResultQuote($quote,$this->customerId); + $abandonedCart->collectTotals(); $quoteItemsData = $this->getQuoteItemsData($abandonedCart->getEntityId(), $abandonedCart->getStoreId()); - + $abandonedCartRepository = $this->quoteRepository->get($abandonedCart->getId()); $abandonedCartData = [ "ecomOrder" => [ "externalcheckoutid" => $abandonedCart->getEntityId(), "source" => 1, - "email" => $customerEmail, + "email" => $quote->getBillingAddress()->getEmail(), "orderProducts" => $quoteItemsData, "orderDiscounts" => [ "discountAmount" => $this->coreHelper->priceToCents($abandonedCart->getDiscountAmount()) ], "orderUrl" => $this->urlBuilder->getDirectUrl('checkout/cart'), - "abandonedDate" => $this->dateTime->date($abandonedCart->getCreatedAt())->format('Y-m-d H:i:s'), - "externalCreatedDate" => $this->dateTime->date($abandonedCart->getCreatedAt())->format('Y-m-d H:i:s'), - "externalUpdatedDate" => $this->dateTime->date($abandonedCart->getUpdatedAt())->format('Y-m-d H:i:s'), - "shippingMethod" => $abandonedCart->getShippingMethod(), + "abandonedDate" => $this->dateTime->date(strtotime($abandonedCartRepository->getUpdatedAt()))->format('Y-m-d\TH:i:sP'), + "externalCreatedDate" => $this->dateTime->date(strtotime($abandonedCartRepository->getCreatedAt()))->format('Y-m-d\TH:i:sP'), + "externalUpdatedDate" => $this->dateTime->date(strtotime($abandonedCartRepository->getUpdatedAt()))->format('Y-m-d\TH:i:sP'), + "shippingMethod" => $abandonedCart->getShippingAddress()->getShippingMethod(), "totalPrice" => $this->coreHelper->priceToCents($abandonedCart->getGrandTotal()), "shippingAmount" => $this->coreHelper->priceToCents($abandonedCart->getShippingAmount()), "taxAmount" => $this->coreHelper->priceToCents($abandonedCart->getTaxAmount()), @@ -331,7 +296,6 @@ public function sendAbandonedCartData($quoteId = null): array ]; try { - if (is_null($abandonedCart->getAcSyncedDate())) { $abandonedCartResult = $this->curl->sendRequestAbandonedCart( self::METHOD, @@ -349,7 +313,18 @@ public function sendAbandonedCartData($quoteId = null): array if ($abandonedCartResult['success']) { $syncStatus = CronConfig::SYNCED; } else { - $syncStatus = CronConfig::FAIL_SYNCED; + if(!$abandonedCartResult['success'] && $abandonedCartResult['status'] == "404"){ + $abandonedCartResult = $this->curl->sendRequestAbandonedCart( + self::UPDATE_METHOD, + self::ABANDONED_CART_URL_ENDPOINT . "/" . (int)$abandonedCart->getAcOrderSyncId(), + $abandonedCartData + ); + } + if ($abandonedCartResult['success']) { + $syncStatus = CronConfig::SYNCED; + }else{ + $syncStatus = CronConfig::FAIL_SYNCED; + } } if (isset($abandonedCartResult['data']['ecomOrder']['id'])) { @@ -391,7 +366,7 @@ private function getQuoteItemsData($entityId, $storeId): array $quoteItemsData[] = [ "externalid" => $quoteItem->getItemId(), "name" => $quoteItem->getName(), - "price" => $this->coreHelper->priceToCents($quoteItem->getPrice()), + "price" => $this->coreHelper->priceToCents($quoteItem->getPriceInclTax()), "quantity" => $quoteItem->getQty(), "sku" => $quoteItem->getSku(), "description" => $quoteItem->getDescription(), @@ -445,172 +420,12 @@ private function getTelephone($billingId = null): ?string return null; } - /** - * @param $customerId - * @return array - * @throws LocalizedException - * @throws NoSuchEntityException - */ - private function getFieldValues($customerId): array - { - $fieldValues = []; - $customAttributes = $this->customerRepository->getById($customerId)->getCustomAttributes(); - if (!empty($customAttributes)) { - foreach ($customAttributes as $attribute) { - $attributeId = $this->eavAttribute->getIdByCode(CustomerModel::ENTITY, $attribute->getAttributeCode()); - $attributeValues['field'] = $attributeId; - $attributeValues['value'] = $attribute->getValue(); - $fieldValues[] = $attributeValues; - } - } - return $fieldValues; - } public function isGuest($quote): bool { return is_null($quote->getCustomerId()); } - /** - * @param $customerId - * @return void - */ - private function createEcomCustomer($customerId, $quote): void - { - - try { - $ecomCustomerId = 0; - $contact = []; - - if (!$this->isGuest($quote)) { - $customer = $this->getCustomer($customerId); - $customerId = $customer->getId(); - $contact['email'] = $customer->getEmail(); - $customerEmail = $customer->getEmail(); - $contact['firstName'] = $customer->getFirstname(); - $contact['lastName'] = $customer->getLastname(); - $contact['phone'] = $this->getTelephone($customer->getDefaultBilling()); - $contact['fieldValues'] = $this->getFieldValues($customerId); - } else { - $customerId = $quote->getBillingAddress()->getEmail(); - $contact['email'] = $quote->getBillingAddress()->getEmail(); - $customerEmail = $quote->getBillingAddress()->getEmail(); - $contact['firstName'] = $quote->getBillingAddress()->getFirstname(); - $contact['lastName'] = $quote->getBillingAddress()->getLastname(); - $contact['phone'] = $quote->getBillingAddress()->getTelephone(); - $contact['fieldValues'] = []; - } - - - $contactData['contact'] = $contact; - - $contactResult = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT, $contactData); - - $contactId = $contactResult['data']['contact']['id'] ?? null; - - $connectionid = $this->coreHelper->getConnectionId($quote->getStoreId()); - - if (!$this->isGuest($quote)) { - if (isset($contactResult['data']['contact']['id'])) { - if (!$customer->getAcCustomerId()) { - $ecomCustomer['connectionid'] = $connectionid; - $ecomCustomer['externalid'] = $customerId; - $ecomCustomer['email'] = $customerEmail; - $ecomCustomer['acceptsMarketing'] = 1; - $ecomCustomerData['ecomCustomer'] = $ecomCustomer; - $AcCustomer = $this->curl->listAllCustomers( - self::GET_METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $customerEmail - ); - if (isset($AcCustomer['data']['ecomCustomers'][0])) { - foreach ($AcCustomer['data']['ecomCustomers'] as $Ac) { - if ($Ac['connectionid'] === $connectionid) { - $ecomCustomerId = $Ac['id']; - } - } - } - if (!$ecomCustomerId) { - $ecomCustomerResult = $this->curl->createContacts( - self::METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $ecomCustomerData - ); - $ecomCustomerId = $ecomCustomerResult['data']['ecomCustomer']['id'] ?? null; - } - } else { - $ecomCustomerId = $customer->getAcCustomerId(); - } - } - } - - if ($this->isGuest($quote)) { - - $ecomCustomerResult = $this->curl->listAllCustomers( - self::GET_METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $quote->getBillingAddress()->getEmail() - ); - if (isset($ecomCustomerResult['data']['ecomCustomers'][0])) { - foreach ($ecomCustomerResult['data']['ecomCustomers'] as $Ac) { - if ($Ac['connectionid'] === $connectionid) { - $ecomCustomerId = $Ac['id']; - } - } - } else { - $ecomCustomerData = [ - "ecomCustomer" => [ - "connection" => $connectionid, - 'externals' => $quote->getBillingAddress()->getEmail(), - 'email' => $quote->getBillingAddress()->getEmail(), - ] - ]; - $ecomCustomerResult = $this->curl->createContacts( - self::METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $ecomCustomerData - ); - $ecomCustomerId = $ecomCustomerResult['data']['ecomCustomer']['id'] ?? null; - } - } - if ($ecomCustomerId !== 0) { - $syncStatus = CronConfig::SYNCED; - } else { - $syncStatus = CronConfig::FAIL_SYNCED; - } - - if ($this->isGuest($quote)) { - $this->saveCustomerResultQuote($quote, $ecomCustomerId); - } else { - $this->saveCustomerResult($customerId, $syncStatus, $contactId, $ecomCustomerId); - } - } catch - (\Exception $e) { - $this->logger->critical("MODULE AbandonedCart: " . $e->getMessage()); - } catch (GuzzleException $e) { - $this->logger->critical("MODULE AbandonedCart: " . $e->getMessage()); - } - } - - /** - * @param $customerId - * @param $syncStatus - * @param $contactId - * @param $ecomCustomerId - * @throws AlreadyExistsException - */ - private function saveCustomerResult($customerId, $syncStatus, $contactId, $ecomCustomerId): void - { - if (is_numeric($customerId)) { - $customerModel = $this->customerFactory->create(); - $this->customerResource->load($customerModel, $customerId); - $customerModel->setAcSyncStatus($syncStatus); - $customerModel->setAcContactId($contactId); - $customerModel->setAcCustomerId($ecomCustomerId); - $this->customerResource->save($customerModel); - } - } - /** * @param $quote * @param $ecomCustomerId diff --git a/AbandonedCart/composer.json b/AbandonedCart/composer.json index e1eea16..4a4a5ec 100644 --- a/AbandonedCart/composer.json +++ b/AbandonedCart/composer.json @@ -9,7 +9,7 @@ "config": { "sort-packages": true }, - "version": "2.1.3", + "version": "2.1.5", "require": { "php": "~7.3.0||~7.4.0||~8.0||~8.1||~8.2", "activecampaign/core": "2.1.*" diff --git a/AbandonedCart/etc/module.xml b/AbandonedCart/etc/module.xml index 00fd351..ea1bfb8 100644 --- a/AbandonedCart/etc/module.xml +++ b/AbandonedCart/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/Core/Helper/Curl.php b/Core/Helper/Curl.php index ea1a5e2..7ff8970 100644 --- a/Core/Helper/Curl.php +++ b/Core/Helper/Curl.php @@ -394,6 +394,7 @@ private function sendRequest( $this->logger->critical('MODULE Core: ' . $e->getMessage()); $result['success'] = false; + $result['status'] = $e->getCode(); $result['message'] = $e->getMessage(); } diff --git a/Core/composer.json b/Core/composer.json index 53af9e7..4fe634a 100644 --- a/Core/composer.json +++ b/Core/composer.json @@ -9,7 +9,7 @@ "config": { "sort-packages": true }, - "version": "2.1.1", + "version": "2.1.2", "require": { "php": "~7.3.0||~7.4.0||~8.0||~8.1||~8.2" }, diff --git a/Core/etc/module.xml b/Core/etc/module.xml index 37f3908..bed71bd 100644 --- a/Core/etc/module.xml +++ b/Core/etc/module.xml @@ -1,4 +1,4 @@ - + diff --git a/Customer/Controller/Adminhtml/Customer/MassSync.php b/Customer/Controller/Adminhtml/Customer/MassSync.php index dd93d86..be70c02 100644 --- a/Customer/Controller/Adminhtml/Customer/MassSync.php +++ b/Customer/Controller/Adminhtml/Customer/MassSync.php @@ -15,6 +15,7 @@ use Magento\Ui\Component\MassAction\Filter; use Psr\Log\LoggerInterface; + class MassSync extends AbstractMassAction implements HttpPostActionInterface { const CONTACT_ENDPOINT = "contact/sync"; @@ -78,30 +79,8 @@ public function massAction(AbstractCollection $collection) foreach ($collection->getAllIds() as $customerId) { if (!empty($customerId)) { try { - $contactData = $this->customer->getContactData($customerId); - $isEcomCustomer = $contactData['contact']['isEcomCustomer']; - - unset($contactData['contact']['isEcomCustomer']); - - $contactResult = $this->curl->createContacts( - self::METHOD, - self::CONTACT_ENDPOINT, - $contactData - ); - $contactId = isset($contactResult['data']['contact']['id']) ? $contactResult['data']['contact']['id'] : null; - $syncStatus = ($contactResult['success']) ? CronConfig::SYNCED : CronConfig::FAIL_SYNCED; - - if ($contactResult['success'] && !$isEcomCustomer) { - $ecomCustomerData = $this->customer->getEcomCustomerData($customerId); - $ecomCustomerResult = $this->curl->createContacts( - self::METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $ecomCustomerData - ); - $ecomCustomerId = isset($ecomCustomerResult['data']['ecomCustomer']['id']) ? $ecomCustomerResult['data']['ecomCustomer']['id'] : null; - } - - $this->customer->saveResult($customerId, $syncStatus, $contactId, $ecomCustomerId); + $customer = $this->customer->getCustomerById($customerId); + $this->customer->updateCustomer($customer); } catch (\Exception $exception) { $this->logger->critical("MODULE: Customer " . $exception); } diff --git a/Customer/Cron/CustomerSync.php b/Customer/Cron/CustomerSync.php index fa54e14..a057c7e 100644 --- a/Customer/Cron/CustomerSync.php +++ b/Customer/Cron/CustomerSync.php @@ -2,269 +2,32 @@ namespace ActiveCampaign\Customer\Cron; -use ActiveCampaign\Core\Helper\Curl; -use ActiveCampaign\Core\Helper\Data as CoreHelper; -use ActiveCampaign\Customer\Helper\Data as CustomerHelper; -use ActiveCampaign\Customer\Model\Config\CronConfig; -use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Customer\Api\CustomerRepositoryInterface; -use Magento\Customer\Model\Customer; -use Magento\Customer\Model\CustomerFactory; -use Magento\Customer\Model\ResourceModel\Customer as CustomerResource; -use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerResourceCollectionFactory; -use Magento\Eav\Model\ResourceModel\Entity\Attribute; -use Psr\Log\LoggerInterface; -use Magento\Framework\App\Cache\TypeListInterface; +use ActiveCampaign\Customer\Model\Customer; + class CustomerSync { - const AC_SYNC_STATUS = "ac_sync_status"; - - const CONTACT_ENDPOINT = "contacts"; - - const ECOM_CUSTOMER_ENDPOINT = "ecomCustomers"; - - const METHOD = "POST"; - - const METHOD_PUT = "PUT"; - - /** - * @var CustomerRepositoryInterface - */ - protected $customerRepository; - - /** - * @var AddressRepositoryInterface - */ - protected $addressRepository; - - /** - * @var CustomerResourceCollectionFactory - */ - protected $customerResourceCollectionFactory; - - /** - * @var CustomerFactory - */ - protected $customerFactory; - - /** - * @var CustomerResource - */ - protected $customerResource; - - /** - * @var Attribute - */ - protected $eavAttribute; - - /** - * @var CustomerHelper - */ - protected $customerHelper; - - /** - * @var CoreHelper - */ - private $coreHelper; /** - * @var Curl + * @var Customer */ - protected $curl; + protected $customer; - /** - * @var LoggerInterface - */ - protected $logger; - - /** - * @var CacheTypeList - */ - protected $cacheTypeList; /** * CustomerSync constructor. - * @param CustomerRepositoryInterface $customerRepository - * @param AddressRepositoryInterface $addressRepository - * @param CustomerResourceCollectionFactory $customerResourceCollectionFactory - * @param CustomerFactory $customerFactory - * @param CustomerResource $customerResource - * @param Attribute $eavAttribute - * @param CustomerHelper $customerHelper - * @param CoreHelper $coreHelper - * @param Curl $curl - * @param LoggerInterface $logger + * @param Customer $customer */ public function __construct( - CustomerRepositoryInterface $customerRepository, - AddressRepositoryInterface $addressRepository, - CustomerResourceCollectionFactory $customerResourceCollectionFactory, - CustomerFactory $customerFactory, - CustomerResource $customerResource, - Attribute $eavAttribute, - CustomerHelper $customerHelper, - CoreHelper $coreHelper, - Curl $curl, - LoggerInterface $logger, - TypeListInterface $cacheTypeList - ) { - $this->customerRepository = $customerRepository; - $this->addressRepository = $addressRepository; - $this->customerResourceCollectionFactory = $customerResourceCollectionFactory; - $this->customerFactory = $customerFactory; - $this->customerResource = $customerResource; - $this->eavAttribute = $eavAttribute; - $this->customerHelper = $customerHelper; - $this->coreHelper = $coreHelper; - $this->curl = $curl; - $this->logger = $logger; - $this->cacheTypeList = $cacheTypeList; - } - - public function execute() - { - if ($this->customerHelper->isCustomerSyncingEnabled()) { - $contact = []; - $ecomCustomer = []; - $this->updateCustomers(); - $numberOfCustomers = (int)$this->customerHelper->getNumberOfCustomers(); - - $customers = $this->customerResourceCollectionFactory->create() - ->addAttributeToFilter([ - ['attribute' => self::AC_SYNC_STATUS,'null' => true ], - ['attribute' => self::AC_SYNC_STATUS,'neq' => CronConfig::SYNCED ] - ]) - ->setPageSize($numberOfCustomers); - - foreach ($customers as $customer) { - $contactId = 0; - $customerId = $customer->getId(); - $ecomCustomerId = 0; - $syncStatus = CronConfig::NOT_SYNCED; - $contactData = $this->contactBody($customer); - - try { - $contactResult = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT, $contactData); - $contactId = isset($contactResult['data']['contact']['id']) ? $contactResult['data']['contact']['id'] : null; - - if ($contactResult['success']) { - $ecomCustomer['connectionid'] = $this->coreHelper->getConnectionId($customer->getStoreId()); - $ecomCustomer['externalid'] = $customerId; - $ecomCustomer['email'] = $customer->getEmail(); - $ecomCustomer['acceptsMarketing'] = 1; - $ecomCustomerData['ecomCustomer'] = $ecomCustomer; - $ecomCustomerResult = $this->curl->createContacts( - self::METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $ecomCustomerData - ); - $ecomCustomerId = isset($ecomCustomerResult['data']['ecomCustomer']['id']) ? $ecomCustomerResult['data']['ecomCustomer']['id'] : null; - $syncStatus = CronConfig::SYNCED; - } else { - $syncStatus = CronConfig::FAIL_SYNCED; - } - - $this->saveResult($customerId, $syncStatus, $contactId, $ecomCustomerId); - } catch (\Exception $e) { - $this->logger->critical("MODULE: Customer " . $e); - } - } - } - } - - /** - * @param $customerId - * @param $syncStatus - * @param $contactId - * @param $ecomCustomerId - * @throws \Magento\Framework\Exception\AlreadyExistsException - */ - private function saveResult($customerId, $syncStatus, $contactId, $ecomCustomerId) + Customer $customer + ) { - $customerModel = $this->customerFactory->create(); - if ($customerId) { - $this->customerResource->load($customerModel, $customerId); - } - $customerModel->setAcSyncStatus($syncStatus); - $customerModel->setAcContactId($contactId); - $customerModel->setAcCustomerId($ecomCustomerId); - - $this->customerResource->save($customerModel); + $this->customer = $customer; } - /** - * @param null $billingId - * @return string|null - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function getTelephone($billingId = null) - { - if ($billingId) { - $address = $this->addressRepository->getById($billingId); - return $address->getTelephone(); - } - return null; - } - - /** - * @param $customerId - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException - */ - private function getFieldValues($customerId) + public function execute() { - $fieldValues = []; - $customAttributes = $this->customerRepository->getById($customerId)->getCustomAttributes(); - if (!empty($customAttributes)) { - foreach ($customAttributes as $attribute) { - $attributeId = $this->eavAttribute->getIdByCode(Customer::ENTITY, $attribute->getAttributeCode()); - $attributeValues['field'] = $attributeId; - $attributeValues['value'] = $attribute->getValue(); - $fieldValues[] = $attributeValues; - } - } - return $fieldValues; + $this->customer->syncCustomers(); } - public function updateCustomers(){ - - $numberOfCustomers = (int)$this->customerHelper->getNumberOfCustomers(); - $customers = $this->customerResourceCollectionFactory->create() - ->addAttributeToSelect('ac_contact_id') - ->addAttributeToFilter( 'ac_contact_id',['neq' => null ]) - ->addAttributeToFilter( self::AC_SYNC_STATUS,['eq' => CronConfig::SYNCED ]) - ->addAttributeToFilter('updated_at',['gt' => $this->customerHelper->getLastCustomerUpdateSync()]) - ->setOrder('updated_at','asc') - ->setPageSize($numberOfCustomers); - foreach ($customers as $customer){ - $contactData = $this->contactBody($customer); - $lastUpdate = $this->customerHelper->getLastCustomerUpdateSync(); - try { - $this->curl->createContacts(self::METHOD_PUT, self::CONTACT_ENDPOINT.'/'.$customer->getAcContactId(), $contactData); - $lastUpdate = $customer->getUpdatedAt(); - } catch (\Exception $e) { - $this->logger->critical("MODULE: Customer contact/sync" . $e); - } - } - if(isset($lastUpdate)) { - $this->customerHelper->setLastCustomerUpdateSync($lastUpdate); - $this->cacheTypeList->cleanType('config'); - } - } - - - private function contactBody($customer){ - $customerId = $customer->getId(); - $contact['email'] = $customer->getEmail(); - $contact['firstName'] = $customer->getFirstname(); - $contact['lastName'] = $customer->getLastname(); - $contact['phone'] = $this->getTelephone($customer->getDefaultBilling()); - - $contact['fieldValues'] = $this->getFieldValues($customerId); - $contactData['contact'] = $contact; - - return $contactData; - } } diff --git a/Customer/Model/AcSyncStatus.php b/Customer/Model/AcSyncStatus.php index 53b275b..c32fb99 100644 --- a/Customer/Model/AcSyncStatus.php +++ b/Customer/Model/AcSyncStatus.php @@ -2,28 +2,40 @@ namespace ActiveCampaign\Customer\Model; -use \ActiveCampaign\Customer\Model\Config\CronConfig; +use ActiveCampaign\Customer\Model\Config\CronConfig; -class AcSyncStatus implements \Magento\Framework\Data\OptionSourceInterface +class AcSyncStatus extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource implements \Magento\Framework\Data\OptionSourceInterface { /** * {@inheritdoc} */ public function toOptionArray() { - return [ - [ - 'value' => CronConfig::SYNCED, - 'label' => __('Synced'), - ], - [ - 'value' => CronConfig::NOT_SYNCED, - 'label' => __('Not Synced'), - ], - [ - 'value' => CronConfig::FAIL_SYNCED, - 'label' => __('Not Synced'), - ], - ]; + if ($this->_options === null) { + $this->_options = [ + [ + 'value' => CronConfig::SYNCED, + 'label' => __('Synced')->getText(), + ], + [ + 'value' => CronConfig::NOT_SYNCED, + 'label' => __('Not Synced')->getText(), + ], + [ + 'value' => CronConfig::FAIL_SYNCED, + 'label' => __('Not Synced')->getText(), + ], + ]; + } + return $this->_options; + } + + /** + * @inheritdoc + */ + public function getAllOptions($withEmpty = true, $defaultValues = false) + { + return $this->toOptionArray(); + } } diff --git a/Customer/Model/Customer.php b/Customer/Model/Customer.php index 9f2f77c..8a78223 100644 --- a/Customer/Model/Customer.php +++ b/Customer/Model/Customer.php @@ -2,36 +2,63 @@ namespace ActiveCampaign\Customer\Model; +use ActiveCampaign\Core\Helper\Curl; use ActiveCampaign\Core\Helper\Data as CoreHelper; -use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Customer\Api\CustomerRepositoryInterface; +use ActiveCampaign\Customer\Helper\Data as CustomerHelper; +use ActiveCampaign\Customer\Model\Config\CronConfig; +use \Magento\Customer\Api\AddressRepositoryInterface; use Magento\Customer\Model\CustomerFactory; use Magento\Customer\Model\ResourceModel\Customer as CustomerResource; +use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerResourceCollectionFactory; use Magento\Eav\Model\ResourceModel\Entity\Attribute; - +use Magento\Framework\App\Cache\TypeListInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Psr\Log\LoggerInterface; +use Magento\Customer\Model\Customer as MageCustomer; +use Magento\Newsletter\Model\SubscriberFactory; +use Magento\Store\Model\StoreManagerInterface; class Customer { const AC_CUSTOMER_ID = 'ac_customer_id'; + const AC_SYNC_STATUS = "ac_sync_status"; + + const CONTACT_ENDPOINT = "contacts"; + + const ECOM_CUSTOMER_ENDPOINT = "ecomCustomers"; + + const METHOD = "POST"; + const GET_METHOD = "GET"; + const METHOD_PUT = "PUT"; + + + /** - * @var bool + * @var AddressRepositoryInterface */ - private $isEcomCustomer = false; + protected $addressRepository; /** - * @var CustomerRepositoryInterface + * @var CustomerResourceCollectionFactory */ - protected $customerRepository; + protected $customerResourceCollectionFactory; /** - * @var AddressRepositoryInterface + * @var CustomerFactory */ - protected $addressRepository; + protected $customerFactory; /** - * @var Attribute + * @var CustomerResource */ - protected $eavAttribute; + protected $customerResource; + + + + /** + * @var CustomerHelper + */ + protected $customerHelper; /** * @var CoreHelper @@ -39,77 +66,106 @@ class Customer private $coreHelper; /** - * @var CustomerFactory + * @var Curl */ - protected $customerFactory; + protected $curl; /** - * @var CustomerResource + * @var TypeListInterface */ - protected $customerResource; + protected $cacheTypeList; + + /** + * @var Attribute + */ + protected $eavAttribute; + + /** + * @var CustomerRepositoryInterface + */ + protected $customerRepository; + + /** + * @var LoggerInterface + */ + protected $logger; + + /** + * @var StoreManagerInterface + */ + protected $storeManager; /** * Customer constructor. - * @param CustomerRepositoryInterface $customerRepository - * @param AddressRepositoryInterface $addressRepository - * @param Attribute $eavAttribute - * @param CoreHelper $coreHelper + * @param CustomerResourceCollectionFactory $customerResourceCollectionFactory + * @param CustomerRepositoryInterface $customerRepositoryInterface * @param CustomerFactory $customerFactory * @param CustomerResource $customerResource + * @param CustomerHelper $customerHelper + * @param CoreHelper $coreHelper + * @param Curl $curl + * @param Attribute $eavAttribute + * @param TypeListInterface $cacheTypeList + * @param LoggerInterface $logger + * @param SubscriberFactory $subscriberFactory + * @param AddressRepositoryInterface $addressRepository */ public function __construct( - CustomerRepositoryInterface $customerRepository, - AddressRepositoryInterface $addressRepository, - Attribute $eavAttribute, - CoreHelper $coreHelper, + CustomerResourceCollectionFactory $customerResourceCollectionFactory, + CustomerRepositoryInterface $customerRepositoryInterface, CustomerFactory $customerFactory, - CustomerResource $customerResource + CustomerResource $customerResource, + CustomerHelper $customerHelper, + CoreHelper $coreHelper, + Curl $curl, + Attribute $eavAttribute, + TypeListInterface $cacheTypeList, + LoggerInterface $logger, + SubscriberFactory $subscriberFactory, + AddressRepositoryInterface $addressRepository, + StoreManagerInterface $storeManager ) { - $this->customerRepository = $customerRepository; - $this->addressRepository = $addressRepository; - $this->eavAttribute = $eavAttribute; - $this->coreHelper = $coreHelper; + + $this->customerResourceCollectionFactory = $customerResourceCollectionFactory; + $this->customerRepository = $customerRepositoryInterface; $this->customerFactory = $customerFactory; $this->customerResource = $customerResource; + $this->customerHelper = $customerHelper; + $this->coreHelper = $coreHelper; + $this->curl = $curl; + $this->cacheTypeList = $cacheTypeList; + $this->eavAttribute = $eavAttribute; + $this->logger = $logger; + $this->subscriberFactory = $subscriberFactory; + $this->addressRepository = $addressRepository; + $this->storeManager = $storeManager; } /** * @param $customerId - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @return MageCustomer */ - public function getContactData($customerId) - { - $contact = []; - $customer = $this->customerRepository->getById($customerId); - - $contact['email'] = $customer->getEmail(); - $contact['firstName'] = $customer->getFirstname(); - $contact['lastName'] = $customer->getLastname(); - $contact['phone'] = $this->getTelephone($customer->getDefaultBilling()); - $contact['fieldValues'] = $this->getFieldValues($customer->getCustomAttributes()); - $contact['isEcomCustomer'] = $this->isEcomCustomer; - $contactData['contact'] = $contact; + public function getCustomerById($customerId){ + $customerModel = $this->customerFactory->create(); + $this->customerResource->load($customerModel, $customerId); - return $contactData; + return $customerModel; } + /** - * @param $customerId + * @param $customer * @return array * @throws \Magento\Framework\Exception\LocalizedException * @throws \Magento\Framework\Exception\NoSuchEntityException */ - public function getEcomCustomerData($customerId) + public function getEcomCustomerData($customer) { $ecomCustomer = []; - $customer = $this->customerRepository->getById($customerId); - $ecomCustomer['connectionid'] = $this->coreHelper->getConnectionId($customer->getStoreId()); $ecomCustomer['externalid'] = $customer->getId(); $ecomCustomer['email'] = $customer->getEmail(); - $ecomCustomerData['acceptsMarketing'] = 1; + $ecomCustomerData['acceptsMarketing'] = (int)$this->subscriberFactory->create()->loadByCustomer($customer->getId(),$customer->getWebsiteId())->isSubscribed(); $ecomCustomerData['ecomCustomer'] = $ecomCustomer; return $ecomCustomerData; @@ -129,22 +185,13 @@ private function getTelephone($billingId = null) return null; } - /** - * @param $customAttributes - * @return array - */ - private function getFieldValues($customAttributes) + public function getFieldValues($customer) { $fieldValues = []; + $customAttributes = $customer->getCustomAttributes(); if (!empty($customAttributes)) { foreach ($customAttributes as $attribute) { - $attributeId = $this->eavAttribute->getIdByCode( - \Magento\Customer\Model\Customer::ENTITY, - $attribute->getAttributeCode() - ); - if ($attribute->getAttributeCode() === self::AC_CUSTOMER_ID) { - $this->isEcomCustomer = ($attribute->getValue()) ? true : false; - } + $attributeId = $this->eavAttribute->getIdByCode(MageCustomer::ENTITY, $attribute->getAttributeCode()); $attributeValues['field'] = $attributeId; $attributeValues['value'] = $attribute->getValue(); $fieldValues[] = $attributeValues; @@ -168,13 +215,191 @@ public function saveResult($customerId, $syncStatus, $contactId, $ecomCustomerId } $customerModel->setAcSyncStatus($syncStatus); - if ($contactId) { - $customerModel->setAcContactId($contactId); + $customerModel->setAcContactId($contactId); + $customerModel->setAcCustomerId($ecomCustomerId); + + $this->customerResource->save($customerModel); + } + + + public function contactBody($customer){ + $contact['email'] = $customer->getEmail(); + $contact['firstName'] = $customer->getFirstname(); + $contact['lastName'] = $customer->getLastname(); + $contact['phone'] = $this->getTelephone($customer->getDefaultBilling()); + $contact['fieldValues'] = $this->getFieldValues($customer); + $contactData['contact'] = $contact; + + return $contactData; + } + + + public function updateCustomers() + { + $lastUpdate = $this->customerHelper->getLastCustomerUpdateSync(); + $numberOfCustomers = (int)$this->customerHelper->getNumberOfCustomers(); + $customers = $this->customerResourceCollectionFactory->create() + ->addAttributeToSelect('ac_contact_id') + ->addAttributeToFilter('ac_contact_id', ['neq' => null]) + ->addAttributeToFilter(self::AC_SYNC_STATUS, ['eq' => CronConfig::SYNCED]) + ->addAttributeToFilter('updated_at', ['gt' => $lastUpdate]) + ->setOrder('updated_at', 'asc') + ->setPageSize($numberOfCustomers); + foreach ($customers as $customer) { + $this->updateCustomer($customer); + $lastUpdate = $customer->getUpdatedAt(); } - if ($ecomCustomerId) { - $customerModel->setAcCustomerId($ecomCustomerId); + if (isset($lastUpdate)) { + $this->customerHelper->setLastCustomerUpdateSync($lastUpdate); + $this->cacheTypeList->cleanType('config'); } + } - $this->customerResource->save($customerModel); + public function createGuestContact($data){ + $acContact = NULL; + if($data['email']){ + $acContact = $this->searchContact($data['email'] ); + if(!$acContact){ + $contactData['contact'] = $data; + $result = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT , $contactData); + if(!$result['success'] && $result['status'] == "404"){ + $acContact = NULL; + } + if(count($result['data']['contact'])>0){ + $acContact = $result['data']['contact']['id']; + } + } + } + return $acContact; + } + + public function createGuestCustomer($data, $storeId){ + $acCustomer = NULL; + $acContact = NUll; + + if($data['email']) { + $acContact = $this->createGuestContact($data); + + $acCustomer = $this->searchCustomer($data['email'], $this->coreHelper->getConnectionId($storeId)); + if (!$acCustomer) { + $ecomCustomerData=[]; + $data['connectionid'] = $this->coreHelper->getConnectionId($storeId); + $data['externalid'] = $data['email']; + $data['acceptsMarketing'] = (int)$this->subscriberFactory->create()->loadBySubscriberEmail($data['email'],$this->storeManager->getStore()->getWebsiteId())->isSubscribed(); + $ecomCustomerData['ecomCustomer'] = $data; + + $result = $this->curl->createContacts(self::METHOD, self::ECOM_CUSTOMER_ENDPOINT, $ecomCustomerData); + if (!$result['success'] && $result['status'] == "404") { + $acCustomer = NULL; + } + if ($result['success'] && isset($result['data']['ecomCustomer']['id'])) { + $acCustomer = $result['data']['ecomCustomer']['id']; + } + } + } + return ['ac_contact_id' => $acContact, 'ac_customer_id' => $acCustomer]; } + + public function updateCustomer($customer){ + $contactData = $this->contactBody($customer); + $acContact = NULL; + $acCustomer = NULL; + try { + $acContact =$customer->getAcContactId(); + if($acContact){ + $result = $this->curl->createContacts(self::METHOD_PUT, self::CONTACT_ENDPOINT . '/' . $acContact, $contactData); + if(!$result['success'] && $result['status'] == "404"){ + $acContact = NULL; + } + }else{ + $acContact = $this->searchContact($customer->getEmail() ); + if(!$acContact){ + $result = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT , $contactData); + $acContact = $result['data']['contact']['id']; + } + } + if($acContact){ + $customerData = $this->getEcomCustomerData($customer); + $acCustomer = $customer->getAcCustomerId(); + if($acCustomer){ + $result = $this->curl->createContacts(self::METHOD_PUT, self::ECOM_CUSTOMER_ENDPOINT . '/' . $customer->getAcCustomerId(), $customerData); + if(!$result['success'] && $result['status'] == "404"){ + $acCustomer = NULL; + } + }else{ + $acCustomer = $this->searchCustomer($customer->getEmail(),$this->coreHelper->getConnectionId($customer->getStoreId()) ); + if(!$acCustomer){ + $result = $this->curl->createContacts(self::METHOD, self::ECOM_CUSTOMER_ENDPOINT, $customerData); + $acCustomer = $result['data']['ecomCustomer']['id']; + if(!$result['success'] && $result['status'] == "404") { + $acCustomer = NULL; + } + if($result['success'] && isset($result['data']['ecomCustomer']['id'])){ + $acCustomer = $result['data']['ecomCustomer']['id']; + } + } + + } + if($acCustomer && $acContact){ + $this->saveResult($customer->getId(), CronConfig::SYNCED, $acContact, $acCustomer); + }else{ + $this->saveResult($customer->getId(), CronConfig::NOT_SYNCED, $acContact, $acCustomer); + } + } + } catch (\Exception $e) { + $this->logger->critical("MODULE: Customer contact/sync" . $e->getMessage()); + } + return ['ac_contact_id' => $acContact, 'ac_customer_id' => $acCustomer]; + } + + public function searchCustomer($email, $connectionId){ + $result = 0; + $AcCustomer = $this->curl->listAllCustomers( + self::GET_METHOD, + self::ECOM_CUSTOMER_ENDPOINT, + $email + ); + foreach ($AcCustomer['data']['ecomCustomers'] as $Ac) { + if ($Ac['connectionid'] === $connectionId) { + $result= $Ac['id']; + } + } + return $result; + } + + public function searchContact($email){ + $result = 0; + $AcCustomer = $this->curl->listAllCustomers( + self::GET_METHOD, + self::CONTACT_ENDPOINT, + $email + ); + if($AcCustomer['status'] == 200 && count($AcCustomer['data']['contacts']) > 0){ + $result = $AcCustomer['data']['contacts'][0]['id']; + } + return $result; + } + + public function syncCustomers(){ + if ($this->customerHelper->isCustomerSyncingEnabled()) { + $this->updateCustomers(); + $numberOfCustomers = (int)$this->customerHelper->getNumberOfCustomers(); + + $customers = $this->customerResourceCollectionFactory->create() + ->addAttributeToFilter([ + ['attribute' => self::AC_SYNC_STATUS,'null' => true ], + ['attribute' => self::AC_SYNC_STATUS,'neq' => CronConfig::SYNCED ] + ]) + ->setPageSize($numberOfCustomers); + + foreach ($customers as $customer) { + try { + $this->updateCustomer($customer); + } catch (\Exception $e) { + $this->logger->critical("MODULE: Customer " . $e->getMessage()); + } + } + } + } + } diff --git a/Customer/Observer/CustomerSaveAfter.php b/Customer/Observer/CustomerSaveAfter.php deleted file mode 100644 index 89851a0..0000000 --- a/Customer/Observer/CustomerSaveAfter.php +++ /dev/null @@ -1,97 +0,0 @@ -customer = $customer; - $this->curl = $curl; - $this->logger = $logger; - } - - /** - * Upgrade order customer email when customer has changed email - * - * @param Observer $observer - * @return void - */ - public function execute(Observer $observer): void - { - /** @var Customer $originalCustomer */ - $originalCustomer = $observer->getEvent()->getOrigCustomerDataObject(); - if (!$originalCustomer) { - return; - } - - /** @var Customer $customer */ - $customer = $observer->getEvent()->getCustomerDataObject(); - - $contactId = 0; - $ecomCustomerId = 0; - $syncStatus = CronConfig::NOT_SYNCED; - $customerId = $customer->getId(); - - try { - $contactData = $this->customer->getContactData($customerId); - $isEcomCustomer = $contactData['contact']['isEcomCustomer']; - - unset($contactData['contact']['isEcomCustomer']); - - $contactResult = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT, $contactData); - $contactId = isset($contactResult['data']['contact']['id']) ? $contactResult['data']['contact']['id'] : null; - $syncStatus = ($contactResult['success']) ? CronConfig::SYNCED : CronConfig::FAIL_SYNCED; - - if ($contactResult['success'] && !$isEcomCustomer) { - $ecomCustomerData = $this->customer->getEcomCustomerData($customerId); - $ecomCustomerResult = $this->curl->createContacts( - self::METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $ecomCustomerData - ); - $ecomCustomerId = isset($ecomCustomerResult['data']['ecomCustomer']['id']) ? $ecomCustomerResult['data']['ecomCustomer']['id'] : null; - } - $this->customer->saveResult($customerId, $syncStatus, $contactId, $ecomCustomerId); - } catch (\Exception $e) { - $this->logger->critical("MODULE: Customer " . $e); - } - } -} diff --git a/Customer/Ui/Component/Listing/Column/AcSyncStatus.php b/Customer/Ui/Component/Listing/Column/AcSyncStatus.php index 5b3c634..8bbc7ed 100644 --- a/Customer/Ui/Component/Listing/Column/AcSyncStatus.php +++ b/Customer/Ui/Component/Listing/Column/AcSyncStatus.php @@ -39,4 +39,5 @@ private function getFieldLabel(array $item) } return __('Something Wrong'); } + } diff --git a/Customer/composer.json b/Customer/composer.json index 7e9cf64..42245a1 100644 --- a/Customer/composer.json +++ b/Customer/composer.json @@ -9,7 +9,7 @@ "config": { "sort-packages": true }, - "version": "2.1.5", + "version": "2.1.6", "require": { "php": "~7.3.0||~7.4.0||~8.0||~8.1||~8.2", "activecampaign/core": "2.1.*" diff --git a/Customer/etc/events.xml b/Customer/etc/events.xml deleted file mode 100644 index 43c661e..0000000 --- a/Customer/etc/events.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/Customer/etc/module.xml b/Customer/etc/module.xml index b578eb7..95c184a 100644 --- a/Customer/etc/module.xml +++ b/Customer/etc/module.xml @@ -1,6 +1,6 @@ - + diff --git a/Customer/view/adminhtml/ui_component/customer_listing.xml b/Customer/view/adminhtml/ui_component/customer_listing.xml index 6d3a115..c313b66 100644 --- a/Customer/view/adminhtml/ui_component/customer_listing.xml +++ b/Customer/view/adminhtml/ui_component/customer_listing.xml @@ -15,14 +15,5 @@ - - - - - select - - true - - - + diff --git a/Newsletter/Cron/NewsletterSyncCron.php b/Newsletter/Cron/NewsletterSyncCron.php index 7e84490..c15f020 100644 --- a/Newsletter/Cron/NewsletterSyncCron.php +++ b/Newsletter/Cron/NewsletterSyncCron.php @@ -5,11 +5,15 @@ use ActiveCampaign\Core\Helper\Curl; use ActiveCampaign\Newsletter\Helper\Data as ActiveCampaignNewsletterHelper; use GuzzleHttp\Exception\GuzzleException; +use Magento\Customer\Model\Customer as CustomerModel; use Magento\Framework\App\State; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Api\CartRepositoryInterface; use Magento\Newsletter\Model\ResourceModel\Subscriber\Collection; use Psr\Log\LoggerInterface; +use ActiveCampaign\Customer\Model\Customer; +use Magento\Customer\Model\CustomerFactory; +use Magento\Customer\Model\ResourceModel\Customer as CustomerResource; class NewsletterSyncCron { @@ -51,13 +55,30 @@ class NewsletterSyncCron protected $logger; /** - * OrderSyncCron constructor. + * @var Customer + */ + protected $customer; + + /** + * @var CustomerFactory + */ + protected $customerFactory; + + /** + * @var CustomerResource + */ + protected $customerResource; + + /** + * NewsletterSyncCron constructor. * @param Collection $newsletterCollection * @param ActiveCampaignNewsletterHelper $activeCampaignHelper * @param State $state * @param Curl $curl * @param CartRepositoryInterface $quoteRepository * @param LoggerInterface $logger + * @param Customer $custoner + * @param CustomerFactory $customerFactory */ public function __construct( Collection $newsletterCollection, @@ -65,7 +86,10 @@ public function __construct( State $state, Curl $curl, CartRepositoryInterface $quoteRepository, - LoggerInterface $logger + LoggerInterface $logger, + Customer $custoner, + CustomerFactory $customerFactory, + CustomerResource $customerResource ) { $this->newsletterCollection = $newsletterCollection; @@ -74,6 +98,9 @@ public function __construct( $this->curl = $curl; $this->quoteRepository = $quoteRepository; $this->logger = $logger; + $this->customer = $custoner; + $this->customerFactory = $customerFactory; + $this->customerResource = $customerResource; } /** @@ -100,16 +127,21 @@ public function execute(): void ->setCurPage(1); foreach ($newsletterCollection as $news) { - + $acContact=NULL; try { $contactData = [ - 'contact' => [ 'email' => $news->getSubscriberEmail() - ] ]; - $contactResult = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT, $contactData); - if (isset($contactResult['data']['contact']['id'])) { - $news->setAcNewsletterSyncId($contactResult['data']['contact']['id']); + if($news->getCustomerId()){ + $result = $this->customer->updateCustomer($this->getCustomer($news->getCustomerId())); + $acContact = $result['ac_contact_id']; + }else{ + $acContact = $this->customer->createGuestContact($contactData); + + } + + if ($acContact) { + $news->setAcNewsletterSyncId($acContact); $news->setAcNewsletterSyncStatus(1); $news->save(); } @@ -123,4 +155,17 @@ public function execute(): void } } + /** + * @param $customerId + * @return CustomerModel + */ + private function getCustomer($customerId): CustomerModel + { + $customerModel = $this->customerFactory->create(); + if (is_numeric($customerId)) { + $this->customerResource->load($customerModel, $customerId); + return $customerModel; + } + return $customerModel; + } } diff --git a/Newsletter/composer.json b/Newsletter/composer.json index 6a74f00..00c300f 100644 --- a/Newsletter/composer.json +++ b/Newsletter/composer.json @@ -9,7 +9,7 @@ "config": { "sort-packages": true }, - "version": "1.0.1", + "version": "1.0.2", "require": { "php": "~7.3.0||~7.4.0||~8.0||~8.1||~8.2", "activecampaign/core": "2.1.*" diff --git a/Newsletter/etc/module.xml b/Newsletter/etc/module.xml index ab2e72d..736cb71 100644 --- a/Newsletter/etc/module.xml +++ b/Newsletter/etc/module.xml @@ -1,9 +1,10 @@ - + + diff --git a/Order/Model/OrderData/OrderDataSend.php b/Order/Model/OrderData/OrderDataSend.php index 514f3e0..92913cd 100644 --- a/Order/Model/OrderData/OrderDataSend.php +++ b/Order/Model/OrderData/OrderDataSend.php @@ -21,6 +21,7 @@ use Magento\Store\Api\StoreRepositoryInterface; use Magento\Store\Model\StoreManagerInterface as StoreManagerInterface; use Magento\Quote\Api\CartRepositoryInterface; +use ActiveCampaign\Customer\Model\Customer; class OrderDataSend { @@ -113,6 +114,11 @@ class OrderDataSend */ protected $coreHelper; + /** + * @var Customer + */ + protected $customer; + /** * OrderDataSend constructor. * @param ProductRepositoryInterfaceFactory $productRepositoryFactory @@ -131,6 +137,7 @@ class OrderDataSend * @param CoreHelper $coreHelper * @param CustomerResource $customerResource * @param CartRepositoryInterface $quoteRepository + * @param Customer $customer */ public function __construct( ProductRepositoryInterfaceFactory $productRepositoryFactory, @@ -148,7 +155,8 @@ public function __construct( Attribute $eavAttribute, CoreHelper $coreHelper, CustomerResource $customerResource, - CartRepositoryInterface $quoteRepository + CartRepositoryInterface $quoteRepository, + Customer $customer ) { $this->_productRepositoryFactory = $productRepositoryFactory; $this->imageHelperFactory = $imageHelperFactory; @@ -166,6 +174,7 @@ public function __construct( $this->coreHelper = $coreHelper; $this->customerResource = $customerResource; $this->quoteRepository = $quoteRepository; + $this->customer = $customer; } /** @@ -182,47 +191,20 @@ public function orderDataSend($order): array $connectionId = $this->activeCampaignHelper->getConnectionId($order->getStoreId()); $customerId = $order->getCustomerId(); $customerAcId = 0; + $quote = $this->quoteRepository->get($order->getQuoteId()); if ($customerId) { - $this->createEcomCustomer($order->getCustomerId(), $order); - $customerEmail = $order->getCustomerEmail(); - $customerModel = $this->customerFactory->create(); - $this->customerResource->load($customerModel, $customerId); - if ($customerModel->getAcCustomerId()) { - $customerAcId = $customerModel->getAcCustomerId(); - } - } else { - $customerEmail = $order->getBillingAddress()->getEmail(); - $websiteId = $this->storeManager->getWebsite()->getWebsiteId(); - $customerModel = $this->customerModel; - $customerModel->setWebsiteId($websiteId); - $customerModel->loadByEmail($customerEmail); - if ($customerModel->getId()) { - $customerId = $customerModel->getId(); - } else { - $customerId = 0; - } - $this->createEcomCustomer($customerId, $order); - $customerModel = $this->customerFactory->create(); - $this->customerResource->load($customerModel, $customerId); - if ($customerModel->getAcCustomerId()) { - $customerAcId = $customerModel->getAcCustomerId(); - } else { - if ($order->getAcTempCustomerId()) { - $customerAcId = $order->getAcTempCustomerId(); - } else { - $AcCustomer = $this->curl->listAllCustomers( - self::GET_METHOD, - self::ECOM_CUSTOMER_ENDPOINT, - $customerEmail - ); - foreach ($AcCustomer['data']['ecomOrders'] as $Ac) { - if ($Ac['connectionid'] == $connectionId) { - $customerAcId = $Ac['customerid']; - } - } - } - } + $AcCustomer = $this->customer->updateCustomer($this->getCustomer($customerId)); + }else{ + $customerEmail = $quote->getBillingAddress()->getEmail(); + $contact['email'] = $quote->getBillingAddress()->getEmail(); + $contact['firstName'] = $quote->getBillingAddress()->getFirstname(); + $contact['lastName'] = $quote->getBillingAddress()->getLastname(); + $contact['phone'] = $quote->getBillingAddress()->getTelephone(); + $contact['fieldValues'] = []; + $AcCustomer = $this->customer->createGuestCustomer($contact,$quote->getStoreId()); } + $customerAcId = $AcCustomer['ac_customer_id']; + $this->saveCustomerResultQuote($quote,$customerAcId); foreach ($order->getAllVisibleItems() as $item) { $product = $this->_productRepositoryFactory->create() @@ -245,7 +227,7 @@ public function orderDataSend($order): array "ecomOrder" => [ "externalid" => $order->getId(), "source" => 1, - "email" => $customerEmail, + "email" => $quote->getBillingAddress()->getEmail(), "orderProducts" => $items, "orderDiscounts" => [ "discountAmount" => $this->activeCampaignHelper->priceToCents($order->getDiscountAmount()) @@ -265,7 +247,7 @@ public function orderDataSend($order): array ]; if (!$order->getAcOrderSyncId()) { - $quote = $this->quoteRepository->get($order->getQuoteId()); + $AcOrderId = $quote->getAcOrderSyncId(); if($AcOrderId > 0){ $result = $this->curl->orderDataSend( @@ -320,41 +302,6 @@ public function orderDataSend($order): array return $return; } - /** - * @param null $billingId - * @return string|null - * @throws LocalizedException - */ - private function getTelephone($billingId = null): ?string - { - if ($billingId) { - $address = $this->addressRepository->getById($billingId); - return $address->getTelephone(); - } - return null; - } - - /** - * @param $customerId - * @return array - * @throws LocalizedException - * @throws NoSuchEntityException - */ - private function getFieldValues($customerId) - { - $fieldValues = []; - $customAttributes = $this->_customerRepositoryInterface->getById($customerId); - $customAttributes->getCustomAttributes(); - if (!empty($customAttributes)) { - foreach ($customAttributes as $attribute) { - $attributeId = $this->eavAttribute->getIdByCode(CustomerModel::ENTITY, $attribute->getAttributeCode()); - $attributeValues['field'] = $attributeId; - $attributeValues['value'] = $attribute->getValue(); - $fieldValues[] = $attributeValues; - } - } - return $fieldValues; - } /** * @param $customerId @@ -367,107 +314,6 @@ private function getCustomer($customerId): object return $customerModel; } - /** - * @param $customerId - * @return array - */ - private function createEcomCustomer($customerId, $quote) - { - $ecomOrderArray = []; - $ecomCustomerId = 0; - $syncStatus = CronConfig::NOT_SYNCED; - $customer = $this->getCustomer($customerId); - if ($customerId) { - $customerId = $customer->getId(); - $contact['email'] = $customer->getEmail(); - $customerEmail = $customer->getEmail(); - $contact['firstName'] = $customer->getFirstname(); - $contact['lastName'] = $customer->getLastname(); - $contact['phone'] = $this->getTelephone($customer->getDefaultBilling()); - $contact['fieldValues'] = $this->getFieldValues($customerId); - } else { - $customerId = 0; - $contact['email'] = $quote->getBillingAddress()->getEmail(); - $customerEmail = $quote->getBillingAddress()->getEmail(); - $contact['firstName'] = $quote->getBillingAddress()->getFirstname(); - $contact['lastName'] = $quote->getBillingAddress()->getLastname(); - $contact['phone'] = $quote->getBillingAddress()->getTelephone(); - $contact['fieldValues'] = []; - } - $contactData['contact'] = $contact; - try { - $contactResult = $this->curl->createContacts(self::METHOD, self::CONTACT_ENDPOINT, $contactData); - $contactId = isset($contactResult['data']['contact']['id']) ? $contactResult['data']['contact']['id'] : null; - $connectionid = $this->coreHelper->getConnectionId($quote->getStoreId()); - - if (isset($contactResult['data']['contact']['id'])) { - if (!$customer->getAcCustomerId()) { - $ecomCustomer['connectionid'] = $connectionid; - $ecomCustomer['externalid'] = $customerId; - $ecomCustomer['email'] = $customerEmail; - $ecomCustomerData['ecomCustomer'] = $ecomCustomer; - $AcCustomer = $this->curl->listAllCustomers( - self::GET_METHOD, - self::ECOM_CUSTOMERLIST_ENDPOINT, - $customerEmail - ); - if (isset($AcCustomer['data']['ecomCustomers'][0])) { - foreach ($AcCustomer['data']['ecomCustomers'] as $Ac) { - if ($Ac['connectionid'] == $connectionid) { - $ecomCustomerId = $Ac['id']; - } - } - } - if (!$ecomCustomerId) { - $ecomCustomerResult = $this->curl->createContacts( - self::METHOD, - self::ECOM_CUSTOMERLIST_ENDPOINT, - $ecomCustomerData - ); - $ecomCustomerId = isset($ecomCustomerResult['data']['ecomCustomer']['id']) ? $ecomCustomerResult['data']['ecomCustomer']['id'] : null; - } - } else { - $ecomCustomerId = $customer->getAcCustomerId(); - } - } - - if ($ecomCustomerId != 0) { - $syncStatus = CronConfig::SYNCED; - } else { - $syncStatus = CronConfig::FAIL_SYNCED; - } - - if ($customerId) { - $this->saveCustomerResult($customerId, $syncStatus, $contactId, $ecomCustomerId); - } else { - $this->saveCustomerResultQuote($quote, $ecomCustomerId); - } - } catch (\Exception $e) { - $this->logger->critical("MODULE Order " . $e); - } - } - - /** - * @param $customerId - * @param $syncStatus - * @param $contactId - * @param $ecomCustomerId - * @throws \Magento\Framework\Exception\AlreadyExistsException - */ - private function saveCustomerResult($customerId, $syncStatus, $contactId, $ecomCustomerId) - { - $customerModel = $this->customerFactory->create(); - if ($customerId) { - $this->customerResource->load($customerModel, $customerId); - } - - $customerModel->setAcSyncStatus($syncStatus); - - $customerModel->setAcContactId($contactId); - $customerModel->setAcCustomerId($ecomCustomerId); - - $this->customerResource->save($customerModel); - } /** * @param $quote diff --git a/Order/composer.json b/Order/composer.json index 01f182a..1c9c23a 100644 --- a/Order/composer.json +++ b/Order/composer.json @@ -9,7 +9,7 @@ "config": { "sort-packages": true }, - "version": "2.1.1", + "version": "2.1.2", "require": { "php": "~7.3.0||~7.4.0||~8.0||~8.1||~8.2", "activecampaign/core": "2.1.*" diff --git a/Order/etc/module.xml b/Order/etc/module.xml index 139b88d..eb97154 100644 --- a/Order/etc/module.xml +++ b/Order/etc/module.xml @@ -1,8 +1,9 @@ - + + diff --git a/composer.json b/composer.json index 877616b..4023226 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "activecampaign/module-integration", "description": "ActiveCampaign extension for Magento 2.3 and 2.4", "type": "magento2-component", - "version": "2.0.12", + "version": "2.0.14", "license": "OSL-3.0", "require": { "php": "~7.3.0||~7.4.0||~8.0||~8.1||~8.2" diff --git a/marketplace-composer.json b/marketplace-composer.json index 044ea9f..a0178c4 100644 --- a/marketplace-composer.json +++ b/marketplace-composer.json @@ -2,7 +2,7 @@ "name": "activecampaign/module-integration", "description": "ActiveCampaign extension for Magento 2.3 and 2.4", "type": "metapackage", - "version": "2.0.13", + "version": "2.0.14", "license": [ "OSL-3.0" ],