Skip to content

Commit

Permalink
Merge pull request #67 from jorgeeurekalabs/main
Browse files Browse the repository at this point in the history
Refactoring of the customer module
  • Loading branch information
jorgeeurekalabs authored Jan 18, 2024
2 parents 82af49c + 70c4a2f commit 2948a6c
Show file tree
Hide file tree
Showing 24 changed files with 467 additions and 889 deletions.
267 changes: 41 additions & 226 deletions AbandonedCart/Model/AbandonedCartSendData.php

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion AbandonedCart/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.*"
Expand Down
2 changes: 1 addition & 1 deletion AbandonedCart/etc/module.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="ActiveCampaign_AbandonedCart" setup_version="2.1.3">
<module name="ActiveCampaign_AbandonedCart" setup_version="2.1.5">
<sequence>
<module name="Magento_Product"/>
<module name="Magento_Sales"/>
Expand Down
1 change: 1 addition & 0 deletions Core/Helper/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
2 changes: 1 addition & 1 deletion Core/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
},
Expand Down
2 changes: 1 addition & 1 deletion Core/etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="ActiveCampaign_Core" setup_version="2.1.1"/>
<module name="ActiveCampaign_Core" setup_version="2.1.2"/>
</config>
27 changes: 3 additions & 24 deletions Customer/Controller/Adminhtml/Customer/MassSync.php
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
}
Expand Down
257 changes: 10 additions & 247 deletions Customer/Cron/CustomerSync.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Loading

0 comments on commit 2948a6c

Please sign in to comment.