Repository: mailchimp/mc-magento2
Branch: develop-2.3
Commit: b510447126bf
Files: 230
Total size: 915.5 KB
Directory structure:
gitextract_1npkxmtb/
├── Block/
│ ├── Adminhtml/
│ │ ├── Customer/
│ │ │ └── Edit/
│ │ │ └── Tabs/
│ │ │ ├── Mailchimp.php
│ │ │ └── View/
│ │ │ └── Customer.php
│ │ ├── Stores/
│ │ │ ├── Edit/
│ │ │ │ ├── Form.php
│ │ │ │ ├── Tab/
│ │ │ │ │ ├── Address.php
│ │ │ │ │ └── Info.php
│ │ │ │ └── Tabs.php
│ │ │ └── Edit.php
│ │ └── System/
│ │ └── Config/
│ │ ├── Account.php
│ │ ├── CreateAbandonedCart.php
│ │ ├── CreateWebhook.php
│ │ ├── Date.php
│ │ ├── DeleteStore.php
│ │ ├── Fieldset/
│ │ │ └── Hint.php
│ │ ├── FixMailchimpJS.php
│ │ ├── Form/
│ │ │ └── Field/
│ │ │ ├── CustomerMap.php
│ │ │ ├── MailchimpMap.php
│ │ │ └── VarsMap.php
│ │ ├── OauthWizard.php
│ │ ├── ResetErrors.php
│ │ ├── ResetErrorsNoRetry.php
│ │ ├── ResetStore.php
│ │ ├── ResyncProducts.php
│ │ └── ResyncSubscriber.php
│ ├── Catcher.php
│ ├── Checkout/
│ │ └── Success.php
│ ├── Loadquote.php
│ ├── Mailchimpjs.php
│ ├── Newsletter.php
│ └── Subscribe.php
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Controller/
│ ├── Adminhtml/
│ │ ├── Batch/
│ │ │ ├── GetResponse.php
│ │ │ └── Index.php
│ │ ├── Carts/
│ │ │ └── Index.php
│ │ ├── Cron/
│ │ │ └── Index.php
│ │ ├── Ecommerce/
│ │ │ ├── CreateWebhook.php
│ │ │ ├── DeleteStore.php
│ │ │ ├── FixMailchimpJS.php
│ │ │ ├── GetInterest.php
│ │ │ ├── Getaccountdetails.php
│ │ │ ├── Register.php
│ │ │ ├── ResetLocalErrors.php
│ │ │ ├── ResetLocalErrorsNoRetry.php
│ │ │ ├── ResetStore.php
│ │ │ ├── ResyncProducts.php
│ │ │ ├── ResyncSubscribers.php
│ │ │ └── SyncLog.php
│ │ ├── Errors/
│ │ │ ├── Getresponse.php
│ │ │ └── Index.php
│ │ ├── Lists/
│ │ │ └── Get.php
│ │ ├── Orders/
│ │ │ ├── Campaign.php
│ │ │ └── Member.php
│ │ ├── Stores/
│ │ │ ├── Delete.php
│ │ │ ├── Edit.php
│ │ │ ├── Get.php
│ │ │ ├── Index.php
│ │ │ └── Save.php
│ │ └── Stores.php
│ ├── Campaign/
│ │ └── Check.php
│ ├── Cart/
│ │ └── Loadquote.php
│ ├── Checkout/
│ │ └── Success.php
│ └── WebHook/
│ └── Index.php
├── Cron/
│ ├── BatchesClean.php
│ ├── Ecommerce.php
│ ├── ErrorsClean.php
│ ├── GenerateStatistics.php
│ ├── SyncStatistics.php
│ ├── Webhook.php
│ └── WebhookClean.php
├── Helper/
│ ├── Data.php
│ ├── Http.php
│ ├── Sync.php
│ └── VarsMap.php
├── ISSUE_TEMPLATE.md
├── LICENSE.txt
├── Model/
│ ├── Api/
│ │ ├── Cart.php
│ │ ├── Customer.php
│ │ ├── Order.php
│ │ ├── Product.php
│ │ ├── PromoCodes.php
│ │ ├── PromoRules.php
│ │ ├── Result.php
│ │ └── Subscriber.php
│ ├── Config/
│ │ ├── Backend/
│ │ │ ├── ApiKey.php
│ │ │ ├── MonkeyList.php
│ │ │ ├── MonkeyStore.php
│ │ │ └── VarsMap.php
│ │ ├── ModuleVersion.php
│ │ └── Source/
│ │ ├── ApiKey.php
│ │ ├── CampaignAction.php
│ │ ├── CleanPeriod.php
│ │ ├── Cmspage.php
│ │ ├── Details.php
│ │ ├── Interest.php
│ │ ├── MonkeyList.php
│ │ ├── MonkeyStore.php
│ │ ├── Months.php
│ │ ├── Timeout.php
│ │ └── WebhookDelete.php
│ ├── HTTP/
│ │ └── Client/
│ │ └── Curl.php
│ ├── Logger/
│ │ ├── Handler.php
│ │ └── Logger.php
│ ├── MailChimpErrors.php
│ ├── MailChimpInterestGroup.php
│ ├── MailChimpStores.php
│ ├── MailChimpSyncBatches.php
│ ├── MailChimpSyncEcommerce.php
│ ├── MailChimpSyncEcommerceFactory.php
│ ├── MailChimpWebhookRequest.php
│ ├── MailchimpNotification.php
│ ├── Plugin/
│ │ ├── AccountManagement.php
│ │ ├── Coupon.php
│ │ ├── Creditmemo.php
│ │ ├── Invoice.php
│ │ ├── Newsletter/
│ │ │ └── Save.php
│ │ ├── Quote.php
│ │ ├── Ship.php
│ │ └── Subscriber.php
│ └── ResourceModel/
│ ├── Carts/
│ │ └── Collection.php
│ ├── MailChimpErrors.php
│ ├── MailChimpInterestGroup/
│ │ └── Collection.php
│ ├── MailChimpInterestGroup.php
│ ├── MailChimpStores/
│ │ ├── Collection.php
│ │ └── Grid/
│ │ └── Collection.php
│ ├── MailChimpStores.php
│ ├── MailChimpSyncBatches/
│ │ └── Collection.php
│ ├── MailChimpSyncBatches.php
│ ├── MailChimpSyncEcommerce/
│ │ └── Collection.php
│ ├── MailChimpSyncEcommerce.php
│ ├── MailChimpWebhookRequest/
│ │ └── Collection.php
│ ├── MailChimpWebhookRequest.php
│ ├── MailchimpNotification/
│ │ └── Collection.php
│ ├── MailchimpNotification.php
│ └── Schedule/
│ └── Collection.php
├── Observer/
│ ├── Adminhtml/
│ │ ├── Customer/
│ │ │ └── SaveAfter.php
│ │ └── Product/
│ │ ├── DeleteAfter.php
│ │ ├── ImportAfter.php
│ │ └── SaveAfter.php
│ ├── ConfigObserver.php
│ ├── Customer/
│ │ └── SaveBefore.php
│ ├── Sales/
│ │ └── Order/
│ │ ├── SaveAfter.php
│ │ ├── SubmitAfter.php
│ │ └── SubmitBefore.php
│ ├── SalesRule/
│ │ └── Rule/
│ │ ├── DeleteAfter.php
│ │ └── SaveAfter.php
│ └── Subscriber/
│ └── SaveAfter.php
├── README.md
├── Setup/
│ ├── InstallData.php
│ ├── InstallSchema.php
│ ├── Uninstall.php
│ ├── UpgradeData.php
│ └── UpgradeSchema.php
├── Ui/
│ └── Component/
│ ├── Batch/
│ │ └── Grid/
│ │ └── Column/
│ │ └── Batches.php
│ ├── Carts/
│ │ └── Grid/
│ │ └── Column/
│ │ ├── Actions.php
│ │ ├── Customer.php
│ │ └── Mailchimp.php
│ ├── Errors/
│ │ └── Grid/
│ │ └── Column/
│ │ └── Batch.php
│ ├── Listing/
│ │ └── Column/
│ │ ├── Customers.php
│ │ ├── Monkey.php
│ │ └── Products.php
│ └── Stores/
│ └── Grid/
│ └── Column/
│ └── Actions.php
├── composer.json
├── etc/
│ ├── acl.xml
│ ├── adminhtml/
│ │ ├── events.xml
│ │ ├── menu.xml
│ │ ├── routes.xml
│ │ └── system.xml
│ ├── config.xml
│ ├── cron_groups.xml
│ ├── crontab.xml
│ ├── di.xml
│ ├── events.xml
│ ├── fieldset.xml
│ ├── frontend/
│ │ ├── di.xml
│ │ ├── events.xml
│ │ └── routes.xml
│ └── module.xml
├── i18n/
│ ├── es_ES.csv
│ ├── fr_FR.csv
│ └── it_IT.csv
├── modman
├── registration.php
└── view/
├── adminhtml/
│ ├── layout/
│ │ ├── customer_index_edit.xml
│ │ ├── default.xml
│ │ ├── mailchimp_batch_index.xml
│ │ ├── mailchimp_carts_index.xml
│ │ ├── mailchimp_cron_index.xml
│ │ ├── mailchimp_errors_index.xml
│ │ ├── mailchimp_stores_edit.xml
│ │ ├── mailchimp_stores_grid.xml
│ │ └── mailchimp_stores_index.xml
│ ├── requirejs-config.js
│ ├── templates/
│ │ ├── customer/
│ │ │ └── edit/
│ │ │ └── tabs/
│ │ │ └── mailchimp.phtml
│ │ ├── system/
│ │ │ └── config/
│ │ │ ├── create_abandonedcart_automation.phtml
│ │ │ ├── createwebhook.phtml
│ │ │ ├── deletestore.phtml
│ │ │ ├── fieldset/
│ │ │ │ └── hint.phtml
│ │ │ ├── fixmailchimpjs.phtml
│ │ │ ├── js.phtml
│ │ │ ├── oauth_wizard.phtml
│ │ │ ├── reseterrors.phtml
│ │ │ ├── reseterrorsnoretry.phtml
│ │ │ ├── resetstore.phtml
│ │ │ ├── resyncproducts.phtml
│ │ │ └── resyncsubscriber.phtml
│ │ └── tab/
│ │ └── view.phtml
│ ├── ui_component/
│ │ ├── customer_listing.xml
│ │ ├── mailchimp_batch_grid.xml
│ │ ├── mailchimp_carts_grid.xml
│ │ ├── mailchimp_cron_grid.xml
│ │ ├── mailchimp_errors_grid.xml
│ │ ├── mailchimp_stores_grid.xml
│ │ ├── product_listing.xml
│ │ └── sales_order_grid.xml
│ └── web/
│ ├── css/
│ │ └── styles.css
│ └── js/
│ ├── apikey.js
│ ├── configapikey.js
│ └── mailchimpconfirmation.js
└── frontend/
├── layout/
│ ├── checkout_onepage_success.xml
│ ├── default.xml
│ ├── mailchimp_cart_loadquote.xml
│ └── newsletter_manage_index.xml
├── requirejs-config.js
├── templates/
│ ├── catcher.phtml
│ ├── checkout/
│ │ └── order/
│ │ └── success.phtml
│ ├── footer.phtml
│ ├── form/
│ │ └── newsletter.phtml
│ ├── loadquote.phtml
│ └── mailchimpjs.phtml
└── web/
└── js/
└── campaigncatcher.js
================================================
FILE CONTENTS
================================================
================================================
FILE: Block/Adminhtml/Customer/Edit/Tabs/Mailchimp.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/29/17 1:55 PM
* @file: Mailchimp.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Customer\Edit\Tabs;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Ui\Component\Layout\Tabs\TabInterface;
use Magento\Backend\Block\Widget\Form;
use Magento\Backend\Block\Widget\Form\Generic;
class Mailchimp extends \Magento\Backend\Block\Template implements TabInterface
{
/**
* @var \Magento\Store\Model\System\Store
*/
protected $_systemStore;
/**
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* Mailchimp constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Data\FormFactory $formFactory
* @param \Magento\Store\Model\System\Store $systemStore
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data = []
) {
$this->_coreRegistry = $registry;
$this->_systemStore = $systemStore;
parent::__construct($context, $data);
}
public function getCustomerId()
{
return $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabLabel()
{
return __('MailChimp');
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabTitle()
{
return __('MailChimp');
}
/**
* @return bool
*/
public function canShowTab()
{
if ($this->getCustomerId()) {
return true;
}
return false;
}
/**
* @return bool
*/
public function isHidden()
{
if ($this->getCustomerId()) {
return false;
}
return true;
}
/**
* Tab class getter
*
* @return string
*/
public function getTabClass()
{
return '';
}
/**
* Return URL link to Tab content
*
* @return string
*/
public function getTabUrl()
{
return '';
}
/**
* Tab should be loaded trough Ajax call
*
* @return bool
*/
public function isAjaxLoaded()
{
return false;
}
}
================================================
FILE: Block/Adminhtml/Customer/Edit/Tabs/View/Customer.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/29/17 2:49 PM
* @file: Customer.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Customer\Edit\Tabs\View;
class Customer extends \Magento\Backend\Block\Template
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @var \Magento\Framework\Registry
*/
protected $registry;
/**
* Customer constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Magento\Framework\Registry $registry,
array $data
) {
parent::__construct($context, $data);
$this->helper = $helper;
$this->subscriberFactory = $subscriberFactory;
$this->registry = $registry;
}
public function getInterest()
{
$subscriber = $this->subscriberFactory->create();
$customerId = $this->registry->registry(\Magento\Customer\Controller\RegistryConstants::CURRENT_CUSTOMER_ID);
$subscriber->loadByCustomerId($customerId);
return $this->helper->getSubscriberInterest($subscriber->getSubscriberId(), $subscriber->getStoreId());
}
}
================================================
FILE: Block/Adminhtml/Stores/Edit/Form.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/10/17 4:04 PM
* @file: Form.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Stores\Edit;
use Magento\Backend\Block\Widget\Form\Generic;
class Form extends Generic
{
protected function _prepareForm()
{
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
[
'data' => [
'id' => 'edit_form',
'action' => $this->getData('action'),
'method' => 'post'
]
]
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
================================================
FILE: Block/Adminhtml/Stores/Edit/Tab/Address.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/12/17 5:07 PM
* @file: Address.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Stores\Edit\Tab;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Data\FormFactory;
class Address extends Generic implements TabInterface
{
/**
* @var \Magento\Directory\Model\Config\Source\Country
*/
protected $_country;
/**
* Address constructor.
* @param Context $context
* @param Registry $registry
* @param FormFactory $formFactory
* @param \Magento\Directory\Model\Config\Source\Country $country
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Directory\Model\Config\Source\Country $country,
array $data = []
) {
$this->_country = $country;
parent::__construct($context, $registry, $formFactory, $data);
}
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('mailchimp_stores');
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('stores_');
$form->setFieldNameSuffix('stores');
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('Address')]
);
if ($model->getId()) {
$fieldset->addField(
'id',
'hidden',
['name' => 'id']
);
}
$fieldset->addField(
'address_address_one',
'text',
[
'name' => 'address_address_one',
'label' => __('Street'),
'required' => true
]
);
$fieldset->addField(
'address_address_two',
'text',
[
'name' => 'address_address_two',
'label' => __('Street'),
'required' => false
]
);
$fieldset->addField(
'address_city',
'text',
[
'name' => 'address_city',
'label' => __('City'),
'required' => true
]
);
$fieldset->addField(
'address_postal_code',
'text',
[
'name' => 'address_postal_code',
'label' => __('Postal Code'),
'required' => false
]
);
$country = $this->_country->toOptionArray();
$countryArray = [''=> __('Select one')];
foreach ($country as $c) {
$countryArray[$c['value']] = $c['label'];
}
$fieldset->addField(
'address_country_code',
'select',
[
'name' => 'address_country_code',
'label' => __('Country'),
'required' => true,
'options' => $countryArray
]
);
$data = $model->getData();
$form->setValues($data);
$this->setForm($form);
return parent::_prepareForm();
}
public function getTabLabel()
{
return __('Store Address Info');
}
public function getTabTitle()
{
return __('Store Address Info');
}
public function canShowTab()
{
return true;
}
public function isHidden()
{
return false;
}
}
================================================
FILE: Block/Adminhtml/Stores/Edit/Tab/Info.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/12/17 11:03 AM
* @file: Info.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Stores\Edit\Tab;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
use Magento\Framework\Data\FormFactory;
class Info extends Generic implements TabInterface
{
/**
* @var \Magento\Config\Model\Config\Source\Locale\Timezone
*/
protected $_timezone;
/**
* @var \Magento\Config\Model\Config\Source\Yesno
*/
protected $_yesno;
/**
* @var \Magento\Config\Model\Config\Source\Locale\Currency
*/
protected $_currency;
/**
* @var \Magento\Config\Model\Config\Source\Locale
*/
protected $_locale;
/**
* @var \Ebizmarts\MailChimp\Model\Config\Source\ApiKey
*/
protected $_apikey;
/**
* Info constructor.
* @param Context $context
* @param Registry $registry
* @param FormFactory $formFactory
* @param \Magento\Config\Model\Config\Source\Locale\Timezone $timezone
* @param \Magento\Config\Model\Config\Source\Yesno $yesno
* @param \Magento\Config\Model\Config\Source\Locale\Currency $currency
* @param \Magento\Config\Model\Config\Source\Locale $locale
* @param \Ebizmarts\MailChimp\Model\Config\Source\ApiKey $apiKey
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Config\Model\Config\Source\Locale\Timezone $timezone,
\Magento\Config\Model\Config\Source\Yesno $yesno,
\Magento\Config\Model\Config\Source\Locale\Currency $currency,
\Magento\Config\Model\Config\Source\Locale $locale,
\Ebizmarts\MailChimp\Model\Config\Source\ApiKey $apiKey,
array $data = []
) {
$this->_timezone = $timezone;
$this->_yesno = $yesno;
$this->_currency = $currency;
$this->_locale = $locale;
$this->_apikey = $apiKey;
parent::__construct($context, $registry, $formFactory, $data);
}
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('mailchimp_stores');
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('stores_');
$form->setFieldNameSuffix('stores');
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('General')]
);
if ($model->getId()) {
$fieldset->addField(
'id',
'hidden',
['name' => 'id']
);
$fieldset->addField(
'apikey',
'hidden',
['name' => 'apikey']
);
$fieldset->addField(
'storeid',
'hidden',
['name' => 'storeid']
);
} else {
$this->_apikey->getAllApiKeys();
$apikey = $this->_apikey->toOptionArray();
$apikeyArray = [];
foreach ($apikey as $a) {
$apikeyArray[$a['value']] = $a['label'];
}
$url = $this->_urlBuilder->getUrl('mailchimp/stores/getList');
$fieldset->addField(
'apikey',
'select',
[
'name' => 'apikey',
'label' => __('Apikey'),
'required' => true,
'options' => $apikeyArray,
]
);
$listArray = [''=>__('Select first an ApiKey')];
$fieldset->addField(
'list_id',
'select',
[
'name' => 'list_id',
'label' => __('List'),
'required' => true,
'options' => $listArray,
]
);
}
$fieldset->addField(
'name',
'text',
[
'name' => 'name',
'label' => __('Name'),
'required' => true
]
);
$fieldset->addField(
'domain',
'text',
[
'name' => 'domain',
'label' => __('Domain'),
'required' => true
]
);
$fieldset->addField(
'email_address',
'text',
[
'name' => 'email_address',
'label' => __('Email'),
'required' => true
]
);
$currency = $this->_currency->toOptionArray();
$currencyArray = [''=> __('Select one')];
foreach ($currency as $c) {
$currencyArray[$c['value']] = $c['label'];
}
$fieldset->addField(
'currency_code',
'select',
[
'name' => 'currency_code',
'label' => __('Currency'),
'required' => true,
'options' => $currencyArray
]
);
$locale = $this->_locale->toOptionArray();
$localeArray = [''=> __('Select one')];
foreach ($locale as $l) {
$localeArray[$l['value']] = $l['label'];
}
$fieldset->addField(
'primary_locale',
'select',
[
'name' => 'primary_locale',
'label' => __('Locale'),
'required' => true,
'options' => $localeArray
]
);
$timezone = $this->_timezone->toOptionArray();
$timezoneArray = [''=> __('Select one')];
foreach ($timezone as $t) {
$timezoneArray[$t['value']] = $t['label'];
}
$fieldset->addField(
'timezone',
'select',
[
'name' => 'timezone',
'label' => __('TimeZone'),
'required' => true,
'options' => $timezoneArray
]
);
$fieldset->addField(
'phone',
'text',
[
'name' => 'phone',
'label' => __('Phone'),
'required' => true
]
);
$data = $model->getData();
$form->setValues($data);
$this->setForm($form);
return parent::_prepareForm();
}
public function getTabLabel()
{
return __('Store Info');
}
public function getTabTitle()
{
return __('Store Info');
}
public function canShowTab()
{
return true;
}
public function isHidden()
{
return false;
}
}
================================================
FILE: Block/Adminhtml/Stores/Edit/Tabs.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/12/17 11:01 AM
* @file: Tabs.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Stores\Edit;
use Magento\Backend\Block\Widget\Tabs as WidgetTabs;
class Tabs extends WidgetTabs
{
/**
* Class constructor
*
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('stores_edit_tabs');
$this->setDestElementId('edit_form');
$this->setTitle(__('Mailchimp Store Information'));
}
/**
* @return $this
*/
protected function _beforeToHtml()
{
$this->addTab(
'stores_info',
[
'label' => __('General'),
'title' => __('General'),
'content' => $this->getLayout()->createBlock(
\Ebizmarts\MailChimp\Block\Adminhtml\Stores\Edit\Tab\Info::class
)->toHtml(),
'active' => true
]
);
$this->addTab(
'stores_address',
[
'label' => __('Address'),
'title' => __('Address'),
'content' => $this->getLayout()->createBlock(
\Ebizmarts\MailChimp\Block\Adminhtml\Stores\Edit\Tab\Address::class
)->toHtml(),
'active' => false
]
);
return parent::_beforeToHtml();
}
}
================================================
FILE: Block/Adminhtml/Stores/Edit.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/10/17 1:08 PM
* @file: Edit.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\Stores;
use Magento\Backend\Block\Widget\Form\Container;
use Magento\Backend\Block\Widget\Context;
use Magento\Framework\Registry;
class Edit extends Container
{
/**
* @var Registry
*/
protected $_coreRegistry;
/**
* Edit constructor.
* @param Context $context
* @param Registry $registry
* @param array $data
*/
public function __construct(
Context $context,
Registry $registry,
array $data = []
) {
$this->_coreRegistry = $registry;
parent::__construct($context, $data);
}
protected function _construct()
{
$this->_objectId = 'id';
$this->_controller = 'adminhtml_stores';
$this->_blockGroup = 'Ebizmarts_MailChimp';
parent::_construct();
$this->buttonList->update('save', 'label', __('Save'));
$this->buttonList->add(
'saveandcontinue',
[
'label' => __('Save and Continue Edit'),
'class' => 'save',
'data_attribute' => [
'mage-init' => [
'button' => [
'event' => 'saveAndContinueEdit',
'target' => '#edit_form'
]
]
]
],
-100
);
$this->buttonList->update('delete', 'label', __('Delete'));
}
/**
* Retrieve text for header element depending on loaded news
*
* @return string
*/
public function getHeaderText()
{
$storeRegistry = $this->_coreRegistry->registry('mailchimp_stores');
if ($storeRegistry->getId()) {
$storeTitle = $this->escapeHtml($storeRegistry->getTitle());
return __("Edit Store '%1'", $storeTitle);
} else {
return __('Add Store');
}
}
}
================================================
FILE: Block/Adminhtml/System/Config/Account.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class Account extends \Magento\Config\Block\System\Config\Form\Field
{
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$values = $element->getValues();
$html = '
';
$html .= '
';
if ($values) {
foreach ($values as $dat) {
if ($dat['value']!=='') {
$html .= "{$dat['label']}: {$dat['value']} ";
} else {
$html .= "{$dat['label']} ";
}
}
}
$html .= ' ';
$html .= '
';
return $html;
}
}
================================================
FILE: Block/Adminhtml/System/Config/CreateAbandonedCart.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class CreateAbandonedCart extends \Magento\Config\Block\System\Config\Form\Field
{
protected $_template = 'system/config/create_abandonedcart_automation.phtml';
private $_url = "https://admin.mailchimp.com/#/create-campaign/explore/abandonedCart";
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->authorizeRequestUrl(),
'html_id' => $element->getHtmlId(),
]);
return parent::_toHtml();
;
}
public function authorizeRequestUrl()
{
return $this->_url;
}
}
================================================
FILE: Block/Adminhtml/System/Config/CreateWebhook.php
================================================
_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/createwebhook.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
public function getButtonHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->getAjaxCreateWebhookUrl(),
'html_id' => $element->getHtmlId(),
]);
return $this->_toHtml();
}
public function getAjaxCreateWebhookUrl()
{
$params = $this->getRequest()->getParams();
$scope = [];
if (isset($params['website'])) {
$scope = ['website'=>$params['website']];
} elseif (isset($params['store'])) {
$scope = ['store'=>$params['store']];
}
return $this->_urlBuilder->getUrl('mailchimp/ecommerce/CreateWebhook', $scope);
}
}
================================================
FILE: Block/Adminhtml/System/Config/Date.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 9/30/16 2:38 PM
* @file: Date.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class Date extends \Magento\Config\Block\System\Config\Form\Field
{
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$element->setDateFormat(\Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT);
$element->setTimeFormat(null);
return parent::render($element);
}
}
================================================
FILE: Block/Adminhtml/System/Config/DeleteStore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/20/17 3:25 PM
* @file: ResetErrors.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class DeleteStore extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* ResetErrors constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data = []
) {
$this->_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/deletestore.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
public function getButtonHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]);
return $this->_toHtml();
}
public function getAjaxCheckUrl()
{
$params = $this->getRequest()->getParams();
$scope = [];
if (isset($params['website'])) {
$scope = ['website'=>$params['website']];
} elseif (isset($params['store'])) {
$scope = ['store'=>$params['store']];
}
return $this->_urlBuilder->getUrl('mailchimp/ecommerce/DeleteStore', $scope);
}
}
================================================
FILE: Block/Adminhtml/System/Config/Fieldset/Hint.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Fieldset;
class Hint extends \Magento\Backend\Block\Template implements
\Magento\Framework\Data\Form\Element\Renderer\RendererInterface
{
/**
* @var string
*/
protected $_template = 'Ebizmarts_MailChimp::system/config/fieldset/hint.phtml';
/**
* @var \Magento\Framework\App\ProductMetadataInterface
*/
private $_metaData;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var \Magento\Backend\Block\Template\Context
*/
private $_context;
/**
* @var \Ebizmarts\MailChimp\Model\Config\ModuleVersion
*/
private $_moduleVersion;
/**
* Hint constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\App\ProductMetadataInterface $productMetaData
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\Config\ModuleVersion $moduleVersion
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\App\ProductMetadataInterface $productMetaData,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\Config\ModuleVersion $moduleVersion,
array $data = []
) {
parent::__construct($context, $data);
$this->_metaData = $productMetaData;
$this->_helper = $helper;
$this->_moduleVersion = $moduleVersion;
$this->_context = $context;
}
/**
* @param \Magento\Framework\Data\Form\Element\AbstractElement $element
* @return mixed
*/
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
return $this->toHtml();
}
public function getModuleVersion()
{
return $this->_moduleVersion->getModuleVersion('Ebizmarts_MailChimp');
}
public function getHasApiKey()
{
$apikey = $this->_helper->getApiKey($this->_context->getStoreManager()->getStore()->getId());
if ($apikey) {
return true;
} else {
return false;
}
}
public function getScope()
{
$params = $this->getRequest()->getParams();
$scope = 'default';
if (isset($params['website'])) {
$scope = 'website';
} elseif (isset($params['store'])) {
$scope = 'store';
}
return $scope;
}
public function getScopeId()
{
$params = $this->getRequest()->getParams();
$scopeId = 0;
if (isset($params['website'])) {
$scopeId = $params['website'];
} elseif (isset($params['store'])) {
$scopeId = $params['store'];
}
return $scopeId;
}
public function getRegisterToken()
{
$scopeId = $this->getScopeId();
$scope = $this->getScope();
$token = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_STATISTICS_TOKEN, $scopeId, $scope);
return $token;
}
}
================================================
FILE: Block/Adminhtml/System/Config/FixMailchimpJS.php
================================================
_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/fixmailchimpjs.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
}
================================================
FILE: Block/Adminhtml/System/Config/Form/Field/CustomerMap.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/27/17 12:01 PM
* @file: CustomerMap.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Form\Field;
class CustomerMap extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray
{
/**
* @var VarsMap
*/
protected $_varsRenderer=null;
protected $_mailchimpRenderer=null;
protected function _getVarsRenderer()
{
if (!$this->_varsRenderer) {
$this->_varsRenderer = $this->getLayout()->createBlock(
\Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Form\Field\VarsMap::class,
'',
['data' => ['is_render_to_js_template' => true]]
);
$this->_varsRenderer->setClass('customer_field_select');
}
return $this->_varsRenderer;
}
protected function _getMailchimpRenderer()
{
if (!$this->_mailchimpRenderer) {
$this->_mailchimpRenderer = $this->getLayout()->createBlock(
\Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Form\Field\MailchimpMap::class,
'',
['data' => ['is_render_to_js_template' => true]]
);
$this->_mailchimpRenderer->setClass('mailchimp_field_select');
}
return $this->_mailchimpRenderer;
}
protected function _prepareToRender()
{
// $this->addColumn('mailchimp', ['label' => __('Mailchimp')]);
$this->addColumn(
'mailchimp_field_id',
['label' => __('Mailchimp'), 'renderer' => $this->_getMailchimpRenderer()]
);
$this->addColumn(
'customer_field_id',
['label' => __('Magento'), 'renderer' => $this->_getVarsRenderer()]
);
$this->_addAfter = false;
$this->_addButtonLabel = __('Add');
}
protected function _prepareArrayRow(\Magento\Framework\DataObject $row)
{
$optionExtraAttr = [];
$optionExtraAttr['option_' . $this->_getVarsRenderer()->calcOptionHash($row->getData('customer_field_id'))] =
'selected="selected"';
$optionExtraAttr['option_' . $this->_getMailchimpRenderer()->calcOptionHash(
$row->getData('mailchimp_field_id')
)
] =
'selected="selected"';
$row->setData(
'option_extra_attrs',
$optionExtraAttr
);
}
}
================================================
FILE: Block/Adminhtml/System/Config/Form/Field/MailchimpMap.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/9/18 1:17 PM
* @file: MailchimpMap.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Form\Field;
class MailchimpMap extends \Magento\Framework\View\Element\Html\Select
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @var \Magento\Framework\App\RequestInterface
*/
protected $_request;
/**
* MailchimpMap constructor.
* @param \Magento\Framework\View\Element\Context $context
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data = []
) {
parent::__construct($context, $data);
$this->_helper = $helper;
$this->_storeManager = $storeManager;
$this->_request = $context->getRequest();
}
protected function _getMailchimpTags()
{
$ret = [];
$storeId = (int) $this->_request->getParam("store", 0);
if ($this->_request->getParam('website', 0)) {
$scope = 'website';
$storeId = $this->_request->getParam('website', 0);
} elseif ($this->_request->getParam('store', 0)) {
$scope = 'stores';
$storeId = $this->_request->getParam('store', 0);
} else {
$scope = 'default';
}
$api = $this->_helper->getApi($storeId, $scope);
try {
$merge = $api->lists->mergeFields->getAll(
$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST,
$storeId,
$scope
),
null,
null,
\Ebizmarts\MailChimp\Helper\Data::MAX_MERGEFIELDS
);
if (is_array($merge) && key_exists('merge_fields', $merge)) {
foreach ($merge['merge_fields'] as $item) {
$ret[$item['tag']] = $item['tag'] . ' (' . $item['name'] . ' : ' . $item['type'] . ')';
}
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
}
return $ret;
}
public function setInputName($value)
{
return $this->setName($value);
}
/**
* Render block HTML
*
* @return string
*/
public function _toHtml()
{
if (!$this->getOptions()) {
foreach ($this->_getMailchimpTags() as $attId => $attLabel) {
$this->addOption($attId, $this->escapeHtmlAttr($attLabel));
}
}
return parent::_toHtml();
}
}
================================================
FILE: Block/Adminhtml/System/Config/Form/Field/VarsMap.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/27/17 3:41 PM
* @file: VarsMap.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Form\Field;
class VarsMap extends \Magento\Framework\View\Element\Html\Select
{
/**
* @var \Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory
*/
private $_attCollection;
/**
* VarsMap constructor.
* @param \Magento\Framework\View\Element\Context $context
* @param \Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory $attCollection
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Context $context,
\Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory $attCollection,
array $data = []
) {
parent::__construct($context, $data);
$this->_attCollection = $attCollection;
}
protected function _getAddressAtt()
{
$ret = [];
$ret['default_shipping##zip'] = __('Shipping Zip Code');
$ret['default_shipping##country'] = __('Shipping Country');
$ret['default_shipping##city'] = __('Shipping City');
$ret['default_shipping##state'] = __('Shipping State');
$ret['default_shipping##telephone'] = __('Shipping Telephone');
$ret['default_shipping##company'] = __('Shipping Company');
$ret['default_shipping##street'] = __('Shipping Street');
$ret['default_billing##zip'] = __('Billing Zip Code');
$ret['default_billing##country'] = __('Billing Country');
$ret['default_billing##city'] = __('Billing City');
$ret['default_billing##state'] = __('Billing State');
$ret['default_billing##telephone'] = __('Billing Telephone');
$ret['default_billing##company'] = __('Billing Company');
$ret['default_billing##street'] = __('Billing Street');
return $ret;
}
protected function _getBindableAttributes()
{
$systemAtt = $this->_getCustomerAtt();
$extraAtt = $this->_getAddressAtt();
// Note: We cannot use array_merge here because we need to hold
// numeric indexes as they are
$ret = $systemAtt + $extraAtt;
natsort($ret);
return $ret;
}
protected function _getCustomerAtt()
{
$ret = [];
$collection = $this->_attCollection->create();
/**
* @var $item \Magento\Customer\Model\Attribute
*/
foreach ($collection as $item) {
$ret[$item->getId()] = $item->getFrontendLabel();
}
natsort($ret);
return $ret;
}
public function setInputName($value)
{
return $this->setName($value);
}
/**
* Render block HTML
*
* @return string
*/
public function _toHtml()
{
if (!$this->getOptions()) {
foreach ($this->_getBindableAttributes() as $attId => $attLabel) {
$this->addOption($attId, $this->escapeHtmlAttr($attLabel));
}
}
return parent::_toHtml();
}
}
================================================
FILE: Block/Adminhtml/System/Config/OauthWizard.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class OauthWizard extends \Magento\Config\Block\System\Config\Form\Field
{
protected $_template = 'system/config/oauth_wizard.phtml';
private $_authorizeUri = "https://login.mailchimp.com/oauth2/authorize";
private $_accessTokenUri = "https://login.mailchimp.com/oauth2/token";
private $_redirectUri = "https://ebizmarts.com/magento/mc-magento2/oauth2/complete.php";
private $_clientId = 390007044048;
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->authorizeRequestUrl(),
'html_id' => $element->getHtmlId(),
]);
return parent::_toHtml();
;
}
public function authorizeRequestUrl()
{
$url = $this->_authorizeUri;
$redirectUri = urlencode($this->_redirectUri);
return "{$url}?redirect_uri={$redirectUri}&response_type=code&client_id={$this->_clientId}";
}
}
================================================
FILE: Block/Adminhtml/System/Config/ResetErrors.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/20/17 3:25 PM
* @file: ResetErrors.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class ResetErrors extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* ResetErrors constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data = []
) {
$this->_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/reseterrors.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
public function getButtonHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]);
return $this->_toHtml();
}
public function getAjaxCheckUrl()
{
$params = $this->getRequest()->getParams();
$scope = [];
if (isset($params['website'])) {
$scope = ['website'=>$params['website']];
} elseif (isset($params['store'])) {
$scope = ['store'=>$params['store']];
}
return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetLocalErrors', $scope);
}
}
================================================
FILE: Block/Adminhtml/System/Config/ResetErrorsNoRetry.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/20/17 3:25 PM
* @file: ResetErrors.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class ResetErrorsNoRetry extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* ResetErrors constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data = []
) {
$this->_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/reseterrorsnoretry.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
public function getButtonHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]);
return $this->_toHtml();
}
public function getAjaxCheckUrl()
{
$params = $this->getRequest()->getParams();
$scope = [];
if (isset($params['website'])) {
$scope = ['website'=>$params['website']];
} elseif (isset($params['store'])) {
$scope = ['store'=>$params['store']];
}
return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetLocalErrorsNoRetry', $scope);
}
}
================================================
FILE: Block/Adminhtml/System/Config/ResetStore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/20/17 3:25 PM
* @file: ResetErrors.php
*/
namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config;
class ResetStore extends \Magento\Config\Block\System\Config\Form\Field
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* ResetErrors constructor.
* @param \Magento\Backend\Block\Template\Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data = []
) {
$this->_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/resetstore.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
public function getButtonHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$label = $originalData['button_label'];
$this->addData([
'button_label' => __($label),
'button_url' => $this->getAjaxCheckUrl(),
'html_id' => $element->getHtmlId(),
]);
return $this->_toHtml();
}
public function getAjaxCheckUrl()
{
$params = $this->getRequest()->getParams();
$scope = [];
if (isset($params['website'])) {
$scope = ['website'=>$params['website']];
} elseif (isset($params['store'])) {
$scope = ['store'=>$params['store']];
}
return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetStore', $scope);
}
}
================================================
FILE: Block/Adminhtml/System/Config/ResyncProducts.php
================================================
_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/resyncproducts.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
}
================================================
FILE: Block/Adminhtml/System/Config/ResyncSubscriber.php
================================================
_helper = $helper;
parent::__construct($context, $data);
}
protected function _construct()
{
parent::_construct();
$this->setTemplate('system/config/resyncsubscriber.phtml');
}
protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
$originalData = $element->getOriginalData();
$this->addData(
[
'button_label' => __($originalData['button_label']),
'html_id' => $element->getHtmlId(),
]
);
return $this->_toHtml();
}
}
================================================
FILE: Block/Catcher.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/25/17 3:35 PM
* @file: Catcher.php
*/
namespace Ebizmarts\MailChimp\Block;
use Magento\Framework\View\Element\Template;
class Catcher extends Template
{
/**
* @var string $_template
*/
protected $_template = "catcher.phtml";
// write your methods here...
}
================================================
FILE: Block/Checkout/Success.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/13/17 4:41 PM
* @file: Success.php
*/
namespace Ebizmarts\MailChimp\Block\Checkout;
class Success extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $_subscriberFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory
*/
protected $_interestGroupFactory;
/**
* @var \Magento\Framework\View\Element\Template\Context
*/
protected $_context;
/**
* Success constructor.
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory,
array $data
) {
parent::__construct($context, $data);
$this->_checkoutSession = $checkoutSession;
$this->_helper = $helper;
$this->_subscriberFactory = $subscriberFactory;
$this->_interestGroupFactory= $interestGroupFactory;
$this->_context = $context;
}
public function getInterest()
{
$order = $this->_checkoutSession->getLastRealOrder();
/**
* @var $subscriber \Magento\Newsletter\Model\Subscriber
*/
$subscriber = $this->_subscriberFactory->create();
$subscriber->loadByEmail($order->getCustomerEmail());
return $this->_helper->getSubscriberInterest($subscriber->getSubscriberId(), $subscriber->getStoreId());
}
protected function getValues($category)
{
$rc =[];
foreach ($category as $c) {
$rc[] = ['value'=>$c['id'],'label'=>$c['name']];
}
return $rc;
}
public function getMessageBefore()
{
return $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_INTEREST_SUCCESS_HTML_BEFORE);
}
public function getMessageAfter()
{
return $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_INTEREST_SUCCESS_HTML_AFTER);
}
public function getFormUrl()
{
$order = $this->_checkoutSession->getLastRealOrder();
return $this->_helper->getSuccessInterestUrl($order->getStoreId());
}
public function _toHtml()
{
if (!$this->_helper->isMailChimpEnabled($this->_context->getStoreManager()->getStore()->getId())) {
return "";
}
return parent::_toHtml();
}
}
================================================
FILE: Block/Loadquote.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/8/17 12:00 PM
* @file: Mailchimpjs.php
*/
namespace Ebizmarts\MailChimp\Block;
use Magento\Store\Model\ScopeInterface;
class Mailchimpjs extends \Magento\Framework\View\Element\Template
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* Mailchimpjs constructor.
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data
) {
parent::__construct($context, $data);
$this->_helper = $helper;
$this->_storeManager = $context->getStoreManager();
}
public function getJsUrl()
{
$storeId = $this->_storeManager->getStore()->getId();
$url = $this->_scopeConfig->getValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_JS_URL, ScopeInterface::SCOPE_STORES,
$storeId
);
$active = $this->_scopeConfig->getValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ACTIVE, ScopeInterface::SCOPE_STORES,
$storeId
);
// if we have URL cached or integration is disabled
// then avoid initialization of Mailchimp Helper and all linked classes (~30 classes)
if ($active && !$url) {
$url = $this->_helper->getJsUrl($storeId);
}
return $url;
}
}
================================================
FILE: Block/Newsletter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/23/17 4:40 PM
* @file: Newsletter.php
*/
namespace Ebizmarts\MailChimp\Block;
class Newsletter extends \Magento\Framework\View\Element\Template
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;
/**
* Newsletter constructor.
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Ebizmarts\MailChimp\Helper\Data $helper,
array $data
) {
parent::__construct($context, $data);
$this->_helper = $helper;
$this->subscriberFactory = $subscriberFactory;
$this->customerSession = $customerSession;
}
public function getInterest()
{
$subscriber = $this->subscriberFactory->create();
$subscriber->loadByCustomerId($this->customerSession->getCustomerId());
// $subscriber = $this->getSubscriptionObject();
return $this->_helper->getSubscriberInterest($subscriber->getSubscriberId(), $subscriber->getStoreId());
}
public function getFormUrl()
{
return $this->getUrl('mailchimp/accountmanage/save');
}
}
================================================
FILE: Block/Subscribe.php
================================================
context = $context;
$this->helper = $helper;
}
public function getPopupUrl()
{
$storeId = $this->context->getStoreManager()->getStore()->getId();
return $this->helper->getConfigValue(MailchimpHelper::XML_POPUP_URL,$storeId);
}
}
================================================
FILE: CHANGELOG.md
================================================
# Change Log
## [102.3.78](https://github.com/mailchimp/mc-magento2/tree/102.3.78)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.77...102.3.78)
**Fixed bugs:**
- Error when delete the current mailchimp store and access the configuration [\#2268](https://github.com/mailchimp/mc-magento2/issues/2268)
- New order/cart send product as new [\#2262](https://github.com/mailchimp/mc-magento2/issues/2262)
- Products permanently stuck in SYNCERROR or NEEDTORESYNC [\#2256](https://github.com/mailchimp/mc-magento2/issues/2256)
- Array to string conversion warning [\#2250](https://github.com/mailchimp/mc-magento2/issues/2250)
## [102.3.77](https://github.com/mailchimp/mc-magento2/tree/102.3.77)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.76...102.3.77)
**Implemented enhancements:**
- Send an event every time visit an abandoned cart [\#2233](https://github.com/mailchimp/mc-magento2/issues/2233)
**Fixed bugs:**
- Ebizmarts\MailChimp\Model\Api\Product.php can break during iteration [\#2239](https://github.com/mailchimp/mc-magento2/issues/2239)
- Incorrect DATETIME value: '' [\#2227](https://github.com/mailchimp/mc-magento2/issues/2227)
## [102.3.76](https://github.com/mailchimp/mc-magento2/tree/102.3.76)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.75...102.3.76)
**Implemented enhancements:**
- Feature Request: Store customers email in logs for abandoned baskets. [\#2084](https://github.com/mailchimp/mc-magento2/issues/2084)
**Fixed bugs:**
- Error cleaning the mailchimp\_statistics table [\#2210](https://github.com/mailchimp/mc-magento2/issues/2210)
## [102.3.75](https://github.com/mailchimp/mc-magento2/tree/102.3.75)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.74...102.3.75)
**Implemented enhancements:**
- Add total amount of subscribers to the registration [\#2199](https://github.com/mailchimp/mc-magento2/issues/2199)
- Add data to the registration [\#2192](https://github.com/mailchimp/mc-magento2/issues/2192)
## [102.3.74](https://github.com/mailchimp/mc-magento2/tree/102.3.74)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.73...102.3.74)
**Implemented enhancements:**
- Add flag to sync not salable products [\#2181](https://github.com/mailchimp/mc-magento2/issues/2181)
## [102.3.73](https://github.com/mailchimp/mc-magento2/tree/102.3.73)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.72...102.3.73)
**Implemented enhancements:**
- Change the way that the statistics are synced [\#2167](https://github.com/mailchimp/mc-magento2/issues/2167)
## [102.3.72](https://github.com/mailchimp/mc-magento2/tree/102.3.72)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.71...102.3.72)
**Implemented enhancements:**
- Add support for grouped products [\#2156](https://github.com/mailchimp/mc-magento2/issues/2156)
## [102.3.71](https://github.com/mailchimp/mc-magento2/tree/102.3.71)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.70...102.3.71)
**Implemented enhancements:**
- Add the bundle product itself to the lines of the cart [\#2142](https://github.com/mailchimp/mc-magento2/issues/2142)
- Add the bundle product itself to the lines of the order [\#2136](https://github.com/mailchimp/mc-magento2/issues/2136)
## [102.3.70](https://github.com/mailchimp/mc-magento2/tree/102.3.70)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.69...102.3.70)
**Implemented enhancements:**
- Add clean period for mailchimp\_notification table [\#2118](https://github.com/mailchimp/mc-magento2/issues/2118)
- Add bundle products support [\#2112](https://github.com/mailchimp/mc-magento2/issues/2112)
**Fixed bugs:**
- Add translation for options mergevar [\#2124](https://github.com/mailchimp/mc-magento2/issues/2124)
## [102.3.69](https://github.com/mailchimp/mc-magento2/tree/HEAD)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.68...102.3.69)
**Fixed bugs:**
- Huge memory usage from ebizmarts\_generate\_statistics cron [\#2098](https://github.com/mailchimp/mc-magento2/issues/2098)
# [102.3.68](https://github.com/mailchimp/mc-magento2/tree/102.3.68)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.67...102.3.68)
**Fixed bugs:**
- SyncStatistics error when the data in mailchimp\_notification is not a valid json [\#2083](https://github.com/mailchimp/mc-magento2/issues/2083)
## [102.3.67](https://github.com/mailchimp/mc-magento2/tree/102.3.67)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.66...102.3.67)
**Fixed bugs:**
- Cron is taking long time \(special price related\) [\#2063](https://github.com/mailchimp/mc-magento2/issues/2063)
- Deprecated Warning in Order.php - Null passed to hash\(\) on orders without email \(PHP 8.3\) [\#2062](https://github.com/mailchimp/mc-magento2/issues/2062)
## [102.3.66](https://github.com/mailchimp/mc-magento2/tree/102.3.66)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.65...102.3.66)
**Implemented enhancements:**
- Include the Billing and Shipping street in the maps fields [\#2043](https://github.com/mailchimp/mc-magento2/issues/2043)
- Generate support data [\#2041](https://github.com/mailchimp/mc-magento2/issues/2041)
- Put a config to sync only customers with orders [\#2035](https://github.com/mailchimp/mc-magento2/issues/2035)
## [102.3.65](https://github.com/mailchimp/mc-magento2/tree/102.3.65)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.64...102.3.65)
**Implemented enhancements:**
- missing i18n translation [\#1983](https://github.com/mailchimp/mc-magento2/issues/1983)
**Fixed bugs:**
- Merge field value is deleted on the Magento store, but not on Mailchimp [\#1388](https://github.com/mailchimp/mc-magento2/issues/1388)
- Wrong total revenue in MailChimp [\#395](https://github.com/mailchimp/mc-magento2/issues/395)
## [102.3.64](https://github.com/mailchimp/mc-magento2/tree/102.3.64)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.63...102.3.64)
**Fixed bugs:**
- Manage deleted and not salable products [\#2003](https://github.com/mailchimp/mc-magento2/issues/2003)
- Configuration page in Magento's backend takes a long time to load in certain cases [\#2002](https://github.com/mailchimp/mc-magento2/issues/2002)
## [102.3.63](https://github.com/mailchimp/mc-magento2/tree/102.3.63)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.62...103.3.63)
**Implemented enhancements:**
- Add the date to the error grid [\#1972](https://github.com/mailchimp/mc-magento2/issues/1972)
**Fixed bugs:**
- Order status change is not synced when done through webapi [\#1985](https://github.com/mailchimp/mc-magento2/issues/1985)
- Column not found: 1054 Unknown column 'mailchimp\_sync' in 'order clause' [\#1981](https://github.com/mailchimp/mc-magento2/issues/1981)
## [102.3.62](https://github.com/mailchimp/mc-magento2/tree/102.3.62)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.61...102.3.62)
**Fixed bugs:**
- Bad financial status in mailchimp [\#1962](https://github.com/mailchimp/mc-magento2/issues/1962)
## [101.2.61](https://github.com/mailchimp/mc-magento2/tree/102.3.61)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.60...102.3.61)
**Implemented enhancements:**
- Put the inventory\_quantity = 0 when delete a product in magento [\#1945](https://github.com/mailchimp/mc-magento2/issues/1945)
**Fixed bugs:**
- Doesn't search for customer activity for modified orders [\#1951](https://github.com/mailchimp/mc-magento2/issues/1951)
- Abandoned cart button doesn't load the cart when click on it [\#1939](https://github.com/mailchimp/mc-magento2/issues/1939)
## [102.3.60](https://github.com/mailchimp/mc-magento2/tree/102.3.60)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.59...102.3.60)
**Fixed bugs:**
- The token change and can't retrieve the cart from the abandoned cart email [\#1930](https://github.com/mailchimp/mc-magento2/issues/1930)
- Abs fail when discount amount is null [\#1921](https://github.com/mailchimp/mc-magento2/issues/1921)
- Error table prefix [\#1920](https://github.com/mailchimp/mc-magento2/issues/1920)
- Check in webhook cron if the listid is OK when get the groups [\#1914](https://github.com/mailchimp/mc-magento2/issues/1914)
## [102.3.58](https://github.com/mailchimp/mc-magento2/tree/102.3.58)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.57...102.3.58)
**Implemented enhancements:**
- Add controls to the webhook cron to exclude stores with no mailchimp store [\#1880](https://github.com/mailchimp/mc-magento2/issues/1880)
- Use the activity API end point to fill the campaign id [\#1866](https://github.com/mailchimp/mc-magento2/issues/1866)
**Fixed bugs:**
- Sometimes the mailchimp\_sync\_modified and mailchimp\_sent fields in mailchimp\_sync\_ecommerce are not synchronized [\#1891](https://github.com/mailchimp/mc-magento2/issues/1891)
- SQL Error on config page right after installation [\#1865](https://github.com/mailchimp/mc-magento2/issues/1865)
- Trinidad & Tobago country incorrectly synced [\#1863](https://github.com/mailchimp/mc-magento2/issues/1863)
- Unescaped output [\#1841](https://github.com/mailchimp/mc-magento2/issues/1841)
- Cannot save some customers [\#1840](https://github.com/mailchimp/mc-magento2/issues/1840)
- Error "Resource Not Found for Api Call:" when try to access batches grid [\#1834](https://github.com/mailchimp/mc-magento2/issues/1834)
- Magento subscription email sent despite 'Magento always managed emails' set to 'No' [\#1311](https://github.com/mailchimp/mc-magento2/issues/1311)
## [102.3.57](https://github.com/mailchimp/mc-magento2/tree/102.3.57)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.56...102.3.57)
**Fixed bugs:**
- The order is not marked as modified when cancel [\#1822](https://github.com/mailchimp/mc-magento2/issues/1822)
- Unable to assign a customer to another website [\#1818](https://github.com/mailchimp/mc-magento2/issues/1818)
## [102.3.56](https://github.com/mailchimp/mc-magento2/tree/102.3.56)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.55...102.3.56)
**Implemented enhancements:**
- MailChimp Customer Tab Empty [\#1804](https://github.com/mailchimp/mc-magento2/issues/1804)
## [102.3.55](https://github.com/mailchimp/mc-magento2/tree/102.3.55)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.54...102.3.55)
**Fixed bugs:**
- Checkout is broken (error in the etc/di.xml) [\#1790](https://github.com/mailchimp/mc-magento2/issues/1790)
## [102.3.54](https://github.com/mailchimp/mc-magento2/tree/102.3.54)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.53...102.3.54)
**Implemented enhancements:**
- Performance: Excessive SQL usage in Sales and Products Grid [\#1759](https://github.com/mailchimp/mc-magento2/issues/1759)
- Remove unused code in Heper/Data.php [\#1753](https://github.com/mailchimp/mc-magento2/issues/1753)
**Fixed bugs:**
- Upgrade to 103.4.53 caused UPDATE on over 60% of the existing \(old\) orders [\#1772](https://github.com/mailchimp/mc-magento2/issues/1772)
- ebizmarts\_ecommerce job unchecks "Use Default Value" checkbox for some product attributes [\#1758](https://github.com/mailchimp/mc-magento2/issues/1758)
- Check if the Abandoned cart is enabled, the ecommerce must be enabled [\#1745](https://github.com/mailchimp/mc-magento2/issues/1745)
## [102.3.53](https://github.com/mailchimp/mc-magento2/tree/102.3.53)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.52...102.3.53)
**Fixed bugs:**
- Cannot upgrade to latest version due to patch error [\#1732](https://github.com/mailchimp/mc-magento2/issues/1732)
## [102.3.52](https://github.com/mailchimp/mc-magento2/tree/102.3.52)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.51...102.3.52)
**Implemented enhancements:**
- Optimize the product grid to avoid access the ecommerce table [\#1714](https://github.com/mailchimp/mc-magento2/issues/1714)
- Optimize the order grid to avoid access the ecommerce table [\#1708](https://github.com/mailchimp/mc-magento2/issues/1708)
- Add an option in the configuration page to modify the timeout in the Mailchimp api connections [\#1697](https://github.com/mailchimp/mc-magento2/issues/1697)
- Add links to campaign and member in mailchimp in the order grid [\#1690](https://github.com/mailchimp/mc-magento2/issues/1690)
**Fixed bugs:**
- The sync of orders fails if the order has no billing address [\#1720](https://github.com/mailchimp/mc-magento2/issues/1720)
## [102.3.51](https://github.com/mailchimp/mc-magento2/tree/102.3.51)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.50...102.3.51)
**Implemented enhancements:**
- Put tracking\_number when the order is shipped [\#1667](https://github.com/mailchimp/mc-magento2/issues/1667)
- Create a grid to show our cronjobs in the cron\_schedule [\#1648](https://github.com/mailchimp/mc-magento2/issues/1648)
- Create JS code that automatically enables ecommerce syncing when abandoned cart syncing is disabled [\#1633](https://github.com/mailchimp/mc-magento2/issues/1633)
**Fixed bugs:**
- Invoice and shipment pluging doesn't work [\#1668](https://github.com/mailchimp/mc-magento2/issues/1668)
- Error fetching store ID row in batch grid [\#1656](https://github.com/mailchimp/mc-magento2/issues/1656)
- Duplicate entries in the stores grid [\#1650](https://github.com/mailchimp/mc-magento2/issues/1650)
- Resync subscribers and Resync products always resyncs default store [\#1640](https://github.com/mailchimp/mc-magento2/issues/1640)
- Database schema needed for batch grid won't be created after upgrading module as opposed to installing it [\#1627](https://github.com/mailchimp/mc-magento2/issues/1627)
- Bad class name [\#1613](https://github.com/mailchimp/mc-magento2/issues/1613)
- Fail phpcs test [\#1607](https://github.com/mailchimp/mc-magento2/issues/1607)
## [102.3.50](https://github.com/mailchimp/mc-magento2/tree/102.3.50)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.49...102.3.50)
**Implemented enhancements:**
- Clean the error table automatically based on a configuration setting [\#1577](https://github.com/mailchimp/mc-magento2/issues/1577)
- Slow-query optimization for product special prices [\#1569](https://github.com/mailchimp/mc-magento2/issues/1569)
- Create grid in admin that shows batch information [\#1465](https://github.com/mailchimp/mc-magento2/issues/1465)
**Fixed bugs:**
- The carts are not deleted from mailchimp when are converted in an order [\#1595](https://github.com/mailchimp/mc-magento2/issues/1595)
- Add a button to fix the chimpstatic js in the frontend [\#1584](https://github.com/mailchimp/mc-magento2/issues/1584)
## [102.3.49](https://github.com/mailchimp/mc-magento2/tree/102.3.49)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.48...102.3.49)
**Implemented enhancements:**
- Query optimization for special prices [\#1535](https://github.com/mailchimp/mc-magento2/issues/1535)
**Fixed bugs:**
- Wrong query when load the configuration page and use db prefix [\#1557](https://github.com/mailchimp/mc-magento2/issues/1557)
- The subcribe at the bottom doesn't work [\#1551](https://github.com/mailchimp/mc-magento2/issues/1551)
- "Magento always manage emails" configuration blocking default Magento newsletter confirm email sending [\#1545](https://github.com/mailchimp/mc-magento2/issues/1545)
- Wrong column name in mailchimp\_stores [\#1533](https://github.com/mailchimp/mc-magento2/issues/1533)
## [102.3.48](https://github.com/mailchimp/mc-magento2/tree/102.3.48) (2022-08-18)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.47...102.3.48)
**Implemented enhancements:**
- Point the wiki to the github wiki [\#1522](https://github.com/mailchimp/mc-magento2/issues/1522)
**Fixed bugs:**
- Observer name "sales\_order\_save\_after" is too generic. [\#1516](https://github.com/mailchimp/mc-magento2/issues/1516)
- Error saving configuration when install the extension for the first time [\#1510](https://github.com/mailchimp/mc-magento2/issues/1510)
## [102.3.47](https://github.com/mailchimp/mc-magento2/tree/102.3.47) (2022-08-15)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.46...102.3.47)
**Implemented enhancements:**
- Add a button to truncate the error table BUT not to retry the objects with erros [\#1498](https://github.com/mailchimp/mc-magento2/issues/1498)
- Change the footer subscribe button and open a popup with the mailchimp form to subscribe [\#1487](https://github.com/mailchimp/mc-magento2/issues/1487)
- Large mailchimp\_sync\_ecommerce table with unused registers [\#1475](https://github.com/mailchimp/mc-magento2/issues/1475)
**Fixed bugs:**
- Custom boolean customer attribute not synced correctly to Mailchimp [\#1474](https://github.com/mailchimp/mc-magento2/issues/1474)
- Migrate the update data to the patches approach [\#1472](https://github.com/mailchimp/mc-magento2/issues/1472)
## [102.3.46](https://github.com/mailchimp/mc-magento2/tree/102.3.46) (2022-07-19)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.45...102.3.46)
**Implemented enhancements:**
- Rewrite "This MailChimp account is not connected to Magento" label to make it more clear [\#1448](https://github.com/mailchimp/mc-magento2/issues/1448)
- Add a synchorization column in the customer grid [\#1439](https://github.com/mailchimp/mc-magento2/issues/1439)
- Add a synchorization column in the product grid [\#1438](https://github.com/mailchimp/mc-magento2/issues/1438)
- Add button on backend to create the abandoned cart automation [\#1432](https://github.com/mailchimp/mc-magento2/issues/1432)
**Fixed bugs:**
- Missing fields in Cart.php on db call [\#1460](https://github.com/mailchimp/mc-magento2/issues/1460)
- Wrong field map value when is null [\#1425](https://github.com/mailchimp/mc-magento2/issues/1425)
- Can't get the response file from a batch [\#1414](https://github.com/mailchimp/mc-magento2/issues/1414)
- Unmark the modified flag in the ecommerce table when an object is synced [\#1408](https://github.com/mailchimp/mc-magento2/issues/1408)
- Don't use Zend\_Db\_Select::COLUMNS [\#1405](https://github.com/mailchimp/mc-magento2/issues/1405)
## [102.3.45](https://github.com/mailchimp/mc-magento2/tree/102.3.45)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.44...102.3.45)
**Implemented enhancements:**
- Query optimization for ecommerce table [\#1391](https://github.com/mailchimp/mc-magento2/issues/1391)
- Add the possibility to send the company as a merge field [\#1369](https://github.com/mailchimp/mc-magento2/issues/1369)
- Make uninstall [\#1347](https://github.com/mailchimp/mc-magento2/issues/1347)
- Performance Issue During Product Import [\#1309](https://github.com/mailchimp/mc-magento2/issues/1309)
**Fixed bugs:**
- Subscribers are not added to mailchimp [\#1359](https://github.com/mailchimp/mc-magento2/issues/1359)
- The sync fails when an order contains a deleted product [\#1330](https://github.com/mailchimp/mc-magento2/issues/1330)
- Problem syncing country with customer address [\#1329](https://github.com/mailchimp/mc-magento2/issues/1329)
- Chimpstatic wrong url when change the mailchimp store [\#1322](https://github.com/mailchimp/mc-magento2/issues/1322)
- Error creating the webhook, wrong webhook url [\#1316](https://github.com/mailchimp/mc-magento2/issues/1316)
## [102.3.44](https://github.com/mailchimp/mc-magento2/tree/102.3.44)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.43...102.3.44)
**Implemented enhancements:**
- Add option in the error grid to link to the register with error [\#1279](https://github.com/mailchimp/mc-magento2/issues/1279)
**Fixed bugs:**
- Incorrect image url with some extensions \(p.e. cloudinary extension\) [\#1288](https://github.com/mailchimp/mc-magento2/issues/1288)
- Modify order totals to $0 when order is cancelled [\#1272](https://github.com/mailchimp/mc-magento2/issues/1272)
- Typo at https://github.com/mailchimp/mc-magento2/blob/develop-2.3/Model/Api/Order.php\#L29 [\#1249](https://github.com/mailchimp/mc-magento2/issues/1249)
- Deleting error records causes database lockup [\#1242](https://github.com/mailchimp/mc-magento2/issues/1242)
- Change the echo with helper-\>log in https://github.com/mailchimp/mc-magento2/blob/develop-2.3/Observer/Adminhtml/Product/ImportAfter.php\#L40 [\#1228](https://github.com/mailchimp/mc-magento2/issues/1228)
- ImportAfter observer is throwing exceptions if the \_store column is not present in the import data [\#1224](https://github.com/mailchimp/mc-magento2/issues/1224)
- Error retrieving the response of a batch from mailchimp [\#1204](https://github.com/mailchimp/mc-magento2/issues/1204)
- Avoid duplicate entries in the stores grid [\#1217](https://github.com/mailchimp/mc-magento2/issues/1217)
- Unable to create a new Mailchimp Store in admin [\#1208](https://github.com/mailchimp/mc-magento2/issues/1208)
## [102.3.43](https://github.com/mailchimp/mc-magento2/tree/102.3.43)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.42...102.3.43)
**Implemented enhancements:**
- Add a button in the admin to resync all products [\#1184](https://github.com/mailchimp/mc-magento2/issues/1184)
- Missing indexes on mailchimp\_errors [\#1162](https://github.com/mailchimp/mc-magento2/issues/1162)
- Ignore modified items when flagging store as synced [\#1140](https://github.com/mailchimp/mc-magento2/issues/1140)
- Only fetch specific columns from sales\_order [\#1134](https://github.com/mailchimp/mc-magento2/issues/1134)
- Error table never getting cleaned up [\#1107](https://github.com/mailchimp/mc-magento2/issues/1107)
**Fixed bugs:**
- Change the low value for date sync to a valid one [\#1192](https://github.com/mailchimp/mc-magento2/issues/1192)
- Exclude the bundle and grouped products for the product collection [\#1191](https://github.com/mailchimp/mc-magento2/issues/1191)
- The product image url don't contain the secure url if Use Secure URLs on Storefront is ON [\#1179](https://github.com/mailchimp/mc-magento2/issues/1179)
- Mark products as modified when use import products from the admin [\#1167](https://github.com/mailchimp/mc-magento2/issues/1167)
- Issue with "Magento Always Manage Emails" when Unsubscribing from a Customer Account [\#1157](https://github.com/mailchimp/mc-magento2/issues/1157)
- errors in cron related to ebizmarts\_webhooks [\#1152](https://github.com/mailchimp/mc-magento2/issues/1152)
- Ecommerce order send loop [\#1112](https://github.com/mailchimp/mc-magento2/issues/1112)
- Allow more than 10 interest inside a group [\#1103](https://github.com/mailchimp/mc-magento2/issues/1103)
- observer name that breaks Magento 2 DOM XML [\#1102](https://github.com/mailchimp/mc-magento2/issues/1102)
- CSP Whitelist Support [\#1097](https://github.com/mailchimp/mc-magento2/issues/1097)
- Infinite loop on customer account creation if email present in newsletter subscribers list [\#1090](https://github.com/mailchimp/mc-magento2/issues/1090)
- Ecommerce Cron error "Requested country is not available." [\#1084](https://github.com/mailchimp/mc-magento2/issues/1084)
- Subscribing for a second time does not work. [\#1078](https://github.com/mailchimp/mc-magento2/issues/1078)
## [102.3.42](https://github.com/mailchimp/mc-magento2/tree/102.3.42)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.41...102.3.42)
**Implemented enhancements:**
- Create custom field mapping [\#1025](https://github.com/mailchimp/mc-magento2/issues/1025)
**Fixed bugs:**
- Subscribing for a second time does not work. [\#1078](https://github.com/mailchimp/mc-magento2/issues/1078)
- Invalid date format when use mysql 8 [\#1066](https://github.com/mailchimp/mc-magento2/issues/1066)
- Unable to capture the order for a campaign [\#1065](https://github.com/mailchimp/mc-magento2/issues/1065)
- Notice: Undefined index: image\_url Model/Api/Product.php [\#1059](https://github.com/mailchimp/mc-magento2/issues/1059)
- Multistore product sync wrong name [\#1055](https://github.com/mailchimp/mc-magento2/issues/1055)
## [102.3.41](https://github.com/mailchimp/mc-magento2/tree/102.3.41)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.40...102.3.41)
**Implemented enhancements:**
- Coupon Codes \(Promo Codes\) Do Not Send to Mailchimp With Order Data [\#1032](https://github.com/mailchimp/mc-magento2/issues/1032)
**Fixed bugs:**
- "Unable to unserialize value." issue avoids ecommerce syncing. This happens some times when "Send Promo Codes and Promo Rules" is enabled [\#1035](https://github.com/mailchimp/mc-magento2/issues/1035)
- Fallback to JQueryUI Compat activated. [\#1034](https://github.com/mailchimp/mc-magento2/issues/1034)
- Abandoned Cart revenue not showing on Mailchimp account [\#1033](https://github.com/mailchimp/mc-magento2/issues/1033)
## [102.3.40](https://github.com/mailchimp/mc-magento2/tree/102.3.40)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.39...102.3.40)
**Implemented enhancements:**
- Add magento 2.4 compatibility [\#1027](https://github.com/mailchimp/mc-magento2/issues/1027)
## [102.3.39](https://github.com/mailchimp/mc-magento2/tree/102.3.39)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.38...102.3.39)
**Implemented enhancements:**
- Licensing? [\#996](https://github.com/mailchimp/mc-magento2/issues/996)
**Fixed bugs:**
- Typo in campaigncatcher.js causing Javascript error [\#1015](https://github.com/mailchimp/mc-magento2/issues/1015)
- The mailchimp groups are not shown correctly in the customer account [\#1009](https://github.com/mailchimp/mc-magento2/issues/1009)
- Improper call to interest-categories in the webhook processing [\#1002](https://github.com/mailchimp/mc-magento2/issues/1002)
- MapFields not getting synced when configured in storeView. [\#998](https://github.com/mailchimp/mc-magento2/issues/998)
- Eternal Spinning gif after invalid API key has been entered in the configuration [\#990](https://github.com/mailchimp/mc-magento2/issues/990)
- Syncing customer group changed some customers group id to 0 [\#989](https://github.com/mailchimp/mc-magento2/issues/989)
- Issue syncing DOB merge field [\#987](https://github.com/mailchimp/mc-magento2/issues/987)
- JS error on product page with slow internet [\#912](https://github.com/mailchimp/mc-magento2/issues/912)
## [102.3.38](https://github.com/mailchimp/mc-magento2/tree/102.3.38)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.37...102.3.38)
**Implemented enhancements:**
- Optimize MailChimp JS block [\#895](https://github.com/mailchimp/mc-magento2/issues/895)
- Optimize MailChimp JS block [\#891](https://github.com/mailchimp/mc-magento2/pull/891) ([andrey-legayev](https://github.com/andrey-legayev))
**Fixed bugs:**
- Incorrect import in Webhook controller [\#976](https://github.com/mailchimp/mc-magento2/issues/976)
- The street line 3 is not synced in orders [\#963](https://github.com/mailchimp/mc-magento2/issues/963)
- Loading screen stuck when attempting to save the API key. [\#940](https://github.com/mailchimp/mc-magento2/issues/940)
- \[Performance Issue\] HTTP calls to mailchimp on every page request and config cache flush [\#939](https://github.com/mailchimp/mc-magento2/issues/939)
- Strong check for interest groups [\#932](https://github.com/mailchimp/mc-magento2/issues/932)
- Take the first date value from storeview scope. [\#931](https://github.com/mailchimp/mc-magento2/issues/931)
- Bad management of the groups in the webhooks [\#926](https://github.com/mailchimp/mc-magento2/issues/926)
- Error grid, bad data when try to sort for one field 3 times [\#922](https://github.com/mailchimp/mc-magento2/issues/922)
- Uncaught TypeError: strpos\(\) expects parameter 1 to be string, null given in vendor/magento/module-theme/Controller/Result/JsFooterPlugin.php:44 in Magento 2.3.3 [\#920](https://github.com/mailchimp/mc-magento2/issues/920)
- JS error on product page with slow internet [\#912](https://github.com/mailchimp/mc-magento2/issues/912)
- Invalid API key error when attempting to update settings. [\#906](https://github.com/mailchimp/mc-magento2/issues/906)
- Typo in Ecommerce cron when mark an object with error [\#900](https://github.com/mailchimp/mc-magento2/issues/900)
- Error in cron when split databases [\#887](https://github.com/mailchimp/mc-magento2/issues/887)
- Make changes to pass code sniffer [\#881](https://github.com/mailchimp/mc-magento2/issues/881)
- Fix catching campaign with enabled Varnish FPC [\#874](https://github.com/mailchimp/mc-magento2/issues/874)
- Fix incorrect import in Webhook controller [\#973](https://github.com/mailchimp/mc-magento2/pull/973) ([ihor-sviziev](https://github.com/ihor-sviziev))
## [102.3.37](https://github.com/mailchimp/mc-magento2/tree/102.3.37)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.36...102.3.37)
**Implemented enhancements:**
- Make strong check for the API key [\#849](https://github.com/mailchimp/mc-magento2/issues/849)
- Add alt text to the order grid in the mailchimp sync image [\#810](https://github.com/mailchimp/mc-magento2/issues/810)
- Send the merge\_fields for customers [\#790](https://github.com/mailchimp/mc-magento2/issues/790)
**Fixed bugs:**
- Do not add anything to frontend if module disabled [\#866](https://github.com/mailchimp/mc-magento2/issues/866)
- Made sure a missing "simple\_sku" won't break the entire sync [\#862](https://github.com/mailchimp/mc-magento2/issues/862)
- Not all batches are saved when multi store enabled [\#857](https://github.com/mailchimp/mc-magento2/issues/857)
- Mark orders with error to not try to re-sync [\#841](https://github.com/mailchimp/mc-magento2/issues/841)
- PayPal Express orders sync fails - Last name is NULL [\#840](https://github.com/mailchimp/mc-magento2/issues/840)
- Bad management of old batches [\#821](https://github.com/mailchimp/mc-magento2/issues/821)
- Bad batches management [\#817](https://github.com/mailchimp/mc-magento2/issues/817)
- Bad way to test if the json\_encode fails [\#805](https://github.com/mailchimp/mc-magento2/issues/805)
- Rename delete customer account option [\#801](https://github.com/mailchimp/mc-magento2/issues/801)
- Orders with no products are not marked as synced [\#797](https://github.com/mailchimp/mc-magento2/issues/797)
- Re sync the subscriber when the customer is modified [\#786](https://github.com/mailchimp/mc-magento2/issues/786)
- Use always the md5 of the customer email to identify the customer [\#782](https://github.com/mailchimp/mc-magento2/issues/782)
- Error when select a website scope in config [\#773](https://github.com/mailchimp/mc-magento2/issues/773)
- Change the Resync Customers button [\#768](https://github.com/mailchimp/mc-magento2/issues/768)
- ebizmarts\_ecommerce has an error [\#767](https://github.com/mailchimp/mc-magento2/issues/767)
- Unhandled `Magento\Framework\Serialize\Serializer\Json::\(un\)serialize` calls [\#758](https://github.com/mailchimp/mc-magento2/issues/758)
## [102.3.36](https://github.com/mailchimp/mc-magento2/tree/102.3.36)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.35...102.3.36)
**Implemented enhancements:**
- Take the version from the composer.json [\#759](https://github.com/mailchimp/mc-magento2/issues/759)
## [102.3.35](https://github.com/mailchimp/mc-magento2/tree/102.3.35)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.34...101.2.35)
**Implemented enhancements:**
- Show the amount of list subscribers [\#740](https://github.com/mailchimp/mc-magento2/issues/740)
- Wrong error message in order grid [\#710](https://github.com/mailchimp/mc-magento2/issues/710)
- Add a button to re sync customers [\#702](https://github.com/mailchimp/mc-magento2/issues/702)
- Encrypt sensitive data [\#701](https://github.com/mailchimp/mc-magento2/issues/701)
- Some exceptions are not added into logs, making it hard to find the error message. [\#700](https://github.com/mailchimp/mc-magento2/issues/700)
**Fixed bugs:**
- Remove error message when resend an item with error [\#719](https://github.com/mailchimp/mc-magento2/issues/719)
- Error message 'Resource Not Found' on creating new customers [\#715](https://github.com/mailchimp/mc-magento2/issues/715)
- Don't delete the cart from ecommerce table when the order is made [\#706](https://github.com/mailchimp/mc-magento2/issues/706)
- Success unsubscription, if subscribe again doesn't send confirm subscription emails [\#696](https://github.com/mailchimp/mc-magento2/issues/696)
- Customer and subscriber with same email sent to mailchimp with different id [\#692](https://github.com/mailchimp/mc-magento2/issues/692)
- Order is not marked to resync when the credit memo comes via magento API [\#687](https://github.com/mailchimp/mc-magento2/issues/687)
- Order is not marked to resync when the invoice comes via magento API [\#682](https://github.com/mailchimp/mc-magento2/issues/682)
- Order is not marked to resync when the shipment comes via magento API [\#678](https://github.com/mailchimp/mc-magento2/issues/678)
- Multistore with different Mailchimp account wrong synchronization on customer delete/unsubcribe from magento admin [\#674](https://github.com/mailchimp/mc-magento2/issues/674)
- MySQL error during setup:upgrade after module install \(with split database Magento EE feature enabled\) [\#664](https://github.com/mailchimp/mc-magento2/issues/664)
## [102.3.34](https://github.com/mailchimp/mc-magento2/tree/102.3.34)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.3.33...102.3.34)
**Implemented enhancements:**
- Add link to Terms of service [\#641](https://github.com/mailchimp/mc-magento2/issues/641)
- Delete the Cart register in the sync\_commerce table when confirm the order [\#626](https://github.com/mailchimp/mc-magento2/issues/626)
- Add some other logs [\#602](https://github.com/mailchimp/mc-magento2/issues/602)
- Clean the maichimp\_sync\_batches table [\#598](https://github.com/mailchimp/mc-magento2/issues/598)
- Avoid getByEmail calls when sending Orders and Carts to Mailchimp [\#468](https://github.com/mailchimp/mc-magento2/issues/468)
- Put a column in the order grid to show if the order was synced [\#140](https://github.com/mailchimp/mc-magento2/issues/140)
**Fixed bugs:**
- Change the version numeration to meet the magento marketplace requirements [\#649](https://github.com/mailchimp/mc-magento2/issues/649)
- Save the email in the quote only with the agreement from the customer [\#645](https://github.com/mailchimp/mc-magento2/issues/645)
- Not send the carts until the store is completely synced [\#636](https://github.com/mailchimp/mc-magento2/issues/636)
- Defer the load of the mailchimp js [\#630](https://github.com/mailchimp/mc-magento2/issues/630)
- No first and lastname when the order is from a guest [\#609](https://github.com/mailchimp/mc-magento2/issues/609)
- Subscriber not sent if country state is empty. [\#593](https://github.com/mailchimp/mc-magento2/issues/593)
- Ecommerce cronjob stuck on customers with no address \(error occurs\) [\#400](https://github.com/mailchimp/mc-magento2/issues/400)
## [1.3.33](https://github.com/mailchimp/mc-magento2/tree/1.3.33)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.32...1.3.33)
**Implemented enhancements:**
- Change all mentions from MailChimp to Mailchimp and change the menu icon to the new one [\#565](https://github.com/mailchimp/mc-magento2/issues/565)
- Add possibility to send the product's price including taxes [\#532](https://github.com/mailchimp/mc-magento2/issues/532)
- Sync performance in large stores [\#502](https://github.com/mailchimp/mc-magento2/issues/502)
- Clean the table mailchimp\_webhook\_request [\#486](https://github.com/mailchimp/mc-magento2/issues/486)
- Add option to not send Promo Codes and Promo Rules [\#481](https://github.com/mailchimp/mc-magento2/issues/481)
- Ask for confirmation when removing mailchimp store [\#480](https://github.com/mailchimp/mc-magento2/issues/480)
- add magento 2.3 compatibility [\#494](https://github.com/mailchimp/mc-magento2/pull/494) ([gonzaloebiz](https://github.com/gonzaloebiz))
**Fixed bugs:**
- Spelling error in order status sent to mailchimp [\#574](https://github.com/mailchimp/mc-magento2/issues/574)
- Error during sync: "A campaign with the provided ID does not exist in the account for this list." [\#561](https://github.com/mailchimp/mc-magento2/issues/561)
- No campaign assigned to orders [\#554](https://github.com/mailchimp/mc-magento2/issues/554)
- Missing Customer Fields Mapping [\#553](https://github.com/mailchimp/mc-magento2/issues/553)
- Customers generate entries in the mailchimp\_sycn\_ecommerce with related\_id = null [\#541](https://github.com/mailchimp/mc-magento2/issues/541)
- Re sync the parent product when modifiy a child one [\#537](https://github.com/mailchimp/mc-magento2/issues/537)
- Could not resolve host: xx.api.mailchimp.com [\#523](https://github.com/mailchimp/mc-magento2/issues/523)
- Incorrect price in configurable product [\#513](https://github.com/mailchimp/mc-magento2/issues/513)
- No timezone saved when create a new Mailchimp store [\#512](https://github.com/mailchimp/mc-magento2/issues/512)
- Cart not updated in a Abandoned Cart Series [\#498](https://github.com/mailchimp/mc-magento2/issues/498)
- "Unable to unserialize value " when run the ecommerce cron process [\#473](https://github.com/mailchimp/mc-magento2/issues/473)
- multi-site Customer Fields Mapping not syncing correctly [\#471](https://github.com/mailchimp/mc-magento2/issues/471)
- Previously unsubscribed guest/customer is not resubscribed when selecting groups on success page [\#365](https://github.com/mailchimp/mc-magento2/issues/365)
## [1.0.31](https://github.com/mailchimp/mc-magento2/tree/1.0.31)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.30...1.0.31)
**Implemented enhancements:**
- Add a combo in the Customer Fields Mapping with the MailChimp defined tags [\#423](https://github.com/mailchimp/mc-magento2/issues/423)
**Fixed bugs:**
- Error of serialization when processing webhook data [\#455](https://github.com/mailchimp/mc-magento2/issues/455)
- Don't use serialize function directly [\#451](https://github.com/mailchimp/mc-magento2/issues/451)
- Error when a product has SKU = null [\#448](https://github.com/mailchimp/mc-magento2/issues/448)
- Send the product id in the order when is a configurable [\#445](https://github.com/mailchimp/mc-magento2/issues/445)
- main.CRITICAL: API Key Missing for Api Call: https://usxx.api.mailchimp.com/3.0/lists//merge-fields - Your request did not include an API key. [\#442](https://github.com/mailchimp/mc-magento2/issues/442)
- Wrong parent id in the cart [\#432](https://github.com/mailchimp/mc-magento2/issues/432)
- Abandoned cart email queue in Mailchimp dashboard not getting reset on placing the order [\#431](https://github.com/mailchimp/mc-magento2/issues/431)
- Collissions with mailchimp cookies [\#429](https://github.com/mailchimp/mc-magento2/issues/429)
- Subscriber which was added in MailChimp doesn't have storeId in Magento2 [\#427](https://github.com/mailchimp/mc-magento2/issues/427)
- Product Image does not show on abandoned cart email template / order details [\#425](https://github.com/mailchimp/mc-magento2/issues/425)
- Total orders\_count and total\_spent sent incorrectly in order [\#420](https://github.com/mailchimp/mc-magento2/issues/420)
- NULL price when special price is not set, but special price dates are set [\#416](https://github.com/mailchimp/mc-magento2/issues/416)
- field \[operations.item:2\] : Schema describes object, array found instead [\#409](https://github.com/mailchimp/mc-magento2/issues/409)
- Empty data in the batch json for custom products types [\#406](https://github.com/mailchimp/mc-magento2/issues/406)
- After syncing data with MailChimp the wrong products are show for my stores [\#404](https://github.com/mailchimp/mc-magento2/issues/404)
- Fix unique type validation in di.xml [\#450](https://github.com/mailchimp/mc-magento2/pull/450) ([ihor-sviziev](https://github.com/ihor-sviziev))
## [1.0.30](https://github.com/mailchimp/mc-magento2/tree/1.0.30) (2018-09-18)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.29...1.0.30)
**Implemented enhancements:**
- Adding extra logging on import parts of the Cronjob [\#393](https://github.com/mailchimp/mc-magento2/issues/393)
- Add an option to choose between send MailChimp or Magento mails [\#372](https://github.com/mailchimp/mc-magento2/issues/372)
- Log batch totals for each run [\#361](https://github.com/mailchimp/mc-magento2/issues/361)
- Add debug information [\#359](https://github.com/mailchimp/mc-magento2/issues/359)
- High CPU load when API not available [\#325](https://github.com/mailchimp/mc-magento2/issues/325)
**Fixed bugs:**
- MailChimp breaks order processing when it's done through CLI [\#378](https://github.com/mailchimp/mc-magento2/issues/378)
- Disabled in Admin Panel Mailchimp block Magento default newsletter flow. [\#339](https://github.com/mailchimp/mc-magento2/issues/339)
- Special prices management in Magento Enterprise [\#391](https://github.com/mailchimp/mc-magento2/issues/391)
- Failed to open stream: No such file or directory [\#388](https://github.com/mailchimp/mc-magento2/issues/388)
- Promo rules are not updated [\#370](https://github.com/mailchimp/mc-magento2/issues/370)
- Error in the configuration when selecting other website than default [\#368](https://github.com/mailchimp/mc-magento2/issues/368)
- Orders not synced when products in the order not already synced [\#366](https://github.com/mailchimp/mc-magento2/issues/366)
- Wrong website set on customer [\#357](https://github.com/mailchimp/mc-magento2/issues/357)
- Issue with coupons for free shipping [\#355](https://github.com/mailchimp/mc-magento2/issues/355)
- Error downloading response from error grid when batch not exist [\#351](https://github.com/mailchimp/mc-magento2/issues/351)
- Unable to set custom Env.php API Credentials [\#345](https://github.com/mailchimp/mc-magento2/issues/345)
- Webhook processing fails when list id does not match any list configured in Magento [\#337](https://github.com/mailchimp/mc-magento2/issues/337)
- Sending modified products in order or cart [\#335](https://github.com/mailchimp/mc-magento2/issues/335)
- Base table or view not found Magento 2.2.4 [\#321](https://github.com/mailchimp/mc-magento2/issues/321)
- Unknown column 'at\_special\_from\_date\_default.value' in 'on clause' [\#309](https://github.com/mailchimp/mc-magento2/issues/309)
## [1.0.29](https://github.com/mailchimp/mc-magento2/tree/1.0.29) (2018-05-31)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.28...1.0.29)
**Implemented enhancements:**
- Add check before renaming 'address\_address1' table column [\#283](https://github.com/mailchimp/mc-magento2/pull/283) ([rob-aimes](https://github.com/rob-aimes))
**Fixed bugs:**
- No cron\_groups.xml is defined [\#316](https://github.com/mailchimp/mc-magento2/issues/316)
- Wrong url for a generic product of configurable producs [\#313](https://github.com/mailchimp/mc-magento2/issues/313)
- No image url when the product and the parent has no image [\#307](https://github.com/mailchimp/mc-magento2/issues/307)
- web\_hooks error somewhere - first/last name being required [\#302](https://github.com/mailchimp/mc-magento2/issues/302)
- In the mailchimpstore grid not all the apikeys are taken [\#295](https://github.com/mailchimp/mc-magento2/issues/295)
- Error getting interest groups [\#293](https://github.com/mailchimp/mc-magento2/issues/293)
- Multistore with different Mailchimp accounts not saving correctly [\#289](https://github.com/mailchimp/mc-magento2/issues/289)
- Exception is thrown when Promotion is marked for removal [\#280](https://github.com/mailchimp/mc-magento2/issues/280)
- Webhook cronjob fails when updating customer [\#278](https://github.com/mailchimp/mc-magento2/issues/278)
- Cron Ecommerce: cannot create batches data because update existed products in orders or carts [\#277](https://github.com/mailchimp/mc-magento2/issues/277)
- Cancelled or pending orders added to revenue in mailchimp [\#274](https://github.com/mailchimp/mc-magento2/issues/274)
- Bad registers are generated in mailchimp\_sync\_ecommerce table [\#267](https://github.com/mailchimp/mc-magento2/issues/267)
- PHP warning in Helper/Data.php line 340 [\#266](https://github.com/mailchimp/mc-magento2/issues/266)
- Subscriber fields not updated when Ecommerce Data not enabled [\#258](https://github.com/mailchimp/mc-magento2/issues/258)
- The instest groups are not reloaded when the list changes [\#257](https://github.com/mailchimp/mc-magento2/issues/257)
- The user can select non existing group in admin [\#256](https://github.com/mailchimp/mc-magento2/issues/256)
- Don't process stores with no mailchimp store [\#255](https://github.com/mailchimp/mc-magento2/issues/255)
- Error when attempting to edit a customer from the backend [\#240](https://github.com/mailchimp/mc-magento2/issues/240)
- 2.2 Error Importing Configuration [\#223](https://github.com/mailchimp/mc-magento2/issues/223)
- No Abandoned Cart Data Sent [\#220](https://github.com/mailchimp/mc-magento2/issues/220)
- Magento 2.2.1: Changes like "unsubscribe" and "delete" to subscribers in Magento backend aren't synched [\#147](https://github.com/mailchimp/mc-magento2/issues/147)
- Change cron group id to 'mailchimp'. [\#282](https://github.com/mailchimp/mc-magento2/pull/282) ([jhruehl](https://github.com/jhruehl))
- fix decodeArrayFieldValue error [\#265](https://github.com/mailchimp/mc-magento2/pull/265) ([gundamkid](https://github.com/gundamkid))
## [1.0.28](https://github.com/mailchimp/mc-magento2/tree/1.0.28) (2018-03-27)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.27...1.0.28)
**Implemented enhancements:**
- Not necessary mailchimp/script/get requests [\#248](https://github.com/mailchimp/mc-magento2/issues/248)
- Add a button to create the webhooks [\#229](https://github.com/mailchimp/mc-magento2/issues/229)
- Add get Api credentials button using oauth. [\#207](https://github.com/mailchimp/mc-magento2/issues/207)
- Special price management [\#194](https://github.com/mailchimp/mc-magento2/issues/194)
- Use a checkbox on Checkout to determine Opt-in status. [\#36](https://github.com/mailchimp/mc-magento2/issues/36)
**Fixed bugs:**
- Wrong product marked as modified in ecommerce table [\#253](https://github.com/mailchimp/mc-magento2/issues/253)
- Don't delete the batch\_id when modify a register [\#246](https://github.com/mailchimp/mc-magento2/issues/246)
- Invalid argument supplied for foreach\(\) [\#243](https://github.com/mailchimp/mc-magento2/issues/243)
- Missing argument on call to \_updateSyncData\(\) [\#241](https://github.com/mailchimp/mc-magento2/issues/241)
- MailChimp js file loaded each time the page loads [\#232](https://github.com/mailchimp/mc-magento2/issues/232)
- Mark non existing batchs as canceled [\#216](https://github.com/mailchimp/mc-magento2/issues/216)
- Modified carts are not re synced [\#212](https://github.com/mailchimp/mc-magento2/issues/212)
- Try to get result for not existing batch [\#210](https://github.com/mailchimp/mc-magento2/issues/210)
- Wrong error management [\#204](https://github.com/mailchimp/mc-magento2/issues/204)
- When modify a simple product, the variant is empty [\#202](https://github.com/mailchimp/mc-magento2/issues/202)
- Abandoned cart email product price has range starting at $0 when using configurable products [\#197](https://github.com/mailchimp/mc-magento2/issues/197)
- Error due to customer data race condition [\#112](https://github.com/mailchimp/mc-magento2/issues/112)
- Update default.xml [\#180](https://github.com/mailchimp/mc-magento2/pull/180) ([jhruehl](https://github.com/jhruehl))
- Show "Mailchimp" customer tab when the extension is enabled [\#201](https://github.com/mailchimp/mc-magento2/pull/201) ([t-richards](https://github.com/t-richards))
## [1.0.27](https://github.com/mailchimp/mc-magento2/tree/1.0.27) (2018-01-30)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.26...1.0.27)
**Implemented enhancements:**
- Send categories in product vendor attribute [\#129](https://github.com/mailchimp/mc-magento2/issues/129)
**Fixed bugs:**
- Merge Names not synching [\#188](https://github.com/mailchimp/mc-magento2/issues/188)
- Error in ebizmarts\_ecommerce after upgrading to 1.0.26 [\#186](https://github.com/mailchimp/mc-magento2/issues/186)
- Installation error when the database has a prefix [\#184](https://github.com/mailchimp/mc-magento2/issues/184)
## [1.0.26](https://github.com/mailchimp/mc-magento2/tree/1.0.26) (2018-01-24)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.25...1.0.26)
**Implemented enhancements:**
- Copy suggestions for List Group enhancement [\#173](https://github.com/mailchimp/mc-magento2/issues/173)
- Add support for List Groups [\#122](https://github.com/mailchimp/mc-magento2/issues/122)
- Magento 2.2 compatibility [\#116](https://github.com/mailchimp/mc-magento2/issues/116)
- Add mergevars [\#110](https://github.com/mailchimp/mc-magento2/issues/110)
**Fixed bugs:**
- MailChimp connected sites List Settings syncing seemingly forever [\#66](https://github.com/mailchimp/mc-magento2/issues/66)
- Products are not marked as modified in the sync\_ecommerce table [\#177](https://github.com/mailchimp/mc-magento2/issues/177)
- Child product update when parent has not been sent yet [\#160](https://github.com/mailchimp/mc-magento2/issues/160)
- Guest Abandoned Carts failing to load when accessing from automation. [\#153](https://github.com/mailchimp/mc-magento2/issues/153)
- Guest Abandoned Carts not associating email address at checkout [\#152](https://github.com/mailchimp/mc-magento2/issues/152)
- Sync only works, if eCommerce is enabled [\#150](https://github.com/mailchimp/mc-magento2/issues/150)
- Intallation error in EE when the database is already splitted [\#149](https://github.com/mailchimp/mc-magento2/issues/149)
- Compatibility with Magento Enterprise Edition 2.1.x [\#144](https://github.com/mailchimp/mc-magento2/issues/144)
- Send duplicates promo codes [\#121](https://github.com/mailchimp/mc-magento2/issues/121)
- Mark customer as modified when any data was modified [\#118](https://github.com/mailchimp/mc-magento2/issues/118)
- Error when the webhook is created [\#117](https://github.com/mailchimp/mc-magento2/issues/117)
- Exception when running cron [\#114](https://github.com/mailchimp/mc-magento2/issues/114)
- Cron error "Requested country is not available." [\#58](https://github.com/mailchimp/mc-magento2/issues/58)
- Fix for broken admin grid in production [\#176](https://github.com/mailchimp/mc-magento2/pull/176) ([duckchip](https://github.com/duckchip))
- Module Dependancy [\#126](https://github.com/mailchimp/mc-magento2/pull/126) ([valguss](https://github.com/valguss))
## [1.0.25](https://github.com/mailchimp/mc-magento2/tree/1.0.25) (2017-11-06)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.24...1.0.25)
**Implemented enhancements:**
- Add support for Promo Rules and Promo Codes [\#100](https://github.com/mailchimp/mc-magento2/issues/100)
- Total subscribers in admin display the total subscriber of the account [\#94](https://github.com/mailchimp/mc-magento2/issues/94)
- Performance cron ebizmarts\_ecommerce [\#93](https://github.com/mailchimp/mc-magento2/issues/93)
**Fixed bugs:**
- The cart url for abandoned cart not work [\#111](https://github.com/mailchimp/mc-magento2/issues/111)
- Store is always syncing [\#97](https://github.com/mailchimp/mc-magento2/issues/97)
- Module doesn't install if database uses a prefix [\#95](https://github.com/mailchimp/mc-magento2/issues/95)
## [1.0.24](https://github.com/mailchimp/mc-magento2/tree/1.0.24) (2017-09-18)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.23...1.0.24)
**Implemented enhancements:**
- Major Admin Order Grid Slowdown [\#88](https://github.com/mailchimp/mc-magento2/issues/88)
**Fixed bugs:**
- Error installation when use split database [\#85](https://github.com/mailchimp/mc-magento2/issues/85)
- Incorrect cart url [\#84](https://github.com/mailchimp/mc-magento2/issues/84)
- Incorrect image url [\#82](https://github.com/mailchimp/mc-magento2/issues/82)
- Change $this-\>\_helper-\>\_\_\(\) to \_\_\(\) [\#80](https://github.com/mailchimp/mc-magento2/pull/80) ([rikardwissing](https://github.com/rikardwissing))
## [1.0.23](https://github.com/mailchimp/mc-magento2/tree/1.0.23) (2017-09-01)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.22...1.0.23)
**Fixed bugs:**
- Guest subscribers issue - STOREID is null [\#75](https://github.com/mailchimp/mc-magento2/issues/75)
- Website scope always taking list from default configuration [\#68](https://github.com/mailchimp/mc-magento2/issues/68)
- Requested product doesn't exist [\#67](https://github.com/mailchimp/mc-magento2/issues/67)
- Bad ajax call [\#65](https://github.com/mailchimp/mc-magento2/issues/65)
- Resubscribing a customer from Magento throws a 500 error due to Fatal Uncaught Error: "Call to a member function getStreetLine\(\) on string" [\#62](https://github.com/mailchimp/mc-magento2/issues/62)
- Display appropriate thumbnails for items [\#43](https://github.com/mailchimp/mc-magento2/issues/43)
- New customers are not added to MailChimp [\#42](https://github.com/mailchimp/mc-magento2/issues/42)
- remove the use of data helper from InstallSchema [\#70](https://github.com/mailchimp/mc-magento2/pull/70) ([BlackIkeEagle](https://github.com/BlackIkeEagle))
## [1.0.22](https://github.com/mailchimp/mc-magento2/tree/1.0.22) (2017-07-26)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.21...1.0.22)
## [1.0.21](https://github.com/mailchimp/mc-magento2/tree/1.0.21) (2017-07-14)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.20...1.0.21)
## [1.0.20](https://github.com/mailchimp/mc-magento2/tree/1.0.20) (2017-07-12)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.19...1.0.20)
## [1.0.19](https://github.com/mailchimp/mc-magento2/tree/1.0.19) (2017-07-12)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.18...1.0.19)
## [1.0.18](https://github.com/mailchimp/mc-magento2/tree/1.0.18) (2017-06-29)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.17...1.0.18)
**Implemented enhancements:**
- Add a commit call when use a connection directly [\#53](https://github.com/mailchimp/mc-magento2/issues/53)
**Fixed bugs:**
- Reset the errors when no more mailchimp store are connected [\#54](https://github.com/mailchimp/mc-magento2/issues/54)
## [1.0.17](https://github.com/mailchimp/mc-magento2/tree/1.0.17) (2017-06-21)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.16...1.0.17)
**Fixed bugs:**
- Error in mc.js when change the mailchimp store [\#51](https://github.com/mailchimp/mc-magento2/issues/51)
- Prevent sending customers to other store views even when they belong to the same website [\#48](https://github.com/mailchimp/mc-magento2/issues/48)
## [1.0.16](https://github.com/mailchimp/mc-magento2/tree/1.0.16) (2017-06-19)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.15...1.0.16)
**Implemented enhancements:**
- Limit the process of the webhooks [\#47](https://github.com/mailchimp/mc-magento2/issues/47)
**Fixed bugs:**
- Invalid product url on simple products not visible [\#49](https://github.com/mailchimp/mc-magento2/issues/49)
## [1.0.15](https://github.com/mailchimp/mc-magento2/tree/1.0.15) (2017-06-05)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.14...1.0.15)
**Implemented enhancements:**
- List MC account and List [\#22](https://github.com/mailchimp/mc-magento2/issues/22)
- Add the download response link to error grid [\#8](https://github.com/mailchimp/mc-magento2/issues/8)
- Process the webhooks in a separate cron process [\#46](https://github.com/mailchimp/mc-magento2/issues/46)
- Show the list in the configuration page [\#41](https://github.com/mailchimp/mc-magento2/issues/41)
- Add actions to webhooks [\#40](https://github.com/mailchimp/mc-magento2/issues/40)
- Add webhooks [\#39](https://github.com/mailchimp/mc-magento2/issues/39)
- Request: Move MailChimp Store above Account Details on the Configuration page [\#31](https://github.com/mailchimp/mc-magento2/issues/31)
- Autoselect store when only one exists [\#28](https://github.com/mailchimp/mc-magento2/issues/28)
- Change the configuration to use jquery and ajax [\#27](https://github.com/mailchimp/mc-magento2/issues/27)
- Installation of MC.js pixel [\#18](https://github.com/mailchimp/mc-magento2/issues/18)
**Fixed bugs:**
- Ecomm Data uploaded to MailChimp should display if reselecting a connected store. [\#32](https://github.com/mailchimp/mc-magento2/issues/32)
- Account no longer syncing [\#26](https://github.com/mailchimp/mc-magento2/issues/26)
- Multiple stores not showing in Configuration dropdown [\#25](https://github.com/mailchimp/mc-magento2/issues/25)
- MC Account information displayed in Configuration does not change when API key is toggled. [\#24](https://github.com/mailchimp/mc-magento2/issues/24)
- Remove old warning message on Configuration [\#23](https://github.com/mailchimp/mc-magento2/issues/23)
- In the MailChimp Store, the street is not saved [\#21](https://github.com/mailchimp/mc-magento2/issues/21)
- Pull all lists for dropdown when creating a store [\#20](https://github.com/mailchimp/mc-magento2/issues/20)
- Use "MailChimp" instead of "Mailchimp" [\#19](https://github.com/mailchimp/mc-magento2/issues/19)
- Change the order \# when sync [\#45](https://github.com/mailchimp/mc-magento2/issues/45)
- Not mark the already synced element like errors [\#44](https://github.com/mailchimp/mc-magento2/issues/44)
- Avoid error when for some reason the process cancel [\#38](https://github.com/mailchimp/mc-magento2/issues/38)
- Review the Customer process [\#37](https://github.com/mailchimp/mc-magento2/issues/37)
- Problem when receive the response of batch [\#35](https://github.com/mailchimp/mc-magento2/issues/35)
- Add ACL permissions [\#34](https://github.com/mailchimp/mc-magento2/issues/34)
- Sorting MailChimp Stores grid by email more than once causes display issues [\#33](https://github.com/mailchimp/mc-magento2/issues/33)
- Enable not saving on a MailChimp store level [\#29](https://github.com/mailchimp/mc-magento2/issues/29)
- Invalid product image url when the product not have any image [\#17](https://github.com/mailchimp/mc-magento2/issues/17)
- Newly added products not synced. [\#13](https://github.com/mailchimp/mc-magento2/issues/13)
- Store information not passing to MailChimp [\#12](https://github.com/mailchimp/mc-magento2/issues/12)
- Purchases made via campaign not attributed to the campaign [\#11](https://github.com/mailchimp/mc-magento2/issues/11)
- APIKey management and store creation [\#10](https://github.com/mailchimp/mc-magento2/issues/10)
## [1.0.14](https://github.com/mailchimp/mc-magento2/tree/1.0.14) (2017-05-04)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.9...1.0.14)
## [1.0.9](https://github.com/mailchimp/mc-magento2/tree/1.0.9) (2017-05-03)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.8...1.0.9)
## [1.0.8](https://github.com/mailchimp/mc-magento2/tree/1.0.8) (2017-05-03)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.7...1.0.8)
## [1.0.7](https://github.com/mailchimp/mc-magento2/tree/1.0.7) (2017-05-02)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.6...1.0.7)
## [1.0.6](https://github.com/mailchimp/mc-magento2/tree/1.0.6) (2017-04-24)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.5...1.0.6)
## [1.0.5](https://github.com/mailchimp/mc-magento2/tree/1.0.5) (2017-04-21)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.4...1.0.5)
## [1.0.4](https://github.com/mailchimp/mc-magento2/tree/1.0.4) (2017-03-22)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.3...1.0.4)
**Fixed bugs:**
- The error grid don't paginate [\#9](https://github.com/mailchimp/mc-magento2/issues/9)
- Add the mailchimp\_store\_id to all auxiliar tables [\#7](https://github.com/mailchimp/mc-magento2/issues/7)
- The reset errors button not work [\#6](https://github.com/mailchimp/mc-magento2/issues/6)
- Error in mailchimp\_errors table [\#5](https://github.com/mailchimp/mc-magento2/issues/5)
- Products not syncing [\#3](https://github.com/mailchimp/mc-magento2/issues/3)
## [1.0.3](https://github.com/mailchimp/mc-magento2/tree/1.0.3) (2017-03-18)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.2...1.0.3)
**Fixed bugs:**
- Clean error don't work [\#4](https://github.com/mailchimp/mc-magento2/issues/4)
## [1.0.2](https://github.com/mailchimp/mc-magento2/tree/1.0.2) (2017-03-17)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.1...1.0.2)
## [1.0.1](https://github.com/mailchimp/mc-magento2/tree/1.0.1) (2017-03-16)
[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.0...1.0.1)
## [1.0.0](https://github.com/mailchimp/mc-magento2/tree/1.0.0) (2017-03-16)
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
================================================
FILE: CONTRIBUTING.md
================================================
### Contribution requirements
1. Contributions must adhere to [Magento coding standards](http://devdocs.magento.com/guides/v2.0/coding-standards/bk-coding-standards.html).
2. Pull requests (PRs) must be accompanied by a meaningful description of their purpose. Comprehensive descriptions increase the chances that a pull request is merged quickly and without additional clarification requests.
3. Commits must be accompanied by meaningful commit messages. (include a **closes** in the commit that close the issue)
4. PRs that include bug fixing must be accompanied by the creation of an issue describing the bug following this [Issue reporting guidelines](https://github.com/mailchimp/mc-magento2/wiki/Issue-reporting-guidelines).
5. For large features or changes, please open an issue and discuss first. This may prevent duplicate or unnecessary effort, and it may gain you some additional contributors.
================================================
FILE: Controller/Adminhtml/Batch/GetResponse.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/3/17 3:28 PM
* @file: Getresponse.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Batch;
use Magento\Framework\Controller\ResultFactory;
class GetResponse extends \Magento\Backend\App\Action
{
const MAX_RETRIES = 5;
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory
*/
protected $_batchFactory;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Result
*/
protected $_result;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
protected $_driver;
/**
* Getresponse constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $errorsFactory
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\Api\Result $result
* @param \Magento\Framework\Filesystem\Driver\File $driver
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Ebizmarts\MailChimp\Model\MailChimpSyncBatchesFactory $_batchFactory,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\Api\Result $result,
\Magento\Framework\Filesystem\Driver\File $driver
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_batchFactory = $_batchFactory;
$this->_result = $result;
$this->_helper = $helper;
$this->_driver = $driver;
}
public function execute()
{
$batchId = $this->getRequest()->getParam('id');
$batches = $this->_batchFactory->create();
$batches->getResource()->load($batches, $batchId);
$batchId = $batches->getBatchId();
$fileContent = [];
$counter = 0;
do {
$counter++;
$files = $this->_result->getBatchResponse($batchId, $batches->getStoreId());
if ($files===false) {
$fileContent = "Response was deleted from MailChimp servers";
break;
}
foreach ($files as &$file) {
$items = json_decode($this->_driver->fileGetContents($file));
foreach ($items as &$item) {
$content = [
'status_code' => $item->status_code,
'operation_id' => $item->operation_id,
'response' => json_decode($item->response)
];
$fileContent[] = $content;
}
$this->_driver->deleteFile($file);
}
$baseDir = $this->_helper->getBaseDir();
if ($this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
\Ebizmarts\MailChimp\Model\Api\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId)) {
$this->_driver->deleteDirectory(
$baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
\Ebizmarts\MailChimp\Model\Api\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId
);
}
} while (!count($fileContent) && $counter_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setHeader('Content-disposition', 'attachment; filename='.$batchId.'.json');
$resultJson->setHeader('Content-type', 'application/json');
$data = json_encode($fileContent, JSON_PRETTY_PRINT);
$resultJson->setJsonData($data);
return $resultJson;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::batch_grid');
}
}
================================================
FILE: Controller/Adminhtml/Batch/Index.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/28/16 4:58 PM
* @file: Index.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Batch;
class Index extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* Index constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
return parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Mailchimp Batches'));
return $page;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::batch_grid');
}
}
================================================
FILE: Controller/Adminhtml/Carts/Index.php
================================================
resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Mailchimp Carts'));
return $page;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::carts_grid');
}
}
================================================
FILE: Controller/Adminhtml/Cron/Index.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/28/16 4:58 PM
* @file: Index.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Cron;
class Index extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* Index constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
return parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Mailchimp Cron'));
return $page;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::cron_grid');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/CreateWebhook.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/12/18 4:14 PM
* @file: CreateWebhook.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
class CreateWebhook extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* DeleteStore constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Config\Model\ResourceModel\Config $config
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Config\Model\ResourceModel\Config $config
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->storeManager = $storeManagerInterface;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
$apiKey = $params['apikey'];
$listId = $params['listId'];
$scope = $params['scope'];
$scopeId = $params['scopeId'];
if ($apiKey=='******') {
$apiKey = $this->helper->getApiKey($scopeId, $scope);
}
$return = $this->helper->createWebHook($apiKey, $listId, $scope, $scopeId);
if (isset($return['message'])) {
$valid = 0;
$message = $return['message'];
}
$resultJson = $this->resultJsonFactory->create();
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("CreateWebhook", $ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/DeleteStore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
class DeleteStore extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Magento\Config\Model\ResourceModel\Config
*/
protected $_config;
/**
* DeleteStore constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Config\Model\ResourceModel\Config $config
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Config\Model\ResourceModel\Config $config
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->storeManager = $storeManagerInterface;
$this->_config = $config;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
if (isset($params['website'])) {
$scope = 'website';
$storeId = $params['website'];
} elseif (isset($params['store'])) {
$scope = 'store';
$storeId = $params['store'];
} else {
//$storeId = $this->storeManager->getDefaultStoreView()->getWebsiteId();
$storeId = 0;
$scope = 'default';
}
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId,
$scope
);
$resultJson = $this->resultJsonFactory->create();
try {
$this->helper->deleteStore($mailchimpStore);
$this->_config->deleteConfig(\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE, $scope, $storeId);
} catch (ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("DeleteStore",$ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/FixMailchimpJS.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
class FixMailchimpJS extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Config\Model\ResourceModel\Config
*/
protected $config;
protected $typeList;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Config\Model\ResourceModel\Config $config
* @param \Magento\Framework\App\Cache\TypeListInterface $typeList
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Config\Model\ResourceModel\Config $config,
\Magento\Framework\App\Cache\TypeListInterface $typeList,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->config = $config;
$this->typeList = $typeList;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
$this->helper->log($params);
$scope = $params['scope'];
$scopeId = $params['scopeId'];
if ($scope == 'store') {
$scope = 'stores';
}
$this->helper->log("Scope $scope id $scopeId");
$resultJson = $this->resultJsonFactory->create();
try {
$this->config->deleteConfig(\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_JS_URL, $scope, $scopeId);
} catch(ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("FixMailchimpJS", $ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/GetInterest.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/23/18 10:05 AM
* @file: GetInterest.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class GetInterest extends Action
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* @var \Magento\Store\Model\StoreManager
*/
protected $_storeManager;
/**
* GetInterest constructor.
* @param Context $context
* @param \Magento\Store\Model\StoreManager $storeManager
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
Context $context,
\Magento\Store\Model\StoreManager $storeManager,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_helper = $helper;
$this->_storeManager = $storeManager;
}
/**
* @return mixed
*/
public function execute()
{
$param = $this->getRequest()->getParams();
$rc = [];
$error = 0;
if (array_key_exists('apikey', $param) && array_key_exists('list', $param)) {
$apiKey = $param['apikey'];
$list = $param['list'];
$encrypt = $param['encrypt'];
try {
if ($encrypt == 3) {
$api = $this->_helper->getApi($this->_storeManager->getStore()->getId());
} else {
$api = $this->_helper->getApiByApiKey($apiKey, $encrypt);
}
$result = $api->lists->interestCategory->getAll($list, null, null, 200);
if (is_array($result['categories']) && count($result['categories'])) {
$rc = $result['categories'];
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
$error = 1;
}
}
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData(['error' => $error, 'data' => $rc]);
return $resultJson;
}
/**
* @return mixed
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/Getaccountdetails.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/5/17 3:40 PM
* @file: GetAccountDetails.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use \Ebizmarts\MailChimp\Helper\Data as MailChimpHelper;
class Getaccountdetails extends Action
{
/**
* @var MailChimpHelper
*/
protected $_helper;
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* @var \Magento\Store\Model\StoreManager
*/
protected $_storeManager;
/**
* @param Context $context
* @param \Magento\Store\Model\StoreManager $storeManager
* @param MailChimpHelper $helper
*/
public function __construct(
Context $context,
\Magento\Store\Model\StoreManager $storeManager,
MailChimpHelper $helper
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_helper = $helper;
$this->_storeManager = $storeManager;
}
public function execute()
{
$param = $this->getRequest()->getParams();
$apiKey = $param['apikey'];
$store = $param['store'];
$encrypt = $param['encrypt'];
$scope = $param['scope'];
$scopeId = $param['scopeId'];
try {
if ($encrypt == 3) {
$api = $this->_helper->getApi($this->_storeManager->getStore()->getId());
} else {
$api = $this->_helper->getApiByApiKey($apiKey, $encrypt);
}
$apiInfo = $api->root->info();
$options = [];
if (isset($apiInfo['account_name'])) {
$options['account_name'] = ['code' => 'account_name','html' => __('Account Name'),'value' => $apiInfo['account_name']];
$options['email'] = ['code' => 'email','html' => __('email'),'value' => $apiInfo['email']];
$options['first_name'] = ['code'=> 'first_name','html' => __('First Name'),'value' => $apiInfo['first_name']];
$options['last_name'] = ['code'=>'last_name','html' => __('Last Name'),'value' => $apiInfo['last_name']];
$options['pricing_plan_type'] = ['code'=>'pricing_plan_type','html' => __('Pricing Plan'),'value' => $apiInfo['pricing_plan_type']];
$options['username'] = ['code'=>'username','html' => __('User name:'), 'value' => $apiInfo['account_name']];
$options['account_id'] = ['code'=> 'account_id','html' => __('Account id:'), 'value' => $apiInfo['account_id']];
$options['total_subscribers'] = ['label' => __('Total Account Subscribers:'), 'value' => $apiInfo['total_subscribers']];
$options['total_account_subscribers'] = ['code' => 'total_subscribers', 'html' => __('Total Account Subscribers:'), 'value' => $apiInfo['total_subscribers']];
$token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope);
if ($store != -1) {
$storeData = $api->ecommerce->stores->get($store);
$options['list_id'] = $storeData['list_id'];
$list = $api->lists->getLists($storeData['list_id']);
$options['list_name'] = $list['name'];
$options['total_list_subscribers'] = ['label' => __('Total List Subscribers:'), 'value' => $list['stats']['member_count']];
$options['token'] = ['label' => __('Registration ID:'), 'value' => $token];
$options['subtitle'] = ['label' => __('Ecommerce Data uploaded to MailChimp:'), 'value' => ''];
$totalCustomers = $api->ecommerce->customers->getAll($store, 'total_items');
$options['total_customers'] = ['label' => __('Total customers:'), 'value' => $totalCustomers['total_items']];
$totalProducts = $api->ecommerce->products->getAll($store, 'total_items');
$options['total_products'] = ['label' => __('Total products:'), 'value' => $totalProducts['total_items']];
$totalOrders = $api->ecommerce->orders->getAll($store, 'total_items');
$options['total_orders'] = ['label' => __('Total orders:'), 'value' => $totalOrders['total_items']];
$totalCarts = $api->ecommerce->carts->getAll($store, 'total_items');
$options['total_carts'] = ['label' => __('Total Carts:'), 'value' => $totalCarts['total_items']];
$options['notsaved'] = ['label' => __('Ecommerce disabled, save configuration to enable.'), 'value' => ''];
} else {
$options['nostore'] = ['label' => __('Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized).'), 'value' => ''];
}
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
$options['error'] = ['label' => 'Error', 'value' => __('--- Invalid API Key ---')];
}
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($options);
return $resultJson;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/Register.php
================================================
_resultFactory = $context->getResultFactory();
$this->_helper = $helper;
$this->_http = $http;
$this->_http->setUrl($helper->getConfigValue(Helper::XML_REGISTER_URL).'/register');
$this->_config = $config;
$this->_storeManager = $storeManager;
$this->_directoryHelper = $directoryHelper;
}
public function execute()
{
$params = $this->getRequest()->getParams();
$scope = $params['scope'];
$scopeId = $params['scopeId'];
$registerData = [];
$error = true;
$token = $this->_helper->getConfigValue(Helper::XML_STATISTICS_TOKEN,$scopeId, $scope);
foreach ($params['data'] as $index => $value) {
$registerData[$index] = $value['value'];
}
$registerData['store_url'] = stripslashes($this->_storeManager->getStore($scopeId)->getBaseUrl());
$registerData['city'] = $this->_helper->getConfigValue(\Magento\Store\Model\Information::XML_PATH_STORE_INFO_CITY,$scopeId, $scope);
$registerData['country'] = $this->_directoryHelper->getDefaultCountry($scopeId);
$registerDataJson = json_encode($registerData);
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
if ($token) {
$ret = $this->_http->patch($token, $registerDataJson);
} else {
$ret = $this->_http->post($registerDataJson);
}
$ret = json_decode($ret,true);
if ( !$ret['error']) {
$error = false;
$token = $ret['token'];
$this->_helper->saveConfigValue(Helper::XML_STATISTICS_TOKEN, $token, $scopeId, $scope);
}
$resultJson->setData(['error' => $error, 'token' => $token]);
return $resultJson;
}
/**
* @return mixed
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/ResetLocalErrors.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class ResetLocalErrors extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->syncHelper = $syncHelper;
$this->storeManager = $storeManagerInterface;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
if (isset($params['website'])) {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$params['website'],
'website'
);
$storeId = $params['website'];
} elseif (isset($params['store'])) {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$params['store'],
'store'
);
$storeId = $params['store'];
} else {
$storeId = $this->storeManager->getStore()->getId();
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
}
$resultJson = $this->resultJsonFactory->create();
try {
$this->syncHelper->resetErrors($mailchimpStore, $storeId, true);
} catch (ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("ResetLocalErrors",$ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/ResetLocalErrorsNoRetry.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class ResetLocalErrorsNoRetry extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->syncHelper = $syncHelper;
$this->storeManager = $storeManagerInterface;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
if (isset($params['website'])) {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$params['website'],
'website'
);
$storeId = $params['website'];
} elseif (isset($params['store'])) {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$params['store'],
'store'
);
$storeId = $params['store'];
} else {
$storeId = $this->storeManager->getStore()->getId();
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
}
$resultJson = $this->resultJsonFactory->create();
try {
$this->syncHelper->resetErrors($mailchimpStore, $storeId, false);
} catch (ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("ResetLocalErrorNoRetry",$ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/ResetStore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
class ResetStore extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* ResetLocalErrors constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->storeManager = $storeManagerInterface;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
if (isset($params['website'])) {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$params['website'],
'website'
);
} elseif (isset($params['store'])) {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$params['store'],
'store'
);
} else {
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$this->storeManager->getStore()
);
}
try {
$resultJson = $this->resultJsonFactory->create();
} catch (ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("ResetStore",$ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/ResyncProducts.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class ResyncProducts extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $helper;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param SyncHelper $syncHelper
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
SyncHelper $syncHelper,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->syncHelper = $syncHelper;
$this->storeManager = $storeManagerInterface;
$this->helper = $helper;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
$mailchimpStore = $params['mailchimpStoreId'];
$resultJson = $this->resultJsonFactory->create();
try {
$this->syncHelper->resyncProducts($mailchimpStore);
} catch (ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("ResyncProducts", $ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/ResyncSubscribers.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/21/17 5:07 PM
* @file: ResetLocalErrors.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\ValidatorException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class ResyncSubscribers extends \Magento\Backend\App\Action
{
/**
* @var JsonFactory
*/
protected $resultJsonFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @param \Magento\Backend\App\Action\Context $context
* @param JsonFactory $resultJsonFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManagerInterface
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
JsonFactory $resultJsonFactory,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
parent::__construct($context);
$this->resultJsonFactory = $resultJsonFactory;
$this->helper = $helper;
$this->syncHelper = $syncHelper;
$this->storeManager = $storeManagerInterface;
}
public function execute()
{
$valid = 1;
$message = '';
$params = $this->getRequest()->getParams();
$mailchimpList = $params['listId'];
$resultJson = $this->resultJsonFactory->create();
try {
$this->syncHelper->resyncAllSubscribers($mailchimpList);
} catch (ValidatorException $e) {
$valid = 0;
$message = $e->getMessage();
}
$ret = [
'valid' => (int)$valid,
'message' => $message,
];
$this->helper->buttonPressed("ResyncSubscribers", $ret);
return $resultJson->setData($ret);
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Ecommerce/SyncLog.php
================================================
_resultFactory = $context->getResultFactory();
$this->_helper = $mailchimpHelper;
$this->_http = $mailchimpHttp;
$this->_url = $mailchimpHelper->getConfigValue(MailchimpHelper::XML_REGISTER_URL);
}
public function execute()
{
$error = 0;
$message = '';
$params = $this->getRequest()->getParams();
$scope = $params['scope'];
$scopeId = $params['scopeId'];
$onoff = $params['onoff'];
$token = $this->_helper->getConfigValue(MailchimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope);
if ($token) {
if ($onoff) {
$this->_http->setUrl($this->_url . '/switchon');
} else {
$this->_http->setUrl($this->_url . '/switchoff');
}
$response = $this->_http->put($token, null);
$res = json_decode($response, true);
if (key_exists('error',$res)) {
$error = $res['error'];
$message = $res['message'];
}
} else {
$error = 1;
$message = 'First register your copy';
}
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData(['error' => $error, 'message' => $message]);
return $resultJson;
}
}
================================================
FILE: Controller/Adminhtml/Errors/Getresponse.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/3/17 3:28 PM
* @file: Getresponse.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Errors;
use Magento\Framework\Controller\ResultFactory;
class Getresponse extends \Magento\Backend\App\Action
{
const MAX_RETRIES = 5;
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory
*/
protected $_errorsFactory;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Result
*/
protected $_result;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
protected $_driver;
/**
* Getresponse constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $errorsFactory
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\Api\Result $result
* @param \Magento\Framework\Filesystem\Driver\File $driver
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $errorsFactory,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\Api\Result $result,
\Magento\Framework\Filesystem\Driver\File $driver
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_errorsFactory = $errorsFactory;
$this->_result = $result;
$this->_helper = $helper;
$this->_driver = $driver;
}
public function execute()
{
$errorId = $this->getRequest()->getParam('id');
$errors = $this->_errorsFactory->create();
$errors->getResource()->load($errors, $errorId);
$batchId = $errors->getBatchId();
$fileContent = [];
$counter = 0;
do {
$counter++;
$files = $this->_result->getBatchResponse($batchId, $errors->getStoreId());
if ($files===false) {
$fileContent = "Response was deleted from MailChimp servers";
break;
}
foreach ($files as $file) {
$items = json_decode($this->_driver->fileGetContents($file));
foreach ($items as $item) {
$content = [
'status_code' => $item->status_code,
'operation_id' => $item->operation_id,
'response' => json_decode($item->response)
];
$fileContent[] = $content;
}
$this->_driver->deleteFile($file);
}
$baseDir = $this->_helper->getBaseDir();
if ($this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
\Ebizmarts\MailChimp\Model\Api\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId)) {
$this->_driver->deleteDirectory(
$baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
\Ebizmarts\MailChimp\Model\Api\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId
);
}
} while (!count($fileContent) && $counter_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setHeader('Content-disposition', 'attachment; filename='.$batchId.'.json');
$resultJson->setHeader('Content-type', 'application/json');
$data = json_encode($fileContent, JSON_PRETTY_PRINT);
$resultJson->setJsonData($data);
return $resultJson;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::error_grid');
}
}
================================================
FILE: Controller/Adminhtml/Errors/Index.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/28/16 4:58 PM
* @file: Index.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Errors;
class Index extends \Magento\Backend\App\Action
{
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
/**
* Index constructor.
* @param \Magento\Backend\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
return parent::__construct($context);
}
public function execute()
{
$page = $this->resultPageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Mailchimp Errors'));
return $page;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::error_grid');
}
}
================================================
FILE: Controller/Adminhtml/Lists/Get.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/20/17 3:20 PM
* @file: Get.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Lists;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Get extends Action
{
const MAX_LISTS = 200;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* @var \Magento\Framework\Encryption\Encryptor
*/
protected $encryptor;
/**
* Get constructor.
* @param Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Framework\Encryption\Encryptor $encryptor
*/
public function __construct(
Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Framework\Encryption\Encryptor $encryptor
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_helper = $helper;
$this->encryptor = $encryptor;
}
public function execute()
{
$param = $this->getRequest()->getParams();
$apiKey = $this->encryptor->decrypt($param['apikey']);
$result = [];
try {
$api = $this->_helper->getApiByApiKey($apiKey);
$lists = $api->lists->getLists(null, null, null, self::MAX_LISTS);
foreach ($lists['lists'] as $list) {
$result['lists'][] = ['id' => $list['id'], 'name' => $list['name']];
}
$result['valid'] = 1;
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$result['valid'] = 0;
$result['errormsg'] = $e->getTitle();
$this->_helper->log($e->getFriendlyMessage());
}
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($result);
return $resultJson;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');
}
}
================================================
FILE: Controller/Adminhtml/Orders/Campaign.php
================================================
helper = $helper;
$this->orderRepository = $orderRepository;
$this->urlBuilder = $urlBuilder;
}
public function execute()
{
$param = $this->getRequest()->getParams();
$orderId = $this->getRequest()->getParam('orderId');
$order = $this->orderRepository->get($orderId);
$api = $this->helper->getApi($order->getStoreId());
try {
$campaign = $api->campaigns->get($order->getMailchimpCampaignId());
$webId = $campaign['web_id'];
$url = $this->urlBuilder->getUrl('https://admin.mailchimp.com/reports/summary') . "?id=$webId";
$this->_redirect($url);
} catch(\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
$this->_redirect($this->urlBuilder->getUrl('sales/order'));
}
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::mailchimp_access');
}
}
================================================
FILE: Controller/Adminhtml/Orders/Member.php
================================================
helper = $helper;
$this->orderRepository = $orderRepository;
$this->urlBuilder = $urlBuilder;
}
public function execute()
{
$param = $this->getRequest()->getParams();
$orderId = $this->getRequest()->getParam('orderId');
$order = $this->orderRepository->get($orderId);
$api = $this->helper->getApi($order->getStoreId());
try {
$email = $order->getCustomerEmail();
$listId = $this->helper->getDefaultList($order->getStoreId());
$member = $api->lists->members->get($listId, hash('md5', strtolower($email)));
$memberId = $member['contact_id'];
$url = $this->urlBuilder->getUrl('https://admin.mailchimp.com/audience/contact-profile') . "?contact_id=$memberId";
$this->_redirect($url);
} catch(\Exception $e) {
$this->messageManager->addErrorMessage($e->getMessage());
$this->_redirect($this->urlBuilder->getUrl('sales/order'));
}
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::mailchimp_access');
}
}
================================================
FILE: Controller/Adminhtml/Stores/Delete.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/17/17 12:03 PM
* @file: Delete.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Stores;
class Delete extends \Ebizmarts\MailChimp\Controller\Adminhtml\Stores
{
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
$storeId = (int) $this->getRequest()->getParam('id');
if ($storeId) {
$storeModel = $this->_mailchimpStoresFactory->create();
$storeModel->getResource()->load($storeModel, $storeId);
try {
$api = $this->_mhelper->getApiByApiKey($storeModel->getApikey(), true);
$api->ecommerce->stores->delete($storeModel->getStoreid());
$this->messageManager->addSuccess(__('You deleted the store.'));
return $resultRedirect->setPath('mailchimp/stores');
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->messageManager->addError(__('Store could not be deleted.'.$e->getMessage()));
$this->_mhelper->log($e->getFriendlyMessage());
return $resultRedirect->setPath('mailchimp/stores/edit', ['id'=>$storeId]);
}
}
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');
}
}
================================================
FILE: Controller/Adminhtml/Stores/Edit.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/5/17 1:23 PM
* @file: Edit.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Stores;
use Ebizmarts\MailChimp\Model\MailChimpStoresFactory;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
class Edit extends \Ebizmarts\MailChimp\Controller\Adminhtml\Stores
{
public function execute()
{
$storeId = $this->getRequest()->getParam('id');
/** @var \Ebizmarts\MailChimp\Model\MailChimpStores $model */
$model = $this->_mailchimpStoresFactory->create();
if ($storeId) {
$model->getResource()->load($model, $storeId);
if (!$model->getId()) {
$this->messageManager->addError(__('This store no longer exists.'));
$this->_redirect('*/*/');
return;
}
}
// Restore previously entered form data from session
$data = $this->_session->getStoreData(true);
if (isset($data['name'])) {
$data['name'] = preg_replace('/ \(Warning: not connected\)/', '', $data['name']);
}
if (!empty($data)) {
$model->setData($data);
}
if (isset($model['name'])) {
$model['name'] = preg_replace('/ \(Warning: not connected\)/', '', $model['name']);
}
$this->_coreRegistry->register('mailchimp_stores', $model);
/** @var \Magento\Backend\Model\View\Result\Page $resultPage */
$resultPage = $this->_resultPageFactory->create();
$resultPage->setActiveMenu('Ebizmarts_MailChimp::main_menu');
$resultPage->getConfig()->getTitle()->prepend(__('Mailchimp Store'));
return $resultPage;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');
}
}
================================================
FILE: Controller/Adminhtml/Stores/Get.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/20/17 3:20 PM
* @file: Get.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Stores;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Get extends Action
{
const MAX_STORES = 200;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_mhelper;
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* Get constructor.
* @param Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_mhelper = $helper;
}
public function execute()
{
$param = $this->getRequest()->getParams();
$apiKey = $param['apikey'];
$encrypt = $param['encrypt'];
try {
$api = $this->_mhelper->getApiByApiKey($apiKey, $encrypt);
$stores = $api->ecommerce->stores->get(null, null, null, self::MAX_STORES);
$result = [];
$result['valid'] = 1;
$result['stores'] = [];
foreach ($stores['stores'] as $store) {
if ($store['platform'] == \Ebizmarts\MailChimp\Helper\Data::PLATFORM) {
if ($store['list_id']=='') {
continue;
}
$list = $api->lists->getLists($store['list_id']);
$result['stores'][] = [
'id' => $store['id'],
'name' => $store['name'],
'list_name' => $list['name'],
'list_id' => $store['list_id']
];
$result['valid'] = 1;
}
}
} catch (\Mailchimp_Error $e) {
$this->_mhelper->log($e->getFriendlyMessage());
$result['valid'] = 0;
$result['errormsg'] = $e->getTitle();
}
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData($result);
return $resultJson;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');
}
}
================================================
FILE: Controller/Adminhtml/Stores/Index.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/24/17 10:38 AM
* @file: Index.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Stores;
use Ebizmarts\MailChimp\Controller\Adminhtml\Stores;
class Index extends Stores
{
public function execute()
{
$this->_mhelper->loadStores();
$page = $this->_resultPageFactory->create();
$page->getConfig()->getTitle()->prepend(__('Mailchimp Stores'));
return $page;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_grid');
}
}
================================================
FILE: Controller/Adminhtml/Stores/Save.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/17/17 11:05 AM
* @file: Save.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml\Stores;
class Save extends \Ebizmarts\MailChimp\Controller\Adminhtml\Stores
{
public function execute()
{
$isPost = $this->getRequest()->getPost();
if ($isPost) {
$resultRedirect = $this->resultRedirectFactory->create();
$returnToEdit = (bool)$this->getRequest()->getParam('back', false);
$storeModel = $this->_mailchimpStoresFactory->create();
$formData = $this->getRequest()->getParam('stores');
$storeId = isset($formData['id']) ? $formData['id'] : null;
if ($storeId) {
$storeModel->getResource()->load($storeModel, $storeId);
}
try {
$formData['storeid'] = $this->_updateMailchimp($formData);
$formData['platform'] = \Ebizmarts\MailChimp\Helper\Data::PLATFORM;
$storeModel->setData($formData);
$storeModel->getResource()->save($storeModel);
if ($returnToEdit) {
if (!$storeId) {
$storeId = $storeModel->getId();
}
return $resultRedirect->setPath('mailchimp/stores/edit', ['id'=>$storeId]);
} else {
return $resultRedirect->setPath('mailchimp/stores');
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->messageManager->addErrorMessage(__('Store could not be saved.'.$e->getMessage()));
$this->_mhelper->log($e->getFriendlyMessage());
return $resultRedirect->setPath('mailchimp/stores/edit', ['id'=>$storeId]);
}
}
}
protected function _updateMailchimp($formData)
{
$api = $this->_mhelper->getApiByApiKey($formData['apikey'], true);
// set the address
$address = [];
$address['address1'] = $formData['address_address_one'];
$address['address2'] = $formData['address_address_two'];
$address['city'] = $formData['address_city'];
$address['province'] = '';
$address['province_code'] = '';
$address['postal_code'] = $formData['address_postal_code'];
$address['country'] = '';
$address['country_code'] = $formData['address_country_code'];
$emailAddress = $formData['email_address'];
$currencyCode = $formData['currency_code'];
$primaryLocale = $formData['primary_locale'];
$timeZone = $formData['timezone'];
$phone = $formData['phone'];
$name = $formData['name'];
$domain = $formData['domain'];
$storeId = isset($formData['storeid']) ? $formData['storeid'] : null;
$is_sync = null;
if ($storeId) {
$api->ecommerce->stores->edit(
$storeId,
\Ebizmarts\MailChimp\Helper\Data::PLATFORM,
$domain,
$name,
$emailAddress,
$currencyCode,
null,
$primaryLocale,
$timeZone,
$phone,
$address,
$is_sync
);
} else {
$date = $this->_mhelper->getDateMicrotime();
$mailchimpStoreId = hash('md5', $name. '_' . $date);
//$mailchimpStoreId = md5($name. '_' . $date);
$is_sync = true;
$ret =$api->ecommerce->stores->add(
$mailchimpStoreId,
$formData['list_id'],
$name,
$currencyCode,
\Ebizmarts\MailChimp\Helper\Data::PLATFORM,
$domain,
$emailAddress,
null,
$primaryLocale,
$timeZone,
$phone,
$address,
$is_sync
);
$formData['storeid'] = $mailchimpStoreId;
}
return $formData['storeid'];
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');
}
}
================================================
FILE: Controller/Adminhtml/Stores.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/12/17 11:35 AM
* @file: Stores.php
*/
namespace Ebizmarts\MailChimp\Controller\Adminhtml;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Ebizmarts\MailChimp\Model\MailChimpStoresFactory;
class Stores extends Action
{
/**
* @var Registry
*/
protected $_coreRegistry;
/**
* @var PageFactory
*/
protected $_resultPageFactory;
/**
* @var MailChimpStoresFactory
*/
protected $_mailchimpStoresFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_mhelper;
/**
* Stores constructor.
* @param Context $context
* @param Registry $registry
* @param PageFactory $resultPageFactory
* @param MailChimpStoresFactory $storesFactory
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
Context $context,
Registry $registry,
PageFactory $resultPageFactory,
MailChimpStoresFactory $storesFactory,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
parent::__construct($context);
$this->_coreRegistry = $registry;
$this->_resultPageFactory = $resultPageFactory;
$this->_mailchimpStoresFactory = $storesFactory;
$this->_mhelper = $helper;
}
public function execute()
{
return 1;
}
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_grid');
}
}
================================================
FILE: Controller/Campaign/Check.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 1/19/19 12:36 PM
* @file: Check.php
*/
namespace Ebizmarts\MailChimp\Controller\Campaign;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
class Check extends \Magento\Framework\App\Action\Action
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var ResultFactory
*/
protected $_resultFactory;
protected $_storeManager;
/**
* Get constructor.
* @param Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_helper = $helper;
$this->_storeManager = $storeManager;
}
public function execute()
{
$param = $this->getRequest()->getParams();
$mc_cid = null;
if (key_exists('mc_cid', $param)) {
$mc_cid = $param['mc_cid'];
$magentoStoreId = $this->_storeManager->getStore()->getId();
$api = $this->_helper->getApi($magentoStoreId);
try {
$campaign =$api->campaigns->get($mc_cid);
$mailchimpList = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST,
$magentoStoreId
);
if ($mailchimpList == $campaign['recipients']['list_id']) {
$valid = 1;
} else {
$valid = 0;
}
} catch (\Exception $e) {
$valid = 0;
}
} else {
$valid = 0;
}
$resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
$resultJson->setData(['valid' => $valid]);
return $resultJson;
}
}
================================================
FILE: Controller/Cart/Loadquote.php
================================================
pageFactory = $pageFactory;
$this->_quote = $quote;
$this->_customerSession = $customerSession;
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_urlHelper = $urlHelper;
$this->_message = $context->getMessageManager();
$this->_customerUrl = $customerUrl;
$this->_checkoutSession = $checkoutSession;
parent::__construct($context);
}
/**
* Index Action
*
* @return \Magento\Framework\View\Result\Page
*/
public function execute()
{
/** @var \Magento\Framework\View\Result\Page $resultPage */
$resultPage = $this->pageFactory->create();
$params = $this->getRequest()->getParams();
if (isset($params['id'])) {
$quote = $this->_quote->create();
$quote->getResource()->load($quote, $params['id']);
$magentoStoreId = $quote->getStoreId();
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$syncCommerce = $this->syncHelper->getChimpSyncEcommerce(
$mailchimpStoreId,
$params['id'],
\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE
);
if (!isset($params['token']) || $params['token'] != $syncCommerce->getMailchimpToken()) {
// @error
$this->_message->addErrorMessage(__("You can't access this cart"));
$url = $this->_urlHelper->getUrl(
$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_PAGE,
$magentoStoreId
)
);
$this->_redirect($url);
} else {
if (isset($params['mc_cid'])) {
$url = $this->_urlHelper->getUrl(
$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_PAGE,
$magentoStoreId
),
['mc_cid'=> $params['mc_cid']]
);
$quote->setData('mailchimp_campaign_id', $params['mc_cid']);
} else {
$url = $this->_urlHelper->getUrl(
$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_PAGE,
$magentoStoreId
)
);
}
$quote->setData('mailchimp_abandonedcart_flag', true);
$quote->getResource()->save($quote);
$this->_helper->sendCartEvent($quote);
if (!$quote->getCustomerId()) {
$this->_checkoutSession->setQuoteId($quote->getId());
$this->_redirect($url);
} else {
if ($this->_customerSession->isLoggedIn()) {
$this->_redirect($url);
} else {
$this->_message->addNoticeMessage(__("Login to complete your order"));
if (isset($params['mc_cid'])) {
$url = $this->_urlHelper->getUrl(
$this->_customerUrl->getLoginUrl(),
['mc_cid'=>$params['mc_cid']]
);
} else {
$url = $this->_customerUrl->getLoginUrl();
}
$this->_redirect($url);
}
}
}
}
return $resultPage;
}
}
================================================
FILE: Controller/Checkout/Success.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/20/17 5:06 PM
* @file: Success.php
*/
namespace Ebizmarts\MailChimp\Controller\Checkout;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Success extends \Magento\Framework\App\Action\Action
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_checkoutSession;
/**
* @var \Magento\Framework\View\Result\PageFactory
*/
protected $_pageFactory;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $_subscriberFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory
*/
protected $_interestGroupFactory;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param \Magento\Framework\View\Result\PageFactory $pageFactory
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory,
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
) {
$this->_pageFactory =$pageFactory;
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_checkoutSession = $checkoutSession;
$this->_subscriberFactory = $subscriberFactory;
$this->_interestGroupFactory= $interestGroupFactory;
parent::__construct($context);
}
public function execute()
{
$params = $this->getRequest()->getParams();
$order = $this->_checkoutSession->getLastRealOrder();
/**
* @var $subscriber \Magento\Newsletter\Model\Subscriber
* @var $interestGroup \Ebizmarts\MailChimp\Model\MailChimpInterestGroup
*/
$subscriber = $this->_subscriberFactory->create();
$interestGroup = $this->_interestGroupFactory->create();
try {
$subscriber->loadByEmail($order->getCustomerEmail());
if ($subscriber->getEmail()==$order->getCustomerEmail()) {
if ($subscriber->getStatus()==\Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED) {
$subscriber->subscribe($subscriber->getEmail());
}
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($this->_helper->serialize($params));
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->_helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
$listId = $this->_helper->getGeneralList($order->getStoreId());
$this->_updateSubscriber($listId, $subscriber->getId(), $this->_helper->getGmtDate(), '', 1);
} else {
$this->_subscriberFactory->create()->subscribe($order->getCustomerEmail());
$subscriber->loadByEmail($order->getCustomerEmail());
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($this->_helper->serialize($params));
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->_helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
}
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
$this->messageManager->addSuccessMessage(__('Thanks for sharing your interest with us'));
$this->_redirect($this->_helper->getBaserUrl(
$order->getStoreId(),
\Magento\Framework\UrlInterface::URL_TYPE_WEB
));
}
protected function _updateSubscriber(
$listId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null
) {
$this->syncHelper->saveEcommerceData(
$listId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER,
$sync_delta,
$sync_error,
$sync_modified
);
}
}
================================================
FILE: Controller/WebHook/Index.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/23/17 3:36 PM
* @file: Index.php
*/
namespace Ebizmarts\MailChimp\Controller\WebHook;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\ResultInterface;
class Index extends Action implements CsrfAwareActionInterface
{
const WEBHOOK__PATH = 'mailchimp/webhook/index';
/**
* @var ResultFactory
*/
protected $_resultFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpWebhookRequestFactory
*/
protected $_chimpWebhookRequestFactory;
private $_remoteAddress;
/**
* Index constructor.
* @param Context $context
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\MailChimpWebhookRequestFactory $chimpWebhookRequestFactory
* @param \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
*/
public function __construct(
Context $context,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\MailChimpWebhookRequestFactory $chimpWebhookRequestFactory,
\Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
) {
parent::__construct($context);
$this->_resultFactory = $context->getResultFactory();
$this->_helper = $helper;
$this->_chimpWebhookRequestFactory = $chimpWebhookRequestFactory;
$this->_remoteAddress = $remoteAddress;
}
/**
* @inheritDoc
*/
public function createCsrfValidationException(
RequestInterface $request
): ?InvalidRequestException {
return null;
}
/**
* @inheritDoc
*/
public function validateForCsrf(RequestInterface $request): ?bool
{
return true;
}
public function execute()
{
$requestKey = $this->getRequest()->getParam('wkey');
/**
* @var ResultInterface $result
*/
$result = $this->_resultFactory->create(ResultFactory::TYPE_RAW);
$result->setContents('');
if (!$requestKey) {
$this->_helper->log('No wkey parameter from ip: '.$this->_remoteAddress->getRemoteAddress());
$result->setHttpResponseCode(403);
return $result;
}
$key = $this->_helper->getWebhooksKey();
if ($key!=$requestKey) {
$this->_helper->log('wkey parameter is invalid from ip: '.$this->_remoteAddress->getRemoteAddress());
$result->setHttpResponseCode(403);
return $result;
}
if ($this->getRequest()->getPost('type')) {
$request = $this->getRequest()->getPost();
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_WEBHOOK_ACTIVE) ||
$request['type']==\Ebizmarts\MailChimp\Cron\Webhook::TYPE_SUBSCRIBE) {
try {
$chimpRequest = $this->_chimpWebhookRequestFactory->create();
$chimpRequest->setType($request['type']);
$chimpRequest->setFiredAt($request['fired_at']);
$chimpRequest->setDataRequest($this->_helper->serialize($request['data']));
$chimpRequest->setProcessed(false);
$chimpRequest->getResource()->save($chimpRequest);
$result->setHttpResponseCode(200);
} catch(\Exception $e) {
$this->_helper->log($e->getMessage());
$this->_helper->log($request['data']);
$result->setHttpResponseCode(403);
}
}
} else {
$this->_helper->log('An empty request comes from ip: '.$this->_remoteAddress->getRemoteAddress());
$result->setHttpResponseCode(200);
}
return $result;
}
}
================================================
FILE: Cron/BatchesClean.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 22/11/18 10:02 AM
* @file: BatchesClean.php
*/
namespace Ebizmarts\MailChimp\Cron;
class BatchesClean
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncBatches
*/
protected $mailChimpSyncBatches;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpErrors
*/
protected $mailChimpErrors;
/**
* BatchesClean constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncBatches $mailChimpSyncBatches
* @param \Ebizmarts\MailChimp\Model\MailChimpErrors $chimpErrors
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\MailChimpSyncBatches $mailChimpSyncBatches,
\Ebizmarts\MailChimp\Model\MailChimpErrors $chimpErrors
) {
$this->helper = $helper;
$this->mailChimpSyncBatches = $mailChimpSyncBatches;
$this->mailChimpErrors = $chimpErrors;
}
public function execute()
{
try {
$connection = $this->mailChimpSyncBatches->getResource()->getConnection();
$tableName = $this->mailChimpSyncBatches->getResource()->getMainTable();
$quoteInto = $connection->quoteInto(
'status IN("completed","canceled") and ( date_add(modified_date, interval ? month) < now() OR modified_date IS NULL)',
1
);
$connection->delete($tableName, $quoteInto);
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
try {
$connection = $this->mailChimpSyncBatches->getResource()->getConnection();
$tableName = $this->mailChimpSyncBatches->getResource()->getMainTable();
$select = $connection->select();
$select->from($tableName, ['batch_id']);
$existingBatchIds = $connection->fetchCol($select);
$connection = $this->mailChimpErrors->getResource()->getConnection();
$tableName = $this->mailChimpErrors->getResource()->getMainTable();
if ($existingBatchIds) {
$connection->delete($tableName, [
'batch_id NOT IN (?)' => $existingBatchIds,
]);
} else {
$connection->delete($tableName);
}
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
}
}
================================================
FILE: Cron/Ecommerce.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/1/16 10:02 AM
* @file: Ecommerce.php
*/
namespace Ebizmarts\MailChimp\Cron;
class Ecommerce
{
/**
* @var \Magento\Store\Model\StoreManager
*/
private $_storeManager;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Product
*/
private $_apiProduct;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Result
*/
private $_apiResult;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Customer
*/
private $_apiCustomer;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Order
*/
private $_apiOrder;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Cart
*/
private $_apiCart;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncBatchesFactory
*/
private $_mailChimpSyncBatchesFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
private $_chimpSyncEcommerce;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Subscriber
*/
private $_apiSubscribers;
/**
* @var \Ebizmarts\MailChimp\Model\Api\PromoCodes
*/
private $_apiPromoCodes;
/**
* @var \Ebizmarts\MailChimp\Model\Api\PromoRules
*/
private $_apiPromoRules;
/**
* @var \Magento\Framework\Filesystem\DirectoryList
*/
private $_dir;
/**
* Ecommerce constructor.
* @param \Magento\Store\Model\StoreManager $storeManager
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\Api\Product $apiProduct
* @param \Ebizmarts\MailChimp\Model\Api\Result $apiResult
* @param \Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer
* @param \Ebizmarts\MailChimp\Model\Api\Order $apiOrder
* @param \Ebizmarts\MailChimp\Model\Api\Cart $apiCart
* @param \Ebizmarts\MailChimp\Model\Api\Subscriber $apiSubscriber
* @param \Ebizmarts\MailChimp\Model\Api\PromoCodes $apiPromoCodes
* @param \Ebizmarts\MailChimp\Model\Api\PromoRules $apiPromoRules
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncBatchesFactory $mailChimpSyncBatchesFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce
* @param \Magento\Framework\Filesystem\DirectoryList $dir
*/
public function __construct(
\Magento\Store\Model\StoreManager $storeManager,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\Api\Product $apiProduct,
\Ebizmarts\MailChimp\Model\Api\Result $apiResult,
\Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer,
\Ebizmarts\MailChimp\Model\Api\Order $apiOrder,
\Ebizmarts\MailChimp\Model\Api\Cart $apiCart,
\Ebizmarts\MailChimp\Model\Api\Subscriber $apiSubscriber,
\Ebizmarts\MailChimp\Model\Api\PromoCodes $apiPromoCodes,
\Ebizmarts\MailChimp\Model\Api\PromoRules $apiPromoRules,
\Ebizmarts\MailChimp\Model\MailChimpSyncBatchesFactory $mailChimpSyncBatchesFactory,
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce,
\Magento\Framework\Filesystem\DirectoryList $dir
) {
$this->_storeManager = $storeManager;
$this->_helper = $helper;
$this->_apiProduct = $apiProduct;
$this->_mailChimpSyncBatchesFactory = $mailChimpSyncBatchesFactory;
$this->_apiResult = $apiResult;
$this->_apiCustomer = $apiCustomer;
$this->_apiOrder = $apiOrder;
$this->_apiCart = $apiCart;
$this->_apiSubscribers = $apiSubscriber;
$this->_chimpSyncEcommerce = $chimpSyncEcommerce;
$this->_apiPromoCodes = $apiPromoCodes;
$this->_apiPromoRules = $apiPromoRules;
$this->_dir = $dir;
}
public function execute()
{
$connection = $this->_chimpSyncEcommerce->getResource()->getConnection();
$tableName = $this->_chimpSyncEcommerce->getResource()->getMainTable();
$connection->delete(
$tableName,
'batch_id is null and mailchimp_sync_modified != 1 and mailchimp_sync_error is null'
);
foreach ($this->_storeManager->getStores() as $storeId => $val) {
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ACTIVE, $storeId)) {
if (!$this->_ping($storeId)) {
$this->_helper->log('MailChimp is not available');
return;
}
$this->_storeManager->setCurrentStore($storeId);
$listId = $this->_helper->getGeneralList($storeId);
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
if ($mailchimpStoreId != -1 && $mailchimpStoreId != '') {
$this->_apiResult->processResponses($storeId, true, $mailchimpStoreId);
$batchId = $this->_processStore($storeId, $mailchimpStoreId, $listId);
if ($batchId) {
$connection->update(
$tableName,
[
'batch_id' => $batchId,
'mailchimp_sync_modified' => 0,
'mailchimp_sync_delta' => $this->_helper->getGmtDate()
],
"batch_id is null and mailchimp_store_id = '$mailchimpStoreId' and mailchimp_sync_error is null"
);
$connection->update(
$tableName,
[
'batch_id' => $batchId,
'mailchimp_sync_modified' => 0,
'mailchimp_sync_delta' => $this->_helper->getGmtDate()],
"batch_id is null and mailchimp_store_id = '$listId' and mailchimp_sync_error is null"
);
}
}
}
}
$syncs = [];
foreach ($this->_storeManager->getStores() as $storeId => $val) {
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
if ($mailchimpStoreId != -1 && $mailchimpStoreId != '') {
$dateSync = $this->_helper->getMCMinSyncDateFlag($storeId);
if (isset($syncs[$mailchimpStoreId])) {
if ($syncs[$mailchimpStoreId] && $syncs[$mailchimpStoreId]['datesync'] < $dateSync) {
$syncs[$mailchimpStoreId]['datesync'] = $dateSync;
$syncs[$mailchimpStoreId]['storeid'] = $storeId;
}
} elseif ($dateSync) {
$syncs[$mailchimpStoreId]['datesync'] = $dateSync;
$syncs[$mailchimpStoreId]['storeid'] = $storeId;
} else {
$syncs[$mailchimpStoreId] = false;
}
}
}
foreach ($syncs as $mailchimpStoreId => $val) {
$flag = $this->_helper->getMCMinSyncDateFlagByMailchimpStore(
$mailchimpStoreId,
0,
'default'
);
if ($val && !$flag) {
$this->updateSyncFlagData($val['storeid'], $mailchimpStoreId);
}
}
}
protected function _processStore($storeId, $mailchimpStoreId, $listId)
{
$batchId = null;
$countCustomers = 0;
$countProducts = 0;
$countOrders = 0;
$batchArray = [];
$this->_helper->resetCounters($storeId);
$results = $this->_apiSubscribers->sendSubscribers($storeId, $listId);
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ECOMMERCE_ACTIVE, $storeId)) {
$this->_helper->log('Generate Products payload');
$products = $this->_apiProduct->_sendProducts($storeId);
$countProducts = count($products);
$results = array_merge($results, $products);
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ALL_CUSTOMERS, $storeId)) {
$this->_helper->log('Generate Customers payload');
$customers = $this->_apiCustomer->sendCustomers($storeId);
$countCustomers = count($customers);
$results = array_merge($results, $customers);
}
$this->_helper->log('Generate Orders payload');
$orders = $this->_apiOrder->sendOrders($storeId);
$countOrders = count($orders);
$results = array_merge($results, $orders);
if ($this->_helper->getMCMinSyncDateFlag($storeId)) {
$this->_helper->log('Generate Carts payload');
$carts = $this->_apiCart->createBatchJson($storeId);
$results = array_merge($results, $carts);
} else {
$this->_helper->log('No Carts will be synced until the store is completely synced');
}
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_SEND_PROMO, $storeId)) {
$this->_helper->log('Generate Rules payload');
$rules = $this->_apiPromoRules->sendRules($storeId);
$results = array_merge($results, $rules);
$this->_helper->log('Generate Coupons payload');
$coupons = $this->_apiPromoCodes->sendCoupons($storeId);
$results = array_merge($results, $coupons);
}
}
if (!empty($results)) {
list($OKOperations, $BadOperations) = $this->encodeOperations($results);
$batchArray['operations'] = $OKOperations;
try {
if (!count($batchArray['operations'])) {
$this->_helper->log('An empty operation was detected');
} else {
$api = $this->_helper->getApi($storeId);
$batchResponse = $api->batchOperation->add($batchArray);
if (!isset($batchResponse['id'])) {
$this->_helper->log('error in the call to batch');
} else {
$batchCounters = $this->_helper->getCounters();
$syncBatches = $this->_mailChimpSyncBatchesFactory->create();
$syncBatches->setStoreId($storeId);
$syncBatches->setBatchId($batchResponse['id']);
$syncBatches->setStatus(\Ebizmarts\MailChimp\Helper\Data::BATCH_PENDING);
$syncBatches->setMailchimpStoreId($mailchimpStoreId);
$syncBatches->setModifiedDate($this->_helper->getGmtDate());
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ALL_CUSTOMERS, $storeId)) {
$syncBatches->setCustomersNewCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::CUS_NEW]);
$syncBatches->setCustomersModifiedCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::CUS_MOD]);
}
$syncBatches->setSubscribersNewCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::SUB_NEW]);
$syncBatches->setProductsNewCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::PRO_NEW]);
$syncBatches->setCartsNewCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::QUO_NEW]);
$syncBatches->setOrdersNewCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::ORD_NEW]);
$syncBatches->setSubscribersModifiedCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::SUB_MOD]);
$syncBatches->setProductsModifiedCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::PRO_MOD]);
$syncBatches->setCartsModifiedCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::QUO_MOD]);
$syncBatches->setOrdersModifiedCount($batchCounters[\Ebizmarts\MailChimp\Helper\Data::ORD_MOD]);
$syncBatches->getResource()->save($syncBatches);
$batchId = $batchResponse['id'];
$this->_showResume($batchId, $storeId);
}
}
if (count($BadOperations)) {
$this->markWithError($BadOperations, $mailchimpStoreId, $listId);
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
} else {
$this->_helper->log("Nothing to sync for store $storeId");
}
$countTotal = $this->_helper->getTotalNewItemsSent();
$syncing = $this->_helper->getMCMinSyncDateFlag($storeId);
if ($countTotal == 0 && $syncing) {
$this->_helper->saveMCMinSyncing(
null,
date('Y-m-d'),
$storeId
);
}
return $batchId;
}
/**
* @param $storeId
* @param $mailchimpStoreId
*/
protected function updateSyncFlagData($storeId, $mailchimpStoreId)
{
$this->apiUpdateSyncFlag($storeId, $mailchimpStoreId);
$this->_helper->saveMCMinSyncing(
$mailchimpStoreId,
date('Y-m-d'),
0,
'default'
);
}
/**
* @param $storeId
* @param $mailchimpStoreId
*/
protected function apiUpdateSyncFlag($storeId, $mailchimpStoreId)
{
try {
$api = $this->_helper->getApi($storeId);
$api->ecommerce->stores->edit(
$mailchimpStoreId,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
false
);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log('MailChimp error when updating syncing flag for store ' . $storeId);
$this->_helper->log($e->getFriendlyMessage());
}
}
protected function _ping($storeId)
{
try {
$api = $this->_helper->getApi($storeId);
$api->root->info();
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
return false;
}
return true;
}
protected function _showResume($batchId, $storeId)
{
$this->_helper->log("Sent batch $batchId for store $storeId");
$this->_helper->log($this->_helper->getCounters());
}
protected function _saveRequest($resquest)
{
$pathLog = $this->_dir->getPath('log').DIRECTORY_SEPARATOR.'Request'.$this->_helper->getGmtTimeStamp().'.log';
error_log(var_export($resquest, true), 3, $pathLog);
$this->_helper->log("Request with error was saved in $pathLog");
}
protected function encodeOperations($operations)
{
$OKOperations = [];
$BadOperations = [];
$batchJson = json_encode($operations);
$jsonLastErrorGeneral = json_last_error();
$jsonLastErrorMsgGeneral = json_last_error_msg();
if ($jsonLastErrorGeneral) {
$this->_helper->log("Encode error");
foreach ($operations as $opIndex => $operation) {
$jsonEncode = json_encode($operation);
$jsonLastErrorItem = json_last_error();
if ($jsonLastErrorItem) {
$jsonLastErrorMsgItem = json_last_error_msg();
$this->_helper->log("");
$this->_helper->log("json_encode error: $jsonLastErrorMsgItem, operation:");
$this->_saveRequest($operation);
/*remove failing operation*/
$BadOperations[] = $operation;
unset($operations[$opIndex]);
} else {
$OKOperations[] = $operation;
}
}
} else {
$OKOperations = $operations;
}
return [$OKOperations, $BadOperations];
}
protected function markWithError($operations, $mailchimpStoreId, $listId)
{
$type = null;
$relatedId = null;
$types = [
\Ebizmarts\MailChimp\Helper\Data::IS_ORDER,
\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE,
\Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER,
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER
];
$connection = $this->_chimpSyncEcommerce->getResource()->getConnection();
$tableName = $this->_chimpSyncEcommerce->getResource()->getMainTable();
foreach ($operations as $operation) {
if (is_array($operation)) {
if (array_key_exists('operation_id', $operation)) {
$operationId = explode("_", $operation['operation_id']);
if (isset($operationId[0])) {
$type = $operationId[0];
if (!in_array($type, $types)) {
$type = '';
} else {
if ($type == \Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER) {
$storeId = $listId;
} else {
$storeId = $mailchimpStoreId;
}
}
}
if (isset($operationId[2])) {
$relatedId = $operationId[2];
}
if ($type && $relatedId) {
$connection->update(
$tableName,
[
'batch_id' => -1,
'mailchimp_sync_modified' => 0,
'mailchimp_sync_delta' => $this->_helper->getGmtDate(),
'mailchimp_sync_error' => __('Json error'),
'mailchimp_sent' => \Ebizmarts\MailChimp\Helper\Data::NOTSYNCED
],
"batch_id is null and mailchimp_store_id = '$storeId' and type ='$type' and related_id = $relatedId"
);
}
}
}
}
}
}
================================================
FILE: Cron/ErrorsClean.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 15/09/22 10:02 AM
* @file: ErrorsClean.php
*/
namespace Ebizmarts\MailChimp\Cron;
class ErrorsClean
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpErrors
*/
protected $chimpErrors;
/**
* @var \Magento\Store\Model\StoreManager
*/
protected $storeManager;
const LIMIT = 1000;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\MailChimpErrors $chimpErrors
* @param \Magento\Store\Model\StoreManager $storeManager
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\MailChimpErrors $chimpErrors,
\Magento\Store\Model\StoreManager $storeManager
)
{
$this->helper = $helper;
$this->chimpErrors = $chimpErrors;
$this->storeManager = $storeManager;
}
public function execute()
{
foreach ($this->storeManager->getStores() as $storeId => $val)
{
$period = $this->helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_CLEAN_ERROR_MONTHS, $storeId);
if ($period > 0) {
try {
$this->helper->log("Cleaning errors for store [$storeId] older than $period months");
$this->chimpErrors->deleteByStorePeriod($storeId,$period,self::LIMIT);
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
}
}
}
}
================================================
FILE: Cron/GenerateStatistics.php
================================================
'Unsubscribe',
1 => 'Delete',
];
public function __construct(
Data $helper,
StoreManager $storeManager,
CustomerCollectionFactory $customerCollectionFactory,
ProductCollectionFactory $productCollectionFactory,
OrderCollectionFactory $orderCollectionFactory,
MailchimpSyncBatchesCollectionFactory $mailchimpSyncBatchesCollectionFactory,
ScheduleCollectionFactory $scheduleCollectionFactory,
ProductMetadataInterface $productMetadata,
ModuleVersion $moduleVersion,
TimezoneInterface $locale
)
{
$this->helper = $helper;
$this->storeManager = $storeManager;
$this->customerCollectionFactory = $customerCollectionFactory;
$this->productCollectionFactory = $productCollectionFactory;
$this->orderCollectionFactory = $orderCollectionFactory;
$this->mailChimpSyncBatchesCollectionFactory = $mailchimpSyncBatchesCollectionFactory;
$this->scheduleCollectionFactory = $scheduleCollectionFactory;
$this->productMetadata = $productMetadata;
$this->moduleVersion = $moduleVersion;
$this->locale = $locale;
}
public function execute()
{
$data = [];
$data['storeURL'] = $this->storeManager->getStore()->getBaseUrl();
$data['time'] = $this->helper->getGmtDate();
foreach ($this->storeManager->getStores() as $storeId => $val)
{
if ($this->helper->isMailChimpEnabled($storeId)) {
$mailChimpStoreId = $this->helper->getConfigValue(Data::XML_MAILCHIMP_STORE, $storeId);
$storeStatistics = [];
// Get currents mailchimp totals (orders, products, customers)
$storeStatistics['mailchimp'] = $this->getMailchimpTotals($storeId);
$storeStatistics['magento'] = $this->getMagentoTotals($storeId);
$data['statistics']['store'][$storeId] = $storeStatistics;
$data['batches']['store'][$storeId] = $this->getBatches($storeId, $mailChimpStoreId);
}
}
$data['jobs'] = $this->getJobs();
if (!empty($data)) {
$this->helper->saveNotification($data);
}
}
private function getMagentoTotals($storeId)
{
$options = [];
$customerCollection = $this->customerCollectionFactory->create();
$customerCollection->addFieldToFilter('store_id', ['eq'=>$storeId]);
$customerCollection->getSelect()->reset(\Magento\Framework\DB\Select::COLUMNS)->columns(['entity_id','store_id']);
$totalCustomers = $customerCollection->getSize();
$options['total_customers'] = $totalCustomers;
unset($customerCollection);
$productCollection = $this->productCollectionFactory->create();
$productCollection->addStoreFilter($storeId);
$productCollection->getSelect()->reset(\Magento\Framework\DB\Select::COLUMNS)->columns(['entity_id']);
$totalProducts = $productCollection->getSize();
$options['total_products'] = $totalProducts;
unset($productCollection);
$orderCollection = $this->orderCollectionFactory->create();
$orderCollection->addFieldToFilter('store_id', ['eq' => $storeId]);
$orderCollection->getSelect()->reset(\Magento\Framework\DB\Select::COLUMNS)->columns(['entity_id']);
$totalOrders = $orderCollection->getSize();
$options['total_orders'] = $totalOrders;
unset($orderCollection);
$storeUrl = stripslashes($this->storeManager->getStore($storeId)->getUrl());
$options['store_url'] = stripslashes($storeUrl);
// get all de configuration
$config = [];
$config['general']['active'] = $this->helper->getConfigValue(Data::XML_PATH_ACTIVE, $storeId);
$config['general']['store'] = $this->helper->getConfigValue(Data::XML_MAILCHIMP_STORE, $storeId);
$config['general']['list'] = $this->helper->getConfigValue(Data::XML_PATH_LIST, $storeId);
$config['general']['popup_form'] = $this->helper->getConfigValue(Data::XML_POPUP_FORM, $storeId);
if ($config['general']['popup_form']) {
$config['general']['popup_url'] = $this->helper->getConfigValue(Data::XML_POPUP_URL, $storeId);
}
$config['general']['magento_email'] = $this->helper->getConfigValue(Data::XML_MAGENTO_MAIL, $storeId);
$config['general']['two-way_sync'] = $this->helper->getConfigValue(Data::XML_PATH_WEBHOOK_ACTIVE, $storeId);
if ( $config['general']['two-way_sync']) {
$config['general']['delete_action'] = $this->deleteAction[$this->helper->getConfigValue(Data::XML_PATH_WEBHOOK_DELETE)];
}
$config['general']['enable_log'] = $this->helper->getConfigValue(Data::XML_PATH_LOG,$storeId);
$config['general']['field_mapping'] = $this->helper->getConfigValue(Data::XML_MERGEVARS, $storeId);
$config['general']['mapping'] = $this->helper->getMapFields($storeId, false);
$config['general']['interest'] = $this->helper->getConfigValue(Data::XML_INTEREST, $storeId);
$config['general']['show_groups'] = $this->helper->getConfigValue(Data::XML_INTEREST_IN_SUCCESS);
if ($config['general']['show_groups']) {
$config['general']['group_description'] = $this->helper->getConfigValue(Data::XML_INTEREST_SUCCESS_HTML_BEFORE, $storeId);
$config['general']['succes_message'] = $this->helper->getConfigValue(Data::XML_INTEREST_SUCCESS_HTML_AFTER, $storeId);
}
$config['general']['timeout'] = $this->helper->getConfigValue(Data::XML_PATH_TIMEOUT, $storeId);
$config['ecommerce']['enabled'] = $this->helper->getConfigValue(Data::XML_PATH_ECOMMERCE_ACTIVE, $storeId);
$config['ecommerce']['sync_all_customers'] = $this->helper->getConfigValue(Data::XML_PATH_ALL_CUSTOMERS, $storeId);
$config['ecommerce']['subscribe_all_customers'] = $this->helper->getConfigValue(Data::XML_ECOMMERCE_OPTIN, $storeId);
$config['ecommerce']['first_date'] = $this->helper->getConfigValue(Data::XML_ECOMMERCE_FIRSTDATE, $storeId);
$config['ecommerce']['send_promo'] = $this->helper->getConfigValue(Data::XML_SEND_PROMO, $storeId);
$config['ecommerce']['include_taxes'] = $this->helper->getConfigValue(Data::XML_INCLUDING_TAXES, $storeId);
$config['ecommerce']['campaign_attribution'] = $this->helper->getConfigValue(Data::XML_CAMPAIGN_ACTION, $storeId);
$config['ecommerce']['monts_to_clear_error_table'] = $this->helper->getConfigValue(Data::XML_CLEAN_ERROR_MONTHS, $storeId);
$config['ac']['enabled'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_ACTIVE, $storeId);
$config['ac']['first_date'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_FIRSTDATE, $storeId);
$config['ac']['redirect_page'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_PAGE, $storeId);
$config['ac']['save_email'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_EMAIL, $storeId);
$options['config'] = $config;
$options['magento_version'] = $this->productMetadata->getVersion();
$options['mc2-version'] = $this->moduleVersion->getModuleVersion('Ebizmarts_MailChimp');
try {
$options['lib-version'] = $this->moduleVersion->getLibVersion('ebizmarts/mailchimp-lib');
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
$options['time_zone'] = $this->locale->getConfigTimezone(\Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeId);
return $options;
}
private function getMailchimpTotals($storeId)
{
$mailchimpList = $this->helper->getGeneralList($storeId);
$mailChimpStoreId = $this->helper->getConfigValue(Data::XML_MAILCHIMP_STORE, $storeId);
$api = $this->helper->getApi($storeId);
$apiInfo = $api->root->info();
$options = [];
$options ['store'] = $mailChimpStoreId;
if (isset($apiInfo['account_name'])) {
$options['webhooks'] = $this->getWebhooks($api, $mailchimpList);
$options['username'] =$apiInfo['account_name'];
$options['total_subscribers'] = $apiInfo['total_subscribers'];
if ($storeId != -1) {
$storeData = $api->ecommerce->stores->get($mailChimpStoreId);
$options['list_id'] = $storeData['list_id'];
$list = $api->lists->getLists($storeData['list_id']);
$options['list_name'] = $list['name'];
$options['total_list_subscribers'] = $list['stats']['member_count'];
$totalCustomers = $api->ecommerce->customers->getAll($mailChimpStoreId, 'total_items');
$options['total_customers'] = $totalCustomers['total_items'];
$totalProducts = $api->ecommerce->products->getAll($mailChimpStoreId, 'total_items');
$options['total_products'] = $totalProducts['total_items'];
$totalOrders = $api->ecommerce->orders->getAll($mailChimpStoreId, 'total_items');
$options['total_orders'] = $totalOrders['total_items'];
$totalCarts = $api->ecommerce->carts->getAll($mailChimpStoreId, 'total_items');
$options['total_carts'] = $totalCarts['total_items'];
$options['currency_code'] = $storeData['currency_code'];
$options['money_format'] = $storeData['money_format'];
$options['primary_locale'] = $storeData['primary_locale'];
$options['timezone'] = $storeData['timezone'];
$options['is_syncing'] = $storeData['is_syncing'];
$contact = [];
$contact['email_address'] = $storeData['email_address'];
$contact['phone_number'] = $storeData['phone'];
$contact['address'] = $storeData['address'];
$options['contact'] = $contact;
} else {
$options['nostore'] = ['label' => __('Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized)'), 'value' => ''];
}
}
return $options;
}
private function getWebhooks($api, $listId)
{
$ret = [];
$webhooks = $api->lists->webhooks->getAll($listId);
foreach ($webhooks['webhooks'] as $webhook) {
$item =[];
$item['url'] = $webhook['url'];
$item['events'] = $webhook['events'];
$item['sources'] = $webhook['sources'];
$ret[] = $item;
}
return $ret;
}
private function getBatches($storeId,$mailchimpStoreId)
{
$batches = [];
$collection = $this->mailChimpSyncBatchesCollectionFactory->create();
$collection
->addFieldToFilter('store_id', ['eq' => $storeId])
->addFieldToFilter('mailchimp_store_id', ['eq' => $mailchimpStoreId]);
$collection->setOrder('modified_date', 'DESC');
$collection->getSelect()->limit(10);
foreach ($collection as $item) {
$batch = [];
$batch['id'] = $item['batch_id'];
$batch['mailchimp_store_id'] = $item['mailchimp_store_id'];
$batch['date'] = $item['modified_date'];
$batch['status'] = $item['status'];
$counters = [];
$counters['carts_new'] = $item['carts_new_count'];
$counters['order_new'] = $item['orders_new_count'];
$counters['products_new'] = $item['products_new_count'];
$counters['customers_new'] = $item['customers_new_count'];
$counters['subscribers_new'] = $item['subscribers_new_count'];
$counters['carts_modified'] = $item['carts_modified_count'];
$counters['customers_modified'] = $item['customers_modified_count'];
$counters['orders_modified'] = $item['orders_modified_count'];
$counters['products_modified'] = $item['products_modified_count'];
$counters['subscribers_modified'] = $item['subscribers_modified_count'];
$batch['counters'] = $counters;
$batches[] = $batch;
}
return $batches;
}
private function getJobs()
{
$jobs = [];
$collection = $this->scheduleCollectionFactory->create();
$collection->addFieldToFilter('job_code', ['eq'=> 'ebizmarts_ecommerce']);
$collection->setOrder('scheduled_at', 'DESC');
$collection->getSelect()->limit(10);
foreach ($collection as $item) {
$job =[];
$job['job_code'] = $item['job_code'];
$job['status'] = $item['status'];
$job['messages'] = $item['messages'];
$job['scheduled_at'] = $item['scheduled_at'];
$job['executed_at'] = $item['executed_at'];
$job['finished_at'] = $item['finished_at'];
$jobs[] = $job;
}
$collection = $this->scheduleCollectionFactory->create();
$collection->addFieldToFilter('job_code', ['eq'=> 'ebizmarts_webhooks']);
$collection->setOrder('scheduled_at', 'DESC');
$collection->getSelect()->limit(10);
foreach ($collection as $item) {
$job =[];
$job['job_code'] = $item['job_code'];
$job['status'] = $item['status'];
$job['messages'] = $item['messages'];
$job['scheduled_at'] = $item['scheduled_at'];
$job['executed_at'] = $item['executed_at'];
$job['finished_at'] = $item['finished_at'];
$jobs[] = $job;
}
return $jobs;
}
}
================================================
FILE: Cron/SyncStatistics.php
================================================
helper = $helper;
$this->mailchimpNotificationCollectionFactory = $mailchimpNotificationCollectionFactory;
$this->mailchimpNotificationFactory = $mailchimpNotificationFactory;
$this->mailchimpNotification = $mailchimpNotification;
$this->mailchimpHttp = $mailchimpHttp;
$mailchimpHttp->setUrl($helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL));
$this->storeManager = $storeManager;
}
public function execute()
{
$count = 0;
$batch = [];
$this->helper->log("SyncStatistics");
if ($this->helper->isSupportEnabled())
{
$scopeId = $this->storeManager->getDefaultStoreView()->getId();
$scope = 'default';
$token = $this->helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope);
if (!$token) {
$this->helper->log("You must first register your copy to sync statistics");
$this->cleanData();
return;
}
$this->mailchimpHttp->setUrl($this->helper->getConfigValue(MailChimpHelper::XML_REGISTER_URL).'/logenabled');
$response = $this->mailchimpHttp->get($token);
$res = json_decode($response, true);
if (key_exists('error',$res) && $res['error']) {
$this->helper->log("Something went wrong while syncing statistics");
$this->cleanData();
return;
} elseif (key_exists('enabled',$res) && !$res['enabled']) {
$this->helper->log("You are not authorized to sync statistics");
$this->cleanData();
return;
}
$this->helper->log("Processing sync statistics");
$url = $this->helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL)."/$token";
$this->mailchimpHttp->setUrl($url);
$collection = $this->getCollection();
/**
* @var $collectionItem \Ebizmarts\MailChimp\Model\MailChimpNotification
*/
foreach ($collection as $collectionItem)
{
if (!($count%self::MAX_BATCH_SIZE)&&$count) {
if ($this->syncData($batch)) {
$batch = [];
$batch[$collectionItem->getId()] = $collectionItem->getNotificationData();
$count++;
} else {
$batch = [];
break;
}
} else {
$batch[$collectionItem->getId()] = $collectionItem->getNotificationData();
$count++;
}
}
if (count($batch)) {
$this->syncData($batch);
}
$this->helper->log("Sync statistics $count registers processed");
} else {
$this->helper->log("Sync statistics not enabled");
}
$this->cleanData();
}
private function getCollection()
{
$collection = $this->mailchimpNotificationCollectionFactory->create();
$collection->addFieldToFilter('processed', 0);
$collection->setOrder('generated_at', 'ASC');
$collection->getSelect()->limit(self::MAX_NOTIFICATIONS);;
return $collection;
}
private function syncData($data)
{
$batch = [];
$continue = true;
foreach ($data as $id => $notification) {
$json = [];
try {
$jsonData = json_decode($notification, true, 50, JSON_THROW_ON_ERROR);
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
$mailchimpNotification = $this->mailchimpNotificationFactory->create();
$mailchimpNotification->getResource()->load($mailchimpNotification, $id);
$mailchimpNotification->setProcessed(true);
$mailchimpNotification->setSyncedAt($this->helper->getGmtDate());
$mailchimpNotification->getResource()->save($mailchimpNotification);
continue;
}
$json['data'] = $jsonData;
$json['id'] = $id;
$batch[] = $json;
}
$post = json_encode($batch);
try {
$response = $this->mailchimpHttp->post($post);
$rjson = json_decode($response, true);
if (is_array($rjson)) {
foreach ($rjson as $r) {
if (is_array($r) && array_key_exists('id', $r)) {
$id = $r['id'];
if (!$r['error']) {
$mailchimpNotification = $this->mailchimpNotificationFactory->create();
$mailchimpNotification->getResource()->load($mailchimpNotification, $id);
$mailchimpNotification->setProcessed(true);
$mailchimpNotification->setSyncedAt($this->helper->getGmtDate());
$mailchimpNotification->getResource()->save($mailchimpNotification);
}
} else {
$this->helper->log("Sync notification failed to sync");
$this->helper->log($r);
}
}
} else {
switch ($this->mailchimpHttp->extractResponse($response)) {
case MailchimpHttp::ERROR_GENERIC:
break;
case MailChimpHttp::ERROR_AUTH:
$continue = false;
break;
case MailChimpHttp::ERROR_JSON:
$this->helper->log("Invalid JSON, syncing process will continue regardless");
break;
}
}
} catch (\Exception $e) {
$this->helper->log('Exception '.$e->getMessage());
return false;
}
return $continue;
}
private function cleanData()
{
$days = $this->helper->getConfigValue(MailChimpHelper::XML_CLEAN_SUPPORT_PERIOD);
try {
$connection = $this->mailchimpNotification->getConnection();
$tableName = $this->mailchimpNotification->getMainTable();
$quoteInto = $connection->quoteInto('processed = 1 or date_add(generated_at, interval ? day) <= NOW()', $days);
$connection->delete($tableName, $quoteInto);
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
}
}
================================================
FILE: Cron/Webhook.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/30/17 8:34 PM
* @file: Webhook.php
*/
namespace Ebizmarts\MailChimp\Cron;
class Webhook
{
const ACTION_DELETE = 'delete';
const ACTION_UNSUBSCRIBE = 'unsub';
const TYPE_SUBSCRIBE = 'subscribe';
const TYPE_UNSUBSCRIBE = 'unsubscribe';
const TYPE_CLEANED = 'cleaned';
const TYPE_UPDATE_EMAIL = 'upemail';
const TYPE_PROFILE = 'profile';
const BATCH_LIMIT = 50;
const NOT_PROCESSED = 0;
const PROCESSED_OK = 1;
const PROCESSED_WITH_ERROR = 2;
const DATA_WITH_ERROR = 3;
const DATA_NOT_CONVERTED = 4;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $_subscriberFactory;
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\CollectionFactory
*/
protected $_webhookCollection;
/**
* @var \Magento\Customer\Model\CustomerFactory
*/
protected $_customer;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory
*/
protected $interestGroupFactory;
/**
* @var \Magento\Store\Model\StoreManager
*/
protected $storeManager;
protected $groups = [];
/**
* Webhook constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\CollectionFactory $webhookCollection
* @param \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
* @param \Magento\Store\Model\StoreManager $storeManager
* @param \Magento\Customer\Model\CustomerFactory $customer
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\CollectionFactory $webhookCollection,
\Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory,
\Magento\Store\Model\StoreManager $storeManager,
\Magento\Customer\Model\CustomerFactory $customer
) {
$this->_helper = $helper;
$this->_subscriberFactory = $subscriberFactory;
$this->_webhookCollection = $webhookCollection;
$this->_customer = $customer;
$this->interestGroupFactory = $interestGroupFactory;
$this->storeManager = $storeManager;
}
public function execute()
{
$this->processWebhooks();
}
public function processWebhooks()
{
$this->_loadGroups();
/**
* @var $collection \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\Collection
*/
$collection = $this->_webhookCollection->create();
$collection->addFieldToFilter('processed', ['eq'=>self::NOT_PROCESSED]);
$collection->getSelect()->limit(self::BATCH_LIMIT);
/**
* @var $item \Ebizmarts\MailChimp\Model\MailChimpWebhookRequest
*/
foreach ($collection as $item) {
try {
$data = $this->_helper->unserialize($item->getDataRequest());
$stores = $this->_helper->getMagentoStoreIdsByListId($data['list_id']);
if (count($stores)) {
switch ($item->getType()) {
case self::TYPE_SUBSCRIBE:
$this->_subscribe($data);
break;
case self::TYPE_UNSUBSCRIBE:
$this->_unsubscribe($data);
break;
case self::TYPE_CLEANED:
$this->_clean($data);
break;
case self::TYPE_UPDATE_EMAIL:
$this->_updateEmail($data);
break;
case self::TYPE_PROFILE:
$this->_profile($data);
}
$processed = self::PROCESSED_OK;
} else {
$processed = self::PROCESSED_WITH_ERROR;
}
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
$processed = self::PROCESSED_WITH_ERROR;
}
$item->setProcessed($processed);
$item->getResource()->save($item);
}
}
protected function _subscribe($data)
{
$listId = $data['list_id'];
$email = $data['email'];
$subscribers = $this->_helper->loadListSubscribers($listId, $email);
/**
* @var $sub \Magento\Newsletter\Model\Subscriber
*/
if ($subscribers->count()) {
foreach ($subscribers as $sub) {
if ($sub->getSubscriberStatus() != \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED) {
$sub->setSubscriberStatus(\Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
$sub->getResource()->save($sub);
}
}
} else {
$storeIds = $this->_helper->getMagentoStoreIdsByListId($listId);
if (count($storeIds) > 0) {
foreach ($storeIds as $storeId) {
$sub = $this->_subscriberFactory->create();
$sub->setStoreId($storeId);
$sub->setSubscriberEmail($email);
$this->_subscribeMember($sub, \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
}
} else {
$sub = $this->_subscriberFactory->create();
$sub->setSubscriberEmail($email);
$this->_subscribeMember($sub, \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
}
}
}
protected function _unsubscribe($data)
{
$listId = $data['list_id'];
$email = $data['email'];
$subscribers = $this->_helper->loadListSubscribers($listId, $email);
/**
* @var $sub \Magento\Newsletter\Model\Subscriber
*/
foreach ($subscribers as $sub) {
try {
$action = isset($data['action']) ? $data['action'] : self::ACTION_DELETE;
switch ($action) {
case self::ACTION_DELETE:
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_WEBHOOK_DELETE)) {
$sub->getResource()->delete($sub);
} elseif ($sub->getSubscriberStatus()!=\Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED) {
$this->_subscribeMember($sub, \Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED);
}
break;
case self::ACTION_UNSUBSCRIBE:
if ($sub->getSubscriberStatus()!=\Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED) {
$this->_subscribeMember($sub, \Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED);
}
break;
}
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
}
}
protected function _clean($data)
{
$subscribers = $this->_helper->loadListSubscribers($data['list_id'], $data['email']);
/**
* @var $sub \Magento\Newsletter\Model\Subscriber
*/
foreach ($subscribers as $sub) {
$sub->getResource()->delete($sub);
}
}
protected function _updateEmail($data)
{
$oldEmail = $data['old_email'];
$newEmail = $data['new_email'];
$listId = $data['list_id'];
$oldSubscribers = $this->_helper->loadListSubscribers($listId, $oldEmail);
$newSubscribers = $this->_helper->loadListSubscribers($listId, $newEmail);
/**
* @var $sub \Magento\Newsletter\Model\Subscriber
*/
if (!$newSubscribers->count()) {
if ($oldSubscribers->count()) {
foreach ($oldSubscribers as $sub) {
$sub->setSubscriberEmail($newEmail);
$sub->getResource()->save($sub);
}
} else {
$sub = $this->_subscriberFactory->create();
$sub->setSubscriberEmail($newEmail);
$this->_subscribeMember($sub, \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
}
}
}
protected function _profile($data)
{
$listId = $data['list_id'];
$email = $data['email'];
$customers = $this->_helper->loadListCustomers($listId, $email);
if ($customers->count() > 0) {
/**
* @var $customer \Magento\Customer\Model\Customer
*/
foreach ($customers as $c) {
$customer = $this->_customer->create();
$customer->getResource()->load($customer, $c->getEntityId());
$this->_processMerges($customer,$data);
$customer->getResource()->save($customer);
}
} else {
$subscribers = $this->_helper->loadListSubscribers($listId, $email);
if ($subscribers->count() == 0) {
$subscriber = $this->_subscriberFactory->create();
$subscriber->setSubscriberEmail($email);
$stores = $this->_helper->getMagentoStoreIdsByListId($listId);
if (count($stores)) {
$subscriber->setStoreId($stores[0]);
try {
$api = $this->_helper->getApi($stores[0]);
$member = $api->lists->members->get($listId, hash('md5', strtolower($email)));
if ($member) {
if ($member['status'] == \Mailchimp::SUBSCRIBED) {
$this->_subscribeMember($subscriber, \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED);
} elseif ($member['status'] == \Mailchimp::UNSUBSCRIBED) {
$this->_subscribeMember($subscriber, \Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED);
}
}
} catch (\Mailchimp_Error $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
}
}
}
/**
* @param \Magento\Customer\Model\Customer $customer
* @param $data
*/
protected function _processMerges(\Magento\Customer\Model\Customer $customer, $data)
{
$mapFields = $this->_helper->getMapFields($customer->getStoreId());
foreach($data['merges'] as $key=> $value) {
if (!empty($value)) {
if ($key=='GROUPINGS') {
$groups = ['group' => []];
foreach($value as $item) {
if (!empty($item['groups'])) {
$groups['group'][$item['unique_id']] = $this->_getGroups($item['groups'],$item['unique_id']);
}
}
$serializedGroups = $this->_helper->serialize($groups);
$subscriber = $this->_subscriberFactory->create();
$subscriber->loadByCustomerId($customer->getId());
$interestGroup = $this->interestGroupFactory->create();
if ($subscriber->getEmail()==$customer->getEmail()) {
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($serializedGroups);
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->_helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
$listId = $this->_helper->getGeneralList($subscriber->getStoreId());
} else {
$this->_subscriberFactory->create()->subscribe($customer->getEmail());
$subscriber->loadByEmail($customer->getEmail());
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($serializedGroups);
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->_helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
}
} else {
if (is_array($mapFields)) {
foreach ($mapFields as $map) {
if ($map['mailchimp'] == $key) {
if (!$map['isAddress'] && $map['customer_field'] != "dob" && strpos($map['customer_field'], '##') !== false) {
if (count($map['options'])) {
foreach ($map['options'] as $option) {
if ($option['label'] == $value) {
$customer->setData($map['customer_field'], $option['value']);
}
}
} else {
$customer->setData($map['customer_field'], $value);
}
}
}
}
}
}
}
}
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @param string $status
* @throws \Exception
*/
protected function _subscribeMember(\Magento\Newsletter\Model\Subscriber $subscriber, int $status)
{
$subscriber->setImportMode(true);
$subscriber->setStatus($status);
$subscriber->setSubscriberConfirmCode($subscriber->randomSequence());
$subscriber->setIsStatusChanged(true);
$subscriber->getResource()->save($subscriber);
}
protected function _loadGroups()
{
foreach ($this->storeManager->getStores() as $storeId => $val) {
if (!$this->_helper->isMailChimpEnabled($storeId)) {
continue;
}
$listId =$this->_helper->getDefaultList($storeId);
if (!$listId||$listId==-1) {
$this->_helper->log("ListId [$listId] is invalid for Store [$storeId]");
continue;
} else {
$api = $this->_helper->getApi($storeId);
try {
$interestsCat = $api->lists->interestCategory->getAll($listId, null, null, 200);
if (isset($interestsCat['categories'])) {
foreach ($interestsCat['categories'] as $cat) {
$interests = $api->lists->interestCategory->interests->getAll($listId, $cat['id'], null, null, 200);
$this->groups = array_merge_recursive($this->groups, $interests['interests']);
}
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$error = $e->getMessage();
$this->_helper->log("Error: [$error] for store [$storeId]");
}
}
}
}
protected function _getGroups($groups, $cat)
{
$rc = [];
$gr = explode(",",$groups);
foreach ($gr as $g) {
foreach ($this->groups as $group) {
if (trim($g)==$group['name']&&$group['category_id']==$cat) {
$rc[$group['id']] = $group['id'];
break;
}
}
}
return $rc;
}
}
================================================
FILE: Cron/WebhookClean.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 22/11/18 10:02 AM
* @file: WebhookClean.php
*/
namespace Ebizmarts\MailChimp\Cron;
class WebhookClean
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpWebhookRequest
*/
protected $webhooks;
/**
* WebhookClean constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\MailChimpWebhookRequest $webhookRequest
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\MailChimpWebhookRequest $webhookRequest
) {
$this->helper = $helper;
$this->webhooks = $webhookRequest;
}
public function execute()
{
try {
$connection = $this->webhooks->getResource()->getConnection();
$tableName = $this->webhooks->getResource()->getMainTable();
$quoteInto = $connection->quoteInto('processed = ? and date_add(fired_at, interval 1 month) < now()', 1);
$connection->delete($tableName, $quoteInto);
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
}
}
================================================
FILE: Helper/Data.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Helper;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\ValidatorException;
use Magento\Store\Model\Store;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Model\MailchimpNotificationFactory as MailchimpNotificationFactory;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
const XML_PATH_ACTIVE = 'mailchimp/general/active';
const XML_PATH_APIKEY = 'mailchimp/general/apikey';
const XML_PATH_APIKEY_LIST = 'mailchimp/general/apikeylist';
const XML_PATH_MAXLISTAMOUNT = 'mailchimp/general/maxlistamount';
const XML_PATH_LIST = 'mailchimp/general/monkeylist';
const XML_PATH_WEBHOOK_ACTIVE = 'mailchimp/general/webhook_active';
const XML_PATH_WEBHOOK_DELETE = 'mailchimp/general/webhook_delete';
const XML_PATH_LOG = 'mailchimp/general/log';
const XML_PATH_TIMEOUT = 'mailchimp/general/timeout';
const XML_PATH_MAPPING = 'mailchimp/general/mapping';
const XML_MAILCHIMP_STORE = 'mailchimp/general/monkeystore';
const XML_MAILCHIMP_JS_URL = 'mailchimp/general/mailchimpjsurl';
const XML_PATH_CONFIRMATION_FLAG = 'newsletter/subscription/confirm';
const XML_PATH_STORE = 'mailchimp/ecommerce/store';
const XML_PATH_ECOMMERCE_ACTIVE = 'mailchimp/ecommerce/active';
const XML_PATH_ALL_CUSTOMERS = 'mailchimp/ecommerce/all_customers';
const XML_PATH_SYNC_DATE = 'mailchimp/general/mcminsyncdateflag';
const XML_ECOMMERCE_OPTIN = 'mailchimp/ecommerce/customer_optin';
const XML_ECOMMERCE_FIRSTDATE = 'mailchimp/ecommerce/firstdate';
const XML_ABANDONEDCART_ACTIVE = 'mailchimp/abandonedcart/active';
const XML_ABANDONEDCART_FIRSTDATE = 'mailchimp/abandonedcart/firstdate';
const XML_ABANDONEDCART_PAGE = 'mailchimp/abandonedcart/page';
const XML_PATH_IS_SYNC = 'mailchimp/general/issync';
const XML_ABANDONEDCART_EMAIL = 'mailchimp/abandonedcart/save_email_in_quote';
const XML_MERGEVARS = 'mailchimp/general/map_fields';
const XML_INTEREST = 'mailchimp/general/interest';
const XML_INTEREST_IN_SUCCESS = 'mailchimp/general/interest_in_success';
const XML_INTEREST_SUCCESS_HTML_BEFORE = 'mailchimp/general/interest_success_html_before';
const XML_INTEREST_SUCCESS_HTML_AFTER = 'mailchimp/general/interest_success_html_after';
const XML_MAGENTO_MAIL = 'mailchimp/general/magentoemail';
const XML_SEND_PROMO = 'mailchimp/ecommerce/send_promo';
const XML_SYNC_SALABLE = 'mailchimp/ecommerce/syncsalable';
const XML_INCLUDING_TAXES = 'mailchimp/ecommerce/including_taxes';
const XML_CAMPAIGN_ACTION = 'mailchimp/ecommerce/campaign_action';
const XML_POPUP_FORM = 'mailchimp/general/popup_form';
const XML_POPUP_URL = 'mailchimp/general/popup_url';
const XML_CLEAN_ERROR_MONTHS = 'mailchimp/ecommerce/clean_errors_months';
const XML_ENABLE_SUPPORT = 'mailchimp/general/enable_support';
const SYNC_TOKEN = 'mailchimp/statistics/token';
const SYNC_NOTIFICATION_URL = 'mailchimp/statistics/notification_url';
const XML_CLEAN_SUPPORT_PERIOD = 'mailchimp/general/clean_support_period';
const XML_REGISTER_URL = 'mailchimp/statistics/register_url';
const XML_STATISTICS_TOKEN = 'mailchimp/register/token';
const ORDER_STATE_OK = 'complete';
const GUEST_GROUP = 'NOT LOGGED IN';
const IS_CUSTOMER = "CUS";
const IS_PRODUCT = "PRO";
const IS_ORDER = "ORD";
const IS_QUOTE = "QUO";
const IS_SUBSCRIBER = "SUB";
const IS_PROMO_RULE = "PRL";
const IS_PROMO_CODE = "PCD";
const PLATFORM = 'Magento2';
const MAXSTORES = 200;
const SUB_MOD = "SubscriberModified";
const SUB_NEW = "SubscriberNew";
const PRO_MOD = "ProductModified";
const PRO_NEW = "ProductNew";
const PRO_DELETED = "ProductDeleted";
const CUS_MOD = "CustomerModified";
const CUS_NEW = "CustomerNew";
const ORD_MOD = "OrderModified";
const ORD_NEW = "OrderNew";
const QUO_MOD = "QuoteModified";
const QUO_NEW = "QuoteNew";
const SYNCED = 1;
const NEEDTORESYNC = 2;
const WAITINGSYNC = 3;
const SYNCERROR = 4;
const NOTSYNCED = 5;
const NEVERSYNC = 0;
const BATCH_CANCELED = 'canceled';
const BATCH_COMPLETED = 'completed';
const BATCH_PENDING = 'pending';
const BATCH_ERROR = 'error';
const MAX_MERGEFIELDS = 100;
protected $counters = [];
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
private $_storeManager;
/**
* @var \Ebizmarts\MailChimp\Model\Logger\Logger
*/
private $_mlogger;
/**
* @var \Magento\Customer\Model\GroupRegistry
*/
private $_groupRegistry;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
private $_scopeConfig;
/**
* @var \Magento\Framework\App\RequestInterface
*/
protected $_request;
/**
* @var \Magento\Framework\App\State
*/
private $_state;
/**
* @var \Magento\Framework\Module\ModuleList\Loader
*/
private $_loader;
/**
* @var \Magento\Config\Model\ResourceModel\Config
*/
private $_config;
/**
* @var \Mailchimp
*/
private $_api;
/**
* @var \Magento\Customer\Model\ResourceModel\Customer\CustomerRepository
*/
private $_customer;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncBatches
*/
private $_syncBatches;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpStoresFactory
*/
private $_mailChimpStoresFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpStores
*/
private $_mailChimpStores;
/**
* @var \Magento\Framework\Encryption\Encryptor
*/
private $_encryptor;
/**
* @var \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory
*/
private $_subscriberCollection;
/**
* @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory
*/
private $_customerCollection;
private $_addressRepositoryInterface;
/**
* @var \Magento\Framework\DB\Adapter\AdapterInterface
*/
private $connection;
/**
* @var \Magento\Framework\App\ResourceConnection
*/
private $_resource;
/**
* @var \Magento\Framework\App\Cache\TypeListInterface
*/
private $_cacheTypeList;
/**
* @var \Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory
*/
private $_attCollection;
/**
* @var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
/**
* @var \Magento\Directory\Api\CountryInformationAcquirerInterface
*/
protected $_countryInformation;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory
*/
protected $_interestGroupFactory;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $_date;
/**
* @var \Magento\Framework\App\DeploymentConfig
*/
protected $_deploymentConfig;
/**
* @var \Magento\Framework\Serialize\Serializer\Json
*/
protected $_serializer;
/**
* @var \Magento\Directory\Model\CountryFactory
*/
protected $countryFactory;
/**
* @var \Magento\Framework\Locale\Resolver
*/
protected $resolver;
/**
* @var MailchimpNotificationFactory
*/
protected $mailchimpNotificationFactory;
private $customerAtt = null;
private $addressAtt = null;
private $_mapFields = null;
/**
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Ebizmarts\MailChimp\Model\Logger\Logger $logger
* @param \Magento\Customer\Model\GroupRegistry $groupRegistry
* @param \Magento\Framework\App\State $state
* @param \Magento\Framework\Module\ModuleList\Loader $loader
* @param \Magento\Config\Model\ResourceModel\Config $config
* @param \Mailchimp $api
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Customer\Model\ResourceModel\CustomerRepository $customer
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncBatches $syncBatches
* @param \Ebizmarts\MailChimp\Model\MailChimpStoresFactory $mailChimpStoresFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpStores $mailChimpStores
* @param \Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory $attCollection
* @param \Magento\Framework\Encryption\Encryptor $encryptor
* @param \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory $subscriberCollection
* @param \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollection
* @param \Magento\Customer\Api\AddressRepositoryInterface $addressRepositoryInterface
* @param \Magento\Customer\Model\CustomerFactory $customerFactory
* @param \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation
* @param ResourceConnection $resource
* @param \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
* @param \Magento\Framework\Serialize\Serializer\Json $serializer
* @param \Magento\Framework\App\DeploymentConfig $deploymentConfig
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Magento\Directory\Model\CountryFactory $countryFactory
* @param \Magento\Framework\Locale\Resolver $resolver
* @param MailchimpNotificationFactory $mailchimpNotificationFactory
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Ebizmarts\MailChimp\Model\Logger\Logger $logger,
\Magento\Customer\Model\GroupRegistry $groupRegistry,
\Magento\Framework\App\State $state,
\Magento\Framework\Module\ModuleList\Loader $loader,
\Magento\Config\Model\ResourceModel\Config $config,
\Mailchimp $api,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Customer\Model\ResourceModel\CustomerRepository $customer,
\Ebizmarts\MailChimp\Model\MailChimpSyncBatches $syncBatches,
\Ebizmarts\MailChimp\Model\MailChimpStoresFactory $mailChimpStoresFactory,
\Ebizmarts\MailChimp\Model\MailChimpStores $mailChimpStores,
\Magento\Customer\Model\ResourceModel\Attribute\CollectionFactory $attCollection,
\Magento\Framework\Encryption\Encryptor $encryptor,
\Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory $subscriberCollection,
\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollection,
\Magento\Customer\Api\AddressRepositoryInterface $addressRepositoryInterface,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation,
\Magento\Framework\App\ResourceConnection $resource,
\Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory,
\Magento\Framework\Serialize\Serializer\Json $serializer,
\Magento\Framework\App\DeploymentConfig $deploymentConfig,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Magento\Directory\Model\CountryFactory $countryFactory,
\Magento\Framework\Locale\Resolver $resolver,
MailchimpNotificationFactory $mailchimpNotificationFactory
) {
$this->_storeManager = $storeManager;
$this->_mlogger = $logger;
$this->_groupRegistry = $groupRegistry;
$this->_scopeConfig = $context->getScopeConfig();
$this->_request = $context->getRequest();
$this->_state = $state;
$this->_loader = $loader;
$this->_config = $config;
$this->_api = $api;
$this->_customer = $customer;
$this->_syncBatches = $syncBatches;
$this->_mailChimpStores = $mailChimpStores;
$this->_mailChimpStoresFactory = $mailChimpStoresFactory;
$this->_encryptor = $encryptor;
$this->_subscriberCollection = $subscriberCollection;
$this->_customerCollection = $customerCollection;
$this->_addressRepositoryInterface = $addressRepositoryInterface;
$this->_resource = $resource;
$this->connection = $resource->getConnection();
$this->_cacheTypeList = $cacheTypeList;
$this->_attCollection = $attCollection;
$this->_customerFactory = $customerFactory;
$this->_countryInformation = $countryInformation;
$this->_interestGroupFactory = $interestGroupFactory;
$this->_serializer = $serializer;
$this->_deploymentConfig = $deploymentConfig;
$this->_date = $date;
$this->countryFactory = $countryFactory;
$this->mailchimpNotificationFactory = $mailchimpNotificationFactory;
$this->resolver = $resolver;
parent::__construct($context);
}
/**
* @param null $store
* @return mixed
*/
public function isMailChimpEnabled($store = null)
{
return $this->getConfigValue(self::XML_PATH_ACTIVE, $store);
}
public function isSupportEnabled()
{
return $this->getConfigValue(self::XML_ENABLE_SUPPORT);
}
/**
* @param null $store
* @return mixed
*/
public function isDoubleOptInEnabled($store = null)
{
return $this->getConfigValue(self::XML_PATH_CONFIRMATION_FLAG, $store);
}
/**
* @param null $store
* @return mixed
*/
public function getApiKey($store = null, $scope = null)
{
$apiKey =$this->getConfigValue(self::XML_PATH_APIKEY, $store, $scope);
return $this->_encryptor->decrypt($apiKey);
}
public function getTimeOut($store=null, $scope=null)
{
return $this->getConfigValue(self::XML_PATH_TIMEOUT, $store, $scope);
}
/**
* @param null $store
* @return \Mailchimp
*/
public function getApi($store = null, $scope = null)
{
$apiKey = $this->getApiKey($store, $scope);
$timeOut = $this->getTimeOut($store,$scope);
$this->_api->setApiKey($apiKey);
$this->_api->setHelper($this);
$this->_api->setStoreURL($this->_storeManager->getStore($store)->getBaseUrl());
$this->_api->setUserAgent('Mailchimp4Magento' . (string)$this->getModuleVersion());
if ($timeOut) {
$this->_api->setTimeOut($timeOut);
}
return $this->_api;
}
private function getBindableAttributes()
{
$systemAtt = $this->getCustomerAtts();
$extraAtt = $this->getAddressAtt();
// Note: We cannot use array_merge here because we need to hold
// numeric indexes as they are
$ret = $systemAtt + $extraAtt;
return $ret;
}
private function getCustomerAtts()
{
$ret = [];
if (!$this->customerAtt) {
$collection = $this->_attCollection->create();
/**
* @var $item \Magento\Customer\Model\Attribute
*/
foreach ($collection as $item) {
try {
if ($item->usesSource()) {
$options = $item->getSource()->getAllOptions();
} else {
$options = [];
}
} catch (\Exception $e) {
$options = [];
}
$isDate = ($item->getBackendModel()==\Magento\Eav\Model\Entity\Attribute\Backend\Datetime::class) ? 1:0;
$isAddress = (
$item->getBackendModel()==\Magento\Customer\Model\Customer\Attribute\Backend\Billing::class ||
$item->getBackendModel()==\Magento\Customer\Model\Customer\Attribute\Backend\Shipping::class) ? 1:0;
$ret[$item->getId()] = [
'attCode' => $item->getAttributeCode(),
'isDate' =>$isDate,
'isAddress' => $isAddress,
'options'=>$options
] ;
}
$this->customerAtt = $ret;
}
return $this->customerAtt;
}
private function getAddressAtt()
{
$ret = [];
if (!$this->addressAtt) {
$elements = [
'default_shipping##zip',
'default_shipping##country',
'default_shipping##city',
'default_shipping##state',
'default_shipping##telephone',
'default_shipping##company',
'default_shipping##street',
'default_billing##zip',
'default_billing##country',
'default_billing##city',
'default_billing##state',
'default_billing##telephone',
'default_billing##company',
'default_billing##street'
];
foreach($elements as $item) {
$ret[$item] = [
'attCode' => $item,
'isDate' => false,
'isAddress' => false,
'options' => []
];
}
$this->addressAtt = $ret;
}
return $this->addressAtt;
}
public function resetMapFields()
{
$this->_mapFields = null;
}
public function getMapFields($storeId = null, $options=true)
{
if (!$this->_mapFields) {
$customerAtt = $this->getBindableAttributes();
$data = $this->getConfigValue(self::XML_MERGEVARS, $storeId);
try {
$data = $this->unserialize($data);
if (is_array($data)) {
foreach ($data as $customerFieldId => $mailchimpName) {
$this->_mapFields[] = [
'mailchimp' => strtoupper($mailchimpName),
'customer_field' => $customerAtt[$customerFieldId]['attCode'],
'isDate' => $customerAtt[$customerFieldId]['isDate'],
'isAddress' => $customerAtt[$customerFieldId]['isAddress'],
'options' => $options ? $customerAtt[$customerFieldId]['options'] : false
];
}
}
} catch (\Exception $e) {
$this->log($e->getMessage());
}
}
return $this->_mapFields;
}
public function getDateFormat()
{
return 'm/d/Y';
}
/**
* @param $apiKey
* @param bool $encrypted
* @return \Mailchimp
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getApiByApiKey($apiKey, $encrypted = false)
{
if ($encrypted) {
$this->_api->setApiKey($this->_encryptor->decrypt($apiKey));
} else {
$this->_api->setApiKey($apiKey);
}
$this->_api->setUserAgent('Mailchimp4Magento' . (string)$this->getModuleVersion());
$this->_api->setHelper($this);
$this->_api->setStoreURL($this->_storeManager->getStore()->getBaseUrl());
return $this->_api;
}
/**
* @param $path
* @param null $storeId
* @return mixed
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getConfigValue($path, $storeId = null, $scope = null)
{
if ($scope) {
$value = $this->_scopeConfig->getValue($path, $scope, $storeId);
} else {
$value = $this->_scopeConfig->getValue($path, \Magento\Store\Model\ScopeInterface::SCOPE_STORES, $storeId);
}
return $value;
}
public function deleteConfig($path, $storeId = null, $scope = null)
{
$this->_config->deleteConfig($path, $scope, $storeId);
}
public function saveConfigValue($path, $value, $storeId = null, $scope = null)
{
if ($scope) {
$this->_config->saveConfig($path, $value, $scope, $storeId);
} else {
$this->_config->saveConfig($path, $value, \Magento\Store\Model\ScopeInterface::SCOPE_STORES, $storeId);
}
$this->_cacheTypeList->cleanType('config');
}
public function saveMCMinSyncing($mailchimpStoreId, $value, $storeId = null, $scope = null)
{
if ($mailchimpStoreId) {
$this->saveConfigValue(self::XML_PATH_IS_SYNC . "/$mailchimpStoreId", $value, $storeId, $scope);
} else {
$this->saveConfigValue(self::XML_PATH_IS_SYNC, $value, $storeId, $scope);
}
}
public function getCartUrl($storeId, $cartId, $token)
{
$rc = $this->_storeManager->getStore($storeId)->getUrl(
'mailchimp/cart/loadquote',
[
'id' => $cartId,
'token' => $token,
'_nosid' => true,
'_secure' => true
]
);
return $rc;
}
public function getRedemptionUrl($storeId, $couponId, $token)
{
$rc = $this->_storeManager->getStore($storeId)->getUrl(
'mailchimp/cart/loadcoupon',
[
'id' => $couponId,
'token' => $token,
'_nosid' => true,
'_secure' => true
]
);
return $rc;
}
public function getSuccessInterestUrl($storeId)
{
$rc = $this->_storeManager->getStore($storeId)->getUrl(
'mailchimp/checkout/success',
[
'_nosid' => true,
'_secure' => true
]
);
return $rc;
}
/**
* @param null $store
* @return mixed
*/
public function getDefaultList($store = null)
{
return $this->getConfigValue(self::XML_PATH_LIST, $store);
}
/**
* @return \Psr\Log\LoggerInterface
*/
public function getLogger()
{
return $this->_logger;
}
/**
* @param $message
* @param null $store
*/
public function log($message, $store = null, $file = null)
{
if ($this->getConfigValue(self::XML_PATH_LOG, $store)) {
$this->_mlogger->mailchimpLog($message, $file);
}
}
public function saveNotification($data)
{
$mailchimpNotification = $this->mailchimpNotificationFactory->create();
$mailchimpNotification->setNotificationData(json_encode($data));
$mailchimpNotification->setProcessed(false);
$mailchimpNotification->getResource()->save($mailchimpNotification);
}
/**
* @return string
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function getModuleVersion()
{
$modules = $this->_loader->load();
$v = "";
if (isset($modules['Ebizmarts_MailChimp'])) {
$v = $modules['Ebizmarts_MailChimp']['setup_version'];
}
return $v;
}
public function deleteStore($mailchimpStore)
{
try {
// $storeId = $this->getConfigValue(self::XML_MAILCHIMP_STORE);
$this->getApi()->ecommerce->stores->delete($mailchimpStore);
$this->cancelAllPendingBatches($mailchimpStore);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
} catch (Exception $e) {
$this->log($e->getMessage());
}
}
public function markAllBatchesAs($mailchimpStore, $fromStatus, $toStatus)
{
$connection = $this->_syncBatches->getResource()->getConnection();
$tableName = $this->_syncBatches->getResource()->getMainTable();
$connection->update(
$tableName,
['status' => $toStatus],
"mailchimp_store_id = '" . $mailchimpStore . "' and status = '" . $fromStatus . "'"
);
}
public function cancelAllPendingBatches($mailchimpStore)
{
$this->markAllBatchesAs($mailchimpStore, self::BATCH_PENDING, self::BATCH_CANCELED);
}
public function restoreAllCanceledBatches($mailchimpStore)
{
$this->markAllBatchesAs($mailchimpStore, self::BATCH_CANCELED, self::BATCH_PENDING);
}
public function getMCStoreName($storeId)
{
return $this->_storeManager->getStore($storeId)->getFrontendName();
}
public function getBaserUrl($storeId, $type)
{
return $this->_storeManager->getStore($storeId)->getBaseUrl($type, true);
}
public function createStore($listId = null, $storeId)
{
if ($listId) {
//generate store id
$date = date('Y-m-d-His');
$baseUrl = $this->_storeManager->getStore($storeId)->getName();
$mailchimpStoreId = hash('md5', parse_url($baseUrl, PHP_URL_HOST) . '_' . $date);
$currencyCode = $this->_storeManager->getStore($storeId)->getDefaultCurrencyCode();
$name = $this->getMCStoreName($storeId);
//create store in mailchimp
try {
$this->getApi()->ecommerce->stores->add(
$mailchimpStoreId,
$listId,
$name,
$currencyCode,
self::PLATFORM
);
return $mailchimpStoreId;
} catch (\Mailchimp_Error $e) {
$this->log($e->getFriendlyMessage());
} catch (Exception $e) {
return null;
}
}
return null;
}
public function getMCMinSyncDateFlag($storeId = null)
{
$syncDate = $this->getConfigValue(self::XML_PATH_IS_SYNC, $storeId);
if ($syncDate=='') {
$syncDate = '1900-01-01';
}
return $syncDate;
}
public function getMCMinSyncDateFlagByMailchimpStore($mailchimpStoreId = null, $storeId = null, $scope = null)
{
$syncDate = $this->getConfigValue(self::XML_PATH_IS_SYNC. "/$mailchimpStoreId", $storeId, $scope);
return $syncDate;
}
public function getBaseDir()
{
return BP;
}
/**
* @param \Magento\Customer\Model\Customer $customer
* @param $storeId
* @param null $email
* @return array|null
*/
public function getMergeVars(\Magento\Customer\Model\Customer $customer, $storeId)
{
$mergeVars = [];
$mapFields = $this->getMapFields($storeId);
if (is_array($mapFields)) {
foreach ($mapFields as $map) {
$value = null;
if (strpos($map['customer_field'], '##') !== false) {
$parts = explode('##', $map['customer_field']);
$attributeCode = $parts[0];
$fieldName = $parts[1];
$customerAddress = $customer->getPrimaryAddress($attributeCode);
if ($customerAddress !== false) {
if ($fieldName!='company') {
$addressData = $this->_getAddressValues($customerAddress);
if (!empty($addressData[$fieldName])) {
$value = $addressData[$fieldName];
}
} else {
$value = $customerAddress->getCompany();
}
}
}
else {
$value = $customer->getData($map['customer_field']);
if (!is_null($value)) {
if ($map['isDate']) {
$format = $this->getDateFormat();
if ($map['customer_field'] == 'dob') {
$format = substr($format, 0, 3);
}
$value = date($format, strtotime($value));
} elseif ($map['isAddress']) {
$customerAddress = $customer->getPrimaryAddress($map['customer_field']);
$value = [];
if ($customerAddress !== false) {
$value = $this->_getAddressValues($customerAddress);
}
} elseif (count($map['options'])) {
foreach ($map['options'] as $option) {
if ($option['value'] == $value) {
$value = __($option['label']);
break;
}
}
}
}
}
if (!empty($value)) {
$mergeVars[$map['mailchimp']] = $value;
} else {
$mergeVars[$map['mailchimp']] = '';
}
}
}
return (!empty($mergeVars)) ? $mergeVars : null;
}
/**
* @param \Magento\Customer\Model\Address\AbstractAddress $value
* @return array
*/
private function _getAddressValues(\Magento\Customer\Model\Address\AbstractAddress $address)
{
$addressData = [];
if ($address) {
$street = $address->getStreet();
if (count($street) > 1) {
$addressData["street"] = $street[0].' '.$street[1];
} else {
if (!empty($street[0])) {
$addressData["street"] = $street[0];
}
}
if ($address->getCity()) {
$addressData["city"] = $address->getCity();
}
if ($address->getRegion()) {
$addressData["state"] = $address->getRegion();
} else {
$addressData["state"] = "";
}
if ($address->getPostcode()) {
$addressData["zip"] = $address->getPostcode();
}
if ($address->getCountry()) {
$country = $this->countryFactory->create()->loadByCode($address->getCountryId());
$addressData["country"] = $country->getName('en_US');
}
if ($address->getTelephone()) {
$addressData['telephone'] = $address->getTelephone();
}
}
return $addressData;
}
public function getMergeVarsBySubscriber(\Magento\Newsletter\Model\Subscriber $subscriber, $email = null)
{
$mergeVars = [];
$storeId = $subscriber->getStoreId();
$webSiteId = $this->getWebsiteId($subscriber->getStoreId());
if (!$email) {
$email = $subscriber->getEmail();
}
try {
/**
* @var $customer \Magento\Customer\Model\Customer
*/
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($webSiteId);
$customer->loadByEmail($email);
if ($customer->getData('email') == $email) {
$mergeVars = $this->getMergeVars($customer, $storeId);
}
} catch (\Exception $e) {
$this->log($e->getMessage());
}
return $mergeVars;
}
/**
* @param \Magento\Customer\Model\Customer $customer
* @param $email
* @return array|null
*/
public function getMergeVarsByCustomer(\Magento\Customer\Model\Customer $customer, $email)
{
return $this->getMergeVars($customer, $customer->getData('store_id'));
}
public function getGeneralList($storeId)
{
return $this->getConfigValue(self::XML_PATH_LIST, $storeId);
}
public function getListForMailChimpStore($mailchimpStoreId, $apiKey)
{
try {
$api = $this->getApiByApiKey($apiKey);
$store = $api->ecommerce->stores->get($mailchimpStoreId);
if (isset($store['list_id'])) {
return $store['list_id'];
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
}
return null;
}
public function getDateMicrotime()
{
$microtime = explode(' ', microtime());
$msec = $microtime[0];
$msecArray = explode('.', $msec);
$date = date('Y-m-d-H-i-s') . '-' . $msecArray[1];
return $date;
}
public function loadStores()
{
$mcUserName = [];
$allStores = [];
$connection = $this->_mailChimpStores->getResource()->getConnection();
$tableName = $this->_mailChimpStores->getResource()->getMainTable();
$connection->truncateTable($tableName);
$keys = $this->getAllApiKeys();
foreach ($keys as $apiKey) {
if (!$apiKey || $apiKey =='') {
continue;
}
$this->_api->setApiKey(trim($apiKey));
$this->_api->setUserAgent('Mailchimp4Magento' . (string)$this->getModuleVersion());
$this->_api->setHelper($this);
try {
$apiStores = $this->_api->ecommerce->stores->get(null, null, null, self::MAXSTORES);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
continue;
}
foreach ($apiStores['stores'] as $store) {
if ($store['platform']!=self::PLATFORM||in_array($store['id'],$allStores)) {
continue;
}
if (isset($store['connected_site'])) {
$name = $store['name'];
} else {
$name = $store['name'].' (Warning: not connected)';
}
$allStores[] = $store['id'];
$mstore = $this->_mailChimpStoresFactory->create();
$mstore->setApikey($this->_encryptor->encrypt(trim($apiKey)));
$mstore->setStoreid($store['id']);
$mstore->setListId($store['list_id']);
$mstore->setName($name);
$mstore->setPlatform($store['platform']);
$mstore->setIsSync($store['is_syncing']);
$mstore->setEmailAddress($store['email_address']);
$mstore->setDomain($store['domain']);
$mstore->setCurrencyCode($store['currency_code']);
$mstore->setPrimaryLocale($store['primary_locale']);
$mstore->setTimezone($store['timezone']);
$mstore->setPhone($store['phone']);
$mstore->setAddressAddressOne($store['address']['address1']);
$mstore->setAddressAddressTwo($store['address']['address2']);
$mstore->setAddressCity($store['address']['city']);
$mstore->setAddressProvince($store['address']['province']);
$mstore->setAddressProvinceCode($store['address']['province_code']);
$mstore->setAddressPostalCode($store['address']['postal_code']);
$mstore->setAddressCountry($store['address']['country']);
$mstore->setAddressCountryCode($store['address']['country_code']);
if (!isset($mcUserName[$apiKey])) {
$mcInfo = $this->_api->root->info();
$mcUserName[$apiKey] = $mcInfo['account_name'];
}
try {
$listInfo = $this->_api->lists->getLists($store['list_id']);
if (isset($listInfo['name'])) {
$mstore->setListName($listInfo['name']);
$mstore->setMcAccountName($mcUserName[$apiKey]);
$mstore->getResource()->save($mstore);
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
}
}
}
}
public function saveJsUrl($storeId, $scope = null, $mailChimpStoreId = null)
{
if (!$scope) {
$scope = \Magento\Store\Model\ScopeInterface::SCOPE_STORES;
}
if ($this->getConfigValue(self::XML_PATH_ACTIVE, $storeId, $scope)) {
try {
$api = $this->getApi($storeId);
$storeData = $api->ecommerce->stores->get($mailChimpStoreId);
if (isset($storeData['connected_site']['site_script']['url'])) {
$url = $storeData['connected_site']['site_script']['url'];
$this->_config->saveConfig(
self::XML_MAILCHIMP_JS_URL,
$url,
$scope,
$storeId
);
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
}
}
}
public function getJsUrl($storeId)
{
$url = $this->getConfigValue(self::XML_MAILCHIMP_JS_URL, $storeId);
if ($this->getConfigValue(self::XML_PATH_ACTIVE, $storeId) && !$url) {
$mailChimpStoreId = $this->getConfigValue(self::XML_MAILCHIMP_STORE, $storeId);
try {
$api = $this->getApi($storeId);
$storeData = $api->ecommerce->stores->get($mailChimpStoreId);
if (isset($storeData['connected_site']['site_script']['url'])) {
$url = $storeData['connected_site']['site_script']['url'];
$this->_config->saveConfig(
self::XML_MAILCHIMP_JS_URL,
$url,
\Magento\Store\Model\ScopeInterface::SCOPE_STORES,
$storeId
);
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
}
}
return $url;
}
public function getWebhooksKey()
{
$keys =explode("\n", $this->_encryptor->exportKeys());
$crypt = hash('md5', (string)$keys[0]);
$key = substr($crypt, 0, (strlen($crypt) / 2));
return $key;
}
public function createWebHook($apikey, $listId, $scope=null, $scopeId=null)
{
$events = [
'subscribe' => true,
'unsubscribe' => true,
'profile' => true,
'cleaned' => true,
'upemail' => true,
'campaign' => false
];
$sources = [
'user' => true,
'admin' => true,
'api' => true
];
try {
$api = $this->getApiByApiKey($apikey);
$hookUrl = $this->_getUrl(\Ebizmarts\MailChimp\Controller\WebHook\Index::WEBHOOK__PATH, [
'_scope' => $scopeId,
'wkey' => $this->getWebhooksKey(),
'_nosid' => true,
'_secure' => true]);
// the urlencode of the hookUrl not work
$ret = $api->lists->webhooks->add($listId, $hookUrl, $events, $sources);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
$ret ['message']= $e->getMessage();
}
return $ret;
}
public function deleteWebHook($apikey, $listId)
{
if (empty($listId)) {
return;
}
try {
$api = $this->getApiByApiKey($apikey);
$webhooks = $api->lists->webhooks->getAll($listId);
$hookUrl = $this->_getUrl(\Ebizmarts\MailChimp\Controller\WebHook\Index::WEBHOOK__PATH, [
'_nosid' => true,
'_secure' => true]);
if (isset($webhooks['webhooks'])) {
foreach ($webhooks['webhooks'] as $wh) {
if ($wh['url'] == $hookUrl) {
$api->lists->webhooks->delete($listId, $wh['id']);
}
}
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
}
}
/**
* @param $listId
* @param $mail
* @return \Magento\Newsletter\Model\ResourceModel\Subscriber\Collection
*/
public function loadListSubscribers($listId, $mail)
{
$collection = null;
$storeIds = $this->getMagentoStoreIdsByListId($listId);
$storeIds[] = 0;
if (count($storeIds) > 0) {
$collection = $this->_subscriberCollection->create();
$collection
->addFieldToFilter('store_id', ['in'=>$storeIds])
->addFieldToFilter('subscriber_email', ['eq'=>$mail]);
}
return $collection;
}
public function getMagentoStoreIdsByListId($listId)
{
$storeIds = [];
foreach ($this->_storeManager->getStores() as $storeId => $val) {
if ($this->isMailChimpEnabled($storeId)) {
$storeListId = $this->getConfigValue(self::XML_PATH_LIST, $storeId);
if ($storeListId == $listId) {
$storeIds[] = $storeId;
}
}
}
return $storeIds;
}
/**
* @param $listId
* @param $email
* @return \Magento\Customer\Model\ResourceModel\Customer\Collection
*/
public function loadListCustomers($listId, $email)
{
$customer = null;
$storeIds = $this->getMagentoStoreIdsByListId($listId);
if (count($storeIds) > 0) {
$customer = $this->_customerCollection->create();
$customer
->addFieldToSelect('entity_id')
->addFieldToFilter('store_id', ['in' => $storeIds])
->addFieldToFilter('email', ['eq' => $email]);
}
return $customer;
}
/**
* @param $tableName
* @param string $conn
* @return string
*/
public function getTableName($tableName, $conn = ResourceConnection::DEFAULT_CONNECTION)
{
$connection = $this->_resource->getConnection($conn);
$tablePrefix = $this->_resource->getTablePrefix();
if ($tablePrefix && strpos($tableName, $tablePrefix) !== 0) {
$tableName = $tablePrefix . $tableName;
}
return $connection->getTableName($tableName, $conn);
}
public function getWebsiteId($storeId)
{
return $this->_storeManager->getStore($storeId)->getWebsiteId();
}
public function getInterest($storeId)
{
$rc = [];
$interest = $this->getConfigValue(self::XML_INTEREST, $storeId);
if ($interest!='') {
$interest = explode(",", $interest);
} else {
$interest = [];
}
try {
$api = $this->getApi($storeId);
$listId = $this->getConfigValue(self::XML_PATH_LIST, $storeId);
$allInterest = $api->lists->interestCategory->getAll($listId, null, null, 200);
if (is_array($allInterest) &&
array_key_exists('categories', $allInterest) &&
is_array($allInterest['categories'])) {
foreach ($allInterest['categories'] as $item) {
if (in_array($item['id'], $interest)) {
$rc[$item['id']]['interest'] =
['id' => $item['id'], 'title' => $item['title'], 'type' => $item['type']];
}
}
foreach ($interest as $interestId) {
$mailchimpInterest = $api->lists->interestCategory->interests->getAll($listId, $interestId, null, null, 200);
foreach ($mailchimpInterest['interests'] as $mi) {
$rc[$mi['category_id']]['category'][$mi['display_order']] =
['id' => $mi['id'], 'name' => $mi['name'], 'checked' => false];
}
}
} else {
$this->log(__('Error retrieving interest groups for store ').$storeId);
$rc = [];
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getFriendlyMessage());
}
return $rc;
}
public function getSubscriberInterest($subscriberId, $storeId, $interest = null)
{
if (!$interest) {
$interest = $this->getInterest($storeId);
}
/**
* @var $interestGroup \Ebizmarts\MailChimp\Model\MailChimpInterestGroup
*/
$interestGroup = $this->_interestGroupFactory->create();
$interestGroup->getBySubscriberIdStoreId($subscriberId, $storeId);
$serialized = $interestGroup->getGroupdata();
if ($serialized&&is_array($interest)&&count($interest)) {
try {
$groups = $this->unserialize($serialized);
if (isset($groups['group'])) {
foreach ($groups['group'] as $key => $value) {
if (array_key_exists($key, $interest)) {
if (is_array($value)) {
foreach ($value as $groupId) {
foreach ($interest[$key]['category'] as $gkey => $gvalue) {
if ($gvalue['id'] == $groupId) {
$interest[$key]['category'][$gkey]['checked'] = true;
} elseif (!isset($interest[$key]['category'][$gkey]['checked'])) {
$interest[$key]['category'][$gkey]['checked'] = false;
}
}
}
} else {
foreach ($interest[$key]['category'] as $gkey => $gvalue) {
if ($gvalue['id'] == $value) {
$interest[$key]['category'][$gkey]['checked'] = true;
} else {
$interest[$key]['category'][$gkey]['checked'] = false;
}
}
}
}
}
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->log($e->getMessage());
}
}
return $interest;
}
public function getGmtDate($format = null)
{
return $this->_date->gmtDate($format);
}
public function getGmtTimeStamp()
{
return $this->_date->gmtTimestamp();
}
public function getAllApiKeys()
{
$apiKeys = [];
foreach ($this->_storeManager->getStores() as $storeId => $val) {
$apiKey = $this->getApiKey($storeId);
if (!in_array($apiKey, $apiKeys)) {
$apiKeys[] = $apiKey;
}
}
return $apiKeys;
}
public function modifyCounter($index, $increment = 1)
{
if (array_key_exists($index, $this->counters)) {
$this->counters[$index] = $this->counters[$index] + $increment;
} else {
$this->counters[$index] = 1;
}
}
public function resetCounters($storeId = null)
{
$this->counters = [];
$this->counters = [
self::SUB_NEW => 0,
self::SUB_MOD => 0,
self::ORD_NEW => 0,
self::ORD_MOD => 0,
self::PRO_NEW => 0,
self::PRO_DELETED => 0,
self::PRO_MOD => 0,
self::QUO_NEW => 0,
self::QUO_MOD => 0
];
if ($this->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ALL_CUSTOMERS, $storeId)) {
$this->counters [self::CUS_NEW] = 0;
$this->counters [self::CUS_MOD] = 0;
}
}
public function getCounters()
{
return $this->counters;
}
public function getTotalNewItemsSent()
{
$totalAmount = 0;
$itemArray = [self::ORD_NEW, self::SUB_NEW, self::PRO_NEW, self::CUS_NEW, self::QUO_NEW];
foreach ($itemArray as $item) {
if (array_key_exists($item, $this->counters)) {
$totalAmount += $this->counters[$item];
}
}
return $totalAmount;
}
public function serialize($data)
{
return $this->_serializer->serialize($data);
}
public function unserialize($string)
{
return $this->_serializer->unserialize($string);
}
public function isEmailSavingEnabled($storeId)
{
return $this->_scopeConfig->isSetFlag(
self::XML_ABANDONEDCART_EMAIL,
\Magento\Store\Model\ScopeInterface::SCOPE_STORES,
$storeId
);
}
public function decrypt($value)
{
return $this->_encryptor->decrypt($value);
}
public function encrypt($value)
{
return $this->_encryptor->encrypt($value);
}
public function buttonPressed($button, $result)
{
$data = [];
$data['storeURL'] = $this->_storeManager->getStore()->getBaseUrl();
$data['time'] = $this->getGmtDate();
$data['button']['action'] = $button;
$data['button']['result'] = $result;
$this->saveNotification($data);
}
public function switchLog($on)
{
$storeId = $this->_storeManager->getDefaultStoreView()->getId();
$scope = 'default';
$token = $this->getConfigValue(self::XML_STATISTICS_TOKEN, $storeId, $scope);
}
/**
* @param \Magento\Quote\Model\Quote $quote
* @return void
*/
public function sendCartEvent($quote)
{
$storeId = $quote->getStoreId();
$api = $this->getApi($storeId);
$list = $this->getDefaultList($storeId);
$customerMailchimpId = hash('md5', strtolower($quote->getCustomerEmail()));
$properties = [];
$properties['quote_id'] = $quote->getId();
$properties['store_id'] = $this->getConfigValue(self::XML_MAILCHIMP_STORE, $storeId);
$properties['customer_email'] = $quote->getCustomerEmail();
$properties['total'] = $quote->getGrandTotal();
$properties['currency'] = $quote->getQuoteCurrencyCode();
$properties['customer_id'] = $quote->getCustomerId();
$api->lists->members->memberEvent->add($list, $customerMailchimpId, "abandoned_cart_visit",$properties,false,$this->getGmtDate());
}
}
================================================
FILE: Helper/Http.php
================================================
curl = $curl;
$this->url = $helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL);
$token = $helper->getConfigValue(MailChimpHelper::SYNC_TOKEN);
$headers = ['Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
];
$this->curl->setOption(CURLOPT_RETURNTRANSFER, true);
$this->curl->setHeaders($headers);
$this->helper = $helper;
}
public function setUrl($url)
{
$this->url = $url;
$token = $this->helper->getConfigValue(MailChimpHelper::SYNC_TOKEN);
$headers = ['Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
];
$this->curl->setOption(CURLOPT_RETURNTRANSFER, true);
$this->curl->setHeaders($headers);
}
public function post($body)
{
$this->curl->post($this->url , $body);
$response = $this->curl->getBody();
return $response;
}
public function patch($id,$body)
{
$this->curl->patch($this->url .'/'. $id , $body);
$response = $this->curl->getBody();
return $response;
}
public function get($id)
{
$this->curl->get($this->url .'/'. $id);
$response = $this->curl->getBody();
return $response;
}
public function put($id,$body)
{
$this->curl->put($this->url .'/'. $id , $body);
$response = $this->curl->getBody();
return $response;
}
public function extractResponse($response)
{
try {
$data = json_decode($response, true);
if (is_null($data) || json_last_error() !== JSON_ERROR_NONE) {
return self::ERROR_JSON;
}
if (key_exists('error', $data)) {
if (!$data['error']) {
return self::NO_ERROR;
} else {
$this->helper->log("Error found");
$this->helper->log($response);
$this->helper->log($data['message']);
return self::ERROR_AUTH;
}
}
} catch (\Exception $e) {
$this->helper->log("Exception found");
$this->helper->log($response);
$this->helper->log($e->getMessage());
return self::ERROR_GENERIC;
}
return self::ERROR_GENERIC;
}
}
================================================
FILE: Helper/Sync.php
================================================
chimpSyncEcommerceFactory = $chimpSyncEcommerceFactory;
$this->mailChimpErrors = $mailChimpErrors;
$this->chimpSyncEcommerce = $chimpSyncEcommerce;
parent::__construct($context);
}
public function saveEcommerceData(
$storeId,
$entityId,
$type,
$date = null,
$error = null,
$modified = null,
$deleted = null,
$token = null,
$sent = null,
$isResult = false
) {
if (!empty($entityId)) {
$chimpSyncEcommerce = $this->getChimpSyncEcommerce($storeId, $entityId, $type);
if ($chimpSyncEcommerce->getRelatedId() == $entityId ||
!$chimpSyncEcommerce->getRelatedId() && $modified != 1) {
if ($isResult && $chimpSyncEcommerce->getMailchimpSyncModified()) {
return;
}
$chimpSyncEcommerce->setMailchimpStoreId($storeId);
$chimpSyncEcommerce->setType($type);
$chimpSyncEcommerce->setRelatedId($entityId);
if ($modified!==null) {
$chimpSyncEcommerce->setMailchimpSyncModified($modified);
} else {
$chimpSyncEcommerce->setMailchimpSyncModified(0);
}
if ($date) {
$chimpSyncEcommerce->setMailchimpSyncDelta($date);
}
if ($error) {
$chimpSyncEcommerce->setMailchimpSyncError($error);
}
if ($deleted) {
$chimpSyncEcommerce->setMailchimpSyncDeleted($deleted);
$chimpSyncEcommerce->setMailchimpSyncModified(0);
}
if ($token) {
$chimpSyncEcommerce->setMailchimpToken($token);
}
if ($sent) {
$chimpSyncEcommerce->setMailchimpSent($sent);
}
$chimpSyncEcommerce->getResource()->save($chimpSyncEcommerce);
}
}
}
public function getChimpSyncEcommerce($storeId, $id, $type)
{
$chimp = $this->chimpSyncEcommerceFactory->create();
return $chimp->getByStoreIdType($storeId, $id, $type);
}
public function markEcommerceAsDeleted($relatedId, $type, $relatedDeletedId = null)
{
$this->chimpSyncEcommerce->markAllAsDeleted($relatedId, $type, $relatedDeletedId);
}
public function markEcommorceAsNotDeleted($relatedId, $type)
{
$this->chimpSyncEcommerce->markEcommorceAsNotDeleted($relatedId, $type);
}
public function ecommerceDeleteAllByIdType($id, $type, $mailchimpStoreId)
{
$this->chimpSyncEcommerce->deleteAllByIdType($id, $type, $mailchimpStoreId);
}
public function deleteAllByBatchId($batchId)
{
$this->chimpSyncEcommerce->deleteAllByBatchid($batchId);
}
public function markRegisterAsModified($registerId, $type)
{
if (!empty($registerId)) {
$this->chimpSyncEcommerce->markAllAsModified($registerId, $type);
}
}
public function deleteByTypeAndId($type, $id, $mailchimpStoreId)
{
$this->chimpSyncEcommerce->deleteByTypeAndId($type, $id, $mailchimpStoreId);
}
public function markAllAsModifiedByIds($mailchimpStoreId, $ids, $type)
{
$this->chimpSyncEcommerce->markAllAsModifiedByIds($mailchimpStoreId, $ids, $type);
}
public function resyncAllSubscribers($mailchimpList)
{
$connection = $this->chimpSyncEcommerce->getResource()->getConnection();
$tableName = $this->chimpSyncEcommerce->getResource()->getMainTable();
$connection->update(
$tableName,
['mailchimp_sync_modified' => 1],
"type = '" . \Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER . "' and mailchimp_store_id = '$mailchimpList'"
);
}
public function resyncProducts($mailchimpList)
{
$connection = $this->chimpSyncEcommerce->getResource()->getConnection();
$tableName = $this->chimpSyncEcommerce->getResource()->getMainTable();
$connection->update(
$tableName,
['mailchimp_sync_modified' => 1],
"type = '" . \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT . "' and mailchimp_store_id = '$mailchimpList'"
);
}
public function resetErrors($mailchimpStore, $storeId, $retry)
{
try {
// clean the errors table
$connection = $this->mailChimpErrors->getResource()->getConnection();
$tableName = $this->mailChimpErrors->getResource()->getMainTable();
$connection->delete($tableName, "mailchimp_store_id = '".$mailchimpStore."'");
// clean the syncecommerce table with errors
if ($retry) {
$connection = $this->chimpSyncEcommerce->getResource()->getConnection();
$tableName = $this->chimpSyncEcommerce->getResource()->getMainTable();
$connection->delete(
$tableName,
"mailchimp_store_id = '" . $mailchimpStore . "' and mailchimp_sync_error is not null"
);
}
} catch (\Zend_Db_Exception $e) {
throw new ValidatorException(__($e->getMessage()));
}
}
}
================================================
FILE: Helper/VarsMap.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/30/17 10:35 AM
* @file: VarsMap.php
*/
namespace Ebizmarts\MailChimp\Helper;
class VarsMap extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var Data
*/
protected $_helper;
protected $mathRandom;
/**
* VarsMap constructor.
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\Math\Random $mathRandom
* @param Data $helper
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Math\Random $mathRandom,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
$this->_helper = $helper;
$this->mathRandom = $mathRandom;
parent::__construct($context);
}
public function makeArrayFieldValue($value)
{
$value = $this->unserializeValue($value);
$value = $this->encodeArrayFieldValue($value);
return $value;
}
public function makeStorableArrayFieldValue($value)
{
$value = is_array($value) ? $this->decodeArrayFieldValue($value) : $value;
$value = $this->serializeValue($value);
return $value;
}
/**
* @param $value
* @return bool
*/
protected function isEncodedArrayFieldValue($value)
{
if (!is_array($value)) {
return false;
}
unset($value['__empty']);
foreach ($value as $row) {
if (!is_array($row)
|| !array_key_exists('customer_field_id', $row)
|| !array_key_exists('mailchimp_field_id', $row)
) {
return false;
}
}
return true;
}
protected function decodeArrayFieldValue(array $value)
{
$result = [];
unset($value['__empty']);
foreach ($value as $row) {
if (!is_array($row)
|| !array_key_exists('customer_field_id', $row)
|| !array_key_exists('mailchimp_field_id', $row)
) {
continue;
}
$customer_field_id = $row['customer_field_id'];
$mailchimp_field_id = $row['mailchimp_field_id'];
$result[$customer_field_id] = $mailchimp_field_id;
}
return $result;
}
protected function serializeValue($value)
{
$rc = '';
if (is_array($value)) {
$data = [];
foreach ($value as $customerFiledId => $mailchimpName) {
if (!array_key_exists($customerFiledId, $data)) {
$data[$customerFiledId] = $mailchimpName;
}
}
try {
$rc = $this->_helper->serialize($data);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
}
return $rc;
}
protected function unserializeValue($value)
{
$rc = [];
if (is_string($value) && !empty($value)) {
try {
$rc = $this->_helper->unserialize($value);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
}
return $rc;
}
protected function encodeArrayFieldValue(array $value)
{
$result = [];
foreach ($value as $customerFieldId => $mailchimpName) {
$resultId = $this->mathRandom->getUniqueHash('_');
$result[$resultId] = ['mailchimp_field_id' => $mailchimpName ,'customer_field_id' => $customerFieldId];
}
return $result;
}
}
================================================
FILE: ISSUE_TEMPLATE.md
================================================
# Issue reporting guidelines
To maintain an effective bugfix workflow and make sure issues will be solved in a timely manner we kindly ask reporters to follow some simple guidelines.
Before creating an issue, please do the following:
* Make sure the behavior you are reporting is really a bug, not a feature.
* Check the existing [issues](https://github.com/mailchimp/mc-magento2/issues) to make sure you are not duplicating somebody’s work.
* Make sure, that information you are about to report is a technical issue, please refer to the [Community Forums](http://ebizmarts.com/mailchimp-for-magento-support) for technical questions.
If you are sure that the problem you are experiencing is caused by a bug, file a new issue in a Github issue tracker following the recommendations below.
## Title
Title is a vital part of bug report for developer and trigger to quickly identify a unique issue. A well written title should contain a clear, brief explanation of the issue, making emphasis on the most important points.
Good example would be:
> Unable to place order with Virtual product and PayPal.
Unclear example:
> Can't checkout.
## Issue Description
### Preconditions
Describing preconditions is a great start, provide information on system configuration settings you have changed, detailed information on entities created (Products, Customers, etc), Magento and mc-magento versions. Basically, everything that would help developer set up the same environment as you have.
Example:
1. Magento CE 2.1.7 without sample data is installed.
2. mc-magento2 1.0.21.
3. Test category is set up.
4. Virtual Product is created and assigned to the Test Category.
...
### Steps to reproduce
This part of the bug report is the most important, as developer will use this information to reproduce the issue. Problem is more likely to be fixed if it can be reproduced.
Precisely describe each step you have taken to reproduce the issue. Try to include as much information as possible, sometimes even minor differences can be crucial.
Example:
1. Navigate to storefront as a guest.
2. Open Test Category.
3. Click "Add to Cart" on the Virtual Product.
4. Open mini shopping cart and click "Proceed to Checkout".
...
### Actual and Expected result
To make sure that everybody involved in the fix are on the same page, precisely describe the result you expected to get and the result you actually observed after performing the steps.
Example:
Expected result:
Order is placed successfully, customer is redirected to the success page.
Actual result:
"Place order" button is not visible, order cannot be placed.
### Additional information
Additional information is often requested when the bug report is processed, you can save time by providing Magento and browser logs, screenshots, any other artifacts related to the issue at your own judgement.
================================================
FILE: LICENSE.txt
================================================
Open Software License ("OSL") v. 3.0
This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work:
Licensed under the Open Software License version 3.0
1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following:
1. to reproduce the Original Work in copies, either alone or as part of a collective work;
2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work;
3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License;
4. to perform the Original Work publicly; and
5. to display the Original Work publicly.
2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works.
3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work.
4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license.
5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c).
6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.
7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer.
8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation.
9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c).
10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.
11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License.
12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.
13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.
14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.
16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process.
================================================
FILE: Model/Api/Cart.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/7/17 12:42 PM
* @file: Cart.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
use \Magento\GroupedProduct\Model\Product\Type\Grouped as GroupedProductType;
class Cart
{
const BATCH_LIMIT = 100;
protected $_firstDate;
protected $_counter;
protected $_batchId;
protected $_api = null;
protected $_token = null;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory
*/
protected $_quoteCollection;
/**
* @var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
/**
* @var Product
*/
protected $_apiProduct;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
*/
protected $_orderCollectionFactory;
/**
* @var Customer
*/
protected $_apiCustomer;
/**
* @var \Magento\Directory\Model\CountryFactory
*/
protected $_countryFactory;
/**
* @var \Magento\Framework\Url
*/
protected $_urlHelper;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteColletcion
* @param \Magento\Customer\Model\CustomerFactory $customerFactory
* @param Product $apiProduct
* @param Customer $apiCustomer
* @param \Magento\Directory\Model\CountryFactory $countryFactory
* @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
* @param \Magento\Framework\Url $urlHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteColletcion,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Ebizmarts\MailChimp\Model\Api\Product $apiProduct,
\Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer,
\Magento\Directory\Model\CountryFactory $countryFactory,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
\Magento\Framework\Url $urlHelper
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_quoteCollection = $quoteColletcion;
$this->_customerFactory = $customerFactory;
$this->_apiProduct = $apiProduct;
$this->_apiCustomer = $apiCustomer;
$this->_orderCollectionFactory = $orderCollectionFactory;
$this->_countryFactory = $countryFactory;
$this->_urlHelper = $urlHelper;
}
/**
* @param $mailchimpStoreId
* @param $magentoStoreId
* @return array
*/
public function createBatchJson($magentoStoreId)
{
$allCarts = [];
if (!$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_ACTIVE,
$magentoStoreId
)
) {
return $allCarts;
}
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$this->_firstDate = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_FIRSTDATE,
$magentoStoreId
);
if (!$this->_firstDate) {
$this->_firstDate = $this->_helper->getMCMinSyncDateFlagByMailchimpStore(
$mailchimpStoreId,
0,
'default'
);
}
$this->_counter = 0;
$date = $this->_helper->getDateMicrotime();
$this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_QUOTE.'_'.$date;
// get all the carts converted in orders (must be deleted on mailchimp)
$allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId));
// get all the carts modified but not converted in orders
$allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId));
// get new carts
$allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId));
return $allCarts;
}
/**
* @param $mailchimpStoreId
* @param $magentoStoreId
* @return array
*/
protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId)
{
$allCarts = [];
$convertedCarts = $this->_getQuoteCollection();
// get only the converted quotes
$convertedCarts->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);
$convertedCarts->addFieldToFilter('is_active', ['eq' => 0]);
$convertedCarts->getSelect()->reset(\Zend_Db_Select::COLUMNS)->columns(['entity_id','customer_email']);
//join with mailchimp_ecommerce_sync_data table to filter by sync data.
$convertedCarts->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE."'
AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'",
['m4m.*']
);
// be sure that the quotes are already in mailchimp and not deleted
$convertedCarts->getSelect()->where("m4m.mailchimp_sync_deleted is null and m4m.related_id is not null");
// limit the collection
$convertedCarts->getSelect()->limit(self::BATCH_LIMIT);
/**
* @var $cart \Magento\Quote\Model\Quote
*/
foreach ($convertedCarts as $cart) {
$cartId = $cart->getEntityId();
// we need to delete all the carts associated with this email
$allCartsForEmail = $this->_getAllCartsByEmail(
$cart->getCustomerEmail(),
$mailchimpStoreId,
$magentoStoreId
);
/**
* @var $cartForEmail \Magento\Quote\Model\Quote
*/
foreach ($allCartsForEmail as $cartForEmail) {
$alreadySentCartId = $cartForEmail->getEntityId();
if ($alreadySentCartId != $cartId) {
$allCarts[$this->_counter]['method'] = 'DELETE';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' .
$alreadySentCartId;
$allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId;
$allCarts[$this->_counter]['body'] = '';
$this->_updateQuote(
$mailchimpStoreId,
$alreadySentCartId,
null,
null,
null,
1
);
$this->_counter += 1;
}
}
$allCartsForEmail->clear();
$allCarts[$this->_counter]['method'] = 'DELETE';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId;
$allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId;
$allCarts[$this->_counter]['body'] = '';
$this->_updateQuote(
$mailchimpStoreId,
$cartId,
null,
null,
null,
1
);
$this->_counter += 1;
}
return $allCarts;
}
/**
* @param $mailchimpStoreId
* @param $magentoStoreId
* @return array
*/
protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId)
{
$allCarts = [];
$modifiedCarts = $this->_getQuoteCollection();
// select carts with no orders
$modifiedCarts->addFieldToFilter('is_active', ['eq'=>1]);
// select carts for the current Magento store id
$modifiedCarts->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);
$modifiedCarts->getSelect()->reset(\Zend_Db_Select::COLUMNS)->columns(['entity_id','customer_id','customer_email','mailchimp_campaign_id','quote_currency_code','grand_total']);
//join with mailchimp_ecommerce_sync_data table to filter by sync data.
$modifiedCarts->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE."'
AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'",
['m4m.*']
);
// be sure that the quotes are already in mailchimp and not deleted
$modifiedCarts->getSelect()->where(
"(m4m.mailchimp_sync_deleted is null or m4m.mailchimp_sync_deleted = 0)".
" AND m4m.mailchimp_sync_modified = 1"
);
// limit the collection
$modifiedCarts->getSelect()->limit(self::BATCH_LIMIT);
/**
* @var $cart \Magento\Quote\Model\Quote
*/
foreach ($modifiedCarts as $cart) {
$this->_token = $cart->getMailchimpToken();
$cartId = $cart->getEntityId();
/**
* @var $customer \Magento\Customer\Model\Customer
*/
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($this->_helper->getWebsiteId($magentoStoreId));
$customer->loadByEmail($cart->getCustomerEmail());
if ($customer->getEmail() != $cart->getCustomerEmail()) {
$allCartsForEmail = $this->_getAllCartsByEmail(
$cart->getCustomerEmail(),
$mailchimpStoreId,
$magentoStoreId
);
/**
* @var $cartForEmail \Magento\Quote\Model\Quote
*/
foreach ($allCartsForEmail as $cartForEmail) {
$alreadySentCartId = $cartForEmail->getEntityId();
if ($alreadySentCartId != $cartId) {
$allCarts[$this->_counter]['method'] = 'DELETE';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' .
$alreadySentCartId;
$allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId;
$allCarts[$this->_counter]['body'] = '';
$this->_updateQuote(
$mailchimpStoreId,
$alreadySentCartId,
null,
null,
null,
1
);
$this->_counter += 1;
}
}
$allCartsForEmail->clear();
}
// avoid carts abandoned as guests when customer email associated to a registered customer.
if (!$cart->getCustomerId() && $customer->getEmail()==$cart->getCustomerEmail()) {
$this->_updateQuote($mailchimpStoreId, $cartId);
continue;
}
// send the products that not already sent
try {
$productData = $this->_apiProduct->sendQuoteModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);
} catch (\Exception $e) {
$error = $e->getMessage();
$this->_helper->log($error);
$this->_updateQuote($mailchimpStoreId, $cartId);
continue;
}
if (count($productData)) {
foreach ($productData as $p) {
$allCarts[$this->_counter] = $p;
$this->_counter += 1;
}
}
if (count($cart->getAllVisibleItems())) {
$cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId);
if ($cartJson!==false) {
if (!empty($cartJson)) {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::QUO_MOD);
$allCarts[$this->_counter]['method'] = 'PATCH';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId .
'/carts/' . $cartId;
$allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId;
$allCarts[$this->_counter]['body'] = $cartJson;
$this->_counter += 1;
$this->_updateQuote($mailchimpStoreId, $cartId);
} else {
$this->_updateQuote(
$mailchimpStoreId,
$cartId,
$this->_helper->getGmtDate(),
"Cart is empty",
0
);
}
} else {
$this->_updateQuote(
$mailchimpStoreId,
$cartId,
$this->_helper->getGmtDate(),
"Json error",
0
);
}
}
}
return $allCarts;
}
/**
* @param $mailchimpStoreId
* @return array
*/
protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId)
{
$allCarts = [];
$newCarts = $this->_getQuoteCollection();
$newCarts->addFieldToFilter('is_active', ['eq'=>1]);
$newCarts->addFieldToFilter('customer_email', ['notnull'=>true]);
$newCarts->addFieldToFilter('items_count', ['gt'=>0]);
// select carts for the current Magento store id
$newCarts->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);
// filter by first date if exists.
if ($this->_firstDate) {
$newCarts->addFieldToFilter('created_at', ['gt' => $this->_firstDate]);
}
$newCarts->getSelect()->reset(\Zend_Db_Select::COLUMNS)->columns(['entity_id','customer_id','customer_email','mailchimp_campaign_id','updated_at','quote_currency_code','grand_total']);
//join with mailchimp_ecommerce_sync_data table to filter by sync data.
$newCarts->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.entity_id and m4m.type = '" . \Ebizmarts\MailChimp\Helper\Data::IS_QUOTE . "'
AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'",
['m4m.*']
);
// be sure that the quotes are already in mailchimp and not deleted
$newCarts->getSelect()->where("m4m.mailchimp_sync_delta IS NULL");
// limit the collection
$newCarts->getSelect()->limit(self::BATCH_LIMIT);
/**
* @var $cart \Magento\Quote\Model\Quote
*/
foreach ($newCarts as $cart) {
$this->_token = null;
$cartId = $cart->getEntityId();
$orderCollection = $this->_getOrderCollection();
$orderCollection->addFieldToFilter('main_table.customer_email', ['eq' => $cart->getCustomerEmail()])
->addFieldToFilter('main_table.updated_at', ['from' => $cart->getUpdatedAt()]);
//if cart is empty or customer has an order made after the abandonment skip current cart.
if (!count($cart->getAllVisibleItems()) || $orderCollection->getSize()) {
$this->_updateQuote($mailchimpStoreId, $cartId);
continue;
}
$customer = $this->_customerFactory->create();
$customer->setWebsiteId($this->_helper->getWebsiteId($magentoStoreId));
$customer->loadByEmail($cart->getCustomerEmail());
if ($customer->getEmail() != $cart->getCustomerEmail()) {
$allCartsForEmail = $this->_getAllCartsByEmail(
$cart->getCustomerEmail(),
$mailchimpStoreId,
$magentoStoreId
);
foreach ($allCartsForEmail as $cartForEmail) {
$alreadySentCartId = $cartForEmail->getEntityId();
$allCarts[$this->_counter]['method'] = 'DELETE';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' .
$alreadySentCartId;
$allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId;
$allCarts[$this->_counter]['body'] = '';
$this->_updateQuote(
$mailchimpStoreId,
$alreadySentCartId,
null,
null,
null,
1
);
$this->_counter += 1;
}
$allCartsForEmail->clear();
}
// don't send the carts for guest customers who are registered
if (!$cart->getCustomerId() && $customer->getEmail()==$cart->getCustomerEmail()) {
$this->_updateQuote(
$mailchimpStoreId,
$cartId,
$this->_helper->getGmtDate(),
null,
0
);
continue;
}
// send the products that not already sent
try {
$productData = $this->_apiProduct->sendQuoteModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);
} catch (\Exception $e) {
$error = $e->getMessage();
$this->_updateQuote($mailchimpStoreId, $cartId, $this->_helper->getGmtDate(), $error, 0);
continue;
}
if (count($productData)) {
foreach ($productData as $p) {
$allCarts[$this->_counter] = $p;
$this->_counter += 1;
}
}
$cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId);
if ($cartJson!==false) {
if (!empty($cartJson)) {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::QUO_NEW);
$allCarts[$this->_counter]['method'] = 'POST';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts';
$allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId;
$allCarts[$this->_counter]['body'] = $cartJson;
$this->_updateQuote($mailchimpStoreId, $cartId);
$this->_counter += 1;
} else {
$this->_updateQuote(
$mailchimpStoreId,
$cartId,
$this->_helper->getGmtDate(),
"Cart is empty",
0
);
}
} else {
$this->_updateQuote(
$mailchimpStoreId,
$cartId,
$this->_helper->getGmtDate(),
"Json error",
0
);
}
}
return $allCarts;
}
/**
* Get all existing carts in the current store view for a given email address.
*
* @param $email
* @param $mailchimpStoreId
* @param $magentoStoreId
* @return object
*/
protected function _getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId)
{
$allCartsForEmail = $this->_getQuoteCollection();
$allCartsForEmail->addFieldToFilter('is_active', ['eq' => 1]);
$allCartsForEmail->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);
$allCartsForEmail->addFieldToFilter('customer_email', ['eq' => $email]);
$allCartsForEmail->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE."'
AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'",
['m4m.*']
);
// be sure that the quotes are already in mailchimp and not deleted
$allCartsForEmail->getSelect()->where("m4m.mailchimp_sync_deleted = 0");
return $allCartsForEmail;
}
/**
* @param $cart
* @param $mailchimpStoreId
* @param $magentoStoreId
* @return string
*/
protected function _makeCart(\Magento\Quote\Model\Quote $cart, $mailchimpStoreId, $magentoStoreId)
{
$campaignId = $cart->getMailchimpCampaignId();
$oneCart = [];
$oneCart['id'] = $cart->getEntityId();
$oneCart['customer'] = $this->_getCustomer($cart, $mailchimpStoreId, $magentoStoreId);
if ($campaignId) {
$oneCart['campaign_id'] = $campaignId;
}
$oneCart['checkout_url'] = $this->_getCheckoutUrl($cart, $magentoStoreId);
$oneCart['currency_code'] = $cart->getQuoteCurrencyCode();
$oneCart['order_total'] = $cart->getGrandTotal();
$oneCart['tax_total'] = 0;
$lines = [];
// get all items on the cart
$items = $cart->getAllVisibleItems();
$itemCount = 0;
/**
* @var $item \Magento\Quote\Model\Quote\Item
*/
foreach ($items as $item) {
$line = [];
if ($item->getProductType()==\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
$variant = null;
if ($item->getOptionByCode('simple_product')) {
$variant = $item->getOptionByCode('simple_product')->getProduct();
}
if (!$variant) {
continue;
}
$variantId = $variant->getId();
} elseif ($item->getProductType() == \Magento\Bundle\Model\Product\Type::TYPE_CODE) {
$itemCount++;
$lines[] = [
"id" => (string)$itemCount,
"product_id" => $item->getProductId(),
"product_variant_id" => $item->getProductId().'-min',
"quantity" => (int)$item->getQtyOrdered(),
"price" => 0
];
$bundleProducts = $cart->getAllItems();
foreach ($bundleProducts as $bundleProduct) {
if ($bundleProduct->getParentItemId() == $item->getItemId()) {
$itemCount++;
$lines[] = [
"id" => (string)$itemCount,
"product_id" => $bundleProduct-> getProductId(),
"product_variant_id" => $bundleProduct-> getProductId(),
"quantity" => (int)$bundleProduct->getQtyOrdered(),
"price" => $bundleProduct->getPrice()
];
}
}
continue;
} else {
$variantId = $item->getProductId();
}
//id can not be 0 so we add 1 to $itemCount before setting the id.
$itemCount++;
$line['id'] = (string)$itemCount;
$line['product_id'] = $item->getProductId();
$line['product_variant_id'] = $variantId;
$line['quantity'] = (int)$item->getQty();
$line['price'] = $item->getPrice();
$lines[] = $line;
}
$jsonData = "";
if ($itemCount) {
$oneCart['lines'] = $lines;
//enconde to JSON
$jsonData = json_encode($oneCart);
if ($jsonData === false) {
$jsonErrormsg = json_last_error_msg();
$this->_helper->log("");
$this->_helper->log("$jsonErrormsg on cart [".$cart->getId()."]");
}
}
return $jsonData;
}
/**
* @param \Magento\Quote\Model\Quote $cart
* @return string
*/
protected function _getCheckoutUrl(\Magento\Quote\Model\Quote $cart, $storeId)
{
if (!$this->_token) {
$this->_token = hash('md5', rand(0, 9999999));
}
$url = $this->_helper->getCartUrl($storeId, $cart->getId(), $this->_token);
return $url;
}
protected function _getCustomer(\Magento\Quote\Model\Quote $cart, $mailchimpStoreId, $magentoStoreId)
{
$customer = [
'id' => hash('md5', strtolower($cart->getCustomerEmail())),
'email_address' => $cart->getCustomerEmail(),
'opt_in_status' => $this->_apiCustomer->getOptin($magentoStoreId)
];
$firstName = $cart->getCustomerFirstname();
if ($firstName) {
$customer["first_name"] = $firstName;
}
$lastName = $cart->getCustomerLastname();
if ($lastName) {
$customer["last_name"] = $lastName;
}
$billingAddress = $cart->getBillingAddress();
if ($billingAddress) {
$street = $billingAddress->getStreet();
$address = [];
if ($street[0]) {
$address['address1'] = $street[0];
}
if (count($street) > 1) {
$address['address1'] = $street[1];
}
if ($billingAddress->getCity()) {
$address['city'] = $billingAddress->getCity();
}
if ($billingAddress->getRegion()) {
$address['province'] = $billingAddress->getRegion();
}
if ($billingAddress->getRegionCode()) {
$address['province_code'] = $billingAddress->getRegionCode();
}
if ($billingAddress->getPostcode()) {
$address['postal_code'] = $billingAddress->getPostcode();
}
if ($billingAddress->getCountryId()) {
/**
* @var $country \Magento\Directory\Model\Country
*/
$country = $this->_countryFactory->create()->loadByCode($billingAddress->getCountryId());
$address['shipping_address']['country'] = $country->getName('en_US');
$address['shipping_address']['country_code'] = $billingAddress->getCountryId();
}
if (count($address)) {
$customer['address'] = $address;
}
}
//company
// if ($billingAddress->getCompany()) {
// $customer["company"] = $billingAddress->getCompany();
// }
return $customer;
}
/**
* @return \Magento\Quote\Model\ResourceModel\Quote\Collection
*/
protected function _getQuoteCollection()
{
return $this->_quoteCollection->create();
}
/**
* @return \Magento\Sales\Model\ResourceModel\Order\Collection
*/
protected function _getOrderCollection()
{
return $this->_orderCollectionFactory->create();
}
/**
* @param $storeId
* @param $entityId
* @param $sync_delta
* @param $sync_error
* @param $sync_modified
* @param $sync_deleted
*/
protected function _updateQuote(
$storeId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null,
$sync_deleted = null
) {
$this->syncHelper->saveEcommerceData(
$storeId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE,
$sync_delta,
$sync_error,
$sync_modified,
$sync_deleted,
$this->_token
);
}
}
================================================
FILE: Model/Api/Customer.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/1/16 12:00 PM
* @file: Customer.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Magento\Directory\Model\CountryFactory;
use Magento\Framework\Exception\State\ExpiredException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Customer
{
const MAX = 100;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory
*/
protected $_collection;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
*/
protected $_orderCollection;
/**
* @var CountryFactory
*/
protected $_countryFactory;
/**
* @var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
/**
* @var \Magento\Customer\Model\Address
*/
protected $_address;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @var string
*/
protected $_batchId;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Customer\Model\CustomerFactory $customerFactory
* @param \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $collection
* @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollection
* @param CountryFactory $countryFactory
* @param \Magento\Customer\Model\Address $address
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $collection,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollection,
\Magento\Directory\Model\CountryFactory $countryFactory,
\Magento\Customer\Model\Address $address,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_collection = $collection;
$this->_orderCollection = $orderCollection;
$this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER. '_' .
$this->_helper->getGmtTimeStamp();
$this->_address = $address;
$this->_customerFactory = $customerFactory;
$this->_countryFactory = $countryFactory;
$this->subscriberFactory = $subscriberFactory;
}
public function sendCustomers($storeId)
{
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
$listId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST, $storeId);
$collection = $this->_collection->create();
$collection->addFieldToFilter('store_id', ['eq'=>$storeId]);
$collection->getSelect()->reset(\Zend_Db_Select::COLUMNS)->columns(['entity_id','store_id']);
$collection->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = e.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER.
"' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'",
['m4m.*']
);
$collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1");
$collection->getSelect()->limit(self::MAX);
$counter = 0;
$customerArray = [];
$this->_helper->resetMapFields();
foreach ($collection as $item) {
$customer = $this->_customerFactory->create();
$customer->getResource()->load($customer, $item->getId());
$data = $this->_buildCustomerData($customer);
$customerJson = '';
$customerJson = json_encode($data);
if ($customerJson!==false) {
if (!empty($customerJson)) {
if ($item->getMailchimpSyncModified() == 1) {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::CUS_MOD);
} else {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::CUS_NEW);
}
$customerMailchimpId = hash('md5', strtolower($customer->getEmail()));
$customerArray[$counter]['method'] = "PUT";
$customerArray[$counter]['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/customers/" .
$customerMailchimpId;
$customerArray[$counter]['operation_id'] = $this->_batchId . '_' . $customer->getId();
$customerArray[$counter]['body'] = $customerJson;
$counter++;
if (!$this->isSubscriber($customer)) {
$subscriberData = $this->buildSubscriberData($customer);
$subscriberJson = json_encode($subscriberData);
if ($subscriberJson !==false) {
$customerArray[$counter]['method'] = "PATCH";
$customerArray[$counter]['path'] = "/lists/" . $listId . "/members/" .
$customerMailchimpId;
$customerArray[$counter]['operation_id'] = $this->_batchId . '_' .
$customer->getId().'_SUB';
$customerArray[$counter]['body'] = $subscriberJson;
$counter++;
}
}
//update customers delta
$this->_updateCustomer($mailchimpStoreId, $customer->getId());
} else {
$this->_updateCustomer(
$mailchimpStoreId,
$customer->getId(),
$this->_helper->getGmtDate(),
'Customer with no data',
0
);
}
} else {
$this->_updateCustomer(
$mailchimpStoreId,
$customer->getId(),
$this->_helper->getGmtDate(),
json_last_error_msg(),
0
);
}
}
return $customerArray;
}
/**
* @param \Magento\Customer\Model\Customer $customer
* @return mixed
*/
protected function buildSubscriberData(\Magento\Customer\Model\Customer $customer)
{
$data = [];
$data["merge_fields"] = $this->_helper->getMergeVars($customer, $customer->getData('store_id'));
return $data;
}
protected function isSubscriber(\Magento\Customer\Model\Customer $customer)
{
$subscriber = $this->subscriberFactory->create();
$subscriber->loadByEmail($customer->getEmail());
if ($subscriber->getEmail() == $customer->getEmail()) {
if ($subscriber->getStatus() === \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED) {
return true;
}
}
return false;
}
/**
* @param \Magento\Customer\Model\Customer $customer
* @return array
*/
protected function _buildCustomerData(\Magento\Customer\Model\Customer $customer)
{
$point = 0;
$data = [];
$data["id"] = hash('md5', strtolower($customer->getEmail()));
$data["email_address"] = $customer->getEmail() ? $customer->getEmail() : '';
$data["first_name"] = $customer->getFirstname() ? $customer->getFirstname() : '';
$data["last_name"] = $customer->getLastname() ? $customer->getLastname() : '';
$data["opt_in_status"] = $this->getOptin();
// customer order data
$orderCollection = $this->_orderCollection->create();
$orderCollection->addFieldToFilter('state', [
['neq',\Magento\Sales\Model\Order::STATE_CANCELED],
['neq',\Magento\Sales\Model\Order::STATE_CLOSED]])
->addAttributeToFilter('customer_id', ['eq' => $customer->getId()]);
$totalOrders = 0;
$totalAmountSpent = 0;
/**
* @var $customerOrder \Magento\Sales\Model\Order
*/
foreach ($orderCollection as $customerOrder) {
$totalOrders++;
$totalAmountSpent += $customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded()
- $customerOrder->getTotalCanceled();
}
$data['orders_count'] = $totalOrders;
$data['total_spent'] = $totalAmountSpent;
$address = $customer->getDefaultBillingAddress();
if ($address) {
$customerAddress = [];
if ($street = $address->getStreet()) {
$street = $address->getStreet();
if ($street[0]) {
$customerAddress["address1"] = $street[0];
}
if (count($street) > 1) {
$customerAddress["address2"] = $street[1];
}
}
if ($address->getCity()) {
$customerAddress["city"] = $address->getCity();
}
if ($address->getRegion()) {
$customerAddress["province"] = $address->getRegion();
}
if ($address->getRegionCode()) {
$customerAddress["province_code"] = $address->getRegionCode();
}
if ($address->getPostcode()) {
$customerAddress["postal_code"] = $address->getPostcode();
}
if ($address->getCountryId()) {
/**
* @var $country \Magento\Directory\Model\Country
*/
$country = $this->_countryFactory->create()->loadByCode($address->getCountryId());
$customerAddress["country"] = preg_replace('/\&/', 'and',$country->getName('en_US'));
$customerAddress["country_code"] = $address->getCountryId();
}
if (count($customerAddress)) {
$data["address"] = $customerAddress;
}
}
return $data;
}
public function getOptin($storeId = 0)
{
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_ECOMMERCE_OPTIN, $storeId)) {
$optin = true;
} else {
$optin = false;
}
return $optin;
}
protected function _updateCustomer(
$storeId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null
) {
$this->syncHelper->saveEcommerceData(
$storeId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER,
$sync_delta,
$sync_error,
$sync_modified,
null,
null,
\Ebizmarts\MailChimp\Helper\Data::WAITINGSYNC
);
}
}
================================================
FILE: Model/Api/Order.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/21/16 3:51 PM
* @file: Order.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Magento\SalesRule\Model\RuleRepository;
use Symfony\Component\Config\Definition\Exception\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
use Magento\Bundle\Model\Product\Type as ProductTypeBundle;
class Order
{
const BATCH_LIMIT = 50;
const PAID = 'paid';
const PARTIALLY_PAID = 'partially_paid';
const SHIPPED = 'shipped';
const PARTIALLY_SHIPPED = 'partially_shipped';
const PENDING = 'pending';
const REFUNDED = 'refunded';
const PARTIALLY_REFUNDED = 'partially_refunded';
const CANCELED = 'cancelled';
const COMPLETE = 'complete';
protected $_api = null;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Sales\Model\Order
*/
protected $_order;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
*/
protected $_orderCollectionFactory;
/**
* @var Product
*/
protected $_apiProduct;
/**
* @var \Magento\Catalog\Model\ResourceModel\Product
*/
protected $_product;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Customer
*/
protected $_apiCustomer;
/**
* @var \Magento\Directory\Model\CountryFactory
*/
protected $_countryFactory;
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $_productFactory;
/**
* @var \Magento\SalesRule\Model\Coupon
*/
protected $couponRepository;
/**
* @var RuleRepository
*/
protected $ruleRepository;
/**
* @var \Magento\Framework\Url
*/
protected $_urlHelper;
protected $_chimpSyncEcommerce;
protected $_firstDate;
protected $_counter;
protected $_batchId;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Sales\Model\OrderRepository $order
* @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
* @param \Magento\Catalog\Model\ResourceModel\Product $product
* @param Product $apiProduct
* @param Customer $apiCustomer
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param \Magento\Directory\Model\CountryFactory $countryFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce
* @param \Magento\SalesRule\Model\Coupon $couponRepository
* @param RuleRepository $ruleRepository
* @param \Magento\Framework\Url $urlHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Sales\Model\OrderRepository $order,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
\Magento\Catalog\Model\ResourceModel\Product $product,
\Ebizmarts\MailChimp\Model\Api\Product $apiProduct,
\Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Directory\Model\CountryFactory $countryFactory,
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce,
\Magento\SalesRule\Model\Coupon $couponRepository,
\Magento\SalesRule\Model\RuleRepository $ruleRepository,
\Magento\Framework\Url $urlHelper
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_order = $order;
$this->_orderCollectionFactory = $orderCollectionFactory;
$this->_apiProduct = $apiProduct;
$this->_productFactory = $productFactory;
$this->_product = $product;
$this->_apiCustomer = $apiCustomer;
$this->_countryFactory = $countryFactory;
$this->_chimpSyncEcommerce = $chimpSyncEcommerce;
$this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_ORDER. '_' . $this->_helper->getGmtTimeStamp();
$this->_counter = 0;
$this->_urlHelper = $urlHelper;
$this->couponRepository = $couponRepository;
$this->ruleRepository = $ruleRepository;
}
/**
* Set the request for orders to be created on MailChimp
*
* @param $mailchimpStoreId
* @param $magentoStoreId
* @return array
*/
public function sendOrders($magentoStoreId)
{
$batchArray = [];
$this->_firstDate = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_ECOMMERCE_FIRSTDATE, $magentoStoreId);
// get all the orders modified
$batchArray = array_merge($batchArray, $this->_getModifiedOrders($magentoStoreId));
// get new orders
$batchArray = array_merge($batchArray, $this->_getNewOrders($magentoStoreId));
return $batchArray;
}
protected function _getCollection()
{
return $this->_orderCollectionFactory->create();
}
protected function _getModifiedOrders($magentoStoreId)
{
$batchArray = [];
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$isSynced = $this->_helper->getMCMinSyncDateFlag($magentoStoreId);
$modifiedOrders = $this->_getCollection();
// select orders for the current Magento store id
$modifiedOrders->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);
$modifiedOrders->addFieldToSelect(['store_id','created_at']);
//join with mailchimp_ecommerce_sync_data table to filter by sync data.
$modifiedOrders->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_ORDER.
"' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'",
['m4m.*']
);
// be sure that the order are already in mailchimp and not deleted
$modifiedOrders->getSelect()->where(
"m4m.mailchimp_sync_modified = 1 AND m4m.mailchimp_store_id = '".$mailchimpStoreId."'"
);
// limit the collection
$modifiedOrders->getSelect()->limit(self::BATCH_LIMIT);
/**
* @var $order \Magento\Sales\Model\Order
*/
foreach ($modifiedOrders as $item) {
try {
$error = '';
$orderId = $item->getEntityId();
$order = $this->_order->get($orderId);
//create missing products first
try {
$productData = $this->_apiProduct->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId);
} catch (\Exception $e) {
$error = $e->getMessage();
$this->_helper->log($error);
$this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);
continue;
}
if (count($productData)) {
foreach ($productData as $p) {
$batchArray[$this->_counter] = $p;
$this->_counter++;
}
}
$payLoadReturn = $this->generatePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, true, $isSynced);
$orderJson = $payLoadReturn['jsonOrder'];
$payLoadError = $payLoadReturn['error'];
if ($orderJson) {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::ORD_MOD);
$batchArray[$this->_counter]['method'] = "PATCH";
$batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' .
$order->getIncrementId();
$batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId;
$batchArray[$this->_counter]['body'] = $orderJson;
//update order delta
$this->_updateOrder($mailchimpStoreId, $orderId);
$this->_counter++;
} else {
$error = __($payLoadError);
$this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);
continue;
}
} catch (Exception $e) {
$this->_helper->log($e->getMessage());
$error = $e->getMessage();
$this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);
}
}
return $batchArray;
}
protected function _getNewOrders($magentoStoreId)
{
$batchArray = [];
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$isSynced = $this->_helper->getMCMinSyncDateFlag($magentoStoreId);
$newOrders = $this->_getCollection();
// select carts for the current Magento store id
$newOrders->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);
$newOrders->addFieldToSelect(['store_id','created_at']);
// filter by first date if exists.
if ($this->_firstDate) {
$newOrders->addFieldToFilter('created_at', ['gt' => $this->_firstDate]);
}
$newOrders->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_ORDER.
"' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'",
['m4m.*']
);
// be sure that the quote are not in mailchimp
$newOrders->getSelect()->where("m4m.mailchimp_sync_delta IS NULL");
// limit the collection
$newOrders->getSelect()->limit(self::BATCH_LIMIT);
/**
* @var $order \Magento\Sales\Model\Order
*/
foreach ($newOrders as $item) {
try {
$error = '';
$orderId = $item->getEntityId();
$order = $this->_order->get($orderId);
//create missing products first
try {
$productData = $this->_apiProduct->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId);
} catch (\Exception $e) {
$error = $e->getMessage();
$this->_helper->log($error);
$this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);
continue;
}
if (count($productData)) {
foreach ($productData as $p) {
$batchArray[$this->_counter] = $p;
$this->_counter++;
}
}
$payLoadReturn = $this->generatePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, false, $isSynced);
$orderJson = $payLoadReturn['jsonOrder'];
$payLoadError = $payLoadReturn['error'];
if ($orderJson) {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::ORD_NEW);
$batchArray[$this->_counter]['method'] = "POST";
$batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders';
$batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId;
$batchArray[$this->_counter]['body'] = $orderJson;
//update order delta
$this->_updateOrder($mailchimpStoreId, $orderId);
$this->_counter++;
} else {
$error = __($payLoadError);
$this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);
continue;
}
} catch (Exception $e) {
$this->_helper->log("Can't load the order $orderId");
$this->_helper->log($e->getMessage());
$error = $e->getMessage();
$this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);
}
}
return $batchArray;
}
/**
* Set all the data for each order to be sent
*
* @param $order
* @param $mailchimpStoreId
* @param $magentoStoreId
* @param $isModifiedOrder
* @return array
*/
protected function generatePOSTPayload(
\Magento\Sales\Model\Order $order,
$mailchimpStoreId,
$magentoStoreId,
$isModifiedOrder,
$isSynced
) {
if (!$order->getCustomerEmail()) {
return ['error' => 'Customer email is empty', 'jsonOrder' => null];
}
$data = [];
$data['id'] = $order->getIncrementId();
if ($order->getMailchimpCampaignId()) {
$data['campaign_id'] = $order->getMailchimpCampaignId();
} elseif ($isSynced) {
if (!$isModifiedOrder && $campaignId = $this->getCampaign($magentoStoreId, $order->getCustomerEmail())) {
$data['campaign_id'] = $campaignId;
$order->setMailchimpCampaignId($campaignId);
$order->setMailchimpFlag(1);
}
}
if ($order->getMailchimpLandingPage()) {
$data['landing_site'] = $order->getMailchimpLandingPage();
}
$data['currency_code'] = $order->getOrderCurrencyCode();
$dataPromo = $this->_getPromoData($order);
if ($dataPromo !== null) {
$data['promos'] = $dataPromo;
}
$statusArray = $this->_getMailChimpStatus($order);
if (isset($statusArray['financial_status'])) {
$data['financial_status'] = $statusArray['financial_status'];
}
if (isset($statusArray['fulfillment_status'])) {
$data['fulfillment_status'] = $statusArray['fulfillment_status'];
$trackNumber = $title = '';
$shipments = $order->getShipmentsCollection();
/**
* @var $ship \Magento\Sales\Model\Order\Shipment
*/
foreach ($shipments as $ship) {
$tracks = $ship->getAllTracks();
foreach ($tracks as $track) {
$title = $track->getTitle();
$trackNumber = $track->getTrackNumber();
}
}
$data['tracking_number'] = $trackNumber;
$data['tracking_carrier'] = $title;
$data['tracking_url'] = '';
}
$data['processed_at_foreign'] = $order->getCreatedAt();
$data['updated_at_foreign'] = $order->getUpdatedAt();
if ($order->getState() == \Magento\Sales\Model\Order::STATE_CANCELED) {
$orderCancelDate = null;
$commentCollection = $order->getStatusHistoryCollection();
/**
* @var $comment \Magento\Sales\Model\Order\Status\History
*/
foreach ($commentCollection as $comment) {
if ($comment->getStatus() === \Magento\Sales\Model\Order::STATE_CANCELED) {
$orderCancelDate = $comment->getCreatedAt();
}
}
if ($orderCancelDate) {
$data['cancelled_at_foreign'] = $orderCancelDate;
}
$data['order_total'] = 0;
$data['tax_total'] = 0;
$data['discount_total'] = 0;
$data['shipping_total'] = 0;
} else {
$data['order_total'] = $order->getGrandTotal();
$data['tax_total'] = $order->getTaxAmount();
$data['discount_total'] = $order->getDiscountAmount() ? abs($order->getDiscountAmount()) : 0;
$data['shipping_total'] = $order->getShippingAmount();
}
$data['lines'] = [];
//order lines
try {
$items = $order->getAllVisibleItems();
$itemCount = 0;
} catch (\Exception $e) {
$this->_helper->log("Can't load all the visible items");
throw $e;
}
/**
* @var $item \Magento\Sales\Model\Order\Item
*/
foreach ($items as $item) {
$variant = null;
try {
$productSyncData = $this->syncHelper->getChimpSyncEcommerce(
$mailchimpStoreId,
$item->getProductId(),
\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT
);
} catch (\Exception $e){
$this->_helper->log($e->getMessage());
continue;
}
if ($productSyncData->getRelatedId()!=$item->getProductId()||($productSyncData->getRelatedId()==$item->getProductId()&&$productSyncData->getMailchimpSyncDeleted()==1)) {
continue;
}
if ($item->getProductType() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
$options = $item->getProductOptions();
if (!isset($options['simple_sku'])) {
$this->_helper->log('The product ['.$item->getId().'] has no simple_sku');
continue;
}
$sku = $options['simple_sku'];
$variant = $this->_productFactory->create()->getIdBySku($sku);
if (!$variant) {
continue;
}
} elseif ($item->getProductType() == \Magento\Bundle\Model\Product\Type::TYPE_CODE) {
$itemCount++;
$data["lines"][] = [
"id" => (string)$itemCount,
"product_id" => $item->getProductId(),
"product_variant_id" => $item-> getProductId().'-min',
"quantity" => (int)$item->getQtyOrdered(),
"price" => 0,
"discount" => 0
];
$bundleProducts = $order->getAllItems();
foreach ($bundleProducts as $bundleProduct) {
if ($bundleProduct->getParentItemId() == $item->getItemId()) {
$itemCount++;
$data["lines"][] = [
"id" => (string)$itemCount,
"product_id" => $bundleProduct-> getProductId(),
"product_variant_id" => $bundleProduct-> getProductId(),
"quantity" => (int)$bundleProduct->getQtyOrdered(),
"price" => $bundleProduct->getPrice(),
"discount" => $bundleProduct->getDiscountAmount() ? abs($bundleProduct->getDiscountAmount()) : 0
];
}
}
continue;
} else {
$variant = $item->getProductId();
}
if ($productSyncData->getRelatedId() == $item->getProductId() &&
$productSyncData->getMailchimpSyncError() == '' && $variant) {
$itemCount++;
$data["lines"][] = [
"id" => (string)$itemCount,
"product_id" => $item->getProductId(),
"product_variant_id" => $variant,
"quantity" => (int)$item->getQtyOrdered(),
"price" => $item->getPrice(),
"discount" => $item->getDiscountAmount() ? abs($item->getDiscountAmount()) : 0
];
}
}
if (!$itemCount) {
unset($data['lines']);
return ['error' => 'Order is empty', 'jsonOrder' => null];
}
//customer data
$data['customer'] = [
'id' => hash('md5', strtolower($order->getCustomerEmail())),
'email_address' => $order->getCustomerEmail(),
'opt_in_status' => $this->_apiCustomer->getOptin($magentoStoreId)
];
$data['order_url'] = $this->_urlHelper->getUrl(
'sales/order/view/',
[
'order_id' => $order->getId(),
'_nosid' => true,
'_secure' => true
]
);
if ($order->getCustomerFirstname()) {
$data["customer"]["first_name"] = $order->getCustomerFirstname();
}
if ($order->getCustomerLastname()) {
$data["customer"]["last_name"] = $order->getCustomerLastname();
}
$billingAddress = $order->getBillingAddress();
if ($billingAddress) {
if ($order->getCustomerIsGuest()) {
if ($billingAddress->getFirstname()) {
$data["customer"]["first_name"] = $billingAddress->getFirstname();
}
if ($billingAddress->getLastname()) {
$data["customer"]["last_name"] = $billingAddress->getLastname();
}
}
$street = $billingAddress->getStreet();
$address = [];
if ($street[0]) {
$address["address1"] = $street[0];
$data['billing_address']["address1"] = $street[0];
}
if (array_key_exists(1, $street)) {
$address["address2"] = $street[1];
$data['billing_address']["address2"] = $street[1];
}
if (array_key_exists(2, $street)) {
if (array_key_exists('address2', $address)) {
$address["address2"] = $address['address2'] . ", " . $street[2];
$data['billing_address']["address2"] = $data['billing_address']["address2"] . ", " . $street[2];
} else {
$address["address2"] = $street[2];
$data['billing_address']["address2"] = $street[2];
}
}
if ($billingAddress->getCity()) {
$address["city"] = $billingAddress->getCity();
$data['billing_address']["city"] = $billingAddress->getCity();
}
if ($billingAddress->getRegion()) {
$address["province"] = $billingAddress->getRegion();
$data['billing_address']["province"] = $billingAddress->getRegion();
}
if ($billingAddress->getRegionCode()) {
$address["province_code"] = $billingAddress->getRegionCode();
$data['billing_address']["province_code"] = $billingAddress->getRegionCode();
}
if ($billingAddress->getPostcode()) {
$address["postal_code"] = $billingAddress->getPostcode();
$data['billing_address']["postal_code"] = $billingAddress->getPostcode();
}
if ($billingAddress->getCountryId()) {
/**
* @var $country \Magento\Directory\Model\Country
*/
$country = $this->_countryFactory->create()->loadByCode($billingAddress->getCountryId());
$address["country"] = $data['billing_address']['country'] = $country->getName('en_US');
$address["country_code"] = $data['billing_address']['country_code'] = $billingAddress->getCountryId();
}
if (count($address)) {
$data["customer"]["address"] = $address;
}
if ($billingAddress->getName()) {
$data['billing_address']['name'] = $billingAddress->getName();
}
//company
if ($billingAddress->getCompany()) {
$data["customer"]["company"] = $billingAddress->getCompany();
$data["billing_address"]["company"] = $billingAddress->getCompany();
}
} else {
$this->_helper->log("Order [".$order->getId()."] as no billing address");
return ['error' => "Order [".$order->getId()."] as no billing address", 'jsonOrder' => null];
}
$shippingAddress = $order->getShippingAddress();
if ($shippingAddress) {
$street = $shippingAddress->getStreet();
if ($shippingAddress->getName()) {
$data['shipping_address']['name'] = $shippingAddress->getName();
}
if ($street[0]) {
$data['shipping_address']["address1"] = $street[0];
}
if (array_key_exists(1, $street)) {
$data['shipping_address']["address2"] = $street[1];
}
if (array_key_exists(2, $street)) {
if (array_key_exists('address2',$data['shipping_address'])) {
$data['shipping_address']["address2"] = $data['shipping_address']["address2"] . ", " . $street[2];
} else {
$data['shipping_address']["address2"] = $street[2];
}
}
if ($shippingAddress->getCity()) {
$data['shipping_address']['city'] = $shippingAddress->getCity();
}
if ($shippingAddress->getRegion()) {
$data['shipping_address']['province'] = $shippingAddress->getRegion();
}
if ($shippingAddress->getRegionCode()) {
$data['shipping_address']['province_code'] = $shippingAddress->getRegionCode();
}
if ($shippingAddress->getPostcode()) {
$data['shipping_address']['postal_code'] = $shippingAddress->getPostcode();
}
if ($shippingAddress->getCountryId()) {
/**
* @var $country \Magento\Directory\Model\Country
*/
$country = $this->_countryFactory->create()->loadByCode($shippingAddress->getCountryId());
$data['shipping_address']["country"] = $country->getName('en_US');
$data['shipping_address']["country_code"] = $shippingAddress->getCountryId();
}
if ($shippingAddress->getCompany()) {
$data["shipping_address"]["company"] = $shippingAddress->getCompany();
}
}
//customer orders data
$orderCollection = $this->_orderCollectionFactory->create();
$orderCollection->addFieldToFilter('state', [
['neq' => \Magento\Sales\Model\Order::STATE_CANCELED],
['neq' => \Magento\Sales\Model\Order::STATE_CLOSED]])
->addAttributeToFilter('customer_email', ['eq' => $order->getCustomerEmail()]);
$orderCollection
->getSelect()
->reset(\Zend_Db_Select::COLUMNS)
->columns(['grand_total', 'total_refunded', 'total_canceled']);
$totalOrders = 0;
$totalAmountSpent = 0;
/**
* @var $customerOrder \Magento\Sales\Model\Order
*/
foreach ($orderCollection as $customerOrder) {
$totalOrders++;
$totalAmountSpent += $customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded()
- $customerOrder->getTotalCanceled();
}
$data["customer"]["orders_count"] = $totalOrders;
$data["customer"]["total_spent"] = $totalAmountSpent;
$jsonData = "";
//enconde to JSON
$jsonData = json_encode($data);
if ($jsonData===false) {
$jsonError = json_last_error();
$jsonErrorMsg = json_last_error_msg();
$this->_helper->log('');
$this->_helper->log("$jsonErrorMsg on order [".$order->getEntityId()."]");
}
return ['error' => null, 'jsonOrder' => $jsonData];
}
protected function _getMailChimpStatus(\Magento\Sales\Model\Order $order)
{
$mailChimpFinancialStatus = null;
$mailChimpFulfillmentStatus = null;
$totalItemsOrdered = $order->getData('total_qty_ordered');
$shippedItemAmount = 0;
$invoicedItemAmount = 0;
$refundedItemAmount = 0;
$mailChimpStatus = [];
/**
* @var $item \Magento\Sales\Model\Order\Item
*/
foreach ($order->getAllVisibleItems() as $item) {
$shippedItemAmount += $item->getQtyShipped();
$invoicedItemAmount += $item->getQtyInvoiced();
$refundedItemAmount += $item->getQtyRefunded();
}
if ($shippedItemAmount > 0) {
if ($totalItemsOrdered > $shippedItemAmount) {
$mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED;
} else {
$mailChimpFulfillmentStatus = self::SHIPPED;
}
}
if ($refundedItemAmount > 0) {
if ($totalItemsOrdered > $refundedItemAmount) {
$mailChimpFinancialStatus = self::PARTIALLY_REFUNDED;
} else {
$mailChimpFinancialStatus = self::REFUNDED;
}
}
if ($invoicedItemAmount > 0) {
if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) {
if ($totalItemsOrdered > $invoicedItemAmount) {
$mailChimpFinancialStatus = self::PARTIALLY_PAID;
} else {
$mailChimpFinancialStatus = self::PAID;
}
}
}
if (!$mailChimpFinancialStatus && $order->getState() == \Magento\Sales\Model\Order::STATE_CANCELED) {
$mailChimpFinancialStatus = self::CANCELED;
}
if (!$mailChimpFinancialStatus) {
$mailChimpFinancialStatus = self::PENDING;
}
if ($mailChimpFinancialStatus) {
$mailChimpStatus['financial_status'] = $mailChimpFinancialStatus;
}
if ($mailChimpFulfillmentStatus) {
$mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus;
}
return $mailChimpStatus;
}
protected function _getPromoData(\Magento\Sales\Model\Order $order)
{
$promo = null;
try {
$couponCode = $order->getCouponCode();
if ($couponCode !== null) {
$code = $this->couponRepository->loadByCode($couponCode);
if ($code->getCouponId() !== null) {
$rule = $this->ruleRepository->getById($code->getRuleId());
if ($rule->getRuleId() !== null) {
$amountDiscounted = $order->getBaseDiscountAmount() ? $order->getBaseDiscountAmount() : 0;
$type = $rule->getSimpleAction();
if ($type == 'by_percent') {
$type = 'percentage';
} else {
$type = 'fixed';
}
$promo = [[
'code' => $couponCode,
'amount_discounted' => abs($amountDiscounted),
'type' => $type
]];
}
}
}
} catch(\Exception $e) {
$this->_helper->log($e->getMessage());
}
return $promo;
}
protected function getCampaign($store, $email)
{
$campaign_id = null;
$api = $this->_helper->getApi($store);
$actions = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_CAMPAIGN_ACTION, $store);
try {
$activity = $api->lists->members->memberActivity->get($this->_helper->getDefaultList($store), hash('md5', $email), null, null, $actions);
if ($activity) {
foreach ($activity['activity'] as $act) {
if (key_exists('action', $act) && key_exists('campaign_id', $act) && $act['campaign_id']) {
$campaign_id = $act['campaign_id'];
break;
}
}
}
} catch (\Mailchimp_Error $e) {
$this->_helper->log("No activity for $email");
}
return $campaign_id;
}
protected function _updateOrder($storeId, $entityId, $sync_delta = null, $sync_error = null, $sync_modified = null)
{
if (!empty($sync_error)) {
$sent = \Ebizmarts\MailChimp\Helper\Data::NOTSYNCED;
} else {
$sent = \Ebizmarts\MailChimp\Helper\Data::WAITINGSYNC;
}
$this->syncHelper->saveEcommerceData(
$storeId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_ORDER,
$sync_delta,
$sync_error,
$sync_modified,
null,
null,
$sent
);
}
}
================================================
FILE: Model/Api/Product.php
================================================
_productRepository = $productRepository;
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_productCollection = $productCollection;
$this->_imageHelper = $imageHelper;
$this->_stockRegistry = $stockRegistry;
$this->_categoryRepository = $categoryRepository;
$this->_chimpSyncEcommerce = $chimpSyncEcommerce;
$this->_chimpSyncEcommerceCollection = $chimpSyncEcommerceCollection;
$this->_configurable = $configurable;
$this->_option = $option;
$this->_categoryCollection = $categoryCollection;
$this->taxHelper = $taxHelper;
$this->_productTypeBundle = $productTypeBundle;
$this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT. '_' .
$this->_helper->getGmtTimeStamp();
}
public function _sendProducts($magentoStoreId)
{
$batchArray = [];
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$this->includingTaxes = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_INCLUDING_TAXES,
$magentoStoreId
);
$syncSalable = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_SYNC_SALABLE, $magentoStoreId);
$this->_markSpecialPrices($magentoStoreId, $mailchimpStoreId);
$batchArray = array_merge($batchArray,$this->processDeletedProducts($magentoStoreId, $mailchimpStoreId));
$collection = $this->_getCollection();
$collection->addFieldToFilter("type_id", ["neq"=>self::GROUPED]);
$collection->addStoreFilter($magentoStoreId);
$collection->getSelect()->reset(\Zend_Db_Select::COLUMNS)->columns(['entity_id']);
$collection->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = e.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT.
"' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'",
['m4m.*']
);
$collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1");
$collection->getSelect()->limit(self::MAX);
foreach ($collection as $item) {
/**
* @var $product \Magento\Catalog\Model\Product
*/
$product = $this->_productRepository->getById($item->getId(), false, $magentoStoreId);
if ($item->getMailchimpSyncModified() && $item->getMailchimpSyncDelta()) {
if ($product->isSalable() || $syncSalable) {
if (!$item->getMailchimpSyncDeleted()) {
$batchArray = array_merge($this->_buildOldProductRequest(
$product,
$this->_batchId,
$mailchimpStoreId,
$magentoStoreId
), $batchArray);
$this->_updateProduct($mailchimpStoreId, $product->getId());
} else {
$data = array_merge($this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId), $batchArray);
$batchArray[] = $data;
$this->syncHelper->markEcommorceAsNotDeleted($product->getId(), \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT);
continue;
}
} else {
$productId = $product->getId();
$batchArray[] = $this->deleteProduct($mailchimpStoreId, $productId,"Product not salable");
}
continue;
} else {
if ($product->isSalable() || $syncSalable) {
$data = $this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId);
} else {
$this->_updateProduct(
$mailchimpStoreId,
$product->getId(),
$this->_helper->getGmtDate(),
"This product is not salable.",
0,
true,
true
);
continue;
}
}
if (!empty($data)) {
$batchArray[] = $data;
//update product delta
$this->_updateProduct($mailchimpStoreId, $product->getId());
} else {
$this->_updateProduct(
$mailchimpStoreId,
$product->getId(),
$this->_helper->getGmtDate(),
"This product type is not supported on MailChimp.",
0
);
}
}
return $batchArray;
}
protected function _markSpecialPrices($magentoStoreId, $mailchimpStoreId)
{
/**
* get the products with current special price that are not synced and mark it as modified
*/
$collection = $this->_getCollection();
$collection->addStoreFilter($magentoStoreId);
$collection->addAttributeToFilter(
'special_price',
['gt'=>0],
'left'
)->addAttributeToFilter(
'special_from_date',
['or' => [ 0 => ['date' => true,
'to' => date('Y-m-d', time()).' 23:59:59'],
1 => ['is' => new \Zend_Db_Expr(
'null'
)],]],
'left'
)->addAttributeToFilter(
'special_to_date',
['or' => [ 0 => ['date' => true,
'from' => date('Y-m-d', time()).' 00:00:00'],
1 => ['is' => new \Zend_Db_Expr(
'null'
)],]],
'left'
);
foreach ($collection as $item) {
$productId = $this->_productRepository->get($item->getSku(),false, $magentoStoreId)->getId();
$mailchimpSync = $this->syncHelper->getChimpSyncEcommerce($mailchimpStoreId, $productId, 'PRO');
if ($mailchimpSync->getMailchimpSyncDelta() < $item->getSpecialFromDate()) {
$this->_updateProduct($mailchimpStoreId, $productId, null, null, 1);
}
}
/**
* get the products that was synced when it have special price and have no more special price
*/
$collection2 = $this->_getCollection();
$collection2->addStoreFilter($magentoStoreId);
$collection2->addAttributeToFilter(
'special_price',
['gt'=>0],
'left'
)->addAttributeToFilter(
'special_to_date',
['or' => [ 0 => ['date' => true,
'to' => date('Y-m-d', time()).' 00:00:00'],
]],
'left'
)->addAttributeToFilter(
'special_to_date',
['or' => [ 0 => ['date' => true,
'from' => date('Y-m-d', strtotime('-1 day')).' 00:00:00'],
]],
'left'
);
foreach ($collection2 as $item) {
$productId = $this->_productRepository->get($item->getSku(),false, $magentoStoreId)->getId();
$mailchimpSync = $this->syncHelper->getChimpSyncEcommerce($mailchimpStoreId, $productId, 'PRO');
if ($mailchimpSync->getMailchimpSyncDelta() < $item->getSpecialToDate()) {
$this->_updateProduct($mailchimpStoreId, $productId, null, null, 1);
}
}
}
protected function processDeletedProducts($magentoStoreId, $mailchimpStoreId)
{
$deletedData = [];
$collection = $this->_getMailchimpCollection();
$collection->getSelect()->where(
"main_table.mailchimp_sync_deleted = 1 ".
" and main_table.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT."'".
" and main_table.mailchimp_store_id = '".$mailchimpStoreId."'".
" and main_table.mailchimp_sent = ".\Ebizmarts\Mailchimp\Helper\Data::NEEDTORESYNC
);
$collection->getSelect()->limit(self::MAX);
foreach ($collection as $item) {
try {
$product = $this->_productRepository->getById($item->getRelatedId(), false, $magentoStoreId);
} catch (NoSuchEntityException $e) {
$productId = $item->getRelatedId();
$deletedData[] = $this->deleteProduct($mailchimpStoreId, $productId, "Deleted product]");
}
}
return $deletedData;
}
protected function deleteProduct($mailchimpStoreId, $productId, $error)
{
$data = [];
$data['method'] = "DELETE";
$data['path'] = "/ecommerce/stores/$mailchimpStoreId/products/$productId";
$data['operation_id'] = $this->_batchId . '_' . $productId;
$data['body'] = "";
$this->_updateProduct(
$mailchimpStoreId,
$productId,
$this->_helper->getGmtDate(),
$error,
0,
true
);
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::PRO_DELETED);
return $data;
}
/**
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
*/
protected function _getCollection()
{
return $this->_productCollection->create();
}
protected function _getMailchimpCollection()
{
return $this->_chimpSyncEcommerceCollection->create();
}
protected function _buildNewProductRequest(
\Magento\Catalog\Model\Product $product,
$mailchimpStoreId,
$magentoStoreId
) {
$variantProducts = [];
switch ($product->getTypeId()) {
case \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE:
$variantProducts[] = $product;
break;
case \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE:
$childProducts = $product->getTypeInstance()->getChildrenIds($product->getId());
$variantProducts[] = $product;
if (count($childProducts[0])) {
foreach ($childProducts[0] as $childId) {
$variantProducts[] = $this->_productRepository->getById($childId, false, $magentoStoreId);
}
}
break;
case \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL:
case self::DOWNLOADABLE:
case ProductTypeBundle::TYPE_CODE:
$variantProducts[] = $product;
break;
default:
return [];
}
$bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts);
$body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT);
if ($body === false) {
$jsonError = json_last_error();
$jsonErrorMsg = json_last_error_msg();
$this->_helper->log("");
$this->_helper->log("$jsonErrorMsg for product [".$product->getId()."]");
return [];
} else {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::PRO_NEW);
$data = [];
$data['method'] = "POST";
$data['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products";
$data['operation_id'] = $this->_batchId . '_' . $product->getId();
$data['body'] = $body;
$this->productPrice = null;
}
return $data;
}
protected function _buildOldProductRequest(
\Magento\Catalog\Model\Product $product,
$batchId,
$mailchimpStoreId,
$magentoStoreId
) {
$operations = [];
$variantProducts = [];
if ($product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE ||
$product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL ||
$product->getTypeId() == self::DOWNLOADABLE) {
$data = $this-> _buildProductData($product, $magentoStoreId);
$variantProducts [] = $product;
// $parentIds = $product->getTypeInstance()->getParentIdsByChild($product->getId());
$parentIds = $this->_configurable->getParentIdsByChild($product->getId());
//add or update variant
foreach ($parentIds as $parentId) {
$productSync = $this->_chimpSyncEcommerce->create()->getByStoreIdType(
$mailchimpStoreId,
$parentId,
\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT
);
if ($productSync->getMailchimpSyncDelta()) {
$variendata = [];
$variendata["id"] = $data["id"];
$variendata["title"] = $data["title"];
$variendata["url"] = $data["url"];
$variendata["sku"] = $data["sku"];
$variendata["price"] = $data["price"];
$variendata["inventory_quantity"] = $data["inventory_quantity"];
$variendata["image_url"] = $data["image_url"];
$variendata["backorders"] = $data["backorders"];
$variendata["visibility"] = $data["visibility"];
$productdata = [];
$productdata['method'] = "PUT";
$productdata['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/" .
$parentId . '/variants/' . $data['id'];
$productdata['operation_id'] = $batchId . '_' . $parentId;
$body = json_encode($variendata);
if ($body===false) {
$jsonErrorMsg = json_last_error_msg();
$this->_helper->log("");
$this->_helper->log("$jsonErrorMsg for product [".$product->getId()."]");
continue;
}
$productdata['body'] = $body;
$operations[] = $productdata;
}
}
$bundleParentIds = $this->_productTypeBundle->getParentIdsByChild($product->getId());
foreach ($bundleParentIds as $bundleParentId) {
$bundleProduct = $this->_productRepository->getById($bundleParentId, false, $magentoStoreId);
$data = $this-> _buildProductData($bundleProduct, $magentoStoreId,false);
$body = json_encode($data);
if ($body===false) {
$jsonErrorMsg = json_last_error_msg();
$this->_helper->log("");
$this->_helper->log("$jsonErrorMsg for product [".$bundleProduct->getId()."]");
continue;
}
$productdata = [];
$productdata['method'] = "PATCH";
$productdata['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/" . $bundleParentId;
$productdata['operation_id'] = $batchId . '_' . $bundleParentId;
$productdata['body'] = $body;
$operations[] = $productdata;
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::PRO_MOD);
}
} elseif ($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
$childProducts = $product->getTypeInstance()->getChildrenIds($product->getId());
$variantProducts[] = $product;
if (count($childProducts[0])) {
foreach ($childProducts[0] as $childId) {
$variantProducts[] = $this->_productRepository->getById($childId, false, $magentoStoreId);
}
}
} else {
return [];
}
$bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts);
$body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT);
if ($body===false) {
$jsonErrorMsg = json_last_error_msg();
$this->_helper->log("");
$this->_helper->log("$jsonErrorMsg for product [".$product->getId()."]");
return [];
}
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::PRO_MOD);
$data = [];
$data['method'] = "PATCH";
$data['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/".$product->getId();
$data['operation_id'] = $this->_batchId . '_' . $product->getId();
$data['body'] = $body;
$operations[] = $data;
$this->productPrice = null;
return $operations;
}
protected function _buildProductData(
\Magento\Catalog\Model\Product $product,
$magentoStoreId,
$isVarient = true,
$variants = []
) {
$data = [];
$parent = null;
//data applied for both root and varient products
$data["id"] = $product->getId();
$data["title"] = $product->getName();
$data["url"] = $product->getProductUrl();
$data["image_url"] = '';
if ($product->getImage() && $product->getImage()!='no_selection') {
$filePath = 'catalog/product/'.ltrim($product->getImage(), '/');
$data["image_url"] = $this->_helper->getBaserUrl($magentoStoreId, \Magento\Framework\UrlInterface::URL_TYPE_MEDIA).$filePath;
} elseif ($this->_parentImage) {
$data['image_url'] = $this->_parentImage;
} else {
$parent = $this->_getParent($product->getId(), $magentoStoreId);
if ($parent && $parent->getImage() && $parent->getImage()!='no_selection') {
$filePath = 'catalog/product/'.ltrim($parent->getImage(), '/');
$data["image_url"] = $this->_helper->getBaserUrl($magentoStoreId, \Magento\Framework\UrlInterface::URL_TYPE_MEDIA).$filePath;
}
}
$data["published_at_foreign"] = "";
if ($isVarient) {
//this is for a varient product
$data["sku"] = $product->getSku() ? $product->getSku() : '';
if ($this->productPrice) {
$data['price'] = $this->productPrice;
} else {
$data['price'] = $this->_getProductPrice($product);
}
//stock
$stock = $this->_stockRegistry->getStockItem($product->getId(), $magentoStoreId);
$data["inventory_quantity"] = (int)$stock->getQty();
$data["backorders"] = (string)$stock->getBackorders();
if ($product->getVisibility() == \Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE) {
$tailUrl = '';
$data["visibility"] = 'false';
if (!$parent) {
$parent = $this->_getParent($product->getId(), $magentoStoreId);
}
if ($parent) {
$options = $parent->getTypeInstance()->getConfigurableAttributesAsArray($parent);
foreach ($options as $option) {
if (strlen($tailUrl)) {
$tailUrl .= '&';
} else {
$tailUrl .= '?';
}
$tailUrl .= $option['attribute_code'] . "=" . $product->getData($option['attribute_code']);
}
$this->_childtUrl = $data['url'] = $parent->getProductUrl() . $tailUrl;
if (empty($data['image_url'])) {
$filePath = 'catalog/product'.$parent->getImage();
$data["image_url"] = $this->_helper->getBaserUrl(
$magentoStoreId,
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).$filePath;
}
}
} else {
$data["visibility"] = 'true';
}
} else {
//this is for a root product
if ($product->getData('description')) {
$data["description"] = $product->getData('description');
}
$categoryName = $this->getProductCategories($product, $magentoStoreId);
if ($categoryName) {
$data['type'] = $data['vendor'] = $categoryName;
}
//missing data
$data["handle"] = "";
if (!empty($data['image_url'])) {
$this->_parentImage = $data['image_url'];
}
if ($product->getTypeId() == ProductTypeBundle::TYPE_CODE) {
list($min, $max) = $this->_bundleVariants($product, $magentoStoreId);
$data["variants"][] = $this->_variantForBundle($product, $magentoStoreId, $min, $product->getSku() . '-min', $product->getId() . '-min');
$data["variants"][] = $this->_variantForBundle($product, $magentoStoreId, $max, $product->getSku() . '-max', $product->getId() . '-max');
} else {
//variants
$data["variants"] = [];
// put the min price of the simples as the price of the parent
foreach ($variants as $variant) {
if ($variant && $variant->getId() != $product->getId()) {
$variantPrice = $this->_getProductPrice($variant);
if ($this->productPrice) {
if ($variantPrice < $this->productPrice) {
$this->productPrice = $variantPrice;
}
} else {
$this->productPrice = $variantPrice;
}
}
}
/**
* @var $variant \Magento\Catalog\Model\Product
*/
foreach ($variants as $variant) {
if ($variant) {
if ($variant->getId() != $product->getId()) {
$this->productPrice = null;
}
$data["variants"][] = $this->_buildProductData($variant, $magentoStoreId);
}
}
if ($this->_childtUrl) {
if ($product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE ||
$product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL ||
$product->getTypeId() == "downloadable") {
$data["url"] = $this->_childtUrl;
}
$this->_childtUrl = null;
}
$this->_parentImage = null;
}
}
return $data;
}
protected function _getParent($productId, $magentoStoreId)
{
$parentIds =$this->_configurable->getParentIdsByChild($productId);
$parent = null;
foreach ($parentIds as $id) {
$parent = $this->_productRepository->getById($id, false, $magentoStoreId);
if ($parent->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
break;
} else {
$parent = null;
}
}
return $parent;
}
/**
* @param \Magento\Catalog\Model\Product $product
* @param $storeId
*/
protected function getProductCategories(\Magento\Catalog\Model\Product $product, $storeId)
{
$categoryIds = $product->getCategoryIds();
$categoryNames = [];
$categoryName = null;
if (is_array($categoryIds) && count($categoryIds)) {
$collection = $this->_categoryCollection->create();
$collection->addAttributeToSelect(['name'])
->setStoreId($storeId)
->addAttributeToFilter('is_active', ['eq'=>'1'])
->addAttributeToFilter('entity_id', ['in'=>$categoryIds])
->addAttributeToSort('level', 'asc');
foreach ($collection as $category) {
$categoryNames[] = $category->getName();
}
$categoryName = (count($categoryNames)) ? implode(" - ", $categoryNames) : 'None';
}
return $categoryName;
}
/**
* @param \Magento\Sales\Model\Order $order
* @param $mailchimpStoreId
* @return array
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function sendModifiedProduct(\Magento\Sales\Model\Order $order, $mailchimpStoreId, $magentoStoreId)
{
$data = [];
$batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT . '_' . $this->_helper->getGmtTimeStamp();
$items = $order->getAllVisibleItems();
foreach ($items as $item) {
//@todo get from the store not the default
try {
$product = $this->_productRepository->getById($item->getProductId(), false, $magentoStoreId);
$productSyncData = $this->_chimpSyncEcommerce->create()->getByStoreIdType(
$mailchimpStoreId,
$product->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT
);
if ($product->getId() != $item->getProductId() || (
$product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE &&
$product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL &&
$product->getTypeId() != \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE &&
$product->getTypeId() != self::DOWNLOADABLE &&
$product->getTypeId() != ProductTypeBundle::TYPE_CODE)) {
$this->_helper->log('The product with id [' . $product->getId() .
'] is not supported [' . $product->getTypeId() . ']');
continue;
}
if ($productSyncData->getMailchimpSyncModified()) {
$data = array_merge(
$data,
$this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId)
);
$this->_updateProduct($mailchimpStoreId, $product->getId());
} elseif (!$productSyncData->getMailchimpSyncDelta()) {
$data[] = $this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId);
$this->_updateProduct($mailchimpStoreId, $product->getId());
}
} catch(\Exception $e) {
$this->_helper->log($e->getMessage());
$this->_helper->log("Skip product [".$item->getProductId()."]");
}
}
return $data;
}
public function sendQuoteModifiedProduct(\Magento\Quote\Model\Quote $quote, $mailchimpStoreId, $magentoStoreId)
{
$data = [];
$batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT . '_' . $this->_helper->getGmtTimeStamp();
$items = $quote->getAllVisibleItems();
/**
* @var $item \Magento\Quote\Model\Quote\Item
*/
foreach ($items as $item) {
//@todo get from the store not the default
$product = $this->_productRepository->getById($item->getProductId(), false, $magentoStoreId);
$productSyncData = $this->_chimpSyncEcommerce->create()->getByStoreIdType(
$mailchimpStoreId,
$product->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT
);
if ($product->getId()!=$item->getProductId() || (
$product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE &&
$product->getTypeId() != \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL &&
$product->getTypeId() != \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE &&
$product->getTypeId() != self::DOWNLOADABLE &&
$product->getTypeId() != ProductTypeBundle::TYPE_CODE)) {
$this->_helper->log(
'The product with id ['.$product->getId().'] is not supported ['.$product->getTypeId().']'
);
continue;
}
if ($productSyncData->getMailchimpSyncModified()) {
$data = array_merge(
$data,
$this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId)
);
$this->_updateProduct($mailchimpStoreId, $product->getId());
} elseif (!$productSyncData->getMailchimpSyncDelta()) {
$data[] = $this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId);
$this->_updateProduct($mailchimpStoreId, $product->getId());
}
}
return $data;
}
protected function _getProductPrice(\Magento\Catalog\Model\Product $product)
{
if ($this->includingTaxes) {
$price = $this->taxHelper->getTaxPrice($product, $product->getFinalPrice(), true);
} else {
$price = $this->taxHelper->getTaxPrice($product, $product->getFinalPrice(), false);
}
return $price;
}
/**
* @param $storeId
* @param $entityId
* @param $sync_delta
* @param $sync_error
* @param $sync_modified
*/
protected function _updateProduct(
$storeId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null,
$deleted = null,
$forcedNoWaiting = false
) {
if ($forcedNoWaiting) {
$sent = \Ebizmarts\MailChimp\Helper\Data::SYNCED;
} else {
$sent = \Ebizmarts\MailChimp\Helper\Data::WAITINGSYNC;
}
$this->syncHelper->saveEcommerceData(
$storeId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT,
$sync_delta,
$sync_error,
$sync_modified,
$deleted,
null,
$sent
);
}
protected function _bundleVariants($product, $magentoStoreId)
{
$productsArray = [];
$simpleProducts = $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
foreach ($simpleProducts as $item) {
$selectionArray = [];
$selectionArray['selection_product_name'] = $item->getName();
$selectionArray['selection_product_quantity'] = $item->getSelectionQty();
$selectionArray['selection_product_price'] = $item->getPrice();
$selectionArray['selection_product_id'] = $item->getProductId();
$productsArray[$item->getOptionId()]['item'][$item->getSelectionId()] = $selectionArray;
}
foreach ($productsArray as $key => $productItem) {
$min = $max = 0;
foreach ($productItem['item'] as $item) {
if ($min == 0) {
$min = $item['selection_product_price']*$item['selection_product_quantity'];
}
if ($item['selection_product_price']*$item['selection_product_quantity'] < $min) {
$min = $item['selection_product_price']*$item['selection_product_quantity'];
}
if ($item['selection_product_price']*$item['selection_product_quantity'] > $max) {
$max = $item['selection_product_price']*$item['selection_product_quantity'];
}
}
$productsArray[$key]['min'] = $min;
$productsArray[$key]['max'] = $max;
}
$min = $max = 0;
foreach ($productsArray as $key => $productItem) {
$min += $productItem['min'];
$max += $productItem['max'];
}
return [$min, $max];
}
protected function _variantForBundle($product, $magentoStoreId, $price, $sku, $id)
{
$data = [];
$parent = null;
//data applied for both root and varient products
$data["id"] = $id;
$data["title"] = $product->getName();
$data["url"] = $product->getProductUrl();
$data["image_url"] = '';
if ($product->getImage() && $product->getImage()!='no_selection') {
$filePath = 'catalog/product/'.ltrim($product->getImage(), '/');
$data["image_url"] = $this->_helper->getBaserUrl(
$magentoStoreId,
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).$filePath;
} elseif ($this->_parentImage) {
$data['image_url'] = $this->_parentImage;
} else {
$parent = $this->_getParent($product->getId(), $magentoStoreId);
if ($parent && $parent->getImage() && $parent->getImage()!='no_selection') {
$filePath = 'catalog/product/'.ltrim($parent->getImage(), '/');
$data["image_url"] = $this->_helper->getBaserUrl(
$magentoStoreId,
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).$filePath;
}
}
$data["published_at_foreign"] = "";
$data["sku"] = $sku;
if ($this->productPrice) {
$data['price'] = $this->productPrice;
} else {
$data['price'] = $price;
}
//stock
$stock = $this->_stockRegistry->getStockItem($product->getId(), $magentoStoreId);
$data["inventory_quantity"] = (int)$stock->getQty();
$data["backorders"] = (string)$stock->getBackorders();
if ($product->getVisibility() == \Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE) {
$tailUrl = '';
$data["visibility"] = 'false';
if (!$parent) {
$parent = $this->_getParent($product->getId(), $magentoStoreId);
}
if ($parent) {
$options = $parent->getTypeInstance()->getConfigurableAttributesAsArray($parent);
foreach ($options as $option) {
if (strlen($tailUrl)) {
$tailUrl .= '&';
} else {
$tailUrl .= '?';
}
$tailUrl .= $option['attribute_code'] . "=" . $product->getData($option['attribute_code']);
}
$this->_childtUrl = $data['url'] = $parent->getProductUrl() . $tailUrl;
if (empty($data['image_url'])) {
$filePath = 'catalog/product'.$parent->getImage();
$data["image_url"] = $this->_helper->getBaserUrl(
$magentoStoreId,
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).$filePath;
}
}
} else {
$data["visibility"] = 'true';
}
return $data;
}
}
================================================
FILE: Model/Api/PromoCodes.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/6/17 1:15 PM
* @file: Coupon.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Magento\TestFramework\Inspection\Exception;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class PromoCodes
{
const MAX = 100;
protected $_batchId;
protected $_token;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory
*/
protected $_couponCollection;
/**
* @var \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory
*/
protected $_ruleCollection;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerceFactory
*/
private $_chimpSyncEcommerce;
/**
* @var PromoRules
*/
private $_promoRules;
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory
*/
private $_syncCollection;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory $couponCollection
* @param \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $ruleCollection
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerceFactory $chimpSyncEcommerce
* @param PromoRules $promoRules
* @param \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory $syncCollection
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\SalesRule\Model\ResourceModel\Coupon\CollectionFactory $couponCollection,
\Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $ruleCollection,
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerceFactory $chimpSyncEcommerce,
\Ebizmarts\MailChimp\Model\Api\PromoRules $promoRules,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory $syncCollection
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_couponCollection = $couponCollection;
$this->_ruleCollection = $ruleCollection;
$this->_chimpSyncEcommerce = $chimpSyncEcommerce;
$this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE. '_' .
$this->_helper->getGmtTimeStamp();
$this->_promoRules = $promoRules;
$this->_syncCollection = $syncCollection;
}
public function sendCoupons($magentoStoreId)
{
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$batchArray = [];
$batchArray = array_merge($batchArray, $this->_sendDeletedCoupons($mailchimpStoreId, $magentoStoreId));
// $batchArray = array_merge($batchArray, $this->_sendModifiedCoupons($mailchimpStoreId, $magentoStoreId));
$batchArray = array_merge($batchArray, $this->_sendNewCoupons($mailchimpStoreId, $magentoStoreId));
return $batchArray;
}
protected function _sendDeletedCoupons($mailchimpStoreId, $magentoStoreId)
{
$batchArray = [];
$websiteId = $this->_helper->getWebsiteId($magentoStoreId);
$collection = $this->_syncCollection->create();
$collection->addFieldToFilter('mailchimp_store_id', ['eq'=>$mailchimpStoreId])
->addFieldToFilter('type', ['eq'=>\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE])
->addFieldToFilter('mailchimp_sync_deleted', ['eq'=>1]);
$collection->getSelect()->limit(self::MAX);
$counter = 0;
/**
* @var $syncCoupon \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
foreach ($collection as $coupon) {
$couponId = $coupon->getRelatedId();
$ruleId = $coupon->getDeletedRelatedId();
$batchArray[$counter]['method'] = 'DELETE';
$batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $couponId;
$batchArray[$counter]['path'] =
"/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId/promo-codes/$couponId";
$counter++;
$syncCoupon =$this->syncHelper->getChimpSyncEcommerce(
$mailchimpStoreId,
$couponId,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE
);
$syncCoupon->getResource()->delete($syncCoupon);
}
return $batchArray;
}
protected function _sendNewCoupons($mailchimpStoreId, $magentoStoreId)
{
$batchArray = [];
$websiteId = $this->_helper->getWebsiteId($magentoStoreId);
/**
* @var $ruleCollection \Magento\SalesRule\Model\ResourceModel\Rule\Collection
*/
$ruleCollection = $this->_ruleCollection->create();
$ruleCollection->addWebsiteFilter($websiteId);
$rulesId = [];
foreach ($ruleCollection as $rule) {
$rulesId[] = $rule->getRuleId();
}
if (count($rulesId)) {
$inRoules = implode(',', $rulesId);
$collection = $this->_couponCollection->create();
$collection->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.coupon_id and m4m.type = '" .
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE .
"' and m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'",
['m4m.*']
);
$collection->getSelect()->joinLeft(
['rules' => $this->_helper->getTableName('salesrule')],
'main_table.rule_id = rules.rule_id'
);
$collection->getSelect()->where("m4m.mailchimp_sync_delta IS null and (rules.use_auto_generation = 1 and main_table.is_primary is null or rules.use_auto_generation = 0 and main_table.is_primary = 1) and main_table.rule_id in ($inRoules)");
$collection->getSelect()->limit(self::MAX);
$counter = 0;
/**
* @var $item \Magento\SalesRule\Model\Coupon
*/
foreach ($collection as $item) {
$this->_token = null;
$ruleId = $item->getRuleId();
$couponId = $item->getCouponId();
try {
$promoRule = $this->syncHelper->getChimpSyncEcommerce(
$mailchimpStoreId,
$ruleId,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE
);
if (!$promoRule->getMailchimpSyncDelta() ||
$promoRule->getMailchimpSyncDelta() < $this->_helper->getMCMinSyncDateFlag($magentoStoreId)) {
// must send the promorule before the promocode
$newPromoRule = $this->_promoRules->getNewPromoRule(
$ruleId,
$mailchimpStoreId,
$magentoStoreId
);
if (!empty($newPromoRule)) {
$batchArray[$counter] = $newPromoRule;
$counter++;
} else {
$error = __('Parent rule with id ' . $ruleId . 'has not been correctly sent.');
$this->_updateSyncData(
$mailchimpStoreId,
$ruleId,
$this->_helper->getGmtDate(),
$error,
0
);
continue;
}
}
if ($promoRule->getMailchimpSyncError()) {
// the promorule associated has an error
$error = __('Parent rule with id ' . $ruleId . 'has not been correctly sent.');
$this->_updateSyncData(
$mailchimpStoreId,
$couponId,
$this->_helper->getGmtDate(),
$error,
0
);
continue;
}
$promoCodeJson = json_encode($this->generateCodeData($item, $magentoStoreId));
if ($promoCodeJson !== false) {
if (!empty($promoCodeJson)) {
$batchArray[$counter]['method'] = 'POST';
$batchArray[$counter]['path'] =
"/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId/promo-codes/";
$batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $couponId;
$batchArray[$counter]['body'] = $promoCodeJson;
} else {
$error = __('Something went wrong when retrieving the information for promo rule');
$this->_updateSyncData(
$mailchimpStoreId,
$couponId,
$this->_helper->getGmtDate(),
$error,
0
);
continue;
}
$counter++;
$this->_updateSyncData($mailchimpStoreId, $couponId);
} else {
$error = json_last_error_msg();
$this->_updateSyncData(
$mailchimpStoreId,
$couponId,
$this->_helper->getGmtDate(),
$error,
0
);
}
} catch (Exception $e) {
$this->_helper->log($e->getMessage());
}
}
}
return $batchArray;
}
protected function generateCodeData($item, $magentoStoreId)
{
$data = [];
$data['id'] = $item->getCouponId();
$data['code'] = $item->getCode();
$data['redemption_url'] = $this->_getRedemptionUrl($item->getCode(), $magentoStoreId);
$data['usage_count'] = (int)$item->getTimesUsed();
return $data;
}
protected function _getRedemptionUrl($code, $magentoStoreId)
{
$token = hash('md5', rand(0, 9999999));
$url = $this->_helper->getRedemptionUrl($magentoStoreId, $code, $token);
$this->_token = $token;
return $url;
}
protected function _updateSyncData(
$storeId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null,
$sync_deleted = null
) {
$this->syncHelper->saveEcommerceData(
$storeId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE,
$sync_delta,
$sync_error,
$sync_modified,
$sync_deleted,
$this->_token
);
}
}
================================================
FILE: Model/Api/PromoRules.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/17/17 2:38 PM
* @file: PromoRules.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Magento\Cms\Test\Unit\Controller\Adminhtml\Page\MassEnableTest;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class PromoRules
{
const TYPE_FIXED = 'fixed';
const TYPE_PERCENTAGE = 'percentage';
const TARGET_PER_ITEM = 'per_item';
const TARGET_TOTAL = 'total';
const TARGET_SHIPPING = 'shipping';
const FREESHIPPING_NO = 0;
const FREESHIPPING_FOR_MATHINGI_TEMS_ONLY = 1;
const FREESHIPPING_FOR_SHIPMENT_WITH_MATCHING_ITEMS = 3;
const MAX = 100;
private $_batchId;
/**
* @var \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory
*/
private $_collection;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\SalesRule\Model\RuleRepository
*/
private $_ruleRepo;
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory
*/
protected $_syncCollection;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collection
* @param \Magento\SalesRule\Model\RuleRepository $ruleRepo
* @param \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory $syncCollection
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collection,
\Magento\SalesRule\Model\RuleRepository $ruleRepo,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory $syncCollection
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_collection = $collection;
$this->_ruleRepo = $ruleRepo;
$this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE. '_' .
$this->_helper->getGmtTimeStamp();
$this->_syncCollection = $syncCollection;
}
public function sendRules($magentoStoreId)
{
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$magentoStoreId
);
$batchArray = [];
$batchArray = array_merge($batchArray, $this->_getDeletedPromoRules($mailchimpStoreId, $magentoStoreId));
$batchArray = array_merge($batchArray, $this->_getModifiedPromoRules($mailchimpStoreId, $magentoStoreId));
return $batchArray;
}
protected function _getDeletedPromoRules($mailchimpStoreId, $magentoStoreId)
{
$batchArray = [];
$collection = $this->_syncCollection->create();
$collection->addFieldToFilter('mailchimp_store_id', ['eq'=>$mailchimpStoreId])
->addFieldToFilter('type', ['eq'=>\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE])
->addFieldToFilter('mailchimp_sync_deleted', ['eq'=>1]);
$collection->getSelect()->limit(self::MAX);
$count = 0;
$api = $this->_helper->getApi($magentoStoreId);
/**
* @var $rule \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
foreach ($collection as $rule) {
$ruleId = $rule->getData('related_id');
try {
$mailchimpRule = $api->ecommerce->promoCodes->getAll($mailchimpStoreId, $ruleId);
foreach ($mailchimpRule['promo_codes'] as $promoCode) {
$this->syncHelper->ecommerceDeleteAllByIdType(
$promoCode['id'],
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE,
$mailchimpStoreId
);
}
$batchArray[$count]['method'] = 'DELETE';
$batchArray[$count]['path'] = "/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId";
$batchArray[$count]['operation_id'] = $this->_batchId . '_' . $ruleId;
$count++;
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
}
$this->syncHelper->ecommerceDeleteAllByIdType(
$ruleId,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE,
$mailchimpStoreId
);
}
return $batchArray;
}
protected function _getModifiedPromoRules($mailchimpStoreId, $magentoStoreId)
{
$batchArray = [];
$websiteId = $this->_helper->getWebsiteId($magentoStoreId);
/**
* @var $collection \Magento\SalesRule\Model\ResourceModel\Rule\Collection
*/
$collection = $this->_collection->create();
$collection->addWebsiteFilter($websiteId);
$collection->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.rule_id and m4m.type = '".
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE.
"' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'",
['m4m.*']
);
$collection->getSelect()->where("m4m.mailchimp_sync_modified = 1");
$collection->getSelect()->limit(self::MAX);
$count = 0;
/**
* @var $rule \Magento\SalesRule\Model\Rule
*/
$api = $this->_helper->getApi($magentoStoreId);
foreach ($collection as $rule) {
$ruleId = $rule->getRuleId();
try {
$mailchimpRule = $api->ecommerce->promoCodes->getAll($mailchimpStoreId, $ruleId);
foreach ($mailchimpRule['promo_codes'] as $promoCode) {
$this->syncHelper->ecommerceDeleteAllByIdType(
$promoCode['id'],
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE,
$mailchimpStoreId
);
}
} catch (\Mailchimp_Error $e) {
$this->_helper->log($e->getFriendlyMessage());
}
$this->syncHelper->ecommerceDeleteAllByIdType(
$rule->getRuleId(),
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE,
$mailchimpStoreId
);
$batchArray[$count]['method'] = 'DELETE';
$batchArray[$count]['path'] = "/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId";
$batchArray[$count]['operation_id'] = $this->_batchId. '_' . $rule->getRuleId();
$count++;
}
return $batchArray;
}
public function getNewPromoRule($ruleId, $mailchimpStoreId, $magentoStoreId)
{
$data = [];
/**
* @var $rule \Magento\SalesRule\Model\Rule
*/
try {
$rule = $this->_ruleRepo->getById($ruleId);
$promoRules = $this->_generateRuleData($rule);
if (!empty($promoRules)) {
$promoRulesJson = json_encode($promoRules);
if ($promoRulesJson !== false) {
if (!empty($promoRulesJson)) {
$data['method'] = 'POST';
$data['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/promo-rules';
$data['operation_id'] = $this->_batchId . '_' . $ruleId;
$data['body'] = $promoRulesJson;
$this->_updateSyncData($mailchimpStoreId, $ruleId);
} else {
$error = __('Something went wrong when retrieving the information.');
$this->_updateSyncData(
$mailchimpStoreId,
$ruleId,
$this->_helper->getGmtDate(),
$error,
0
);
}
} else {
$error = json_last_error_msg();
$this->_updateSyncData(
$mailchimpStoreId,
$ruleId,
$this->_helper->getGmtDate(),
$error,
0
);
}
} else {
$error = __('Something went wrong when retrieving the information.');
$this->_updateSyncData(
$mailchimpStoreId,
$ruleId,
$this->_helper->getGmtDate(),
$error,
0
);
}
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
return $data;
}
private function _generateRuleData($rule)
{
$data = [];
$data['id'] = $rule->getRuleId();
$data['title'] = $rule->getName();
$data['description'] = $rule->getDescription() ? $rule->getDescription() : $rule->getName();
$fromDate = $rule->getFromDate();
if ($fromDate) {
$data['starts_at'] = $fromDate;
}
$toDate = $rule->getToDate();
if ($toDate) {
$data['ends_at'] = $toDate;
}
$promoAction = $rule->getSimpleAction();
$shipping = $rule->getSimpleFreeShipping();
$data['type'] = $this->_getMailChimpType($promoAction, $shipping);
$data['target'] = $this->_getMailChimpTarget($promoAction, $shipping);
switch ($data['type']) {
case self::TYPE_PERCENTAGE:
$data['amount'] = $rule->getDiscountAmount()/100;
break;
case self::TYPE_FIXED:
if ($data['target']!=self::TARGET_SHIPPING) {
$data['amount'] = $rule->getDiscountAmount();
} else {
$data['amount'] = 0;
}
break;
}
$data['enabled'] = (bool)$rule->getIsActive();
if (!$data['target'] || !$data['type']) {
return [];
}
return $data;
}
/**
* @param $action
* @return null|string
*/
private function _getMailChimpType($action, $shipping)
{
$mailChimpType = null;
if ($shipping==self::FREESHIPPING_NO) {
switch ($action) {
case \Magento\SalesRule\Model\Rule::BY_PERCENT_ACTION:
$mailChimpType = self::TYPE_PERCENTAGE;
break;
case \Magento\SalesRule\Model\Rule::BY_FIXED_ACTION:
case \Magento\SalesRule\Model\Rule::CART_FIXED_ACTION:
$mailChimpType = self::TYPE_FIXED;
break;
}
} else {
$mailChimpType = self::TYPE_FIXED;
}
return $mailChimpType;
}
/**
* @param $action
* @return null|string
*/
private function _getMailChimpTarget($action, $shipping)
{
$mailChimpTarget = null;
if ($shipping==self::FREESHIPPING_NO) {
switch ($action) {
case \Magento\SalesRule\Model\Rule::CART_FIXED_ACTION:
case \Magento\SalesRule\Model\Rule::BY_PERCENT_ACTION:
$mailChimpTarget = self::TARGET_TOTAL;
break;
case \Magento\SalesRule\Model\Rule::BY_FIXED_ACTION:
$mailChimpTarget = self::TARGET_PER_ITEM;
break;
}
} else {
$mailChimpTarget = self::TARGET_SHIPPING;
}
return $mailChimpTarget;
}
/**
* @param $storeId
* @param $entityId
* @param $sync_delta
* @param string $sync_error
* @param int $sync_modified
*/
protected function _updateSyncData($storeId, $entityId, $sync_delta = null, $sync_error = '', $sync_modified = 0)
{
$this->syncHelper->saveEcommerceData(
$storeId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE,
$sync_delta,
$sync_error,
$sync_modified
);
}
}
================================================
FILE: Model/Api/Result.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/21/16 4:09 PM
* @file: Result.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
use Ebizmarts\Mailchimp\Helper\Data as Helper;
class Result
{
const MAILCHIMP_TEMP_DIR = 'Mailchimp';
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches\CollectionFactory
*/
private $_batchCollection;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Framework\Archive
*/
private $_archive;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory
*/
private $_chimpErrors;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
private $_driver;
/**
* @var \Magento\Framework\HTTP\Client\CurlFactory
*/
private $_curlFactory;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches\CollectionFactory $batchCollection
* @param \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $chimpErrors
* @param \Magento\Framework\Archive $archive
* @param \Magento\Framework\Filesystem\Driver\File $driver
* @param \Magento\Framework\HTTP\Client\CurlFactory $curlFactory
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches\CollectionFactory $batchCollection,
\Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $chimpErrors,
\Magento\Framework\Archive $archive,
\Magento\Framework\Filesystem\Driver\File $driver,
\Magento\Framework\HTTP\Client\CurlFactory $curlFactory
) {
$this->_batchCollection = $batchCollection;
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_archive = $archive;
$this->_chimpErrors = $chimpErrors;
$this->_driver = $driver;
$this->_curlFactory = $curlFactory;
}
public function processResponses($storeId, $isMailChimpStoreId = false, $mailchimpStoreId)
{
$collection = $this->_batchCollection->create();
$collection
->addFieldToFilter('store_id', ['eq' => $storeId])
->addFieldToFilter('status', ['eq' => 'pending'])
->addFieldToFilter('mailchimp_store_id', ['eq' => $mailchimpStoreId]);
/**
* @var $item \Ebizmarts\MailChimp\Model\MailChimpSyncBatches
*/
$item = null;
foreach ($collection as $item) {
try {
$files = $this->getBatchResponse($item->getBatchId(), $storeId);
if (is_array($files) && count($files)) {
$this->processEachResponseFile($files, $item->getBatchId(), $mailchimpStoreId, $storeId);
$item->setStatus(\Ebizmarts\MailChimp\Helper\Data::BATCH_COMPLETED);
$item->setModifiedDate($this->_helper->getGmtDate());
$item->getResource()->save($item);
} elseif ($files === false) {
$item->setStatus(\Ebizmarts\MailChimp\Helper\Data::BATCH_ERROR);
$item->getResource()->save($item);
$this->syncHelper->deleteAllByBatchId($item->getBatchId());
continue;
}
$baseDir = $this->_helper->getBaseDir();
if ($this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $item->getBatchId())) {
$dirFiles = $this->_driver->readDirectory(
$baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR .
$item->getBatchId().DIRECTORY_SEPARATOR
);
foreach ($dirFiles as $dirFile) {
$this->_driver->deleteFile(
$baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR .
$item->getBatchId().DIRECTORY_SEPARATOR.$dirFile
);
}
$this->_driver->deleteDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $item->getBatchId());
}
} catch (\Exception $e) {
$this->_helper->log("Error with a response: " . $e->getMessage());
}
}
}
public function getBatchResponse($batchId, $storeId = null)
{
$files = [];
try {
$baseDir = $this->_helper->getBaseDir();
$api = $this->_helper->getApi($storeId);
// check the status of the job
$response = $api->batchOperation->status($batchId);
if (isset($response['status']) && $response['status'] == 'finished') {
// Create temporary directory, if that does not exist
if (!$this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . self::MAILCHIMP_TEMP_DIR)) {
$this->_driver->createDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . self::MAILCHIMP_TEMP_DIR);
}
// get the tar.gz file with the results
// for AWS S3 use urldecode, for google drive use without urldecode
// $fileUrl = urldecode($response['response_body_url']);
$fileUrl = $response['response_body_url'];
$fileName = $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId;
$fd = $this->_driver->fileOpen($fileName . '.tar.gz', 'w');
$ch = $this->_curlFactory->create();
$ch->setOption(CURLOPT_URL, $fileUrl);
$ch->setOption(CURLOPT_FILE, $fd);
$ch->setOption(CURLOPT_FOLLOWLOCATION, true);
$r =$ch->get($fileUrl);
$this->_driver->fileClose($fd);
$this->_driver->createDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId);
$archive = $this->_archive;
$archive->unpack(
$fileName . '.tar.gz',
$baseDir . DIRECTORY_SEPARATOR . 'var' .
DIRECTORY_SEPARATOR . self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId
);
$archive->unpack(
$baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId . '/' . $batchId . '.tar',
$baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId
);
$dirFiles = $this->_driver->readDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId);
foreach ($dirFiles as $dirFile) {
$name = pathinfo($dirFile);
if ($name['extension'] == 'json') {
$files[] = $dirFile;
}
}
$this->_driver->deleteFile($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .
self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId . '/' . $batchId . '.tar');
$this->_driver->deleteFile($fileName . '.tar.gz');
}
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
return false;
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
return $files;
}
protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, $storeId)
{
$listId = $this->_helper->getDefaultList($storeId);
foreach ($files as $file) {
$items = json_decode($this->_driver->fileGetContents($file));
if ($items!==false) {
foreach ($items as $item) {
$line = explode('_', $item->operation_id);
$type = $line[0];
$id = $line[2];
if ($item->status_code != 200) {
//parse error
$response = json_decode($item->response);
if (preg_match('/already exists/', $response->detail)) {
$this->_updateSyncData(
$mailchimpStoreId,
$listId,
$type,
$id,
null,
\Ebizmarts\MailChimp\Helper\Data::SYNCED
);
continue;
}
$mailchimpErrors = $this->_chimpErrors->create();
$errorDetails = "";
if (!empty($response->errors)) {
foreach ($response->errors as $error) {
if (isset($error->field) && isset($error->message)) {
$errorDetails .= $errorDetails != "" ? " / " : "";
$errorDetails .= $error->field . " : " . $error->message;
}
}
}
if ($errorDetails == "") {
$errorDetails = $response->detail;
}
$error = $response->title . " : " . $response->detail;
if ($type == Helper::IS_PRODUCT and $item->status_code == 404) {
$this->syncHelper->deleteByTypeAndId($type, $id, $mailchimpStoreId);
} else {
$this->_updateSyncData(
$mailchimpStoreId,
$listId,
$type,
$id,
$error,
\Ebizmarts\MailChimp\Helper\Data::SYNCERROR
);
}
if (property_exists($response, 'type')){
$mailchimpErrors->setType($response->type);
} else {
$mailchimpErrors->setType('Unknown');
}
if (property_exists($response, 'title')){
$mailchimpErrors->setTitle($response->title);
} else {
$mailchimpErrors->setTitle('Unknown');
}
$mailchimpErrors->setStatus($item->status_code);
$mailchimpErrors->setErrors($errorDetails);
$mailchimpErrors->setRegtype($type);
$mailchimpErrors->setOriginalId($id);
$mailchimpErrors->setBatchId($batchId);
$mailchimpErrors->setMailchimpStoreId($mailchimpStoreId);
$mailchimpErrors->setOriginalId($id);
$mailchimpErrors->setBatchId($batchId);
$mailchimpErrors->setStoreId($storeId);
$mailchimpErrors->getResource()->save($mailchimpErrors);
} else {
$this->_updateSyncData(
$mailchimpStoreId,
$listId,
$type,
$id,
null,
\Ebizmarts\MailChimp\Helper\Data::SYNCED
);
}
}
} else {
switch (json_last_error()) {
case JSON_ERROR_DEPTH:
$this->_helper->log(' - Maximum stack depth exceeded');
break;
case JSON_ERROR_CTRL_CHAR:
$this->_helper->log(' - Unexpected control character found');
break;
case JSON_ERROR_SYNTAX:
$this->_helper->log(' - Syntax error, malformed JSON');
break;
case JSON_ERROR_NONE:
$this->_helper->log(' - No errors');
break;
}
}
$this->_driver->deleteFile($file);
}
}
private function _updateSyncData($mailchimpStoreId, $listId, $type, $id, $error, $status)
{
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSync
*/
if ($type == \Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER) {
$mailchimpStore = $listId;
} else {
$mailchimpStore = $mailchimpStoreId;
}
$this->syncHelper->saveEcommerceData(
$mailchimpStore,
$id,
$type,
null,
$error,
null,
null,
null,
$status,
true
);
}
}
================================================
FILE: Model/Api/Subscriber.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/15/17 11:02 AM
* @file: Subscriber.php
*/
namespace Ebizmarts\MailChimp\Model\Api;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Subscriber
{
const BATCH_LIMIT = 100;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory
*/
protected $_subscriberCollection;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $_message;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $_subscriberFactory;
protected $_interest=null;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory $subscriberCollection
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Magento\Framework\Message\ManagerInterface $message
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory $subscriberCollection,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Magento\Framework\Message\ManagerInterface $message
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_subscriberCollection = $subscriberCollection;
$this->_message = $message;
$this->_subscriberFactory = $subscriberFactory;
}
public function sendSubscribers($storeId, $listId)
{
//get subscribers
// $listId = $this->_helper->getGeneralList($storeId);
$this->_interest = $this->_helper->getInterest($storeId);
$collection = $this->_subscriberCollection->create();
$collection->addFieldToFilter('subscriber_status', ['eq' => 1])
->addFieldToFilter('store_id', ['eq' => $storeId]);
$collection->getSelect()->joinLeft(
['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],
"m4m.related_id = main_table.subscriber_id and m4m.type = '".
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER.
"' and m4m.mailchimp_store_id = '".$listId."'",
['m4m.*']
);
$collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1");
$collection->getSelect()->limit(self::BATCH_LIMIT);
$subscriberArray = [];
$date = $this->_helper->getDateMicrotime();
$batchId = \Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER . '_' . $date;
$counter = 0;
/**
* @var $subscriber \Magento\Newsletter\Model\Subscriber
*/
foreach ($collection as $subscriber) {
$data = $this->_buildSubscriberData($subscriber);
$md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));
$subscriberJson = "";
//enconde to JSON
$subscriberJson = json_encode($data);
if ($subscriberJson!==false) {
if (!empty($subscriberJson)) {
if ($subscriber->getMailchimpSyncModified() == 1) {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::SUB_MOD);
} else {
$this->_helper->modifyCounter(\Ebizmarts\MailChimp\Helper\Data::SUB_NEW);
}
$subscriberArray[$counter]['method'] = "PUT";
$subscriberArray[$counter]['path'] = "/lists/" . $listId . "/members/" . $md5HashEmail;
$subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId();
$subscriberArray[$counter]['body'] = $subscriberJson;
//update subscribers delta
$this->_updateSubscriber($listId, $subscriber->getId());
}
$counter++;
} else {
$errorMessage = json_last_error_msg();
$this->_updateSubscriber(
$listId,
$subscriber->getId(),
$this->_helper->getGmtDate(),
$errorMessage,
0
);
}
}
return $subscriberArray;
}
protected function _buildSubscriberData(\Magento\Newsletter\Model\Subscriber $subscriber)
{
$storeId = $subscriber->getStoreId();
$data = [];
$data["email_address"] = $subscriber->getSubscriberEmail();
$mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriber);
if ($mergeVars) {
$data["merge_fields"] = $mergeVars;
}
$data["status_if_new"] = $data["status"] = $this->_getMCStatus($subscriber->getStatus(), $storeId);
$interest = $this->_getInterest($subscriber);
if (count($interest)) {
$data['interests'] = $interest;
}
return $data;
}
protected function _getInterest(\Magento\Newsletter\Model\Subscriber $subscriber)
{
$rc = [];
$interest = $this->_helper->getSubscriberInterest(
$subscriber->getSubscriberId(),
$subscriber->getStoreId(),
$this->_interest
);
foreach ($interest as $i) {
if (array_key_exists('category', $i)) {
foreach ($i['category'] as $key => $value) {
$rc[$value['id']] = $value['checked'];
}
}
}
return $rc;
}
/**
* Get status to send confirmation if Need to Confirm enabled on Magento
*
* @param $status
* @param $storeId
* @return string
*/
protected function _getMCStatus($status, $storeId)
{
$confirmationFlagPath = \Magento\Newsletter\Model\Subscriber::XML_PATH_CONFIRMATION_FLAG;
if ($status == \Magento\Newsletter\Model\Subscriber::STATUS_UNSUBSCRIBED) {
$status = 'unsubscribed';
} elseif ($this->_helper->getConfigValue($confirmationFlagPath, $storeId) &&
($status == \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE ||
$status == \Magento\Newsletter\Model\Subscriber::STATUS_UNCONFIRMED)
) {
$status = 'pending';
} elseif ($status == \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED) {
$status = 'subscribed';
}
return $status;
}
public function deleteSubscriber(\Magento\Newsletter\Model\Subscriber $subscriber)
{
$storeId = $subscriber->getStoreId();
$listId = $this->_helper->getGeneralList($storeId);
$api = $this->_helper->getApi($storeId);
try {
$md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));
$api->lists->members->update($listId, $md5HashEmail, null, 'cleaned');
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage(), $storeId);
$this->_message->addErrorMessage($e->getMessage());
} catch (\Exception $e) {
$this->_helper->log($e->getMessage(), $storeId);
}
}
public function update(\Magento\Newsletter\Model\Subscriber $subscriber)
{
$storeId = $subscriber->getStoreId();
$listId = $this->_helper->getGeneralList($storeId);
$this->_updateSubscriber(
$listId,
$subscriber->getId(),
$this->_helper->getGmtDate(),
'',
1
);
}
protected function _updateSubscriber(
$listId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null
) {
$this->syncHelper->saveEcommerceData(
$listId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER,
$sync_delta,
$sync_error,
$sync_modified
);
}
}
================================================
FILE: Model/Config/Backend/ApiKey.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 9/30/16 12:09 PM
* @file: Monkeylist.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Backend;
use Magento\Framework\App\Config\ScopeConfigInterface;
class ApiKey extends \Magento\Framework\App\Config\Value
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var \Magento\Config\Model\ResourceModel\Config
*/
protected $resourceConfig;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
private $_date;
/**
* @var \Magento\Store\Model\StoreManager
*/
private $_storeManager;
/**
* ApiKey constructor.
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Config\Model\ResourceModel\Config $resourceConfig
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Store\Model\StoreManager $storeManager
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Config\Model\ResourceModel\Config $resourceConfig,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Store\Model\StoreManager $storeManager,
array $data = []
) {
$this->_helper = $helper;
$this->resourceConfig = $resourceConfig;
$this->_date = $date;
$this->_storeManager = $storeManager;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
public function beforeSave()
{
$active = null;
$generalData = $this->getData();
$data = $this->getData('groups');
$found = 0;
if (isset($data['ecommerce']['fields']['active']['value'])) {
$active = $data['ecommerce']['fields']['active']['value'];
} elseif ($data['ecommerce']['fields']['active']['inherit']) {
$active = $data['ecommerce']['fields']['active']['inherit'];
}
if ($active && $this->isValueChanged()) {
$mailchimpStore = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$this->getScopeId(),
$this->getScope()
);
$this->resourceConfig->deleteConfig(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$this->getScope(),
$this->getScopeId()
);
foreach ($this->_storeManager->getStores() as $storeId => $val) {
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE, $storeId) ==
$mailchimpStore) {
$found++;
}
}
if ($found==1) {
$this->_helper->cancelAllPendingBatches($mailchimpStore);
}
}
return parent::beforeSave();
}
}
================================================
FILE: Model/Config/Backend/MonkeyList.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/22/17 3:08 PM
* @file: MonkeyList.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Backend;
class MonkeyList extends \Magento\Framework\App\Config\Value
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var \Magento\Config\Model\ResourceModel\Config
*/
protected $resourceConfig;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
private $_date;
/**
* @var \Magento\Store\Model\StoreManager
*/
private $_storeManager;
/**
* ApiKey constructor.
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Config\Model\ResourceModel\Config $resourceConfig
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Store\Model\StoreManager $storeManager
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Config\Model\ResourceModel\Config $resourceConfig,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Store\Model\StoreManager $storeManager,
array $data = []
) {
$this->_helper = $helper;
$this->resourceConfig = $resourceConfig;
$this->_date = $date;
$this->_storeManager = $storeManager;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
}
================================================
FILE: Model/Config/Backend/MonkeyStore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/29/17 4:29 PM
* @file: MonkeyStore.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Backend;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class MonkeyStore extends \Magento\Framework\App\Config\Value
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Config\Model\ResourceModel\Config
*/
protected $resourceConfig;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
private $_date;
/**
* @var \Magento\Store\Model\StoreManager
*/
private $_storeManager;
private $oldListId = null;
const MAX_LISTS = 200;
/**
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Magento\Config\Model\ResourceModel\Config $resourceConfig
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Store\Model\StoreManager $storeManager
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Magento\Config\Model\ResourceModel\Config $resourceConfig,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
\Magento\Framework\Stdlib\DateTime\DateTime $date,
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Store\Model\StoreManager $storeManager,
array $data = []
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->resourceConfig = $resourceConfig;
$this->_date = $date;
$this->_storeManager = $storeManager;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
public function beforeSave()
{
$data = $this->getData('groups');
$found = 0;
$newListId = null;
if (isset($data['ecommerce']['fields']['active']['value'])) {
$active = $data['ecommerce']['fields']['active']['value'];
} elseif ($data['ecommerce']['fields']['active']['inherit']) {
$active = $data['ecommerce']['fields']['active']['inherit'];
} else {
$active = 0;
}
if ($active && $this->isValueChanged()) {
$mailchimpStore = $this->getOldValue();
// charge the $newListId
if (isset($data['general']['fields']['apikey']['value'])) {
$apiKey = $data['general']['fields']['apikey']['value'];
} else {
$apiKey = $this->_helper->getApiKey($this->getScopeId(), $this->getScope());
}
if (isset($data['general']['fields']['monkeylist']['value'])) {
$newListId = $data['general']['fields']['monkeylist']['value'];
} else {
$newListId = $this->getStore($apiKey, $this->getValue());
$this->_helper->saveConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST,
$newListId,
$this->getScopeId(),
$this->getScope()
);
}
$this->oldListId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST,
$this->getScopeId(),
$this->getScope()
);
$createWebhook = true;
$this->_helper->deleteConfig(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_JS_URL,
$this->getScopeId(),
$this->getScope()
);
foreach ($this->_storeManager->getStores() as $storeId => $val) {
$mstoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
if ($mstoreId == $mailchimpStore) {
$this->_helper->deleteConfig(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_JS_URL,
$storeId,
'stores'
);
$found++;
}
$listId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST, $storeId);
if ($listId == $newListId) {
$createWebhook = false;
}
}
if ($found==1) {
$this->_helper->cancelAllPendingBatches($mailchimpStore);
$this->syncHelper->resetErrors($mailchimpStore, $this->getScopeId(), true);
}
$this->_helper->restoreAllCanceledBatches($this->getValue());
if ($createWebhook) {
$this->_helper->createWebHook($apiKey, $newListId);
}
}
return parent::beforeSave();
}
private function getStore($apiKey, $store)
{
try {
$api = $this->_helper->getApiByApiKey($apiKey);
$store = $api->ecommerce->stores->get($store);
return $store['list_id'];
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
}
return null;
}
}
================================================
FILE: Model/Config/Backend/VarsMap.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/30/17 10:27 AM
* @file: VarsMap.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Backend;
class VarsMap extends \Magento\Framework\App\Config\Value
{
/**
* @var \Ebizmarts\MailChimp\Helper\VarsMap
*/
private $_varsHelper;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* VarsMap constructor.
* @param \Magento\Framework\Model\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\App\Config\ScopeConfigInterface $config
* @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
* @param \Ebizmarts\MailChimp\Helper\VarsMap $varsMap
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource
* @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
\Magento\Framework\Model\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\App\Config\ScopeConfigInterface $config,
\Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
\Ebizmarts\MailChimp\Helper\VarsMap $varsMap,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
\Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
array $data = []
) {
$this->_varsHelper = $varsMap;
$this->_helper = $helper;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
protected function _afterLoad()
{
$value = $this->getValue();
$value = $this->_varsHelper->makeArrayFieldValue($value);
$this->setValue($value);
}
/**
* Prepare data before save
*
* @return void
*/
public function beforeSave()
{
$value = $this->getValue();
if (is_array($value)) {
$value = $this->_varsHelper->makeStorableArrayFieldValue($value);
}
$this->setValue($value);
}
}
================================================
FILE: Model/Config/ModuleVersion.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Model\Config;
use Magento\Framework\Component\ComponentRegistrar;
use Magento\Framework\Component\ComponentRegistrarInterface;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem\Directory\ReadFactory;
class ModuleVersion
{
const COMPOSER_FILE_NAME = 'composer.json';
/**
* @var ComponentRegistrarInterface
*/
private $componentRegistrar;
/**
* @var ReadFactory
*/
private $readFactory;
/**
* ModuleVersion constructor.
* @param ComponentRegistrarInterface $componentRegistrar
* @param ReadFactory $readFactory
*/
public function __construct(ComponentRegistrarInterface $componentRegistrar, ReadFactory $readFactory)
{
$this->componentRegistrar = $componentRegistrar;
$this->readFactory = $readFactory;
}
public function getModuleVersion($moduleName) : string
{
$emptyVersionNumber = '';
$composerJsonData = null;
try {
$path = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, $moduleName);
$directoryRead = $this->readFactory->create($path);
$composerJsonData = $directoryRead->readFile(self::COMPOSER_FILE_NAME);
} catch (\LogicException $pathException) {
return $emptyVersionNumber;
} catch (FileSystemException $fsException) {
return $emptyVersionNumber;
} catch (\Exception $exception) {
return $emptyVersionNumber;
}
try {
$jsonData = json_decode($composerJsonData);
if ($jsonData === null) {
return $emptyVersionNumber;
}
return $jsonData->version ?? $emptyVersionNumber;
} catch (\Exception $exception) {
return $emptyVersionNumber;
}
}
}
================================================
FILE: Model/Config/Source/ApiKey.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/30/17 1:36 PM
* @file: ApiKey.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class ApiKey implements \Magento\Framework\Option\ArrayInterface
{
protected $options = null;
/**
* @var \Magento\Store\Model\StoreManager
*/
protected $storeManager;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var \Magento\Framework\Encryption\Encryptor
*/
protected $encryptor;
/**
* ApiKey constructor.
* @param \Magento\Store\Model\StoreManager $storeManager
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Framework\App\RequestInterface $request
* @param \Magento\Framework\Encryption\Encryptor $encryptor
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function __construct(
\Magento\Store\Model\StoreManager $storeManager,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Framework\App\RequestInterface $request,
\Magento\Framework\Encryption\Encryptor $encryptor
) {
$this->storeManager = $storeManager;
$this->helper = $helper;
$this->encryptor = $encryptor;
$storeId = (int) $request->getParam("store", 0);
if ($request->getParam('website', 0)) {
$scope = 'website';
$storeId = $request->getParam('website', 0);
} elseif ($request->getParam('store', 0)) {
$scope = 'stores';
$storeId = $request->getParam('store', 0);
} else {
$scope = 'default';
}
}
public function toOptionArray()
{
$rc = [];
if (is_array($this->options) && count($this->options)) {
$rc[] = ['value' => -1, 'label' => 'Select one ApiKey'];
foreach ($this->options as $apiKey) {
$rc[] = ['value'=> $this->encryptor->encrypt(trim($apiKey)), 'label' => $this->mask(trim($apiKey))];
}
}
return $rc;
}
public function getAllApiKeys()
{
$this->options = $this->helper->getAllApiKeys();
}
private function mask($str)
{
if (strlen($str) < 4) {
return __('Invalid API Key');
} else {
return substr($str, 0, 6) . str_repeat('*', strlen($str) - 4) . substr($str, -4);
}
}
}
================================================
FILE: Model/Config/Source/CampaignAction.php
================================================
'sent', 'label' => 'Sent'],
['value' => 'open', 'label' => 'Open'],
['value' => 'click', 'label' => 'Click']
];
public function toOptionArray()
{
return $this->actions;
}
}
================================================
FILE: Model/Config/Source/CleanPeriod.php
================================================
'One day', 3=> 'Three days', 7=> 'One week'];
}
}
================================================
FILE: Model/Config/Source/Cmspage.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 9/30/16 2:46 PM
* @file: Cmspage.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class Cmspage
{
/**
* @var \Magento\Cms\Model\Page
*/
private $_page;
/**
* @param \Magento\Cms\Model\Page $page
*/
public function __construct(
\Magento\Cms\Model\Page $page
) {
$this->_page = $page;
}
public function toOptionArray()
{
$pages = $this->_page->getCollection()->addOrder('title', 'asc');
return ['checkout/cart' => 'Shopping Cart (default page)'] + $pages->toOptionIdArray();
}
}
================================================
FILE: Model/Config/Source/Details.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
use Ebizmarts\MailChimp\Helper\Data as MailChimpHelper;
use Ebizmarts\MailChimp\Helper\Http as MailChimpHttp;
use Magento\Directory\Helper\Data as DirectoryHelper;
class Details implements \Magento\Framework\Option\ArrayInterface
{
/**
* @var null
*/
private $_options = null;
/**
* @var MailChimpHelper
*/
private $_helper = null;
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
private $_message;
/**
* @var \Magento\Store\Model\StoreManager
*/
private $storeManager;
/**
* @var MailChimpHttp
*/
private $httpClient;
private $_error = '';
/**
* @param MailChimpHelper $helper
* @param \Magento\Framework\Message\ManagerInterface $message
* @param \Magento\Store\Model\StoreManager $storeManager
* @param \Magento\Framework\App\RequestInterface $request
* @param MailChimpHttp $httpClient
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function __construct(
MailChimpHelper $helper,
\Magento\Framework\Message\ManagerInterface $message,
\Magento\Store\Model\StoreManager $storeManager,
\Magento\Framework\App\RequestInterface $request,
MailChimpHttp $httpClient,
DirectoryHelper $directoryHelper
) {
$this->_message = $message;
$this->_helper = $helper;
$this->storeManager = $storeManager;
$this->httpClient = $httpClient;
$this->httpClient->setUrl($helper->getConfigValue(MailChimpHelper::XML_REGISTER_URL).'/register');
$storeId = (int) $request->getParam("store", 0);
if ($request->getParam('website', 0)) {
$scope = 'website';
$storeId = $request->getParam('website', 0);
} elseif ($request->getParam('store', 0)) {
$scope = 'stores';
$storeId = $request->getParam('store', 0);
} else {
$scope = 'default';
}
if ($this->_helper->getApiKey($storeId, $scope)) {
$api = $this->_helper->getApi($storeId, $scope);
try {
$this->_options = $api->root->info();
$optionsList = $api->lists->getLists(
$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST,
$storeId,
$scope
)
);
if ($optionsList &&
array_key_exists('stats', $optionsList) &&
array_key_exists('member_count', $optionsList['stats'])) {
$this->_options['list_subscribers'] = $optionsList['stats']['member_count'];
}
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId,
$scope
);
if ($mailchimpStoreId && $mailchimpStoreId!=-1 &&
$this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ECOMMERCE_ACTIVE,
$storeId,
$scope
)
) {
$token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $storeId, $scope);
if (!$token) {
$registerData['store_url'] = stripslashes($this->storeManager->getStore($storeId)->getBaseUrl());
$registerData['account_name'] = $this->_options['account_name'];
$registerData['email'] = $this->_options['email'];
$registerData['first_name'] = $this->_options['first_name'];
$registerData['last_name'] = $this->_options['last_name'];
$registerData['pricing_plan_type'] = $this->_options['pricing_plan_type'];
$registerData['username'] = $this->_options['username'];
$registerData['account_id'] = $this->_options['account_id'];
$registerData['city'] = $this->_helper->getConfigValue(\Magento\Store\Model\Information::XML_PATH_STORE_INFO_CITY,$storeId, $scope);
$registerData['country'] = $directoryHelper->getDefaultCountry($storeId);
$registerData['total_subscribers'] = $this->_options['total_subscribers'];
$registerDataJson = json_encode($registerData);
$ret = $this->httpClient->post($registerDataJson);
$ret = json_decode($ret,true);
if ( !$ret['error']) {
$error = false;
$token = $ret['token'];
$this->_helper->saveConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $token, $storeId, $scope);
}
}
$storeInfo = $api->ecommerce->stores->get($mailchimpStoreId);
$this->_options['is_syncing'] = $storeInfo['is_syncing'];
$this->_options['date_sync'] = $this->getDateSync($mailchimpStoreId);
$this->_options['store_exists'] = true;
$totalCustomers = $api->ecommerce->customers->getAll($mailchimpStoreId, 'total_items');
$this->_options['total_customers'] = $totalCustomers['total_items'];
$totalProducts = $api->ecommerce->products->getAll($mailchimpStoreId, 'total_items');
$this->_options['total_products'] = $totalProducts['total_items'];
$totalOrders = $api->ecommerce->orders->getAll($mailchimpStoreId, 'total_items');
$this->_options['total_orders'] = $totalOrders['total_items'];
$totalCarts = $api->ecommerce->carts->getAll($mailchimpStoreId, 'total_items');
$this->_options['total_carts'] = $totalCarts['total_items'];
} else {
$this->_options['store_exists'] = false;
}
$token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $storeId, $scope);
$this->_options['token'] = $token;
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
$this->_error = $e->getMessage();
$this->_options['store_exists'] = false;
}
} else {
$this->_options = '--- Enter your API Key ---';
}
}
/**
* @return array
*/
public function toOptionArray()
{
$ret = '';
if ($this->_error != '') {
$ret = [['label' => 'Important', 'value' => __("Store not found")]];
} elseif(is_array($this->_options)) {
if (isset($this->_options['account_name'])) {
$ret = [
['label' => __('Username'), 'value' => $this->_options['account_name']],
['label' => 'Total Member Subscribers', 'value' => $this->_options['total_subscribers']]];
if (array_key_exists('list_subscribers', $this->_options)) {
$ret = array_merge(
$ret,
[['label' => 'Total List Subscribers', 'value' => $this->_options['list_subscribers']]]
);
}
$ret = array_merge($ret, [['label'=> __('Registration ID'), 'value' => $this->_options['token']]]);
if (isset($this->_options['store_exists']) && $this->_options['store_exists']) {
$ret = array_merge($ret, [
['label' => 'Ecommerce Data uploaded to MailChimp', 'value' => ''],
['label' => ' Total Customers', 'value' => $this->_options['total_customers']],
['label' => ' Total Products', 'value' => $this->_options['total_products']],
['label' => ' Total Orders', 'value' => $this->_options['total_orders']],
['label' => ' Total Carts', 'value' => $this->_options['total_carts']]
]);
if ($this->_options['is_syncing']) {
$ret = array_merge($ret, [
['label'=> __('This account is currently syncing'), 'value'=>'']
]);
} else {
$ret = array_merge($ret, [
['label'=> __('Account Synced since'), 'value'=>$this->_options['date_sync']]
]);
}
} else {
$ret = array_merge($ret, [
['label'=>'Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized).','value'=>'']
]);
}
}
} elseif (!$this->_options) {
$ret = [
['label' => 'Error', 'value' => __('--- Invalid API Key ---')]
];
} else {
$ret = [['label' => 'Important', 'value' => __($this->_options)]];
}
return $ret;
}
private function getDateSync($mailchimpStoreId)
{
return $this->_helper->getMCMinSyncDateFlagByMailchimpStore(
$mailchimpStoreId,
0,
"default"
);
}
}
================================================
FILE: Model/Config/Source/Interest.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/13/17 12:07 PM
* @file: Interest.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class Interest implements \Magento\Framework\Option\ArrayInterface
{
private $options = null;
/**
* Interest constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Framework\App\RequestInterface $request
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Framework\App\RequestInterface $request
) {
$storeId = (int) $request->getParam("store", 0);
if ($request->getParam('website', 0)) {
$scope = 'website';
$storeId = $request->getParam('website', 0);
} elseif ($request->getParam('store', 0)) {
$scope = 'stores';
$storeId = $request->getParam('store', 0);
} else {
$scope = 'default';
}
if ($helper->getApiKey($storeId, $scope)) {
try {
$this->options = $helper->getApi($storeId, $scope)->lists->interestCategory->getAll(
$helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST, $storeId, $scope),
null,
null,
200
);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$helper->log($e->getFriendlyMessage());
}
}
}
public function toOptionArray()
{
if (is_array($this->options) && is_array($this->options['categories']) && count($this->options['categories'])) {
$rc = [];
foreach ($this->options['categories'] as $interest) {
$rc[] = ['value'=> $interest['id'], 'label' => $interest['title']];
}
} else {
$rc[] = ['value' => [], 'label' => __('---No Data---')];
}
return $rc;
}
public function toArray()
{
$rc = [];
$rc[$this->options['id']] = $this->options['name'];
return $rc;
}
}
================================================
FILE: Model/Config/Source/MonkeyList.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/28/17 10:57 AM
* @file: MonkeyStore.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class MonkeyList implements \Magento\Framework\Option\ArrayInterface
{
private $options = null;
/**
* MonkeyList constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Framework\App\RequestInterface $request
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Framework\App\RequestInterface $request
) {
$storeId = (int) $request->getParam("store", 0);
if ($request->getParam('website', 0)) {
$scope = 'website';
$storeId = $request->getParam('website', 0);
} elseif ($request->getParam('store', 0)) {
$scope = 'stores';
$storeId = $request->getParam('store', 0);
} else {
$scope = 'default';
}
if ($helper->getApiKey($storeId, $scope)) {
try {
$this->options = $helper->getApi($storeId, $scope)->lists->getLists(
$helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST, $storeId, $scope)
);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$helper->log($e->getFriendlyMessage());
}
}
}
public function toOptionArray()
{
if (is_array($this->options)) {
$rc = [];
if (isset($this->options['id'])) {
$rc[] = ['value' => $this->options['id'], 'label' => $this->options['name']];
}
} else {
$rc[] = ['value' => 0, 'label' => __('---No Data---')];
}
return $rc;
}
public function toArray()
{
$rc = [];
$rc[$this->options['id']] = $this->options['name'];
return $rc;
}
}
================================================
FILE: Model/Config/Source/MonkeyStore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/28/17 10:57 AM
* @file: MonkeyStore.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class MonkeyStore implements \Magento\Framework\Option\ArrayInterface
{
private $options = null;
/**
* MonkeyStore constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Framework\App\RequestInterface $request
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Framework\App\RequestInterface $request
) {
$storeId = (int) $request->getParam("store", 0);
if ($request->getParam('website', 0)) {
$scope = 'website';
$storeId = $request->getParam('website', 0);
} elseif ($request->getParam('store', 0)) {
$scope = 'stores';
$storeId = $request->getParam('store', 0);
} else {
$scope = 'default';
}
if ($helper->getApiKey($storeId, $scope)) {
try {
$this->options = $helper->getApi($storeId, $scope)->ecommerce->stores->get(
null,
null,
null,
\Ebizmarts\MailChimp\Helper\Data::MAXSTORES
);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$helper->log($e->getFriendlyMessage());
}
}
}
public function toOptionArray()
{
if (is_array($this->options)) {
$rc = [];
$rc[] = ['value' => -1, 'label' => 'Select one Mailchimp Store'];
foreach ($this->options['stores'] as $store) {
if ($store['platform'] == \Ebizmarts\MailChimp\Helper\Data::PLATFORM) {
if ($store['list_id']=='') {
continue;
}
if (isset($store['connected_site'])) {
$label = $store['name'];
} else {
$label = $store['name'].' (Warning: not connected)';
}
$rc[] = ['value'=> $store['id'], 'label' => $label];
}
}
} else {
$rc[] = ['value' => 0, 'label' => __('---No Data---')];
}
return $rc;
}
public function toArray()
{
$rc = [];
foreach ($this->options['stores'] as $store) {
$rc[$store['id']] = $store['name'];
}
return $rc;
}
}
================================================
FILE: Model/Config/Source/Months.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 15/09/22 12:07 PM
* @file: Months.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class Months implements \Magento\Framework\Option\ArrayInterface
{
public function toOptionArray()
{
return ["0" => __("No"), "1"=> "1", "2" =>"2", "3" => "3", "4" => "4"];
}
}
================================================
FILE: Model/Config/Source/Timeout.php
================================================
10, 20=> 20, 30=>30];
}
}
================================================
FILE: Model/Config/Source/WebhookDelete.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/31/17 11:26 AM
* @file: WebhookDelete.php
*/
namespace Ebizmarts\MailChimp\Model\Config\Source;
class WebhookDelete implements \Magento\Framework\Option\ArrayInterface
{
public function toOptionArray()
{
return [
['value' => 0, 'label'=>__('Unsubscribe')],
['value' => 1, 'label'=>__('Delete subscriber')]
];
}
}
================================================
FILE: Model/HTTP/Client/Curl.php
================================================
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @api
*/
class Curl implements \Magento\Framework\HTTP\ClientInterface
{
/**
* Max supported protocol by curl CURL_SSLVERSION_TLSv1_2
* @var int
*/
private $sslVersion;
/**
* Hostname
* @var string
*/
protected $_host = 'localhost';
/**
* @var int
*/
protected $_port = 80;
/**
* Stream resource
* @var object
*/
protected $_sock = null;
/**
* Request headers
* @var array
*/
protected $_headers = [];
/**
* Fields for POST method - hash
* @var array
*/
protected $_postFields = [];
/**
* Request cookies
* @var array
*/
protected $_cookies = [];
/**
* @var array
*/
protected $_responseHeaders = [];
/**
* @var string
*/
protected $_responseBody = '';
/**
* @var int
*/
protected $_responseStatus = 0;
/**
* Request timeout
* @var int type
*/
protected $_timeout = 300;
/**
* TODO
* @var int
*/
protected $_redirectCount = 0;
/**
* Curl
* @var resource
*/
protected $_ch;
/**
* User overrides options hash
* Are applied before curl_exec
*
* @var array
*/
protected $_curlUserOptions = [];
/**
* Header count, used while parsing headers
* in CURL callback function
* @var int
*/
protected $_headerCount = 0;
/**
* Set request timeout
*
* @param int $value value in seconds
* @return void
*/
public function setTimeout($value)
{
$this->_timeout = (int)$value;
}
/**
* @param int|null $sslVersion
*/
public function __construct($sslVersion = null)
{
$this->sslVersion = $sslVersion;
}
/**
* Set headers from hash
*
* @param array $headers
* @return void
*/
public function setHeaders($headers)
{
$this->_headers = $headers;
}
/**
* Add header
*
* @param string $name name, ex. "Location"
* @param string $value value ex. "http://google.com"
* @return void
*/
public function addHeader($name, $value)
{
$this->_headers[$name] = $value;
}
/**
* Remove specified header
*
* @param string $name
* @return void
*/
public function removeHeader($name)
{
unset($this->_headers[$name]);
}
/**
* Authorization: Basic header
*
* Login credentials support
*
* @param string $login username
* @param string $pass password
* @return void
*/
public function setCredentials($login, $pass)
{
$val = base64_encode("{$login}:{$pass}");
$this->addHeader("Authorization", "Basic {$val}");
}
/**
* Add cookie
*
* @param string $name
* @param string $value
* @return void
*/
public function addCookie($name, $value)
{
$this->_cookies[$name] = $value;
}
/**
* Remove cookie
*
* @param string $name
* @return void
*/
public function removeCookie($name)
{
unset($this->_cookies[$name]);
}
/**
* Set cookies array
*
* @param array $cookies
* @return void
*/
public function setCookies($cookies)
{
$this->_cookies = $cookies;
}
/**
* Clear cookies
*
* @return void
*/
public function removeCookies()
{
$this->setCookies([]);
}
/**
* Make GET request
*
* @param string $uri uri relative to host, ex. "/index.php"
* @return void
*/
public function get($uri)
{
$this->makeRequest("GET", $uri);
}
/**
* Make POST request
*
* String type was added to parameter $param in order to support sending JSON or XML requests.
* This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373
*
* @param string $uri
* @param array|string $params
* @return void
*
* @see \Magento\Framework\HTTP\Client#post($uri, $params)
*/
public function post($uri, $params)
{
$this->makeRequest("POST", $uri, $params);
}
public function patch($uri, $params)
{
$this->makeRequest("PATCH", $uri, $params);
}
public function put($uri, $params)
{
$this->makeRequest("PUT", $uri, $params);
}
/**
* Get response headers
*
* @return array
*/
public function getHeaders()
{
return $this->_responseHeaders;
}
/**
* Get response body
*
* @return string
*/
public function getBody()
{
return $this->_responseBody;
}
/**
* Get cookies response hash
*
* @return array
*/
public function getCookies()
{
if (empty($this->_responseHeaders['Set-Cookie'])) {
return [];
}
$out = [];
foreach ($this->_responseHeaders['Set-Cookie'] as $row) {
$values = explode("; ", $row ?? '');
$c = count($values);
if (!$c) {
continue;
}
list($key, $val) = explode("=", $values[0]);
if ($val === null) {
continue;
}
$out[trim($key)] = trim($val);
}
return $out;
}
/**
* Get cookies array with details
* (domain, expire time etc)
*
* @return array
*/
public function getCookiesFull()
{
if (empty($this->_responseHeaders['Set-Cookie'])) {
return [];
}
$out = [];
foreach ($this->_responseHeaders['Set-Cookie'] as $row) {
$values = explode("; ", $row ?? '');
$c = count($values);
if (!$c) {
continue;
}
list($key, $val) = explode("=", $values[0]);
if ($val === null) {
continue;
}
$out[trim($key)] = ['value' => trim($val)];
array_shift($values);
$c--;
if (!$c) {
continue;
}
for ($i = 0; $i < $c; $i++) {
list($subkey, $val) = explode("=", $values[$i]);
$out[trim($key)][trim($subkey)] = $val !== null ? trim($val) : '';
}
}
return $out;
}
/**
* Get response status code
*
* @see lib\Magento\Framework\HTTP\Client#getStatus()
*
* @return int
*/
public function getStatus()
{
return $this->_responseStatus;
}
/**
* Make request
*
* String type was added to parameter $param in order to support sending JSON or XML requests.
* This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373
*
* @param string $method
* @param string $uri
* @param array|string $params - use $params as a string in case of JSON or XML POST request.
*
* @return void
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function makeRequest($method, $uri, $params = [])
{
$this->_ch = curl_init();
$this->curlOption(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS);
$this->curlOption(CURLOPT_URL, $uri);
if ($method == 'POST') {
$this->curlOption(CURLOPT_POST, 1);
$this->curlOption(CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params);
} elseif ($method == "GET") {
$this->curlOption(CURLOPT_HTTPGET, 1);
} else {
$this->curlOption(CURLOPT_CUSTOMREQUEST, $method);
$this->curlOption(CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params);
}
if (count($this->_headers)) {
$heads = [];
foreach ($this->_headers as $k => $v) {
$heads[] = $k . ': ' . $v;
}
$this->curlOption(CURLOPT_HTTPHEADER, $heads);
}
if (count($this->_cookies)) {
$cookies = [];
foreach ($this->_cookies as $k => $v) {
$cookies[] = "{$k}={$v}";
}
$this->curlOption(CURLOPT_COOKIE, implode(";", $cookies));
}
if ($this->_timeout) {
$this->curlOption(CURLOPT_TIMEOUT, $this->_timeout);
}
if ($this->_port != 80) {
$this->curlOption(CURLOPT_PORT, $this->_port);
}
$this->curlOption(CURLOPT_RETURNTRANSFER, 1);
$this->curlOption(CURLOPT_HEADERFUNCTION, [$this, 'parseHeaders']);
if ($this->sslVersion !== null) {
$this->curlOption(CURLOPT_SSLVERSION, $this->sslVersion);
}
if (count($this->_curlUserOptions)) {
foreach ($this->_curlUserOptions as $k => $v) {
$this->curlOption($k, $v);
}
}
$this->_headerCount = 0;
$this->_responseHeaders = [];
$this->_responseBody = curl_exec($this->_ch);
$err = curl_errno($this->_ch);
if ($err) {
$this->doError(curl_error($this->_ch));
}
curl_close($this->_ch);
}
/**
* Throw error exception
*
* @param string $string
* @return void
* @throws \Exception
*/
public function doError($string)
{
// phpcs:ignore Magento2.Exceptions.DirectThrow
curl_close($this->_ch);
throw new \Exception($string);
}
/**
* Parse headers - CURL callback function
*
* @param resource $ch curl handle, not needed
* @param string $data
* @return int
* @throws \Exception
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
protected function parseHeaders($ch, $data)
{
$data = $data !== null ? $data : '';
if ($this->_headerCount == 0) {
$line = explode(" ", trim($data), 3);
if (count($line) < 2) {
$this->doError("Invalid response line returned from server: " . $data);
}
$this->_responseStatus = (int)$line[1];
} else {
$name = $value = '';
$out = explode(": ", trim($data), 2);
if (count($out) == 2) {
$name = $out[0];
$value = $out[1];
}
if (strlen($name)) {
if ('set-cookie' === strtolower($name)) {
$this->_responseHeaders['Set-Cookie'][] = $value;
} else {
$this->_responseHeaders[$name] = $value;
}
}
}
$this->_headerCount++;
return strlen($data);
}
/**
* Set curl option directly
*
* @param string $name
* @param mixed $value
* @return void
*/
protected function curlOption($name, $value)
{
curl_setopt($this->_ch, $name, $value);
}
/**
* Set curl options array directly
*
* @param array $arr
* @return void
*/
protected function curlOptions($arr)
{
curl_setopt_array($this->_ch, $arr);
}
/**
* Set CURL options overrides array
*
* @param array $arr
* @return void
*/
public function setOptions($arr)
{
$this->_curlUserOptions = $arr;
}
/**
* Set curl option
*
* @param string $name
* @param mixed $value
* @return void
*/
public function setOption($name, $value)
{
$this->_curlUserOptions[$name] = $value;
}
}
================================================
FILE: Model/Logger/Handler.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Model\Logger;
use Monolog;
class Handler extends \Magento\Framework\Logger\Handler\Base
{
/**
* File name
* @var string
*/
protected $fileName = '/var/log/MailChimp.log';
/**
* Logging level
* @var int
*/
protected $loggerType = Logger::INFO;
}
================================================
FILE: Model/Logger/Logger.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Model\Logger;
class Logger extends \Monolog\Logger
{
public function mailchimpLog($message, $file)
{
if ($file) {
$fileName = BP. DIRECTORY_SEPARATOR .'var'. DIRECTORY_SEPARATOR.'log'.
DIRECTORY_SEPARATOR.$file.'_Request.log';
$this->pushHandler(new \Monolog\Handler\StreamHandler($fileName));
}
try {
if ($message===null) {
$message = "NULL";
}
if (is_array($message)) {
$message = json_encode($message, JSON_PRETTY_PRINT);
}
if (is_object($message)) {
$message = json_encode($message, JSON_PRETTY_PRINT);
}
if (!empty(json_last_error())) {
$message = (string)json_last_error();
}
$message = (string)$message;
} catch (\Exception $e) {
$message = "INVALID MESSAGE";
}
$message .= "\r\n";
$this->info($message);
if ($file) {
$this->popHandler();
}
}
}
================================================
FILE: Model/MailChimpErrors.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/21/16 4:55 PM
* @file: MailChimpErrors.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpErrors extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
$this->_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpErrors::class);
}
public function getByStoreIdType($storeId, $id, $type)
{
$this->getResource()->getByStoreIdType($this, $storeId, $id, $type);
return $this;
}
public function deleteByStorePeriod($storeId, $interval, $limit)
{
return $this->getResource()->deleteByStorePeriod($this, $storeId, $interval, $limit);
}
}
================================================
FILE: Model/MailChimpInterestGroup.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/20/17 3:43 PM
* @file: MailChimpInterestGroup.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpInterestGroup extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
parent::_construct();
$this->_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpInterestGroup::class);
}
public function getBySubscriberIdStoreId($subscriberId, $storeId)
{
$this->getResource()->getBySubscriberIdStoreId($this, $subscriberId, $storeId);
return $this;
}
}
================================================
FILE: Model/MailChimpStores.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/21/16 4:55 PM
* @file: MailChimpErrors.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpStores extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
$this->_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpStores::class);
}
}
================================================
FILE: Model/MailChimpSyncBatches.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/17/16 4:07 PM
* @file: MailChimpSyncBatches.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpSyncBatches extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
$this->_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches::class);
}
}
================================================
FILE: Model/MailChimpSyncEcommerce.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/21/16 4:55 PM
* @file: MailChimpSyncEcommerce.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpSyncEcommerce extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
parent::_construct();
$this->_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce::class);
}
public function getByStoreIdType($storeId, $id, $type)
{
$this->getResource()->getByStoreIdType($this, $storeId, $id, $type);
return $this;
}
public function markAllAsDeleted($id, $type, $relatedDeletedId)
{
$this->getResource()->markAllAsDeleted($this, $id, $type, $relatedDeletedId);
return $this;
}
public function markEcommorceAsNotDeleted($id, $type)
{
$this->getResource()->markEcommorceAsNotDeleted($this, $id, $type);
return $this;
}
public function markAllAsModified($id, $type)
{
$this->getResource()->markAllAsModified($this, $id, $type);
return $this;
}
public function deleteAllByIdType($id, $type, $mailchimpStoreId)
{
$this->getResource()->deleteAllByIdType($this, $id, $type, $mailchimpStoreId);
return $this;
}
public function deleteAllByBatchid($batchId)
{
$this->getResource()->deleteAllByBatchid($this, $batchId);
}
public function deleteByTypeAndId($type, $id, $mailchimpStoreId)
{
$this->getResource()->deleteByTypeAndId($this, $type, $id, $mailchimpStoreId);
}
public function markAllAsModifiedByIds($mailchimpStoreId, $ids, $type)
{
$this->getResource()->markAllAsModifiedByIds($this, $mailchimpStoreId, $ids, $type);
}
}
================================================
FILE: Model/MailChimpSyncEcommerceFactory.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/28/17 7:24 PM
* @file: MailChimpSyncEcommerceFactory.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpSyncEcommerceFactory
{
protected $_objectManager;
protected $_instanceName;
/**
* MailChimpSyncEcommerceFactory constructor.
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param string $instanceName
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
$instanceName = \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce::class
) {
$this->_objectManager = $objectManager;
$this->_instanceName = $instanceName;
}
/**
* @param array $data
* @return \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
public function create(array $data = [])
{
return $this->_objectManager->create($this->_instanceName, $data);
}
}
================================================
FILE: Model/MailChimpWebhookRequest.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/26/17 11:32 AM
* @file: MailChimpWebhookRequest.php
*/
namespace Ebizmarts\MailChimp\Model;
class MailChimpWebhookRequest extends \Magento\Framework\Model\AbstractModel
{
protected function _construct()
{
$this->_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest::class);
}
}
================================================
FILE: Model/MailchimpNotification.php
================================================
_init(\Ebizmarts\MailChimp\Model\ResourceModel\MailchimpNotification::class);
}
}
================================================
FILE: Model/Plugin/AccountManagement.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/24/17 5:33 PM
* @file: AccountManagement.php
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
class AccountManagement
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Checkout\Model\Session
*/
protected $_session;
/**
* @var \Magento\Quote\Model\QuoteFactory
*/
protected $_quote;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* AccountManagement constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Checkout\Model\Session $checkoutSession
* @param \Magento\Quote\Model\QuoteFactory $quote
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Quote\Model\QuoteFactory $quote,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->_helper = $helper;
$this->_quote = $quote;
$this->_session = $checkoutSession;
$this->_storeManager = $storeManager;
}
/**
* @param \Magento\Customer\Model\AccountManagement $accountManagement
* @param \Closure $proceed
* @param $customerEmail
* @param null $websiteId
*/
public function aroundIsEmailAvailable(
\Magento\Customer\Model\AccountManagement $accountManagement,
\Closure $proceed,
$customerEmail,
$websiteId = null
) {
$ret = $proceed($customerEmail, $websiteId);
if ($this->_session && $this->_helper->isEmailSavingEnabled($this->_storeManager->getStore()->getId())) {
$quoteId = $this->_session->getQuoteId();
if ($quoteId) {
$quote = $this->_quote->create();
$quote->getResource()->load($quote, $quoteId);
$quote->setCustomerEmail($customerEmail);
$quote->setUpdatedAt(date('Y-m-d H:i:s'));
$quote->getResource()->save($quote);
}
}
return$ret;
}
}
================================================
FILE: Model/Plugin/Coupon.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/23/17 1:32 PM
* @file: Coupon.php
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Coupon
{
/**
* @var SyncHelper
*/
protected $syncHelper;
/**
* @param SyncHelper $syncHelper
*/
public function __construct(
SyncHelper $syncHelper
) {
$this->syncHelper = $syncHelper;
}
public function afterAfterDelete(\Magento\SalesRule\Model\Coupon $coupon)
{
$this->syncHelper->markEcommerceAsDeleted(
$coupon->getCouponId(),
\Ebizmarts\MailChimp\Helper\Data::IS_PROMO_CODE,
$coupon->getRuleId()
);
}
}
================================================
FILE: Model/Plugin/Creditmemo.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Sales\Api\CreditmemoRepositoryInterface as SalesCreditmemoRepositoryInterface;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Creditmemo
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
}
public function afterSave(
SalesCreditmemoRepositoryInterface $subject,
CreditmemoInterface $creditmemo
) {
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$creditmemo->getStoreId()
);
$this->syncHelper->saveEcommerceData(
$mailchimpStoreId,
$creditmemo->getOrderId(),
\Ebizmarts\MailChimp\Helper\Data::IS_ORDER,
null,
null,
1,
null,
null,
\Ebizmarts\MailChimp\Helper\Data::NEEDTORESYNC
);
return $creditmemo;
}
}
================================================
FILE: Model/Plugin/Invoice.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Sales\Model\Order\Invoice as SalesInvoice;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Invoice
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
}
public function afterSave(
SalesInvoice $subject,
InvoiceInterface $invoice
) {
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$invoice->getStoreId()
);
$this->syncHelper->saveEcommerceData(
$mailchimpStoreId,
$invoice->getOrderId(),
\Ebizmarts\MailChimp\Helper\Data::IS_ORDER,
null,
null,
1,
null,
null,
\Ebizmarts\MailChimp\Helper\Data::NEEDTORESYNC
);
return $invoice;
}
}
================================================
FILE: Model/Plugin/Newsletter/Save.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/27/17 8:14 PM
* @file: Save.php
*/
namespace Ebizmarts\MailChimp\Model\Plugin\Newsletter;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Save
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Customer\Model\Session
*/
protected $customerSession;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @var \Magento\Framework\App\Request\Http
*/
protected $request;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory
*/
protected $interestGroupFactory;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
* @param \Magento\Framework\App\Request\Http $request
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Customer\Model\Session $customerSession,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory,
\Magento\Framework\App\Request\Http $request
) {
$this->helper = $helper;
$this->syncHelper = $syncHelper;
$this->customerSession = $customerSession;
$this->subscriberFactory = $subscriberFactory;
$this->request = $request;
$this->interestGroupFactory = $interestGroupFactory;
}
public function afterExecute()
{
$params = $this->request->getParams();
$subscriber = $this->subscriberFactory->create();
$interestGroup = $this->interestGroupFactory->create();
/**
* @var $customer \Magento\Customer\Model\Customer
*/
$customer = $this->customerSession->getCustomer();
$email = $customer->getEmail();
try {
$subscriber->loadByCustomerId($this->customerSession->getCustomerId());
if ($subscriber->getEmail()==$email) {
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($this->helper->serialize($params));
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
$listId = $this->helper->getGeneralList($subscriber->getStoreId());
$this->_updateSubscriber($listId, $subscriber->getId(), $this->helper->getGmtDate(), null, 1);
} else {
$this->subscriberFactory->create()->subscribe($email);
$subscriber->loadByEmail($email);
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($this->helper->serialize($params));
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
}
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
$this->helper->log($params);
}
}
protected function _updateSubscriber(
$listId,
$entityId,
$sync_delta = null,
$sync_error = null,
$sync_modified = null
) {
$this->syncHelper->saveEcommerceData(
$listId,
$entityId,
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER,
$sync_delta,
$sync_error,
$sync_modified
);
}
}
================================================
FILE: Model/Plugin/Quote.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/25/17 7:40 PM
* @file: Quote.php
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Quote
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/
protected $_cookieManager;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
$this->_cookieManager = $cookieManager;
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
}
public function beforeBeforeSave(\Magento\Quote\Model\Quote $quote)
{
$mailchimp_campaign_id = $this->_cookieManager->getCookie('mailchimp_campaign_id');
if ($mailchimp_campaign_id) {
$quote->setData('mailchimp_campaign_id', $mailchimp_campaign_id);
}
$mailchimp_landing_page = $this->_cookieManager->getCookie('mailchimp_landing_page');
if ($mailchimp_landing_page) {
$quote->setData('mailchimp_landing_page', $mailchimp_landing_page);
}
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$quote->getStoreId()
);
$this->syncHelper->saveEcommerceData(
$mailchimpStoreId,
$quote->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE,
null,
0,
1,
0,
null
);
}
}
================================================
FILE: Model/Plugin/Ship.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Model\Order\Shipment as SalesShipment;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class Ship
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
private $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
}
public function afterSave(
SalesShipment $subject,
ShipmentInterface $shipment
) {
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$shipment->getStoreId()
);
$this->syncHelper->saveEcommerceData(
$mailchimpStoreId,
$shipment->getOrderId(),
\Ebizmarts\MailChimp\Helper\Data::IS_ORDER,
null,
null,
1,
null,
null,
\Ebizmarts\MailChimp\Helper\Data::NEEDTORESYNC
);
return $shipment;
}
}
================================================
FILE: Model/Plugin/Subscriber.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
namespace Ebizmarts\MailChimp\Model\Plugin;
class Subscriber
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Customer\Model\Customer
*/
protected $_customer;
/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Customer\Model\ResourceModel\CustomerRepository $customer
* @param \Magento\Customer\Model\Session $customerSession
*/
protected $_api = null;
/**
* Subscriber constructor.
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Magento\Customer\Model\ResourceModel\CustomerRepository $customer
* @param \Magento\Customer\Model\Session $customerSession
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Magento\Customer\Model\ResourceModel\CustomerRepository $customer,
\Magento\Customer\Model\Session $customerSession,
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->_helper = $helper;
$this->_customer = $customer;
$this->_customerSession = $customerSession;
$this->_storeManager = $storeManager;
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @param $customerId
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function beforeUnsubscribeCustomerById(
\Magento\Newsletter\Model\Subscriber $subscriber,
$customerId
) {
$storeId = $this->getStoreIdFromSubscriber($subscriber);
if ($this->_helper->isMailChimpEnabled($storeId)) {
if (!$this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_MAGENTO_MAIL, $storeId)) {
$subscriber->setImportMode(true);
}
$subscriber->loadByCustomerId($customerId);
if ($subscriber->isSubscribed()) {
$api = $this->_helper->getApi($storeId);
try {
$md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));
$api->lists->members->update(
$this->_helper->getDefaultList($storeId),
$md5HashEmail,
null,
'unsubscribed'
);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
}
return [$customerId];
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @param $customerId
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function beforeSubscribeCustomerById(
\Magento\Newsletter\Model\Subscriber $subscriber,
$customerId
) {
$storeId = $this->getStoreIdFromSubscriber($subscriber);
if ($this->_helper->isMailChimpEnabled($storeId)) {
$subscriber->loadByCustomerId($customerId);
if (!$subscriber->isSubscribed()) {
if (!$this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_MAGENTO_MAIL, $storeId)) {
$subscriber->setImportMode(true);
}
if ($this->_helper->isMailChimpEnabled($storeId)) {
$customer = $this->_customer->getById($customerId);
$email = $customer->getEmail();
$mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriber, $email);
$api = $this->_helper->getApi($storeId);
if ($this->_helper->isDoubleOptInEnabled($storeId)) {
$status = 'pending';
} else {
$status = 'subscribed';
}
try {
$emailHash = hash('md5', strtolower($customer->getEmail()));
$api->lists->members->addOrUpdate(
$this->_helper->getDefaultList($storeId),
$emailHash,
null,
$status,
$mergeVars,
null,
null,
null,
null,
$email,
$status
);
} catch (\Mailchimp_Error $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
}
}
return [$customerId];
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @param $email
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
public function beforeSubscribe(
\Magento\Newsletter\Model\Subscriber $subscriber,
$email
) {
$storeId = $this->getStoreIdFromSubscriber($subscriber);
if ($this->_helper->isMailChimpEnabled($storeId)) {
if (!$this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_MAGENTO_MAIL, $storeId)) {
$subscriber->setImportMode(true);
}
$storeId = $this->_storeManager->getStore()->getId();
if ($this->_helper->isMailChimpEnabled($storeId)) {
$api = $this->_helper->getApi($storeId);
if ($this->_helper->isDoubleOptInEnabled($storeId)) {
$status = 'pending';
} else {
$status = 'subscribed';
}
$mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriber, $email);
try {
$md5HashEmail = hash('md5', strtolower($email));
$return = $api->lists->members->addOrUpdate(
$this->_helper->getDefaultList($storeId),
$md5HashEmail,
null,
$status,
$mergeVars,
null,
null,
null,
null,
$email,
$status
);
} catch (\Mailchimp_Error $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
}
return [$email];
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @return null
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function beforeUnsubscribe(
\Magento\Newsletter\Model\Subscriber $subscriber
) {
$storeId = $this->getStoreIdFromSubscriber($subscriber);
if ($this->_helper->isMailChimpEnabled($storeId)) {
if (!$this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_MAGENTO_MAIL, $storeId)) {
$subscriber->setImportMode(true);
} $api = $this->_helper->getApi($storeId);
try {
$md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));
$api->lists->members->update(
$this->_helper->getDefaultList($storeId),
$md5HashEmail,
null,
'unsubscribed'
);
} catch (\Mailchimp_Error $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @return null
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function afterDelete(
\Magento\Newsletter\Model\Subscriber $subscriber
) {
$storeId = $this->getStoreIdFromSubscriber($subscriber);
if ($this->_helper->isMailChimpEnabled($storeId)) {
$api = $this->_helper->getApi($storeId);
if ($subscriber->isSubscribed()) {
try {
$md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));
if ($subscriber->getCustomerId()) {
$api->lists->members->update(
$this->_helper->getDefaultList($storeId),
$md5HashEmail,
null,
'unsubscribed'
);
} else {
$api->lists->members->delete($this->_helper->getDefaultList($storeId), $md5HashEmail);
}
} catch (\Mailchimp_Error $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
}
return null;
}
/**
* @param \Magento\Newsletter\Model\Subscriber $subscriber
* @return int
*/
protected function getStoreIdFromSubscriber(\Magento\Newsletter\Model\Subscriber $subscriber)
{
return $subscriber->getStoreId();
}
}
================================================
FILE: Model/ResourceModel/Carts/Collection.php
================================================
getSelect()
->where(
"type = 'QUO'"
);
$this->getSelect()->join(['alias' => $this->getTable('quote')], 'main_table.related_id = alias.entity_id',
['customer_id', 'customer_email','customer_firstname','customer_lastname','items_count','items_qty','created_at','updated_at','grand_total']);
return $this;
}
}
================================================
FILE: Model/ResourceModel/MailChimpErrors.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/17/16 1:57 PM
* @file: MailChimpError.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class MailChimpErrors extends AbstractDb
{
protected function _construct()
{
$this->_init('mailchimp_errors', 'id');
}
public function getByStoreIdType(\Ebizmarts\MailChimp\Model\MailChimpErrors $errors, $storeId, $id, $type)
{
$connection = $this->getConnection();
$bind = ['store_id' => $storeId, 'regtype' => $type, 'original_id' => $id];
$select = $connection->select()->from(
$this->getTable('mailchimp_errors')
)->where(
'store_id = :store_id AND regtype = :regtype AND original_id = :original_id'
);
$data = $connection->fetchRow($select, $bind);
if ($data) {
$errors->setData($data);
}
return $errors;
}
public function deleteByStorePeriod(\Ebizmarts\MailChimp\Model\MailChimpErrors $errors, $storeId, $interval, $limit)
{
$connection = $this->getConnection();
$table = $this->getTable('mailchimp_errors');
$ret = $connection->query("DELETE FROM $table WHERE date_add(added_at, interval $interval month) < now() AND store_id = $storeId LIMIT $limit");
return $ret;
}
}
================================================
FILE: Model/ResourceModel/MailChimpInterestGroup/Collection.php
================================================
_init(
\Ebizmarts\MailChimp\Model\MailChimpInterestGroup::class,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpInterestGroup::class
);
}
}
================================================
FILE: Model/ResourceModel/MailChimpInterestGroup.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/20/17 3:51 PM
* @file: MailChimpInterestGroup.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class MailChimpInterestGroup extends AbstractDb
{
protected function _construct()
{
$this->_init('mailchimp_interest_group', 'id');
}
public function getBySubscriberIdStoreId(
\Ebizmarts\MailChimp\Model\MailChimpInterestGroup $mailChimpInterestGroup,
$subscriberId,
$storeId
) {
$connection = $this->getConnection();
$bind = ['subscriber_id'=>$subscriberId, 'store_id' => $storeId];
$select = $connection->select()->from(
$this->getTable('mailchimp_interest_group')
)->where(
'subscriber_id = :subscriber_id AND store_id = :store_id'
);
$data = $connection->fetchRow($select, $bind);
if ($data) {
$mailChimpInterestGroup->setData($data);
}
return $mailChimpInterestGroup;
}
}
================================================
FILE: Model/ResourceModel/MailChimpStores/Collection.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/27/17 1:22 PM
* @file: Collection.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel\MailChimpStores;
class Collection extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{
protected function _construct()
{
$this->_init(
\Ebizmarts\MailChimp\Model\MailChimpStores::class,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpStores::class
);
}
}
================================================
FILE: Model/ResourceModel/MailChimpStores/Grid/Collection.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/3/17 11:42 AM
* @file: MailChimpStores.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class MailChimpStores extends AbstractDb
{
protected function _construct()
{
$this->_init('mailchimp_stores', 'id');
}
}
================================================
FILE: Model/ResourceModel/MailChimpSyncBatches/Collection.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/21/16 4:16 PM
* @file: Collection.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init(
\Ebizmarts\MailChimp\Model\MailChimpSyncBatches::class,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches::class
);
}
}
================================================
FILE: Model/ResourceModel/MailChimpSyncBatches.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/17/16 2:27 PM
* @file: MailChimpSyncBatches.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class MailChimpSyncBatches extends AbstractDb
{
protected function _construct()
{
$this->_init('mailchimp_sync_batches', 'id');
}
}
================================================
FILE: Model/ResourceModel/MailChimpSyncEcommerce/Collection.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 12/1/16 2:36 PM
* @file: Collection.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce::class,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce::class
);
}
}
================================================
FILE: Model/ResourceModel/MailChimpSyncEcommerce.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 12/1/16 2:33 PM
* @file: MailChimpSyncEcommerce.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class MailChimpSyncEcommerce extends AbstractDb
{
protected function _construct()
{
$this->_init('mailchimp_sync_ecommerce', 'id');
}
public function getByStoreIdType(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp, $storeId, $id, $type)
{
$connection = $this->getConnection();
$bind = ['store_id' => $storeId, 'type' => $type, 'related_id' => $id];
$select = $connection->select()->from(
$this->getTable('mailchimp_sync_ecommerce')
)->where(
'mailchimp_store_id = :store_id AND type = :type AND related_id = :related_id'
);
$data = $connection->fetchRow($select, $bind);
if ($data) {
$chimp->setData($data);
}
return $chimp;
}
public function markAllAsDeleted(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp,
$id,
$type,
$relatedDeletedId
) {
$connection = $this->getConnection();
$connection->update(
$this->getTable('mailchimp_sync_ecommerce'),
['mailchimp_sync_deleted'=>1, 'deleted_related_id'=> $relatedDeletedId, 'mailchimp_sent'=> \Ebizmarts\Mailchimp\Helper\Data::NEEDTORESYNC],
['related_id = ?'=> $id,'type = ?'=>$type]
);
return $this;
}
public function markEcommorceAsNotDeleted(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp,
$id,
$type
) {
$connection = $this->getConnection();
$connection->update(
$this->getTable('mailchimp_sync_ecommerce'),
['mailchimp_sync_deleted'=>0, 'mailchimp_sync_error' => null,'mailchimp_sync_modified'=>0,'mailchimp_sent'=>\Ebizmarts\MailChimp\Helper\Data::WAITINGSYNC],
['related_id = ?'=> $id,'type = ?'=>$type]
);
return $this;
}
public function markAllAsModified(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp, $id, $type)
{
$connection = $this->getConnection();
$connection->update(
$this->getTable('mailchimp_sync_ecommerce'),
['mailchimp_sync_modified'=>1,'mailchimp_sent'=>\Ebizmarts\MailChimp\Helper\Data::NEEDTORESYNC,'batch_id'=>null],
['related_id = ?'=> $id, 'type = ?'=>$type]
);
return $this;
}
public function deleteAllByIdType(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp,
$id,
$type,
$mailchimpStoreId
) {
$connection = $this->getConnection();
$connection->delete(
$this->getTable('mailchimp_sync_ecommerce'),
['related_id = ?'=> $id, 'type = ?'=>$type, 'mailchimp_store_id = ?' => $mailchimpStoreId]
);
return $this;
}
public function deleteAllByBatchId(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp, $batchId)
{
$connection = $this->getConnection();
$connection->delete($this->getTable('mailchimp_sync_ecommerce'), ['batch_id = ?' => $batchId]);
return $this;
}
public function deleteByTypeAndId(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp, $type, $id, $mailchimpStoreId)
{
$connection = $this->getConnection();
$connection->delete($this->getTable('mailchimp_sync_ecommerce'), ['type = ?' => $type, 'related_id = ?' => $id, 'mailchimp_store_id = ?' => $mailchimpStoreId]);
return $this;
}
public function markAllAsModifiedByIds(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimp, $mailchimpStore, $ids, $type)
{
$connection = $this->getConnection();
$connection->update(
$this->getTable('mailchimp_sync_ecommerce'),
['mailchimp_sync_modified'=>1],
['related_id in (?)'=> $ids, 'type = ?'=>$type, 'mailchimp_store_id = ?'=>$mailchimpStore]
);
return $this;
}
}
================================================
FILE: Model/ResourceModel/MailChimpWebhookRequest/Collection.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/26/17 11:36 AM
* @file: Collection.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init(
\Ebizmarts\MailChimp\Model\MailChimpWebhookRequest::class,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest::class
);
}
}
================================================
FILE: Model/ResourceModel/MailChimpWebhookRequest.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/26/17 11:33 AM
* @file: MailChimpWebhookRequest.php
*/
namespace Ebizmarts\MailChimp\Model\ResourceModel;
use Magento\Framework\DB\Select;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class MailChimpWebhookRequest extends AbstractDb
{
protected function _construct()
{
$this->_init('mailchimp_webhook_request', 'id');
}
}
================================================
FILE: Model/ResourceModel/MailchimpNotification/Collection.php
================================================
_init(
\Ebizmarts\MailChimp\Model\MailchimpNotification::class,
\Ebizmarts\MailChimp\Model\ResourceModel\MailchimpNotification::class
);
}
}
================================================
FILE: Model/ResourceModel/MailchimpNotification.php
================================================
_init('mailchimp_notification', 'id');
}
}
================================================
FILE: Model/ResourceModel/Schedule/Collection.php
================================================
getSelect()
->where(
"job_code IN (
'ebizmarts_webhooks',
'ebizmarts_ecommerce',
'ebizmarts_clean_webhooks',
'ebizmarts_clean_batches',
'ebizmarts_clean_errors'
)"
);
return $this;
}//end _initSelect()
}//end class
================================================
FILE: Observer/Adminhtml/Customer/SaveAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 12/1/17 2:21 PM
* @file: SaveAfter.php
*/
namespace Ebizmarts\MailChimp\Observer\Adminhtml\Customer;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class SaveAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory
*/
protected $interestGroupFactory;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
* @param \Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
\Ebizmarts\MailChimp\Model\MailChimpInterestGroupFactory $interestGroupFactory
) {
$this->helper = $helper;
$this->syncHelper = $syncHelper;
$this->subscriberFactory = $subscriberFactory;
$this->interestGroupFactory = $interestGroupFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$customer = $observer->getCustomer();
$request = $observer->getEvent()->getRequest();
$allParams = $request->getParams();
$subscriber = $this->subscriberFactory->create();
if (isset($allParams['customer']['interestgroup'])) {
$params = ['group' => $allParams['customer']['interestgroup']];
foreach ($params['group'] as $index => $ig) {
if (is_array($ig)) {
foreach ($ig as $i => $v) {
if ($v == 1) {
$params['group'][$index][$i] = $i;
}
}
}
}
$interestGroup = $this->interestGroupFactory->create();
try {
$subscriber->loadByEmail($customer->getEmail());
if ($subscriber->getEmail() == $customer->getEmail()) {
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($this->helper->serialize($params));
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
$this->syncHelper->markRegisterAsModified(
$subscriber->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER
);
} else {
$this->subscriberFactory->create()->subscribe($customer->getEmail());
$subscriber->loadByEmail($customer->getEmail());
$interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());
$interestGroup->setGroupdata($this->helper->serialize($params));
$interestGroup->setSubscriberId($subscriber->getSubscriberId());
$interestGroup->setStoreId($subscriber->getStoreId());
$interestGroup->setUpdatedAt($this->helper->getGmtDate());
$interestGroup->getResource()->save($interestGroup);
}
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
$this->helper->log($params);
}
} else {
$subscriber->loadByEmail($customer->getEmail());
if ($subscriber->getEmail() == $customer->getEmail()) {
$this->syncHelper->markRegisterAsModified(
$subscriber->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER
);
}
}
$this->syncHelper->markRegisterAsModified($customer->getId(), \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER);
}
}
================================================
FILE: Observer/Adminhtml/Product/DeleteAfter.php
================================================
helper = $helper;
$this->syncHelper = $syncHelper;
$this->configurable = $configurable;
}
function execute(Observer $observer)
{
$product = $observer->getProduct();
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$product->getStoreId()
);
$this->_updateProduct($product->getId());
}
protected function _updateProduct($entityId)
{
$this->syncHelper->markEcommerceAsDeleted($entityId, \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT);
}
}
================================================
FILE: Observer/Adminhtml/Product/ImportAfter.php
================================================
helper = $helper;
$this->syncHelper = $syncHelper;
$this->productCollectionFactory = $productCollectionFactory;
}
public function execute(Observer $observer)
{
try {
$bunch = $observer->getBunch();
$counter = 0;
$skus = [];
foreach ($bunch as $product) {
if ($counter % 100 == 0 && count($skus)) {
$this->updateSkus($skus);
$skus =[];
}
$sku = $product['sku'];
if (key_exists('_store', $product)&&!empty($product['_store'])) {
$storeId = $product['_store'];
} else {
$storeId = 0;
}
$skus[$storeId][]=$sku;
$counter++;
}
if (count($skus)) {
$this->updateSkus($skus);
}
} catch (\Exception $e) {
$this->helper->log($e->getMessage());
}
}
protected function updateSkus($skus)
{
foreach ($skus as $storeId => $storeskus) {
/**
* @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection
*/
$collection = $this->productCollectionFactory->create();
$collection->addStoreFilter($storeId);
$collection->addFieldToFilter('sku', ['in'=>$storeskus]);
$collection->addFieldToSelect('id');
$productIds = [];
foreach ($collection as $item) {
$productIds[] = $item->getId();
}
$this->markAsModified($storeId, $productIds);
}
}
protected function markAsModified($storeId,$productsIds)
{
$mailchimpStoreId = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
$this->syncHelper->markAllAsModifiedByIds($mailchimpStoreId, $productsIds, \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT);
}
}
================================================
FILE: Observer/Adminhtml/Product/SaveAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 1/18/18 12:30 PM
* @file: SaveAfter.php
*/
namespace Ebizmarts\MailChimp\Observer\Adminhtml\Product;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class SaveAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable
*/
protected $configurable;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $configurable
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $configurable
) {
$this->helper = $helper;
$this->syncHelper = $syncHelper;
$this->configurable = $configurable;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
/**
* @var \Magento\Catalog\Model\Product $product
*/
$product = $observer->getProduct();
$mailchimpStore = $this->helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$product->getStoreId()
);
if ($product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE) {
$parents = $this->configurable->getParentIdsByChild($product->getId());
if (is_array($parents)) {
foreach ($parents as $parentid) {
$this->_updateProduct($parentid);
}
} elseif ($parents) {
$this->_updateProduct($parents);
}
}
$this->_updateProduct($product->getId());
}
protected function _updateProduct($entityId)
{
$this->syncHelper->markRegisterAsModified($entityId, \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT);
}
}
================================================
FILE: Observer/ConfigObserver.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/23/17 12:22 PM
* @file: ConfigObserver.php
*/
namespace Ebizmarts\MailChimp\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer as EventObserver;
class ConfigObserver implements ObserverInterface
{
/**
* @var \Magento\Store\Model\StoreManager
*/
protected $_storeManager;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Framework\Registry
*/
protected $_registry;
/**
* ConfigObserver constructor.
* @param \Magento\Store\Model\StoreManager $storeManager
* @param \Magento\Framework\Registry $registry
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
\Magento\Store\Model\StoreManager $storeManager,
\Magento\Framework\Registry $registry,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
$this->_helper = $helper;
$this->_storeManager = $storeManager;
$this->_registry = $registry;
}
public function execute(EventObserver $observer)
{
$oldListId = $this->_registry->registry('oldListId');
$apiKey = $this->_registry->registry('apiKey');
$mustDelete = true;
foreach ($this->_storeManager->getStores() as $storeId => $val) {
$listId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_LIST, $storeId);
if ($listId == $oldListId) {
$mustDelete = false;
}
}
if ($mustDelete) {
$this->_helper->deleteWebHook($apiKey, $oldListId);
}
$this->_registry->unregister('oldListId');
$this->_registry->unregister('apiKey');
}
}
================================================
FILE: Observer/Customer/SaveBefore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/8/17 5:07 PM
* @file: SafeAfter.php
*/
namespace Ebizmarts\MailChimp\Observer\Customer;
use Magento\Framework\Event\Observer;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class SaveBefore implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->subscriberFactory = $subscriberFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
/**
* @var $customer \Magento\Customer\Model\Customer
*/
$customer = $observer->getCustomer();
$storeId = $customer->getStoreId();
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ACTIVE)) {
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ECOMMERCE_ACTIVE)) {
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$storeId
);
$this->syncHelper->saveEcommerceData(
$mailchimpStoreId,
$customer->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER,
null,
null,
1
);
}
$subscriber = $this->subscriberFactory->create();
$subscriber->loadByEmail($customer->getEmail());
if ($subscriber->getEmail() == $customer->getEmail()) {
$this->syncHelper->markRegisterAsModified(
$subscriber->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_SUBSCRIBER
);
}
}
}
}
================================================
FILE: Observer/Sales/Order/SaveAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 2/15/17 3:38 PM
* @file: SaveAfter.php
*/
namespace Ebizmarts\MailChimp\Observer\Sales\Order;
use Magento\Framework\Event\Observer;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class SaveAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param SyncHelper $syncHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
SyncHelper $syncHelper
) {
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$order = $observer->getEvent()->getOrder();
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$order->getStoreId()
);
$this->syncHelper->saveEcommerceData(
$mailchimpStoreId,
$order->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_ORDER,
null,
null,
1,
null,
null,
\Ebizmarts\MailChimp\Helper\Data::NEEDTORESYNC
);
}
}
================================================
FILE: Observer/Sales/Order/SubmitAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/26/17 12:36 PM
* @file: SubmitAfter.php
*/
namespace Ebizmarts\MailChimp\Observer\Sales\Order;
use Magento\Framework\Event\Observer;
class SubmitAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Magento\Framework\Stdlib\CookieManagerInterface
*/
protected $_cookieManager;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
protected $_cookieMetadataFactory;
/**
* @var \Magento\Framework\Session\SessionManagerInterface
*/
protected $_sessionManager;
/**
* SubmitAfter constructor.
* @param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
* @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $metadataFactory
* @param \Magento\Framework\Session\SessionManagerInterface $sessionManager
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
\Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $metadataFactory,
\Magento\Framework\Session\SessionManagerInterface $sessionManager,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
$this->_cookieManager = $cookieManager;
$this->_helper = $helper;
$this->_cookieMetadataFactory = $metadataFactory;
$this->_sessionManager = $sessionManager;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
try {
$this->_cookieManager->deleteCookie(
'mailchimp_campaign_id',
$this->_cookieMetadataFactory
->createCookieMetadata()
->setPath($this->_sessionManager->getCookiePath())
->setDomain($this->_sessionManager->getCookieDomain())
);
$this->_cookieManager->deleteCookie(
'mailchimp_landing_page',
$this->_cookieMetadataFactory
->createCookieMetadata()
->setPath($this->_sessionManager->getCookiePath())
->setDomain($this->_sessionManager->getCookieDomain())
);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
return $this;
}
}
================================================
FILE: Observer/Sales/Order/SubmitBefore.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/14/17 11:26 PM
* @file: SaveBefore.php
*/
namespace Ebizmarts\MailChimp\Observer\Sales\Order;
use Magento\Framework\Event\Observer;
class SubmitBefore implements \Magento\Framework\Event\ObserverInterface
{
private $attributes = [
'mailchimp_abandonedcart_flag',
'mailchimp_campaign_id',
'mailchimp_landing_page'
];
public function execute(\Magento\Framework\Event\Observer $observer)
{
/* @var \Magento\Sales\Model\Order $order */
$order = $observer->getEvent()->getData('order');
/* @var \Magento\Quote\Model\Quote $quote */
$quote = $observer->getEvent()->getData('quote');
$flag = 0;
foreach ($this->attributes as $attribute) {
if ($quote->hasData($attribute)) {
$order->setData($attribute, $quote->getData($attribute));
if ($quote->getData($attribute)) {
$flag = 1;
}
}
}
$order->setData('mailchimp_flag', $flag);
return $this;
}
}
================================================
FILE: Observer/SalesRule/Rule/DeleteAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/19/17 5:26 PM
* @file: DeleteAfter.php
*/
namespace Ebizmarts\MailChimp\Observer\SalesRule\Rule;
use Magento\Framework\Event\Observer;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class DeleteAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
protected $_ecommerce;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce
* @param SyncHelper $syncHelper
*/
public function __construct(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce,
SyncHelper $syncHelper
) {
$this->_ecommerce = $ecommerce;
$this->syncHelper = $syncHelper;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
$rule = $observer->getEvent()->getRule();
$ruleId = $rule->getRuleId();
$this->syncHelper->markEcommerceAsDeleted($ruleId, \Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE);
}
}
================================================
FILE: Observer/SalesRule/Rule/SaveAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/19/17 4:14 PM
* @file: Rule.php
*/
namespace Ebizmarts\MailChimp\Observer\SalesRule\Rule;
use Magento\Framework\Event\Observer;
use Ebizmarts\MailChimp\Helper\Sync as SyncHelper;
class SaveAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
protected $_ecommerce;
/**
* @var SyncHelper
*/
protected $syncHelper;
protected $_date;
/**
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce
* @param SyncHelper $syncHelper
* @param \Magento\Framework\Stdlib\DateTime\DateTime $date
*/
public function __construct(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce,
SyncHelper $syncHelper,
\Magento\Framework\Stdlib\DateTime\DateTime $date
) {
$this->_ecommerce = $ecommerce;
$this->syncHelper = $syncHelper;
$this->_date = $date;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
/**
* @var $rule \Magento\SalesRule\Model\Rule
*/
$rule = $observer->getEvent()->getRule();
$ruleId = $rule->getRuleId();
$this->syncHelper->markRegisterAsModified($ruleId, \Ebizmarts\MailChimp\Helper\Data::IS_PROMO_RULE);
}
}
================================================
FILE: Observer/Subscriber/SaveAfter.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 11/9/17 5:20 PM
* @file: SaveBefore.php
*/
namespace Ebizmarts\MailChimp\Observer\Subscriber;
use Magento\Framework\Event\Observer;
class SaveAfter implements \Magento\Framework\Event\ObserverInterface
{
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce
*/
protected $_ecommerce;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Ebizmarts\MailChimp\Model\Api\Subscriber
*/
protected $_subscriberApi;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $_subscriberFactory;
/**
* SaveBefore constructor.
* @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce
* @param \Ebizmarts\MailChimp\Helper\Data $helper
* @param \Ebizmarts\MailChimp\Model\Api\Subscriber $subscriberApi
* @param \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
*/
public function __construct(
\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce,
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\Api\Subscriber $subscriberApi,
\Magento\Newsletter\Model\SubscriberFactory $subscriberFactory
) {
$this->_ecommerce = $ecommerce;
$this->_helper = $helper;
$this->_subscriberApi = $subscriberApi;
$this->_subscriberFactory = $subscriberFactory;
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
/**
* @var $subscriber \Magento\Newsletter\Model\Subscriber
*/
$factory = $this->_subscriberFactory->create();
$subscriber = $observer->getSubscriber();
$subscriberOld = $factory->loadByCustomerId($subscriber->getCustomerId());
if ($this->_helper->isMailChimpEnabled($subscriberOld->getStoreId()) && $subscriber->getEmail() != $subscriberOld->getEmail()) {
$api = $this->_helper->getApi($subscriberOld->getStoreId());
$mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriberOld, $subscriberOld->getEmail());
$status = 'unsubscribed';
try {
$md5HashEmail = hash('md5', strtolower($subscriberOld->getEmail()));
$return = $api->lists->members->addOrUpdate(
$this->_helper->getDefaultList($subscriberOld->getStoreId()),
$md5HashEmail,
null,
$status,
$mergeVars,
null,
null,
null,
null,
$subscriberOld->getEmail(),
$status
);
} catch (\Mailchimp_Error | \Mailchimp_HttpError $e) {
$this->_helper->log($e->getFriendlyMessage());
}
}
$this->_subscriberApi->update($subscriber);
}
}
================================================
FILE: README.md
================================================
Labels applied by the team
| Label | Description |
| ------------- |-------------|
|  | Bug report contains sufficient information to reproduce. Will be solved for associated Milestone.|
|  | Improvement accepted. Will be added for associated Milestone.|
|  | Issue has been solved and will be applied in the associated Milestone. |
|  | Issue has been already reported and will be closed with no further action. |
|  | Issue has not been created according to requirements at the [Issue reporting guidelines](https://github.com/mailchimp/mc-magento2/wiki/Issue-reporting-guidelines). Will be closed until requirements are met. |
|  | Feature request to be considered by the team. After approval will be labeled as enhancement. |
|  | The team was not able to replicate issue. It will be closed until missing information is given. |
|  | Contact our support team at mailchimp@ebizmarts-desk.zendesk.com. Issue will be closed with no further action. |
|  | Issue is considered as low priority by the team. |
|  | Issue is considered as high priority by the team. |
|  | Issue reports a conflict with other third party extension. |
|  | Feedback is required to continue working on the issue. If there is no answer after a week it will be closed. |
|  | Issue can not be solved due to external causes. |
|  | Issue will be closed. Available documentation: [MailChimp For Magento doc](https://kb.mailchimp.com/integrations/e-commerce/connect-or-disconnect-mailchimp-for-magento-2)|
# Issue reporting guidelines
To maintain an effective bugfix workflow and make sure issues will be solved in a timely manner we kindly ask reporters to follow some simple guidelines.
Before creating an issue, please do the following:
* Check the [documentation](https://kb.mailchimp.com/integrations/e-commerce/connect-or-disconnect-mailchimp-for-magento-2) to make sure the behavior you are reporting is really a bug, not a feature.
* Check the existing [issues](https://github.com/mailchimp/mc-magento2/issues) to make sure you are not duplicating somebody’s work.
* Make sure, that information you are about to report is a technical issue, please refer to the [Community Forums](http://ebizmarts.com/mailchimp-for-magento-support) for technical questions.
If you are sure that the problem you are experiencing is caused by a bug, file a new issue in a Github issue tracker following the recommendations below.
## Title
Title is a vital part of bug report for developer and triager to quickly identify a unique issue. A well written title should contain a clear, brief explanation of the issue, making emphasis on the most important points.
Good example would be:
> Unable to place order with Virtual product and PayPal.
Unclear example:
> Can't checkout.
## Issue Description
### Preconditions
Describing preconditions is a great start, provide information on system configuration settings you have changed, detailed information on entities created (Products, Customers, etc), Magento and mc-magento versions. Basically, everything that would help developer set up the same environment as you have.
Example:
1. Magento CE 2.0.1 without sample data is installed.
2. mc-magento 1.0.6.
3. Test category is set up.
4. Virtual Product is created and assigned to the Test Category.
...
### Steps to reproduce
This part of the bug report is the most important, as developer will use this information to reproduce the issue. Problem is more likely to be fixed if it can be reproduced.
Precisely describe each step you have taken to reproduce the issue. Try to include as much information as possible, sometimes even minor differences can be crucial.
Example:
1. Navigate to storefront as a guest.
2. Open Test Category.
3. Click "Add to Cart" on the Virtual Product.
4. Open mini shopping cart and click "Proceed to Checkout".
...
### Actual and Expected result
To make sure that everybody involved in the fix are on the same page, precisely describe the result you expected to get and the result you actually observed after performing the steps.
Example:
Expected result:
Order is placed successfully, customer is redirected to the success page.
Actual result:
"Place order" button is not visible, order cannot be placed.
### Additional information
Additional information is often requested when the bug report is processed, you can save time by providing Magento and browser logs, screenshots, any other artifacts related to the issue at your own judgement.
## Pull requests
Before creating a pull request please make sure to follow this [guidelines](https://github.com/mailchimp/mc-magento2/wiki/Pull-Request-guideliness) or it will be rejected.
================================================
FILE: Setup/InstallData.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/7/16 1:30 PM
* @file: InstallSchema.php
*/
namespace Ebizmarts\MailChimp\Setup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
return;
}
}
================================================
FILE: Setup/InstallSchema.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/7/16 3:36 PM
* @file: InstallSchema.php
*/
namespace Ebizmarts\MailChimp\Setup;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Symfony\Component\Config\Definition\Exception\Exception;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\DeploymentConfig;
class InstallSchema implements InstallSchemaInterface
{
/**
* @var ResourceConnection
*/
protected $_resource;
/**
* @var DeploymentConfig
*/
protected $_deploymentConfig;
/**
* @var \Magento\Framework\Filesystem\Driver\File
*/
protected $_driver;
/**
* InstallSchema constructor.
* @param ResourceConnection $resource
* @param DeploymentConfig $deploymentConfig
* @param \Magento\Framework\Filesystem\Driver\File $driver
*/
public function __construct(
ResourceConnection $resource,
DeploymentConfig $deploymentConfig,
\Magento\Framework\Filesystem\Driver\File $driver
) {
$this->_resource = $resource;
$this->_deploymentConfig = $deploymentConfig;
$this->_driver = $driver;
}
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$connection = $this->_resource->getConnectionByName('default');
$table = $connection
->newTable($setup->getTable('mailchimp_sync_batches'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Batch Id'
)
->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'Store Id'
)
->addColumn(
'mailchimp_store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'Store Id'
)
->addColumn(
'batch_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
24,
[],
'Batch Id'
)
->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
10,
[],
'Status'
)
->addColumn(
'carts_new_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of new carts'
)
->addColumn(
'customers_new_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of new customers'
)
->addColumn(
'orders_new_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of new orders'
)
->addColumn(
'products_new_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of new products'
)
->addColumn(
'subscribers_new_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of new carts'
)
->addColumn(
'carts_modified_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of modified carts'
)
->addColumn(
'customers_modified_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of modified customers'
)
->addColumn(
'orders_modified_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of modified orders'
)
->addColumn(
'products_modified_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of modified products'
)
->addColumn(
'subscribers_modified_count',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
null,
[],
'Number of modified carts'
);
$connection->createTable($table);
$table = $connection
->newTable($setup->getTable('mailchimp_errors'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Batch Id'
)
->addColumn(
'mailchimp_store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'Store Id'
)
->addColumn(
'type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
256,
[],
'type'
)
->addColumn(
'title',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'title'
)
->addColumn(
'status',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'status'
)
->addColumn(
'errors',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
256,
[],
'errors'
)
->addColumn(
'regtype',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
[],
'regtype'
);
$connection->createTable($table);
$table = $connection
->newTable($setup->getTable('mailchimp_sync_ecommerce'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)
->addColumn(
'mailchimp_store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'Store Id'
)
->addColumn(
'type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
24,
[],
'Type of register'
)
->addColumn(
'related_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
[],
'Id of the related entity'
)
->addColumn(
'mailchimp_sync_modified',
\Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
null,
[],
'If the entity was modified'
)
->addColumn(
'mailchimp_sync_delta',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
[],
'Sync Delta'
)->addColumn(
'mailchimp_sync_error',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
[],
'Error on synchronization'
)->addColumn(
'mailchimp_sync_deleted',
\Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
null,
[],
'If the object was deleted in mailchimp'
)->addColumn(
'mailchimp_token',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
32,
[],
'Quote token'
);
$connection->createTable($table);
if ($this->_deploymentConfig->get(
\Magento\Framework\Config\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/sales'
)
) {
$connection = $this->_resource->getConnectionByName('sales');
}
$connection->addColumn(
$setup->getTable('sales_order'),
'mailchimp_abandonedcart_flag',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
'default' => 0,
'comment' => 'Retrieved from Mailchimp'
]
);
if ($this->_deploymentConfig->get(
\Magento\Framework\Config\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/checkout'
)
) {
$connection = $this->_resource->getConnectionByName('checkout');
}
$connection->addColumn(
$setup->getTable('quote'),
'mailchimp_abandonedcart_flag',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
'default' => 0,
'comment' => 'Retrieved from Mailchimp'
]
);
$path = BP . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'Mailchimp';
if (!$this->_driver->isDirectory($path)) {
$this->_driver->createDirectory($path);
}
}
}
================================================
FILE: Setup/Uninstall.php
================================================
[
'mailchimp_abandonedcart_flag',
'mailchimp_campaign_id',
'mailchimp_landing_page',
'mailchimp_flag'
],
'quote' => [
'mailchimp_abandonedcart_flag',
'mailchimp_campaign_id',
'mailchimp_landing_page'
],
'sales_order_grid' => [
'mailchimp_flag'
]
];
$installer = $setup;
$installer->startSetup();
$connection = $installer->getConnection();
foreach ($tables as $table) {
$connection->dropTable($setup->getTable($table));
}
foreach($tablesFields as $table => $columnArray) {
foreach($columnArray as $column) {
$connection->dropColumn( $setup->getTable($table), $column);
}
}
$installer->endSetup();
}
}
================================================
FILE: Setup/UpgradeData.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/31/16 3:28 PM
* @file: UpgradeData.php
*/
namespace Ebizmarts\MailChimp\Setup;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\DeploymentConfig;
use Magento\Sales\Model\OrderFactory;
use Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory as SyncCollectionFactory;
class UpgradeData implements UpgradeDataInterface
{
/**
* @var ResourceConnection
*/
protected $_resource;
/**
* @var DeploymentConfig
*/
protected $_deploymentConfig;
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpInterestGroup\CollectionFactory
*/
protected $_insterestGroupCollectionFactory;
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\CollectionFactory
*/
protected $_webhookCollectionFactory;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $_helper;
/**
* @var \Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory
*/
protected $configFactory;
/**
* @var SyncCollectionFactory
*/
private $syncCollectionFactory;
/**
* @var OrderFactory
*/
private $orderFactory;
/**
* @param ResourceConnection $resource
* @param DeploymentConfig $deploymentConfig
* @param \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpInterestGroup\CollectionFactory $interestGroupCollectionFactory
* @param \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\CollectionFactory $webhookCollectionFactory
* @param \Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory $configFactory
* @param SyncCollectionFactory $syncCollectionFactory
* @param OrderFactory $orderFactory
* @param \Ebizmarts\MailChimp\Helper\Data $helper
*/
public function __construct(
ResourceConnection $resource,
DeploymentConfig $deploymentConfig,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpInterestGroup\CollectionFactory $interestGroupCollectionFactory,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest\CollectionFactory $webhookCollectionFactory,
\Magento\Config\Model\ResourceModel\Config\Data\CollectionFactory $configFactory,
SyncCollectionFactory $syncCollectionFactory,
OrderFactory $orderFactory,
\Ebizmarts\MailChimp\Helper\Data $helper
) {
$this->_resource = $resource;
$this->_deploymentConfig = $deploymentConfig;
$this->_insterestGroupCollectionFactory = $interestGroupCollectionFactory;
$this->_webhookCollectionFactory = $webhookCollectionFactory;
$this->configFactory = $configFactory;
$this->syncCollectionFactory = $syncCollectionFactory;
$this->orderFactory = $orderFactory;
$this->_helper = $helper;
}
/**
* @param ModuleDataSetupInterface $setup
* @param ModuleContextInterface $context
*/
public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
if (version_compare($context->getVersion(), '1.0.24') < 0) {
$setup->startSetup();
$connection = $this->_resource->getConnectionByName('default');
if ($this->_deploymentConfig->get(
\Magento\Framework\Config\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/sales'
)
) {
$salesConnection = $this->_resource->getConnectionByName('sales');
} else {
$salesConnection = $connection;
}
$table = $setup->getTable('sales_order');
$select = $salesConnection->select()
->from(
false,
['mailchimp_flag' => new \Zend_Db_Expr('IF(mailchimp_abandonedcart_flag OR mailchimp_campaign_id OR mailchimp_landing_page, 1, 0)')]
)->join(['O'=>$table], 'O.entity_id = G.entity_id', []);
$query = $salesConnection->updateFromSelect($select, ['G' => $setup->getTable('sales_order_grid')]);
$salesConnection->query($query);
$setup->endSetup();
}
if (version_compare($context->getVersion(), '1.2.32') < 0) {
// delete the old serialized data from core_config_data
$setup->startSetup();
$connection = $this->_resource->getConnectionByName('default');
$table = $setup->getTable('core_config_data');
try {
$connection->delete($table, ['path = ?'=> \Ebizmarts\MailChimp\Helper\Data::XML_MERGEVARS]);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
// empty table mailchimp_interest_group
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpInterestGroup $item
*/
$table = $setup->getTable('mailchimp_interest_group');
try {
$connection->delete($table);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
// convert table mailchimp_webhook_request
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpWebhookRequest $webhookItem
*/
$lastId = 0;
$done = false;
while (!$done) {
$webhookCollection = $this->_webhookCollectionFactory->create();
$webhookCollection->addFieldToFilter('processed', ['neq' => 1]);
$webhookCollection->addFieldToFilter('id', ['gt' => $lastId]);
$webhookCollection->getSelect()->limit(500);
if (!$webhookCollection->getSize()) {
$done = true;
} else {
foreach ($webhookCollection as $webhookItem) {
try {
$webhookItem->setProcessed(\Ebizmarts\MailChimp\Cron\Webhook::DATA_NOT_CONVERTED);
$webhookItem->getResource()->save($webhookItem);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
$webhookItem->setProcesed(\Ebizmarts\MailChimp\Cron\Webhook::DATA_WITH_ERROR);
$webhookItem->getResource()->save($webhookItem);
}
$lastId = $webhookItem->getId();
}
}
}
}
if (version_compare($context->getVersion(), '102.3.35') < 0) {
$configCollection = $this->configFactory->create();
$configCollection->addFieldToFilter('path', ['eq' => \Ebizmarts\MailChimp\Helper\Data::XML_PATH_APIKEY]);
/**
* @var $config \Magento\Config\Model\ResourceModel\Config
*/
foreach ($configCollection as $config) {
try {
$config->setValue($this->_helper->encrypt($config->getvalue()));
$config->getResource()->save($config);
} catch (\Exception $e) {
$this->_helper->log($e->getMessage());
}
}
$configCollection = $this->configFactory->create();
$configCollection->addFieldToFilter(
'path',
['eq' => \Ebizmarts\MailChimp\Helper\Data::XML_PATH_APIKEY_LIST]
);
foreach ($configCollection as $config) {
$config->getResource()->delete($config);
}
}
}
}
================================================
FILE: Setup/UpgradeSchema.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 10/31/16 5:23 PM
* @file: UpgradeSchema.php
*/
namespace Ebizmarts\MailChimp\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\App\DeploymentConfig;
class UpgradeSchema implements UpgradeSchemaInterface
{
/**
* @var ResourceConnection
*/
protected $_resource;
/**
* @var DeploymentConfig
*/
protected $_deploymentConfig;
public function __construct(ResourceConnection $resource, DeploymentConfig $deploymentConfig)
{
$this->_resource = $resource;
$this->_deploymentConfig = $deploymentConfig;
}
/**
* {@inheritdoc}
*/
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$connection = $this->_resource->getConnectionByName('default');
if (
$this->_deploymentConfig->get(
\Magento\Framework\Config\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/checkout'
)
) {
$checkoutConnection = $this->_resource->getConnectionByName('checkout');
} else {
$checkoutConnection = $connection;
}
if (
$this->_deploymentConfig->get(
\Magento\Framework\Config\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/sales'
)
) {
$salesConnection = $this->_resource->getConnectionByName('sales');
} else {
$salesConnection = $connection;
}
if (version_compare($context->getVersion(), '1.0.5') < 0) {
$table = $connection
->newTable($setup->getTable('mailchimp_stores'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)
->addColumn(
'apikey',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'mailchimp apikey'
)
->addColumn(
'storeid',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'mailchimp store id'
)
->addColumn(
'list_id',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'mailchimp store id'
)
->addColumn(
'name',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
['unsigned' => true, 'nullable' => false],
'store name'
)
->addColumn(
'platform',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store platform'
)
->addColumn(
'is_sync',
\Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
null,
[],
'if the store is synced or not'
)
->addColumn(
'email_address',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
128,
['unsigned' => true, 'nullable' => false],
'email associated to store'
)
->addColumn(
'currency_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
3,
['unsigned' => true, 'nullable' => false],
'store currency code'
)
->addColumn(
'money_format',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
10,
['unsigned' => true, 'nullable' => false],
'symbol of currency'
)
->addColumn(
'primary_locale',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
5,
['unsigned' => true, 'nullable' => false],
'store locale'
)
->addColumn(
'timezone',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
20,
['unsigned' => true, 'nullable' => false],
'store timezone'
)
->addColumn(
'phone',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store phone number'
)
->addColumn(
'address_address1',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store address1'
)
->addColumn(
'address_address2',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store address2'
)
->addColumn(
'address_city',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store city'
)
->addColumn(
'address_province',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store province'
)
->addColumn(
'address_province_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
2,
['unsigned' => true, 'nullable' => false],
'store province code'
)
->addColumn(
'address_postal_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store postal code'
)
->addColumn(
'address_country',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'store country name'
)
->addColumn(
'address_country_code',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
2,
['unsigned' => true, 'nullable' => false],
'store country code'
);
$connection->createTable($table);
}
if (version_compare($context->getVersion(), '1.0.7') < 0) {
$checkoutConnection->addColumn(
$setup->getTable('quote'),
'mailchimp_campaign_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 16,
'default' => '',
'comment' => 'Campaign'
]
);
$salesConnection->addColumn(
$setup->getTable('sales_order'),
'mailchimp_campaign_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 16,
'default' => '',
'comment' => 'Campaign'
]
);
$checkoutConnection->addColumn(
$setup->getTable('quote'),
'mailchimp_landing_page',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 512,
'default' => '',
'comment' => 'Landing Page'
]
);
$salesConnection->addColumn(
$setup->getTable('sales_order'),
'mailchimp_landing_page',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 512,
'default' => '',
'comment' => 'Landing Page'
]
);
}
if (version_compare($context->getVersion(), '1.0.8') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_errors'),
'original_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'length' => 11,
'default' => null,
'comment' => 'Associated object ID'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_errors'),
'batch_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 64,
'default' => null,
'comment' => 'Mailchimp Batch ID'
]
);
}
if (version_compare($context->getVersion(), '1.0.10') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_errors'),
'store_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'length' => 11,
'default' => null,
'comment' => 'Magento Store Id'
]
);
}
if (version_compare($context->getVersion(), '1.0.11') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_stores'),
'domain',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 512,
'default' => null,
'comment' => 'Domain'
]
);
}
if (version_compare($context->getVersion(), '1.0.12') < 0) {
if ($connection->tableColumnExists($setup->getTable('mailchimp_stores'), 'address_address1')) {
$connection->changecolumn(
$setup->getTable('mailchimp_stores'),
'address_address1',
'address_address_one',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 255,
'default' => null,
'comment' => 'first street address'
]
);
}
if ($connection->tableColumnExists($setup->getTable('mailchimp_stores'), 'address_address2')) {
$connection->changecolumn(
$setup->getTable('mailchimp_stores'),
'address_address2',
'address_address_two',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 255,
'default' => null,
'comment' => 'second street address'
]
);
}
}
if (version_compare($context->getVersion(), '1.0.13') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_stores'),
'mc_account_name',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 512,
'default' => null,
'comment' => 'MC account name'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_stores'),
'list_name',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 512,
'default' => null,
'comment' => 'List Name'
]
);
}
if (version_compare($context->getVersion(), '1.0.14') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_sync_ecommerce'),
'batch_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 64,
'default' => null,
'comment' => 'Mailchimp batch Id'
]
);
}
if (version_compare($context->getVersion(), '1.0.15') < 0) {
$table = $connection
->newTable($setup->getTable('mailchimp_webhook_request'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)
->addColumn(
'type',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
50,
['unsigned' => true, 'nullable' => false],
'request type'
)
->addColumn(
'fired_at',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
[],
'date of the request'
)
->addColumn(
'data_request',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
4096,
['unsigned' => true, 'nullable' => false],
'data of the request'
)
->addColumn(
'processed',
\Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
null,
[],
'Already processed'
);
$connection->createTable($table);
}
if (version_compare($context->getVersion(), '1.0.24') < 0) {
$salesConnection->addColumn(
$setup->getTable('sales_order_grid'),
'mailchimp_flag',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
'default' => 0,
'comment' => 'Retrieved from Mailchimp'
]
);
$salesConnection->addColumn(
$setup->getTable('sales_order'),
'mailchimp_flag',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
'default' => 0,
'comment' => 'Retrieved from Mailchimp'
]
);
}
if (version_compare($context->getVersion(), '1.0.25') < 0) {
$connection->addIndex(
$setup->getTable('mailchimp_sync_ecommerce'),
$connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'related_id', 'index'),
'related_id'
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_ecommerce'),
'deleted_related_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
'length' => 11,
'default' => null,
'comment' => 'Id related to deleted item'
]
);
}
if (version_compare($context->getVersion(), '1.0.26') < 0) {
$table = $connection
->newTable($setup->getTable('mailchimp_interest_group'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)
->addColumn(
'subscriber_id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
10,
['unsigned' => true, 'nullable' => false],
'subscriber id'
)
->addColumn(
'store_id',
\Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
5,
['unsigned' => true, 'nullable' => false],
'subscriber id'
)
->addColumn(
'updated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
[],
'date of the request'
)
->addColumn(
'groupdata',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
4096,
['unsigned' => true, 'nullable' => false],
'data'
);
$connection->createTable($table);
}
if (version_compare($context->getVersion(), '1.3.33') < 0) {
$connection->addIndex(
$setup->getTable('mailchimp_sync_ecommerce'),
$connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'type', 'index'),
'type'
);
$connection->addIndex(
$setup->getTable('mailchimp_sync_ecommerce'),
$connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'batch_id', 'index'),
'batch_id'
);
$connection->addIndex(
$setup->getTable('mailchimp_sync_ecommerce'),
$connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'mailchimp_store_id', 'index'),
'mailchimp_store_id'
);
$connection->changecolumn(
$setup->getTable('mailchimp_stores'),
'timezone',
'timezone',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 32,
'nullable' => false,
'comment' => 'store timezone'
]
);
}
if (version_compare($context->getVersion(), '102.3.34') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'modified_date',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
'default' => null,
'comment' => 'modified date'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_ecommerce'),
'mailchimp_sent',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'length' => 1,
'default' => 0,
'comment' => 'Sent to Mailchimp'
]
);
}
if (version_compare($context->getVersion(), '102.3.35') < 0) {
$connection->changeColumn(
$setup->getTable('mailchimp_stores'),
'apikey',
'apikey',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'length' => 128
]
);
}
if (version_compare($context->getVersion(), '102.3.43') < 0) {
$connection->addIndex(
$setup->getTable('mailchimp_errors'),
$connection->getIndexName($setup->getTable('mailchimp_errors'), ['store_id','regtype','original_id'], 'index'),
['store_id','regtype','original_id']
);
}
if (version_compare($context->getVersion(), '102.3.45') < 0) {
$connection->addIndex(
$setup->getTable('mailchimp_sync_ecommerce'),
$connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'mailchimp_sync_delta', 'index'),
'mailchimp_sync_delta'
);
$connection->addIndex(
$setup->getTable('mailchimp_sync_ecommerce'),
$connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'mailchimp_sync_modified', 'index'),
'mailchimp_sync_modified'
);
}
if (version_compare($context->getVersion(), '102.3.50') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_errors'),
'added_at',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT,
'comment' => 'added at date'
]
);
}
if (version_compare($context->getVersion(), '102.3.51') < 0) {
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'carts_modified_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of modified carts'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'customers_modified_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of modified customers'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'orders_modified_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of modified orders'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'products_modified_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of modified products'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'subscribers_modified_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of modified subscribers'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'carts_new_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of new carts'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'customers_new_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of new customers'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'orders_new_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of new orders'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'products_new_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of new products'
]
);
$connection->addColumn(
$setup->getTable('mailchimp_sync_batches'),
'subscribers_new_count',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'default' => null,
'comment' => 'counter of new subscribers'
]
);
}
if (version_compare($context->getVersion(), '102.3.52') < 0) {
$salesConnection->addColumn(
$setup->getTable('sales_order'),
'mailchimp_sync_error',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'default' => null,
'length' => 128,
'comment' => 'Error on synchronization'
]
);
$salesConnection->addColumn(
$setup->getTable('sales_order'),
'mailchimp_sent',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'length' => 1,
'default' => 0,
'comment' => 'Sent to Mailchimp'
]
);
$salesConnection->addColumn(
$setup->getTable('sales_order_grid'),
'mailchimp_sync_error',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'default' => null,
'length' => 128,
'comment' => 'Error on synchronization'
]
);
$salesConnection->addColumn(
$setup->getTable('sales_order_grid'),
'mailchimp_sent',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'length' => 1,
'default' => 0,
'comment' => 'Sent to Mailchimp'
]
);
$salesConnection->addColumn(
$setup->getTable('catalog_product_entity'),
'mailchimp_sync_error',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
'default' => null,
'length' => 128,
'comment' => 'Error on synchronization'
]
);
$salesConnection->addColumn(
$setup->getTable('catalog_product_entity'),
'mailchimp_sent',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'length' => 1,
'default' => 0,
'comment' => 'Sent to Mailchimp'
]
);
}
if (version_compare($context->getVersion(), '102.3.54') < 0) {
$salesConnection->dropColumn(
$setup->getTable('catalog_product_entity'),
'mailchimp_sync_error'
);
$salesConnection->dropColumn(
$setup->getTable('catalog_product_entity'),
'mailchimp_sent'
);
$salesConnection->dropColumn(
$setup->getTable('sales_order'),
'mailchimp_sync_error'
);
$salesConnection->dropColumn(
$setup->getTable('sales_order'),
'mailchimp_sent'
);
$salesConnection->dropColumn(
$setup->getTable('sales_order_grid'),
'mailchimp_sync_error'
);
$salesConnection->dropColumn(
$setup->getTable('sales_order_grid'),
'mailchimp_sent'
);
}
if (version_compare($context->getVersion(), '102.3.66') < 0) {
$table = $connection
->newTable($setup->getTable('mailchimp_notification'))
->addColumn(
'id',
\Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
'Id'
)
->addColumn(
'notification_data',
\Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
\Magento\Framework\DB\Ddl\Table::MAX_TEXT_SIZE,
[],
'Notification Data'
)
->addColumn(
'generated_at',
\Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
null,
['default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
'Generated At'
)
->addColumn(
'synced_at',
\Magento\Framework\DB\Ddl\Table::TYPE_DATETIME,
null,
['default' => null],
'date of sync'
)
->addColumn(
'processed',
\Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN,
null,
['default' => false],
'Already processed'
);
$connection->createTable($table);
}
}
}
================================================
FILE: Ui/Component/Batch/Grid/Column/Batches.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/3/17 3:10 PM
* @file: Batch.php
*/
namespace Ebizmarts\MailChimp\Ui\Component\Batch\Grid\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;
class Batches extends Column
{
/**
* @var UrlInterface
*/
protected $urlBuilder;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpSyncBatches
*/
protected $mailChimpSyncB;
/**
* @var \Ebizmarts\MailChimp\Helper\Data
*/
protected $helper;
private $stores=[];
/**
* Batch constructor.
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param UrlInterface $urlBuilder
* @param array $components
* @param array $data
*/
public function __construct(
\Ebizmarts\MailChimp\Helper\Data $helper,
\Ebizmarts\MailChimp\Model\MailChimpSyncBatches $mailChimpSyncB,
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
UrlInterface $urlBuilder,
array $components = [],
array $data = []
) {
$this->helper = $helper;
$this->mailChimpSyncB = $mailChimpSyncB;
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function getDataSourceData()
{
return $this->getContext()->getDataProvider()->getData();
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as &$batch) {
$batch_status = &$batch['status'];
$batch_status = ucfirst($batch_status);
$mailchimp_store_id = $batch['mailchimp_store_id'];
$magentoStoreId = $batch['store_id'];
$store_name = $this->getMCStoreNameById($mailchimp_store_id, $magentoStoreId);
$batch['store_name'] = $store_name;
$batch['subscribers'] = $batch['subscribers_new_count'] . " new;" . $batch["subscribers_modified_count"] . " modified";
$batch['customers'] = $batch['customers_new_count'] . " new;" . $batch["customers_modified_count"] . " modified";
$batch['orders'] = $batch['orders_new_count'] . " new;" . $batch["orders_modified_count"] . " modified";
$batch['products'] = $batch['products_new_count'] . " new;" . $batch["products_modified_count"] . " modified";
$batch['carts'] = $batch['carts_new_count'] . " new;" . $batch["carts_modified_count"] . " modified";
$batch[$this->getData('name')] = [
'download' => [
'href' => $this->urlBuilder->getUrl(
'mailchimp/batch/getResponse',
['id' => $batch['id']]
),
'label' => 'Download'
]
];
}
}
return $dataSource;
}
private function getMCStoreNameById($mailchimp_store_id, $magentoStoreId)
{
if (!key_exists($mailchimp_store_id, $this->stores)) {
$api = $this->helper->getApi($magentoStoreId);
try {
$store = $api->ecommerce->stores->get($mailchimp_store_id);
$this->stores[$mailchimp_store_id] = $store['name'];
} catch (\Exception $e) {
$this->stores[$mailchimp_store_id] = 'Not existing store';
}
}
return $this->stores[$mailchimp_store_id];
}
}
================================================
FILE: Ui/Component/Carts/Grid/Column/Actions.php
================================================
urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as &$item) {
$customerId = $item['customer_id'];
if ($customerId) {
$item[$this->getData('name')] = [
'viewcustomer' => [
'href' => $this->urlBuilder->getUrl(
'customer/index/edit',
['id' => $customerId]
),
'label' => 'View Customer',
'target' => '_blank'
]
];
}
}
}
return $dataSource;
}
}
================================================
FILE: Ui/Component/Carts/Grid/Column/Customer.php
================================================
escaper = $escaper;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$item[$this->getData('name')] = $item['customer_firstname'] . ' ' . $item['customer_lastname'];
}
}
return $dataSource;
}
}
================================================
FILE: Ui/Component/Carts/Grid/Column/Mailchimp.php
================================================
escaper = $escaper;
$this->_assetRepository = $assetRepository;
$this->_requestInterfase = $requestInterfase;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$params = ['_secure' => $this->_requestInterfase->isSecure()];
$sync = $item['mailchimp_sent'];
$alt = '';
switch ($sync) {
case MailChimpHelper::NEVERSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/no.png',
$params
);
$text = __('No Syncing');
break;
case MailChimpHelper::SYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/yes.png',
$params
);
$text = __('Synced');
$menu = true;
break;
case MailChimpHelper::WAITINGSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/waiting.png',
$params
);
$text = __('Waiting');
break;
case MailChimpHelper::SYNCERROR:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/error.png',
$params
);
$text = __('Error');
break;
case MailChimpHelper::NEEDTORESYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/resync.png',
$params
);
$text = __('Resyncing');
$menu = true;
break;
case MailChimpHelper::NOTSYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/never.png',
$params
);
$text = __('With error');
break;
default:
$url ='';
$text = '';
}
$item[$this->getData('name')] = "$text
";
}
}
return $dataSource;
}
}
================================================
FILE: Ui/Component/Errors/Grid/Column/Batch.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 5/3/17 3:10 PM
* @file: Batch.php
*/
namespace Ebizmarts\MailChimp\Ui\Component\Errors\Grid\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;
class Batch extends Column
{
/**
* @var UrlInterface
*/
protected $urlBuilder;
/**
* Batch constructor.
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param UrlInterface $urlBuilder
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
UrlInterface $urlBuilder,
array $components = [],
array $data = []
) {
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as &$item) {
$edit = false;
switch($item['regtype']) {
case \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER:
$label = 'Edit customer';
$url = 'customer/index/edit';
$id = 'id';
$edit = true;
break;
case \Ebizmarts\MailChimp\Helper\Data::IS_ORDER:
$label = 'Edit order';
$url = 'sales/order/view';
$id = 'order_id';
$edit = true;
break;
case \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT:
$label = 'Edit product';
$url = 'catalog/product/edit';
$id = 'id';
$edit = true;
break;
}
$item[$this->getData('name')] = [
'download' => [
'href' => $this->urlBuilder->getUrl(
'mailchimp/errors/getresponse',
['id' => $item['id']]
),
'label' => 'Download Response'
]
];
if ($edit) {
$item[$this->getData('name')]['edit'] =
[
'href' => $this->urlBuilder->getUrl(
$url,
[$id => $item['original_id']]
),
'label' => $label
];
}
}
}
return $dataSource;
}
}
================================================
FILE: Ui/Component/Listing/Column/Customers.php
================================================
_requestInterface = $requestInterface;
$this->_assetRepository = $assetRepository;
$this->_customerFactory = $customerFactory;
$this->_helper = $helper;
$this->syncHelper = $syncHelper;
$this->_mailChimpErrorsFactory = $mailChimpErrorsFactory;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$params = ['_secure' => $this->_requestInterface->isSecure()];
foreach ($dataSource['data']['items'] as & $item) {
/**
* @var $customer \Magento\Customer\Model\Customer
*/
$customer = $this->_customerFactory->create()->load($item['entity_id']);
$params = ['_secure' => $this->_requestInterface->isSecure()];
$alt = '';
$url = '';
$text = '';
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ACTIVE, $customer->getStoreId())) {
$mailchimpStoreId = $this->_helper->getConfigValue(
\Ebizmarts\MailChimp\Helper\Data::XML_MAILCHIMP_STORE,
$customer->getStoreId()
);
$syncData = $this->syncHelper->getChimpSyncEcommerce(
$mailchimpStoreId,
$customer->getId(),
\Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER
);
if (!$syncData || $syncData->getMailchimpStoreId() != $mailchimpStoreId ||
$syncData->getRelatedId() != $customer->getId() ||
$syncData->getType() != \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER) {
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/no.png',
$params
);
$text = __('Syncing');
} else {
$sync = $syncData->getMailchimpSent();
switch ($sync) {
case \Ebizmarts\MailChimp\Helper\Data::SYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/yes.png',
$params
);
$text = __('Synced');
$alt = $syncData->getMailchimpSyncDelta();
break;
case \Ebizmarts\MailChimp\Helper\Data::WAITINGSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/waiting.png',
$params
);
$text = __('Waiting');
$alt = $syncData->getMailchimpSyncDelta();
break;
case \Ebizmarts\MailChimp\Helper\Data::SYNCERROR:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/error.png',
$params
);
$text = __('Error');
$customerError = $this->_getError($customer->getId(), $customer->getStoreId());
if ($customerError) {
$alt = $customerError->getErrors();
}
break;
case \Ebizmarts\MailChimp\Helper\Data::NEEDTORESYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/resync.png',
$params
);
$text = __('Resyncing');
$alt = $syncData->getMailchimpSyncDelta();
break;
case \Ebizmarts\MailChimp\Helper\Data::NOTSYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/never.png',
$params
);
$text = __('With error');
$alt = $syncData->getMailchimpSyncError();
break;
default:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/error.png',
$params
);
$text = __('Error');
}
}
}
$item['mailchimp_sync'] =
"";
}
}
return $dataSource;
}
private function _getError($customerId, $storeId)
{
/**
* @var $error \Ebizmarts\MailChimp\Model\MailChimpErrors
*/
$error = $this->_mailChimpErrorsFactory->create();
return $error->getByStoreIdType($storeId, $customerId, \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER);
}
}
================================================
FILE: Ui/Component/Listing/Column/Monkey.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 3/15/17 1:23 AM
* @file: Monkey.php
*/
namespace Ebizmarts\MailChimp\Ui\Component\Listing\Column;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Framework\View\Element\UiComponent\ContextInterface;
use \Magento\Framework\View\Element\UiComponentFactory;
use \Magento\Ui\Component\Listing\Columns\Column;
use \Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\UrlInterface;
use Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory as SyncCollectionFactory;
use Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\Collection as SyncCollection;
use Ebizmarts\MailChimp\Helper\Data as MailChimpHelper;
class Monkey extends Column
{
/**
* @var OrderRepositoryInterface
*/
protected $_orderRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $_searchCriteria;
/**
* @var \Magento\Framework\View\Asset\Repository
*/
protected $_assetRepository;
/**
* @var \Magento\Framework\App\RequestInterface
*/
protected $_requestInterfase;
/**
* @var MailChimpHelper
*/
protected $_helper;
/**
* @var SyncHelper
*/
private $syncHelper;
/**
* @var \Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory
*/
protected $_syncCommerceCF;
/**
* @var \Magento\Sales\Model\OrderFactory
*/
protected $_orderFactory;
/**
* @var \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory
*/
protected $_mailChimpErrorsFactory;
/**
* @var UrlInterface
*/
protected $urlBuilder;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
*/
private $orderCollectionFactory;
/**
* @var SyncCollectionFactory
*/
private $syncCollectionFactory;
/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param OrderRepositoryInterface $orderRepository
* @param \Magento\Framework\View\Asset\Repository $assetRepository
* @param \Magento\Framework\App\RequestInterface $requestInterface
* @param SearchCriteriaBuilder $criteria
* @param MailChimpHelper $helper
* @param SyncCollectionFactory $syncCommerceCF
* @param \Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $mailChimpErrorsFactory
* @param \Magento\Sales\Model\OrderFactory $orderFactory
* @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
* @param UrlInterface $urlBuilder
* @param SyncCollectionFactory $syncCollectionFactory
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
OrderRepositoryInterface $orderRepository,
\Magento\Framework\View\Asset\Repository $assetRepository,
\Magento\Framework\App\RequestInterface $requestInterface,
SearchCriteriaBuilder $criteria,
MailChimpHelper $helper,
\Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncEcommerce\CollectionFactory $syncCommerceCF,
\Ebizmarts\MailChimp\Model\MailChimpErrorsFactory $mailChimpErrorsFactory,
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
UrlInterface $urlBuilder,
SyncCollectionFactory $syncCollectionFactory,
array $components = [],
array $data = []
) {
$this->_orderRepository = $orderRepository;
$this->_searchCriteria = $criteria;
$this->_assetRepository = $assetRepository;
$this->_requestInterfase= $requestInterface;
$this->_helper = $helper;
$this->_syncCommerceCF = $syncCommerceCF;
$this->_orderFactory = $orderFactory;
$this->orderCollectionFactory = $orderCollectionFactory;
$this->_mailChimpErrorsFactory = $mailChimpErrorsFactory;
$this->urlBuilder = $urlBuilder;
$this->syncCollectionFactory = $syncCollectionFactory;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$ordersIds = $this->getOrdersIds($dataSource);
$orderMap = $this->getOrderDataByOrderIds($ordersIds);
$syncMap = $this->getSyncDataByOrderIds($ordersIds);
foreach ($dataSource['data']['items'] as & $item) {
$status = $item['mailchimp_flag'];
$orderId = $item['entity_id'];
if (key_exists($item['entity_id'],$syncMap)) {
$sync = $syncMap[$item['entity_id']]->getMailchimpSent();
$syncError = $syncMap[$item['entity_id']]->getMailchimpSyncError();
} else {
$sync = MailChimpHelper::NEVERSYNC;
$syncError = '';
}
$order = $orderMap[$orderId]
?? $this->_orderFactory->create()->loadByIncrementId($orderId); // Backwards Compatibility
$menu = false;
$params = ['_secure' => $this->_requestInterfase->isSecure()];
$storeId = $order->getStoreId();
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ACTIVE, $storeId)) {
$alt = '';
switch ($sync) {
case MailChimpHelper::NEVERSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/no.png',
$params
);
$text = __('Syncing');
break;
case MailChimpHelper::SYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/yes.png',
$params
);
$text = __('Synced');
$menu = true;
break;
case MailChimpHelper::WAITINGSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/waiting.png',
$params
);
$text = __('Waiting');
break;
case MailChimpHelper::SYNCERROR:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/error.png',
$params
);
$text = __('Error');
$orderError = $this->_getError($orderId, $storeId);
if ($orderError) {
$alt = $orderError->getErrors();
}
break;
case MailChimpHelper::NEEDTORESYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/resync.png',
$params
);
$text = __('Resyncing');
$menu = true;
break;
case MailChimpHelper::NOTSYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/never.png',
$params
);
$text = __('With error');
$alt = $syncError;
break;
default:
$url ='';
$text = '';
}
$item['mailchimp_sync'] =
"$text
";
if ($status) {
$item['mailchimp_sync'] =
"$text
";
if ($menu) {
$item[$this->getData('name')] = [
'campaign' => [
'href' => $this->urlBuilder->getUrl(
'mailchimp/orders/campaign',
['orderId' => $item['entity_id']]
),
'label' => 'View campaign',
'target' => '_blank'
],
'member' => [
'href' => $this->urlBuilder->getUrl(
'mailchimp/orders/member',
['orderId' => $item['entity_id']]
),
'label' => 'View member',
'target' => '_blank'
]
];
}
} else {
$item['mailchimp_sync'] =
"$text
";
}
}
}
}
return $dataSource;
}
private function _getError($orderId, $storeId)
{
/**
* @var $error \Ebizmarts\MailChimp\Model\MailChimpErrors
*/
$error = $this->_mailChimpErrorsFactory->create();
return $error->getByStoreIdType($storeId, $orderId, \Ebizmarts\MailChimp\Helper\Data::IS_ORDER);
}
/**
* @param array $orderIds
* @return OrderInterface[]
*/
private function getOrderDataByOrderIds(array $orderIds): array
{
if (empty($orderIds)) {
return [];
}
$orderCollection = $this->orderCollectionFactory->create();
$orderCollection->getSelect()->columns(['entity_id','store_id']);
$orderCollection->addAttributeToFilter(
'entity_id',
['in' => $orderIds]
);
$ordersMap = [];
/** @var OrderInterface $order */
foreach ($orderCollection->getItems() as $order) {
$ordersMap[$order->getEntityId()] = $order;
}
return $ordersMap;
}
private function getOrdersIds(array $dataSource)
{
if (!isset($dataSource['data']['items'])) {
return [];
}
return array_filter(array_unique(array_column($dataSource['data']['items'], 'entity_id')));
}
private function getSyncDataByOrderIds(array $OrderIds)
{
$syncMap = [];
/**
* @var SyncCollection $syncCollection
*/
$syncCollection = $this->syncCollectionFactory->create();
$syncCollection->addFieldToFilter('related_id', ['in' => $OrderIds]);
$syncCollection->addFieldToFilter('type', ['eq' => MailChimpHelper::IS_ORDER]);
foreach($syncCollection as $item) {
$syncMap[$item->getRelatedId()] = $item;
}
return $syncMap;
}
}
================================================
FILE: Ui/Component/Listing/Column/Products.php
================================================
_productFactory = $productFactory;
$this->_requestInterface = $requestInterface;
$this->_helper = $helper;
$this->_assetRepository = $assetRepository;
$this->_mailChimpErrorsFactory = $mailChimpErrorsFactory;
$this->productCollectionFactory = $productCollectionFactory;
$this->syncCollectionFactory = $syncCollectionFactory;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$productsMap = $this->getProductsByEntityIds(
$this->getProductsIds($dataSource)
);
$syncMap = $this->getSyncDataByEntityIds($this->getProductsIds($dataSource));
foreach ($dataSource['data']['items'] as & $item) {
/**
* @var $product \Magento\Catalog\Model\Product
*/
$product = $productsMap[$item['entity_id']]
?? $this->_productFactory->create()->load($item['entity_id']); // Backwards Compatibility
if (key_exists($item['entity_id'],$syncMap)) {
$sync = $syncMap[$item['entity_id']]->getMailchimpSent();
} else {
$sync = MailChimpHelper::NEVERSYNC;
}
$params = ['_secure' => $this->_requestInterface->isSecure()];
$alt = '';
$url = '';
$text = '';
if (in_array($product->getTypeId(), self::SUPPORTED_PRODUCT_TYPES, true)) {
$url = '';
$text = '';
if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ACTIVE, $product->getStoreId())) {
switch ($sync) {
case MailChimpHelper::NEVERSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/no.png',
$params
);
$text = __('Syncing');
break;
case MailChimpHelper::SYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/yes.png',
$params
);
$text = __('Synced');
break;
case MailChimpHelper::WAITINGSYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/waiting.png',
$params
);
$text = __('Waiting');
break;
case MailChimpHelper::SYNCERROR:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/error.png',
$params
);
$text = __('Error');
$orderError = $this->_getError($product->getId(), $product->getStoreId());
if ($orderError) {
$alt = $orderError->getErrors();
}
break;
case MailChimpHelper::NEEDTORESYNC:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/resync.png',
$params
);
$text = __('Resyncing');
break;
case MailChimpHelper::NOTSYNCED:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/never.png',
$params
);
$text = __('With error');
break;
default:
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/error.png',
$params
);
$text = __('Error');
}
}
} else {
$url = $this->_assetRepository->getUrlWithParams(
'Ebizmarts_MailChimp::images/never.png',
$params
);
$text = __('Unsupported');
$alt = "Mailchimp does not support bundled or grouped products.";
}
$item['mailchimp_sync'] =
"";
}
}
return $dataSource;
}
private function _getError($productId, $storeId)
{
/**
* @var $error \Ebizmarts\MailChimp\Model\MailChimpErrors
*/
$error = $this->_mailChimpErrorsFactory->create();
return $error->getByStoreIdType($storeId, $productId, \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT);
}
private function getProductsByEntityIds(array $productIds): array
{
if (empty($productIds)) {
return [];
}
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $productsCollection */
$productsCollection = $this->productCollectionFactory->create();
$productsCollection->addAttributeToFilter('entity_id', ['in' => $productIds]);
$productsMap = [];
foreach ($productsCollection->getItems() as $product) {
$productsMap[$product->getId()] = $product;
}
return $productsMap;
}
private function getProductsIds(array $dataSource)
{
if (!isset($dataSource['data']['items'])) {
return [];
}
return array_filter(array_unique(array_column($dataSource['data']['items'], 'entity_id')));
}
private function getSyncDataByEntityIds(array $productIds)
{
$syncMap = [];
/**
* @var SyncCollection $syncCollection
*/
$syncCollection = $this->syncCollectionFactory->create();
$syncCollection->addFieldToFilter('related_id', ['in' => $productIds]);
$syncCollection->addFieldToFilter('type', ['eq' => MailChimpHelper::IS_PRODUCT]);
foreach($syncCollection as $item) {
$syncMap[$item->getRelatedId()] = $item;
}
return $syncMap;
}
}
================================================
FILE: Ui/Component/Stores/Grid/Column/Actions.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @date: 4/5/17 11:19 AM
* @file: Actions.php
*/
namespace Ebizmarts\MailChimp\Ui\Component\Stores\Grid\Column;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;
use Magento\Framework\UrlInterface;
/**
* Class ProductActions
*/
class Actions extends Column
{
/**
* @var UrlInterface
*/
protected $urlBuilder;
/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param UrlInterface $urlBuilder
* @param array $components
* @param array $data
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
UrlInterface $urlBuilder,
array $components = [],
array $data = []
) {
$this->urlBuilder = $urlBuilder;
parent::__construct($context, $uiComponentFactory, $components, $data);
}
/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
$storeId = $this->context->getFilterParam('store_id');
foreach ($dataSource['data']['items'] as &$item) {
$item[$this->getData('name')]['edit'] = [
'href' => $this->urlBuilder->getUrl(
'mailchimp/stores/edit',
['id' => $item['id']]
),
'label' => __('Edit'),
'hidden' => false,
];
}
}
return $dataSource;
}
}
================================================
FILE: composer.json
================================================
{
"name": "mailchimp/mc-magento2",
"autoload": {
"psr-4": {"Ebizmarts\\MailChimp\\":""},
"files": ["registration.php"]
},
"description": "Connect MailChimp with Magento",
"type": "magento2-module",
"version": "102.3.78",
"authors": [
{
"name": "Ebizmarts Corp",
"email": "mailchimp@ebizmarts-desk.zendesk.com",
"homepage": "http://ebizmarts.com"
}
],
"license": [
"OSL-3.0",
"AFL-3.0"
],
"support": {
"email": "mailchimp@ebizmarts-desk.zendesk.com",
"wiki": "https://connect.mailchimp.com/integrations/magento",
"forum": "http://ebizmarts.com/forums/view/6"
},
"require" : {
"magento/framework": "102.0.*",
"ebizmarts/mailchimp-lib": ">=3.0.44",
"ext-json": "*"
}
}
================================================
FILE: etc/acl.xml
================================================
================================================
FILE: etc/adminhtml/events.xml
================================================
================================================
FILE: etc/adminhtml/menu.xml
================================================
================================================
FILE: etc/adminhtml/routes.xml
================================================
================================================
FILE: etc/adminhtml/system.xml
================================================
Mailchimp
separator-top
Mailchimp
mailchimp
Ebizmarts_MailChimp::config_mailchimp
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Fieldset\Hint
Mailchimp General Configuration
Enabled
Magento\Config\Model\Config\Source\Yesno
Mailchimp's additional terms.]]>
Get API credentials
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\OauthWizard
1
API Key
Magento\Config\Model\Config\Backend\Encrypted
1
Mailchimp Store
Ebizmarts\MailChimp\Model\Config\Source\MonkeyStore
Ebizmarts\MailChimp\Model\Config\Backend\MonkeyStore
You must create a MailChimp Store for this API key to connect to this account
1
Mailchimp List
Ebizmarts\MailChimp\Model\Config\Source\MonkeyList
1
Account Details
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Account
Ebizmarts\MailChimp\Model\Config\Source\Details
1
Magento always manage emails
Magento\Config\Model\Config\Source\Yesno
1
Enable Two Way Sync
Magento\Config\Model\Config\Source\Yesno
1
Create Webhook
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\CreateWebhook
1
1
Webhooks Delete action
Ebizmarts\MailChimp\Model\Config\Source\WebhookDelete
1
Enable log
Magento\Config\Model\Config\Source\Yesno
1
Enable Support
this]]>
Magento\Config\Model\Config\Source\Yesno
1
Clean support period
Ebizmarts\MailChimp\Model\Config\Source\CleanPeriod
1
Customer Fields Mapping
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Form\Field\CustomerMap
Ebizmarts\MailChimp\Model\Config\Backend\VarsMap
Map the magento customer field to mailchimp merge_fields
1
Resync Subscribers
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\ResyncSubscriber
1
Fix Mailchimp JS in frontend
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\FixMailchimpJS
1
Available Groups
Ebizmarts\MailChimp\Model\Config\Source\Interest
1
set up groups in Mailchimp, include them in your checkout page so customers can choose the type of email marketing they want to receive.]]>
1
Show groups after checkout?
Magento\Config\Model\Config\Source\Yesno
here]]>
1
Group Description
1
1
Success message
1
1
Connection timeout
Ebizmarts\MailChimp\Model\Config\Source\Timeout
1
Ecommerce Configuration
Enabled
Magento\Config\Model\Config\Source\Yesno
Sync all customers
Magento\Config\Model\Config\Source\Yesno
1
Subscribe all customers to the newsletter
Magento\Config\Model\Config\Source\Yesno
1
First Date
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Date
1
Sync not salable products
Magento\Config\Model\Config\Source\Yesno
1
Send Promo Rules and Promo Codes
Magento\Config\Model\Config\Source\Yesno
1
Prices including taxes
Magento\Config\Model\Config\Source\Yesno
1
Campaign Attribution Action
Ebizmarts\MailChimp\Model\Config\Source\CampaignAction
1
1
Order attribution based on customer actions
Reset Errors and retry
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\ResetErrors
Truncate the errors table and retry all the registers with error
1
Reset Errors and no retry
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\ResetErrorsNoRetry
Truncate the errors table and retry all the registers with error
1
Months to clear the error table
Ebizmarts\MailChimp\Model\Config\Source\Months
1
Delete Store
Proceed with caution, this delete the mailchimp store for all the connected magento stores
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\DeleteStore
1
Resync all products
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\ResyncProducts
1
Abandoned Cart Configuration
Enabled
Magento\Config\Model\Config\Source\Yesno
First Date
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Date
1
Redirect Page
Ebizmarts\MailChimp\Model\Config\Source\Cmspage
1
Save Email to the Quote before place Order
Select No to prevent saving customer Email to the quote before Order was placed
Magento\Config\Model\Config\Source\Yesno
1
Create Abandoned Cart Automation
Ebizmarts\MailChimp\Block\Adminhtml\System\Config\CreateAbandonedCart
Must be logged in to MailChimp's website previously to see the automation wizard, re-open if not
1
================================================
FILE: etc/config.xml
================================================
7
sent,open,click
Yes
f71334c7039eb7f6574676bd5f43b6bc
https://logs-mc4mage.ebizmarts.com/batches
https://users-mc4mage.ebizmarts.com
================================================
FILE: etc/cron_groups.xml
================================================
1
4
2
10
60
600
1
================================================
FILE: etc/crontab.xml
================================================
*/5 * * * *
*/5 * * * *
0 * * * *
0 * * * *
0 * * * *
0 */12 * * *
0 */1 * * *
================================================
FILE: etc/di.xml
================================================
Ebizmarts\MailChimp\Helper\Data\Proxy
Magento\Framework\Filesystem\Driver\File
MailChimpLogger
- Ebizmarts\MailChimp\Model\Logger\Handler
mailchimp_errors
Ebizmarts\MailChimp\Model\ResourceModel\MailChimpErrors
mailchimp_sync_batches
Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatches
- Ebizmarts\MailChimp\Model\ResourceModel\MailChimpErrors\Collection
- Ebizmarts\MailChimp\Model\ResourceModel\MailChimpStores\Grid\Collection
- Ebizmarts\MailChimp\Model\ResourceModel\MailChimpSyncBatchesGrid\Collection
- Ebizmarts\MailChimp\Model\ResourceModel\Schedule\Collection
- Ebizmarts\MailChimp\Model\ResourceModel\Carts\Collection
mailchimp_stores
Ebizmarts\MailChimp\Model\ResourceModel\MailChimpStores
- sales_order.mailchimp_flag
================================================
FILE: etc/events.xml
================================================
================================================
FILE: etc/fieldset.xml
================================================
================================================
FILE: etc/frontend/di.xml
================================================
================================================
FILE: etc/frontend/events.xml
================================================
================================================
FILE: etc/frontend/routes.xml
================================================
================================================
FILE: etc/module.xml
================================================
================================================
FILE: i18n/es_ES.csv
================================================
MailChimp,MailChimp
Save,Guardar
Save and Continue Edit,Guardar y continuar Editar
Delete,Borrar
Edit Store '%1',Editar Tienda '%1'
Add Store,Añadir Tienda
Address,Dirección
Street,Calle
City,Ciudad
Postal Code,Código Postal
Select one,Seleccionar una
Country,País
Store Address Info,Información de la Dirección de la Tienda
General,General
Apikey,Apikey
Select first an ApiKey,Seleccione primero una ApiKey
List,Lista
Name,Nombre
Domain,Dominio
Email,Correo Electrónico
Currency,Moneda
Locale,Configuración regional
TimeZone,Zona horaria
Phone,Teléfono
Store Info,Información de la Tienda
Mailchimp Store Information,Información de la Tienda MailChimp
button_label,button_label
Mailchimp,Mailchimp
Magento,Magento
Add,Añadir
Shipping Zip Code,Código Postal de Envío
Shipping Country,País de Envío
Shipping City,Ciudad de Envío
Shipping State,Estado de Envío
Shipping Telephone,Teléfono de Envío
Shipping Company,Empresa de Envío
Shipping Street,Calle de envío
Billing Zip Code,Código Postal de Facturación
Billing Country,País de Facturación
Billing City,Ciudad de Facturación
Billing State,Estado de Facturación
Billing Telephone,Teléfono de Facturación
Billing Company,Empresa de Facturación
Billing Street, Calle de facturación
Mailchimp Batches,Lotes de Mailchimp
Mailchimp Cron,Mailchimp Cron
User name:,Nombre de usuario:
Total Account Subscribers:,Total de suscriptores de la cuenta:
Total List Subscribers:,Total de suscriptores de la lista:
Ecommerce Data uploaded to MailChimp:,Datos de comercio electrónico cargados a MailChimp:
Total customers:,Total de clientes:
Total products:,Total de productos:
Total orders:,Total de pedidos:
Total Carts:,Total de carritos:
"Ecommerce disabled, save configuration to enable","Comercio electrónico deshabilitado, guardar configuración para habilitar"
"Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized)","Comercio electrónico deshabilitado, solo se sincronizarán los suscriptores (sus pedidos, productos, etc. no se sincronizarán)"
--- Invalid API Key ---,--- Clave API no válida ---
Mailchimp Errors,Errores de Mailchimp
You deleted the store.,Eliminó la tienda.
'Store could not be deleted.' .,'No se pudo eliminar la tienda.' .
This store no longer exists.,Esta tienda ya no existe.
Mailchimp Store,Tienda Mailchimp
Mailchimp Stores,Tiendas Mailchimp
'Store could not be saved.' .,'No se pudo guardar la tienda.' .
You can't access this cart,No puede acceder a este carrito
Login to complete your order,Inicie sesión para completar su pedido
Thanks for sharing your interest with us,Gracias por compartir su interés con nosotros
Json error,Error de JSON
Error retrieving interest groups for store ,Error al recuperar grupos de interés para la tienda
Order [' . . '] is empty,El pedido [' . . '] está vacío
Parent rule with id ' . . 'has not been correctly sent.,La regla principal con id ' . . ' no se ha enviado correctamente.
Something went wrong when retrieving the information for promo rule,Algo salió mal al recuperar la información para la regla de promoción
Something went wrong when retrieving the information.,Algo salió mal al recuperar la información.
Invalid API Key,Clave API no válida
Username,Nombre de usuario
This account is currently syncing,Esta cuenta se está sincronizando actualmente
Account Synced since,Cuenta sincronizada desde
---No Data---,---Sin datos---
No,No
Unsubscribe,Cancelar suscripción
Delete subscriber,Eliminar suscriptor
Syncing,Sincronizando
Synced,Sincronizado
Waiting,En espera
Error,Error
Resyncing,Resincronizando
With error,Con error
Unsupported,No compatible
Edit,Editar
MailChimp Information,Información de MailChimp
No Interest groups found,No se encontraron grupos de interés
Mailchimp v,Mailchimp v
by,por
Need help? See our ,¿Necesita ayuda? Consulte nuestra
Wiki,Wiki
Got feedback? ,¿Tiene comentarios?
Email us,Envíenos un correo electrónico
You can find more extension in our ,Puede encontrar más extensiones en nuestra
Store,Tienda
Subscribe to more detailed newsletters,Suscríbase a boletines informativos más detallados
Newsletter,Boletín informativo
Sign Up for Our Newsletter:,Suscríbase a nuestro boletín informativo:
Enter your email address,Ingrese su dirección de correo electrónico
Enter your phone,Ingrese su teléfono
Subscribe,Suscribirse
Mailchimp General Configuration,Configuración general de Mailchimp
Enabled,Habilitado
API Key,Clave API
You must create a MailChimp Store for this API key to connect to this account,Debe crear una tienda MailChimp para que esta clave API se conecte a esta cuenta
Mailchimp List,Lista de Mailchimp
Account Details,Detalles de la cuenta
Change the footer link,Cambiar el enlace de pie de página
"Enabling this, the ""Subscribe"" button at the bottom open a popup with the Mailchimp subscription form","Al habilitar esto, el botón ""Suscribirse"" en la parte inferior abre una ventana emergente con el formulario de suscripción de Mailchimp"
Popup Url,URL emergente
Paste the form URL from your MailChimp audience,Pegue la URL del formulario de su audiencia de MailChimp
Magento always manage emails,Magento siempre administra correos electrónicos
Enable Two Way Sync,Habilitar sincronización bidireccional
"If this is set to ""No"", the synchronization will be from Magento's newsletter to Mailchimp only","Si esto se configura en ""No"", la sincronización será solo del boletín informativo de Magento a Mailchimp"
Create Webhook,Crear webhook
Webhooks Delete action,Acción de eliminación de webhooks
Enable Log,Habilitar registro
Customer Fields Mapping,Mapeo de campos de clientes
Add the magento to mailchimp mapping,Agregar el mapeo de magento a mailchimp
Map the magento customer field to mailchimp merge_fields,Mapear el campo de cliente de magento a los campos de combinación de mailchimp
Resync Subscribers,Resincronizar suscriptores
Fix Mailchimp JS in frontend,Reparar Mailchimp JS en el frontend
Available Groups,Grupos disponibles
"If you set up groups in Mailchimp , include them in your checkout page so customers can choose the type of email marketing they want to receive.","Si configura grupos en Mailchimp , inclúyalos en su página de pago para que los clientes puedan elegir el tipo de marketing por correo electrónico que desean recibir."
Show groups after checkout?,¿Mostrar grupos después del pago?
"Don't use in magento 2.1 see at here ","No lo use en Magento 2.1, consulte aquí "
Group Description,Descripción del grupo
Success message,Mensaje de éxito
Connection timeout,Tiempo de espera de conexión
Ecommerce Configuration,Configuración de comercio electrónico
Subscribe all customers to the newsletter,Suscribir a todos los clientes al boletín informativo
First Date,Primera fecha
Send Promo Rules and Promo Codes,Enviar reglas de promoción y códigos de promoción
Prices including taxes,Precios con impuestos incluidos
"You must configure Price Display Settings in Sales/Tax to ""including taxes""","Debe configurar la configuración de visualización de precios en Ventas/Impuestos en ""con impuestos incluidos"""
Campaign Attribution Action,Acción de atribución de campaña
Order attribution based on customer actions,Atribución de pedidos basada en acciones del cliente
Reset Errors and retry,Restablecer errores y volver a intentar
Truncate the errors table and retry all the registers with error,Truncar la tabla de errores y volver a intentar todos los registros con error
Reset Errors and no retry,Restablecer errores y no volver a intentar
Truncate the errors table and no retry all the registers with error,Truncar la tabla de errores y no volver a intentar todos los registros con error
Months to clear the error table,Meses para borrar la tabla de errores
How many month before clean the error from the error table automatically and not retry,¿Cuántos meses antes de limpiar el error de la tabla de errores automáticamente y no volver a intentarlo?
Delete Store,Eliminar tienda
"Proceed with caution, this delete the mailchimp store for all the connected magento stores","Proceda con precaución, esto elimina la tienda de Mailchimp para todas las tiendas Magento conectadas"
Resync all products,Resincronizar todos los productos
Abandoned Cart Configuration,Configuración de carrito abandonado
Redirect Page,Redireccionamiento Página
Save Email to the Quote before place Order,Guardar correo electrónico en la cotización antes de realizar el pedido
Select No to prevent saving customer Email to the quote before Order was placed,Seleccione No para evitar guardar el correo electrónico del cliente en la cotización antes de realizar el pedido
"Must be logged in to MailChimp's website previously to see the automation wizard, re-open if not",Debe haber iniciado sesión en el sitio web de MailChimp previamente para ver el asistente de automatización; vuelva a abrirlo si no lo está
All Store Views,Todas las vistas de la tienda
Store View,Vista de la tienda
ID,ID
Status,Estado
Last modified,Última modificación
#Customers,#Clientes
#Orders,#Pedidos
#Products,#Productos
#Carts,#Carritos
#Subscribers,#Suscriptores
Batch JSON,JSON por lotes
Job Code,Código de trabajo
Messages,Mensajes
Created at,Creado en
Scheduled at,Programado en
Executed at,Ejecutado en
Finished at,Terminado en
Type,Tipo
Title,Título
Date,Fecha
Action,Acción
Create New Mailchimp Store,Crear nueva tienda de Mailchimp
MC Account name,Nombre de la cuenta de MC
Store name,Nombre de la tienda
List name,Nombre de la lista
Mailchimp Sync,Sincronización de Mailchimp
Sync all customers or only customer with orders, Sincronza todos los clientes o solo los que tienen ordenes
================================================
FILE: i18n/fr_FR.csv
================================================
MailChimp,MailChimp
Save,Enregistrer
Save and Continue Edit,Enregistrer et continuer la modification
Delete,Supprimer
Edit Store '%1',Modifier la boutique '%1'
Add Store,Ajouter une boutique
Address,Adresse
Street,Rue
City,Ville
Postal Code,Code postal
Select one,Sélectionnez-en une
Country,Pays
Store Address Info,Informations sur l'adresse de la boutique
General,Général
Apikey,Apikey
Select first an ApiKey,Sélectionnez d'abord une ApiKey
List,Liste
Name,Nom
Domain,Domaine
Email,E-mail
Currency,Devise
Locale,Localité
TimeZone,Fuseau horaire
Phone,Téléphone
Store Info,Informations sur la boutique
Mailchimp Store Information,Informations sur la boutique Mailchimp
button_label,button_label
Mailchimp,Mailchimp
Magento,Magento
Add,Ajouter
Shipping Zip Code,Code postal d'expédition
Shipping Country,Pays d'expédition
Shipping City,Ville d'expédition
Shipping State,État d'expédition
Shipping Telephone,Téléphone d'expédition
Shipping Company,Société de livraison
Shipping Street,Rue de la navigation
Billing Zip Code,Code postal de facturation
Billing Country,Pays de facturation
Billing City,Ville de facturation
Billing State,État de facturation
Billing Telephone,Téléphone de facturation
Billing Company,Société de facturation
Billing Street,Rue de la facturation
Mailchimp Batches,Lots Mailchimp
Mailchimp Cron,Mailchimp Cron
User name:,Nom d'utilisateur :
Total Account Subscribers:,Nombre total d'abonnés au compte :
Total List Subscribers:,Nombre total d'abonnés à la liste :
Ecommerce Data uploaded to MailChimp:,Données de commerce électronique téléchargées sur MailChimp :
Total customers:,Nombre total de clients :
Total products:,Nombre total de produits :
Total orders:,Nombre total de commandes :
Total Carts:,Nombre total de paniers :
"Ecommerce disabled, save configuration to enable","Commerce électronique désactivé, enregistrer la configuration pour activer"
"Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized)","Le commerce électronique est désactivé, seuls les abonnés seront synchronisés (vos commandes, produits, etc. ne seront pas synchronisés)"
--- Invalid API Key ---,--- Clé API non valide ---
Mailchimp Errors,Erreurs Mailchimp
You deleted the store.,Vous avez supprimé la boutique.
'Store could not be deleted.' .,'La boutique n'a pas pu être supprimée.' .
This store no longer exists.,Cette boutique n'existe plus.
Mailchimp Store,Boutique Mailchimp
Mailchimp Stores,Boutiques Mailchimp
'Store could not be saved.' .,'La boutique n'a pas pu être enregistrée.' .
You can't access this cart,Vous ne pouvez pas accéder à ce panier
Login to complete your order,Connectez-vous pour terminer votre commande
Thanks for sharing your interest with us,Merci d'avoir partagé votre intérêt avec nous
Json error,Erreur Json
Error retrieving interest groups for store ,Erreur lors de la récupération des groupes d'intérêt pour la boutique
Order [' . . '] is empty,La commande [' . . '] est vide
Parent rule with id ' . . 'has not been correctly sent.,La règle parente avec l'ID ' . . ' n'a pas été correctement envoyée.
Something went wrong when retrieving the information for promo rule,Une erreur s'est produite lors de la récupération des informations pour la règle de promotion
Something went wrong when retrieving the information.,Une erreur s'est produite lors de la récupération des informations.
Invalid API Key,Clé API non valide
Username,Nom d'utilisateur
This account is currently syncing,Ce compte est en cours de synchronisation
Account Synced since,Compte synchronisé depuis
---No Data---,---Aucune donnée---
No,Non
Unsubscribe,Se désabonner
Delete subscriber,Supprimer l'abonné
Syncing,Synchronisation
Synced,Synchronisé
Waiting,En attente
Error,Erreur
Resyncing,Resynchronisation
With error,Avec erreur
Unsupported,Non pris en charge
Edit,Modifier
MailChimp Information,Informations MailChimp
No Interest groups found,Aucun groupe d'intérêt trouvé
Mailchimp v,Mailchimp v
by,par
Need help? See our ,Besoin d'aide ? Consultez notre
Wiki,Wiki
Got feedback? ,Vous avez des commentaires ?
Email us,Envoyez-nous un e-mail
You can find more extension in our ,Vous pouvez trouver plus d'extensions dans notre
Store,Boutique
Subscribe to more detailed newsletters,Abonnez-vous à des newsletters plus détaillées
Newsletter,Newsletter
Sign Up for Our Newsletter:,Inscrivez-vous à notre newsletter :
Enter your email address,Entrez votre adresse e-mail
Enter your phone,Entrez votre téléphone
Subscribe,S'abonner
Mailchimp General Configuration,Configuration générale de Mailchimp
Enabled,Activé
API Key,Clé API
You must create a MailChimp Store for this API key to connect to this account,Vous devez créer une boutique MailChimp pour que cette clé API se connecte à ce compte
Mailchimp List,Liste Mailchimp
Account Details,Détails du compte
Change the footer link,Modifier le lien de pied de page
"Enabling this, the ""Subscribe"" button at the bottom open a popup with the Mailchimp subscription form","En activant cette option, le bouton « S'abonner » en bas ouvre une fenêtre contextuelle avec le formulaire d'abonnement Mailchimp"
Popup Url,URL de la fenêtre contextuelle
Paste the form URL from your MailChimp audience,Collez l'URL du formulaire à partir de votre audience MailChimp
Magento always manage emails,Magento gère toujours les e-mails
Enable Two Way Sync,Activer la synchronisation bidirectionnelle
"If this is set to ""No"", the synchronization will be from Magento's newsletter to Mailchimp only","Si cette option est définie sur « Non », la synchronisation se fera uniquement de la newsletter de Magento vers Mailchimp"
Create Webhook,Créer un Webhook
Webhooks Delete action,Action de suppression des Webhooks
Enable Log,Activer le journal
Customer Fields Mapping,Mappage des champs client
Add the magento to mailchimp mapping,Ajoutez le mappage magento vers mailchimp
Map the magento customer field to mailchimp merge_fields,Mappez le champ client magento vers les champs de fusion mailchimp
Resync Subscribers,Resynchroniser Abonnés
Fix Mailchimp JS in frontend,Correction du JS Mailchimp dans le frontend
Available Groups,Groupes disponibles
"If you set up groups in Mailchimp , include them in your checkout page so customers can choose the type of email marketing they want to receive.","Si vous configurez des groupes dans Mailchimp , incluez-les dans votre page de paiement afin que les clients puissent choisir le type de marketing par e-mail qu'ils souhaitent recevoir."
Show groups after checkout?,Afficher les groupes après le paiement ?
"Don't use in magento 2.1 see at here ","Ne pas utiliser dans magento 2.1, voir ici "
Group Description,Description du groupe
Success message,Message de réussite
Connection timeout,Délai de connexion expiré
Ecommerce Configuration,Configuration du commerce électronique
Subscribe all customers to the newsletter,Abonnez tous les clients à la newsletter
First Date,Premier rendez-vous
Send Promo Rules and Promo Codes,Envoyer les règles de promotion et les codes promotionnels
Prices including taxes,Prix TTC
"You must configure Price Display Settings in Sales/Tax to ""including taxes""","Vous devez configurer les paramètres d'affichage des prix dans Ventes/Taxes sur ""TTC"""
Campaign Attribution Action,Action d'attribution de campagne
Order attribution based on customer actions,Attribution de commande en fonction des actions du client
Reset Errors and retry,Réinitialiser les erreurs et réessayer
Truncate the errors table and retry all the registers with error,Tronquer la table des erreurs et réessayer tous les registres avec erreur
Reset Errors and no retry,Réinitialiser les erreurs et ne pas réessayer
Truncate the errors table and no retry all the registers with error,Tronquer la table des erreurs et ne pas réessayer tous les registres avec erreur
Months to clear the error table,Mois pour effacer la table des erreurs
How many month before clean the error from the error table automatically and not retry,Combien de mois avant de nettoyer automatiquement l'erreur de la table des erreurs et de ne pas réessayer
Delete Store,Supprimer la boutique
"Proceed with caution, this delete the mailchimp store for all the connected magento stores","Procédez avec prudence, cela supprime la boutique Mailchimp pour toutes les boutiques Magento connectées"
Resync all products,Resynchroniser tout produits
Abandoned Cart Configuration,Configuration du panier abandonné
Redirect Page,Page de redirection
Save Email to the Quote before place Order,Enregistrer l'e-mail dans le devis avant de passer la commande
Select No to prevent saving customer Email to the quote before Order was placed,Sélectionnez Non pour empêcher l'enregistrement de l'e-mail du client dans le devis avant la passation de la commande
"Must be logged in to MailChimp's website previously to see the automation wizard, re-open if not","Vous devez être connecté au site Web de MailChimp au préalable pour voir l'assistant d'automatisation, rouvrez-le si ce n'est pas le cas"
All Store Views,Toutes les vues de la boutique
Store View,Vue de la boutique
ID,ID
Status,Statut
Last modified,Dernière modification
#Customers,#Clients
#Orders,#Commandes
#Products,#Produits
#Carts,#Paniers
#Subscribers,#Abonnés
Batch JSON,Lot JSON
Job Code,Code de tâche
Messages,Messages
Created at,Créé à
Scheduled at,Planifié à
Executed at,Exécuté à
Finished at,Terminé à
Type,Type
Title,Titre
Date,Date
Action,Action
Create New Mailchimp Store,Créer une nouvelle boutique Mailchimp
MC Account name,Nom du compte MC
Store name,Nom de la boutique
List name,Nom de la liste
Mailchimp Sync,Synchronisation Mailchimp
Sync all customers or only customer with orders,Synchroniser tous les clients ou uniquement les clients avec les commandes
================================================
FILE: i18n/it_IT.csv
================================================
MailChimp,MailChimp
Save,Salva
Save and Continue Edit,Salva e continua Modifica
Delete,Elimina
Edit Store '%1',Modifica negozio '%1'
Add Store,Aggiungi negozio
Address,Indirizzo
Street,Via
City,Citt
Postal Code,Codice postale
Select one,Selezionane uno
Country,Paese
Store Address Info,Informazioni indirizzo negozio
General,Generale
Apikey,ApiKey
Select first an ApiKey,Seleziona prima un'ApiKey
List,Elenco
Name,Nome
Domain,Dominio
Email,E-mail
Currency,Valuta
Locale,Locale
TimeZone,Fuso orario
Phone,Telefono
Store Info,Informazioni negozio
Mailchimp Store Information,Informazioni negozio Mailchimp
button_label,button_label
Mailchimp,Mailchimp
Magento,Magento
Add,Aggiungi
Shipping Zip Code,CAP spedizione
Shipping Country,Paese spedizione
Shipping City,Città di spedizione
Shipping State,Stato spedizione
Shipping Telephone,Telefono spedizione
Shipping Company,Compagnia di spedizione
Shipping Street,Via di spedizione
Billing Zip Code,CAP fatturazione
Billing Country,Paese fatturazione
Billing City,Città fatturazione
Billing State,Stato fatturazione
Billing Telephone,Telefono fatturazione
Billing Company,Compagnia fatturazione
Billing Street,Via della fatturazione
Mailchimp Batches,Batch Mailchimp
Mailchimp Cron,Cron Mailchimp
User name:,Nome utente:
Total Account Subscribers:,Totale iscritti account:
Total List Subscribers:,Totale iscritti elenco:
Ecommerce Data uploaded to MailChimp:,Dati e-commerce caricati su MailChimp:
Total customers:,Totale clienti:
Total products:,Totale prodotti:
Total orders:,Totale ordini:
Total Carts:,Totale carrelli:
"Ecommerce disabled, save configuration to enable","E-commerce disabilitato, salva configurazione per abilitare"
"Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized)","Ecommerce disabilitato, solo gli abbonati saranno sincronizzati (i tuoi ordini, prodotti, ecc. non saranno sincronizzati)"
--- Invalid API Key ---,--- Chiave API non valida ---
Mailchimp Errors,Errori Mailchimp
You deleted the store.,Hai eliminato il negozio.
'Store could not be deleted.' .,'Impossibile eliminare il negozio.' .
This store no longer exists.,Questo negozio non esiste più.
Mailchimp Store,Mailchimp Store
Mailchimp Stores,Mailchimp Stores
'Store could not be saved.' .,'Impossibile salvare il negozio.' .
You can't access this cart,Non puoi accedere a questo carrello
Login to complete your order,Accedi per completare l'ordine
Thanks for sharing your interest with us,Grazie per aver condiviso il tuo interesse con noi
Json error,Errore Json
Error retrieving interest groups for store ,Errore nel recupero dei gruppi di interesse per il negozio
Order [' . . '] is empty,L'ordine [' . . '] è vuoto
Parent rule with id ' . . 'has not been correctly sent.,La regola padre con ID ' . . 'non � stata inviata correttamente.
Something went wrong when retrieving the information for promo rule,Si è verificato un errore durante il recupero delle informazioni per la regola promozionale
Something went wrong when retrieving the information.,Si è verificato un problema durante il recupero delle informazioni.
Invalid API Key,Chiave API non valida
Username,Nome utente
This account is currently syncing,Questo account è attualmente in fase di sincronizzazione
Account Synced since,Account sincronizzato da
---No Data---,---Nessun dato---
No,No
Unsubscribe,Annulla iscrizione
Delete subscriber,Elimina abbonato
Syncing,Sincronizzazione
Synced,Sincronizzato
Waiting,In attesa
Error,Errore
Resyncing,Risincronizzazione
With error,Con errore
Unsupported,Non supportato
Edit,Modifica
MailChimp Information,Informazioni MailChimp
No Interest groups found,Nessun gruppo di interesse trovato
Mailchimp v,Mailchimp v
by,di
Need help? See our ,Hai bisogno di aiuto? Consulta il nostro
Wiki,Wiki
Got feedback? ,Hai feedback?
Email us,Inviaci un'e-mail
You can find more extension in our ,Puoi trovare altre estensioni nel nostro
Store,Negozio
Subscribe to more detailed newsletters,Subscribe to more detailed newsletters
Newsletter,Newsletter
Sign Up for Our Newsletter:,Iscriviti alla nostra newsletter:
Enter your email address,Inserisci il tuo indirizzo e-mail
Enter your phone,Inserisci il tuo telefono
Subscribe,Iscriviti
Mailchimp General Configuration,Configurazione generale di Mailchimp
Enabled,Abilitato
API Key,Chiave API
You must create a MailChimp Store for this API key to connect to this account,Devi creare un MailChimp Store per questa chiave API per connetterti a questo account
Mailchimp List,Elenco Mailchimp
Account Details,Dettagli account
Change the footer link,Cambia il collegamento del piè di pagina
"Enabling this, the ""Subscribe"" button at the bottom open a popup with the Mailchimp subscription form","Abilitando questa opzione, il pulsante ""Iscriviti"" in basso apre un popup con il modulo di iscrizione a Mailchimp"
Popup Url,URL popup
Paste the form URL from your MailChimp audience,Incolla l'URL del modulo dal tuo pubblico MailChimp
Magento always manage emails,Magento gestisce sempre le e-mail
Enable Two Way Sync,Abilita sincronizzazione bidirezionale
"If this is set to ""No"", the synchronization will be from Magento's newsletter to Mailchimp only","Se impostato su ""No"", la sincronizzazione avverrà solo dalla newsletter di Magento a Mailchimp"
Create Webhook,Crea webhook
Webhooks Delete action,Azione di eliminazione dei webhook
Enable Log,Abilita registro
Customer Fields Mapping,Mappatura campi cliente
Add the magento to mailchimp mapping,Aggiungi la mappatura di Magento a Mailchimp
Map the magento customer field to mailchimp merge_fields,Mappa il campo cliente di Magento ai merge_field di Mailchimp
Resync Subscribers,Risincronizza gli iscritti
Fix Mailchimp JS in frontend,Correggi Mailchimp JS nel frontend
Available Groups,Gruppi disponibili
"If you set up groups in Mailchimp , include them in your checkout page so customers can choose the type of email marketing they want to receive.","Se configuri gruppi in Mailchimp , includili nella pagina di pagamento in modo che i clienti possano scegliere il tipo di email marketing che desiderano ricevere."
Show groups after checkout?,Mostra i gruppi dopo il checkout?
"Don't use in magento 2.1 see at here ","Non utilizzare in Magento 2.1, vedere qui "
Group Description,Descrizione gruppo
Success message,Messaggio di successo
Connection timeout,Timeout di connessione
Ecommerce Configuration,Configurazione e-commerce
Subscribe all customers to the newsletter,Iscrivi tutti i clienti alla newsletter
First Date,Primo appuntamento
Send Promo Rules and Promo Codes,Invia regole promozionali e codici promozionali
Prices including taxes,Prezzi tasse incluse
"You must configure Price Display Settings in Sales/Tax to ""including taxes""","È necessario configurare le impostazioni di visualizzazione dei prezzi in Vendite/Imposte su ""incluse le imposte"""
Campaign Attribution Action,Azione di attribuzione campagna
Order attribution based on customer actions,Attribuzione ordine in base alle azioni del cliente
Reset Errors and retry,Reimposta errori e riprova
Truncate the errors table and retry all the registers with error,Tronca la tabella degli errori e riprova tutti i registri con errore
Reset Errors and no retry,Reimposta errori e non riprovare
Truncate the errors table and no retry all the registers with error,Tronca la tabella degli errori e non riprovare tutti i registri con errore
Months to clear the error table,Mesi per cancellare la tabella degli errori
How many month before clean the error from the error table automatically and not retry,Quanti mesi prima di pulire automaticamente l'errore dalla tabella degli errori e non riprovare
Delete Store,Elimina negozio
"Proceed with caution, this delete the mailchimp store for all the connected magento stores","Procedi con cautela, questo elimina il negozio MailChimp per tutti i negozi Magento connessi"
Resync all products,Risincronizza tutti i prodotti
Abandoned Cart Configuration,Configurazione carrello abbandonato
Redirect Page,Pagina di reindirizzamento
Save Email to the Quote before place Order,Salva e-mail nel preventivo prima di effettuare l'ordine
Select No to prevent saving customer Email to the quote before Order was placed,Seleziona No per impedire il salvataggio dell'e-mail del cliente nel preventivo prima che l'ordine venisse effettuato
"Must be logged in to MailChimp's website previously to see the automation wizard, re-open if not","Devi aver effettuato l'accesso al sito Web di MailChimp in precedenza per visualizzare la procedura guidata di automazione, riaprire in caso contrario"
All Store Views,Tutte le visualizzazioni del negozio
Store View,Visualizzazione del negozio
ID,ID
Status,Stato
Last modified,Ultima modifica
#Customers,#Clienti
#Orders,#Ordini
#Products,#Prodotti
#Carts,#Carrelli
#Subscribers,#Iscritti
Batch JSON,JSON batch
Job Code,Codice lavoro
Messages,Messaggi
Created at,Creato alle
Scheduled at,Pianificato alle
Executed at,Eseguito at
Finished at,Finito alle
Type,Tipo
Title,Titolo
Date,Data
Action,Azione
Create New Mailchimp Store,Crea nuovo negozio Mailchimp
MC Account name,Nome account MC
Store name,Nome negozio
List name,Nome elenco
Mailchimp Sync,Sincronizzazione Mailchimp
Sync all customers or only customer with orders,Sincronizza tutti i clienti o solo i clienti con gli ordini
================================================
FILE: modman
================================================
* app/code/Ebizmarts/MailChimp
================================================
FILE: registration.php
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Ebizmarts_MailChimp',
__DIR__
);
================================================
FILE: view/adminhtml/layout/customer_index_edit.xml
================================================
50
================================================
FILE: view/adminhtml/layout/default.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_batch_index.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_carts_index.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_cron_index.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_errors_index.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_stores_edit.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_stores_grid.xml
================================================
================================================
FILE: view/adminhtml/layout/mailchimp_stores_index.xml
================================================
Ebizmarts_MailChimp::stores
complex
================================================
FILE: view/adminhtml/requirejs-config.js
================================================
/**
* Ebizmarts_MailChimp Magento JS component
*
* @category Ebizmarts
* @package Ebizmarts_MailChimp
* @author Ebizmarts Team
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
var config = {
"map": {
"*": {
monkeyapikey: 'Ebizmarts_MailChimp/js/apikey',
configmonkeyapikey: 'Ebizmarts_MailChimp/js/configapikey',
mailchimpconfirmation: 'Ebizmarts_MailChimp/js/mailchimpconfirmation'
}
}
};
================================================
FILE: view/adminhtml/templates/customer/edit/tabs/mailchimp.phtml
================================================
getInterest();
?>
= $block->escapeHtml(__('MailChimp Information')) ?>
= $block->escapeHtml($i['interest']['title']) ?>
escapeHtml('selected'); } ?>>= $block->escapeHtml($c['name']) ?>
= $block->escapeHtml(__("No Interest groups found")); ?>
================================================
FILE: view/adminhtml/templates/system/config/create_abandonedcart_automation.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/createwebhook.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/deletestore.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/fieldset/hint.phtml
================================================
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
?>
",
"detailsUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/getaccountdetails'));?>",
"storeGridUrl": "= $block->escapeUrl($block->getUrl('mailchimp/stores/index'));?>",
"createWebhookUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/createWebhook'));?>",
"getInterestUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/getInterest'));?>",
"resyncSubscribersUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/resyncSubscribers'));?>",
"resyncProductsUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/resyncProducts'));?>",
"fixMailchimpjsUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/fixMailchimpJS'));?>",
"registerUrl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/register'));?>",
"scope": "= $block->escapeHtml($block->getScope());?>",
"scopeId": "= $block->escapeUrl($block->getScopeId()); ?>",
"registerToken": "= $block->escapeUrl($block->getRegisterToken()); ?>",
"switchurl": "= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/SyncLog'));?>"
}}'>
================================================
FILE: view/adminhtml/templates/system/config/fixmailchimpjs.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/js.phtml
================================================
"}}'>
================================================
FILE: view/adminhtml/templates/system/config/oauth_wizard.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/reseterrors.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/reseterrorsnoretry.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/resetstore.phtml
================================================
escapeHtml('Reset errors')); ?>
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/resyncproducts.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/system/config/resyncsubscriber.phtml
================================================
= $block->escapeHtml($block->getButtonLabel()) ?>
================================================
FILE: view/adminhtml/templates/tab/view.phtml
================================================
= $block->getChildHtml(); ?>
================================================
FILE: view/adminhtml/ui_component/customer_listing.xml
================================================
Mailchimp
ui/grid/cells/html
false
================================================
FILE: view/adminhtml/ui_component/mailchimp_batch_grid.xml
================================================
-
- mailchimp_batch_grid.mailchimp_batch_grid_data_source
- mailchimp_batch_grid.mailchimp_batch_grid_data_source
- mailchimp_batch_columns
-
Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
mailchimp_batch_grid_data_source
id
id
-
- Magento_Ui/js/grid/provider
-
- id
-
- ui/grid/toolbar
- ui/grid/sticky/toolbar
-
- true
Magento\Store\Ui\Component\Listing\Column\Store\Options
-
- ${ $.parentName }
- store_id
- All Store Views
- Store View
-
- text
- asc
- ID
-
- text
- asc
- Status
-
- text
- asc
- Last modified
Mailchimp Store
ui/grid/cells/html
false
#Customers
ui/grid/cells/html
false
#Orders
ui/grid/cells/html
false
#Products
ui/grid/cells/html
false
#Carts
ui/grid/cells/html
false
#Subscribers
ui/grid/cells/html
false
-
- id
- Batch JSON
================================================
FILE: view/adminhtml/ui_component/mailchimp_carts_grid.xml
================================================
-
- mailchimp_carts_grid.mailchimp_carts_grid_data_source
- mailchimp_carts_grid.mailchimp_carts_grid_data_source
- mailchimp_carts_columns
-
Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
mailchimp_carts_grid_data_source
id
id
-
- Magento_Ui/js/grid/provider
-
- id
-
- ui/grid/toolbar
- ui/grid/sticky/toolbar
-
- true
Magento\Store\Ui\Component\Listing\Column\Store\Options
-
- ${ $.parentName }
- store_id
- All Store Views
- Store View
text
Customer Email
text
Customer Name
text
Items
text
Qty
textRange
Grand Total
dateRange
date
Quote Date
desc
dateRange
date
Sync Date
desc
mailchimp_sync
0
Mailchimp
ui/grid/cells/html
false
-
- id
- Customer
- 120
================================================
FILE: view/adminhtml/ui_component/mailchimp_cron_grid.xml
================================================
-
- mailchimp_cron_grid.mailchimp_cron_grid_data_source
mailchimp_cron_columns
mailchimp_cron_grid.mailchimp_cron_grid_data_source
schedule_id
schedule_id
schedule_id
-
- number
- schedule_id
-
- text
- desc
- true
- 1
- ID
-
- select
-
-
- ebizmarts_clean_batches
- ebizmarts_clean_batches
-
- ebizmarts_clean_errors
- ebizmarts_clean_errors
-
- ebizmarts_clean_webhooks
- ebizmarts_clean_webhooks
-
- ebizmarts_ecommerce
- ebizmarts_ecommerce
-
- ebizmarts_webhooks
- ebizmarts_webhooks
- select
- Job Code
-
- select
-
-
- error
- error
-
- missed
- missed
-
- pending
- pending
-
- running
- running
-
- scheduled
- scheduled
-
- success
- success
- select
- Status
-
- text
- Messages
dateRange
date
Created at
dateRange
date
Scheduled at
dateRange
date
Executed at
dateRange
date
Finished at
================================================
FILE: view/adminhtml/ui_component/mailchimp_errors_grid.xml
================================================
-
- mailchimp_errors_grid.mailchimp_errors_grid_data_source
- mailchimp_errors_grid.mailchimp_errors_grid_data_source
- mailchimp_errors_columns
-
Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
mailchimp_errors_grid_data_source
id
id
-
- Magento_Ui/js/grid/provider
-
- id
-
- ui/grid/toolbar
- ui/grid/sticky/toolbar
-
- true
Magento\Store\Ui\Component\Listing\Column\Store\Options
-
- ${ $.parentName }
- store_id
- All Store Views
- Store View
-
- text
- asc
- ID
-
- text
- asc
- Type
-
- text
- asc
- Title
-
- text
- asc
- Status
-
- text
- asc
- Error
-
- text
- asc
- Date
-
- id
- Action
================================================
FILE: view/adminhtml/ui_component/mailchimp_stores_grid.xml
================================================
-
- mailchimp_stores_grid.mailchimp_stores_grid_data_source
- mailchimp_stores_grid.mailchimp_stores_grid_data_source
- mailchimp_stores_columns
-
-
- add
- Create New Mailchimp Store
- primary
- mailchimp/stores/edit
Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
mailchimp_stores_grid_data_source
id
id
-
- Magento_Ui/js/grid/provider
-
- id
- false
-
- ui/grid/toolbar
- ui/grid/sticky/toolbar
Magento\Store\Ui\Component\Listing\Column\Store\Options
-
- ${ $.parentName }
- store_id
- All Store Views
- Store View
-
- text
- asc
- MC Account name
- 30
-
- text
- asc
- Store name
- 40
-
- text
- asc
- List name
- 50
-
- text
- asc
- Email
- 60
-
- id
- 70
================================================
FILE: view/adminhtml/ui_component/product_listing.xml
================================================
mailchimp_sync
0
true
Mailchimp
ui/grid/cells/html
false
================================================
FILE: view/adminhtml/ui_component/sales_order_grid.xml
================================================
Mailchimp Sync
ui/grid/cells/html
false
-
- id
- MailChimp
================================================
FILE: view/adminhtml/web/css/styles.css
================================================
@font-face {
font-family: 'mailchimp';
src: url('../fonts/mailchimp.eot?3g8ubh');
src: url('../fonts/mailchimp.eot?3g8ubh#iefix') format('embedded-opentype'),
url('../fonts/mailchimp.ttf?3g8ubh') format('truetype'),
url('../fonts/mailchimp.woff?3g8ubh') format('woff'),
url('../fonts/mailchimp.svg?3g8ubh#mailchimp') format('svg');
font-weight: normal;
font-style: normal;}
.admin__menu .item-mailchimp-menu.parent.level-0 > a:before {
font-family: 'mailchimp';
content: "\e991"
}
.admin__data-grid-wrap .data-grid .data-grid-draggable .data-row .data-grid-thumbnail-cell .admin__control-thumbnail > img:before {
border:none;
}
.freddie {
background-image:url('../images/freddie.png');
background-repeat:no-repeat;
font-size:0px;
display:block;
background-size: 20px;
background-position: right bottom;
}
================================================
FILE: view/adminhtml/web/js/apikey.js
================================================
/**
* Ebizmarts_MailChimp Magento JS component
*
* @category Ebizmarts
* @package Ebizmarts_MailChimp
* @author Ebizmarts Team
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
define(
[
'jquery',
'Magento_Ui/js/modal/alert'
],
function ($,alert) {
"use strict";
$.widget('mage.monkeyapikey', {
"options": {
"apikeyUrl": ""
},
_init: function () {
var apiUrl = this.options.apikeyUrl;
$('#stores_apikey').change(function () {
// remove all items in list combo
$('#stores_list_id').empty();
// get the selected apikey
var apiKey = $('#stores_apikey').find(':selected').val();
// get the list for this apikey via ajax
//var apiUrl = this.options.apikeyUrl;
$.ajax({
url: apiUrl,
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, 'encrypt': 1},
type: 'POST',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.valid==1) {
$.each(data.lists, function (i, item) {
$('#stores_list_id').append($('', {
value: item.id,
text: item.name
}));
});
} else {
alert({content:data.errormsg});
}
});
});
}
});
return $.mage.monkeyapikey;
}
);
================================================
FILE: view/adminhtml/web/js/configapikey.js
================================================
/**
* Ebizmarts_MailChimp Magento JS component
*
* @category Ebizmarts
* @package Ebizmarts_MailChimp
* @author Ebizmarts Team
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
define(
[
'jquery',
'Magento_Ui/js/modal/alert',
'Magento_Ui/js/modal/confirm'
],
function ($, alert, confirmation) {
"use strict";
$.widget('mage.configmonkeyapikey', {
"options": {
"storeUrl": "",
"detailsUrl": "",
"storeGridUrl": "",
"createWebhookUrl": "",
"getInterestUrl": "",
"resyncSubscribersUrl": "",
"resyncProductsUrl": "",
"fixMailchimpjsUrl": "",
"registerUrl": "",
"scope": "",
"scopeId": "",
"registerToken": "",
"switchurl": ""
},
_init: function () {
var self = this;
if(!this.options.registerToken && $('#mailchimp_general_monkeystore').find(':selected').val() > 0) {
self._showRegistationDetails();
}
$('#mailchimp_general_apikey').change(function () {
var apiKey = $('#mailchimp_general_apikey').val();
self._loadStores(apiKey);
});
$('#mailchimp_general_monkeystore').change(function () {
self._loadDetails();
// self._loadInterest();
});
$('#row_mailchimp_general_monkeystore').find('.note').append(' here ');
if ($('#mailchimp_general_monkeystore option').length > 1) {
$('#row_mailchimp_general_monkeystore .note').hide();
}
$('#mailchimp_general_webhook_create').click(function () {
var apiKey = $('#mailchimp_general_apikey').val();
var listId = $('#mailchimp_general_monkeylist').find(':selected').val();
self._createWebhook(apiKey, listId);
});
$('#mailchimp_general_resync_subscribers').click(function () {
var listId = $('#mailchimp_general_monkeylist').find(':selected').val();
self._resyncSubscribers(listId);
});
$('#mailchimp_ecommerce_resync_products').click(function () {
var mailchimpStoreId = $('#mailchimp_general_monkeystore').find(':selected').val();
self._resyncProducts(mailchimpStoreId);
});
$('#mailchimp_general_fix_mailchimpjs').click(function () {
self._fixMailchimpJS();
});
$('#mailchimp_ecommerce_active').change(function () {
var ecommerceEnabled = $('#mailchimp_ecommerce_active').find(':selected').val();
var abandonedCartEnabled = $('#mailchimp_abandonedcart_active').find(':selected').val();
if (ecommerceEnabled == 0 && abandonedCartEnabled == 1) {
self._changeEcommerce();
}
});
$('#mailchimp_abandonedcart_active').change(function () {
var ecommerceEnabled = $('#mailchimp_ecommerce_active').find(':selected').val();
var abandonedCartEnabled = $('#mailchimp_abandonedcart_active').find(':selected').val();
if (ecommerceEnabled == 0 && abandonedCartEnabled == 1) {
self._changeAbandonedCart();
}
});
$('#mailchimp_general_enable_support').change(function () {
var supportenabled = $('#mailchimp_general_enable_support').find(':selected').val();
self._switchsupport(supportenabled);
});
$('#mailchimp_support').click(function () {
self._showSupport();
});
var ecommerceEnabled = $('#mailchimp_ecommerce_active').find(':selected').val();
var abandonedCartEnabled = $('#mailchimp_abandonedcart_active').find(':selected').val();
if (ecommerceEnabled == 0 && abandonedCartEnabled == 1) {
self._changeAbandonedCart();
}
$('#mailchimp_ecommerce_campaign_action').attr('size',3);
},
_changeEcommerce: function () {
var self = this;
confirmation( {
content: "If you disable Ecommerce, we will disable Abandoned Cart",
actions: {
confirm: function () {
var tag = '#mailchimp_abandonedcart_active'
$(tag).empty();
$(tag).append($('', {
value: "0",
text: 'No',
selected: "selected"
}));
$(tag).append($(' ', {
value: "1",
text: 'Yes'
}));
self._hideAbandonedCart();
},
cancel: function () {
var tag = '#mailchimp_ecommerce_active'
$(tag).empty();
$(tag).append($(' ', {
value: "0",
text: 'No',
}));
$(tag).append($(' ', {
value: "1",
text: 'Yes',
selected: "selected"
}));
self._showEcommerce();
}
}
}
);
},
_changeAbandonedCart: function () {
var self = this;
confirmation( {
content: "If you enable Abandoned Cart we need to enable Ecommerce",
actions: {
confirm: function () {
var tag = '#mailchimp_ecommerce_active'
$(tag).empty();
$(tag).append($(' ', {
value: "0",
text: 'No'
}));
$(tag).append($(' ', {
value: "1",
text: 'Yes',
selected: "selected"
}));
self._showEcommerce();
},
cancel: function () {
var tag = '#mailchimp_abandonedcart_active'
$(tag).empty();
$(tag).append($(' ', {
value: "0",
text: 'No',
selected: "selected"
}));
$(tag).append($(' ', {
value: "1",
text: 'Yes'
}));
self._hideAbandonedCart();
}
}
}
);
},
_hideAbandonedCart: function () {
$("#row_mailchimp_abandonedcart_firstdate").hide();
$("#row_mailchimp_abandonedcart_page").hide();
$("#row_mailchimp_abandonedcart_save_email_in_quote").hide();
$("#row_mailchimp_abandonedcart_create_abandonedcart_automation").hide();
},
_showEcommerce: function () {
$("#row_mailchimp_ecommerce_all_customers").show();
$("#mailchimp_ecommerce_all_customers").show();
$("#row_mailchimp_ecommerce_customer_optin").show();
$("#mailchimp_ecommerce_customer_optin").show();
$("#row_mailchimp_ecommerce_firstdate").show();
$("#mailchimp_ecommerce_firstdate").show();
$("#row_mailchimp_ecommerce_send_promo").show();
$("#mailchimp_ecommerce_send_promo").show();
$("#row_mailchimp_ecommerce_including_taxes").show();
$("#mailchimp_ecommerce_including_taxes").show();
$("#row_mailchimp_ecommerce_reset_errors_retry").show();
$("#mailchimp_ecommerce_reset_errors_retry").show();
$("#row_mailchimp_ecommerce_reset_errors_noretry").show();
$("#mailchimp_ecommerce_reset_errors_noretry").show();
$("#row_mailchimp_ecommerce_clean_errors_months").show();
$("#mailchimp_ecommerce_clean_errors_months").show();
$("#row_mailchimp_ecommerce_delete_store").show();
$("#mailchimp_ecommerce_delete_store").show();
$("#row_mailchimp_ecommerce_resync_products").show();
$("#mailchimp_ecommerce_resync_products").show();
},
_fixMailchimpJS: function ()
{
var fixMailchimpjsUrl = this.options.fixMailchimpjsUrl;
var scope = this.options.scope;
var scopeId = this.options.scopeId;
$.ajax({
url: fixMailchimpjsUrl,
data: {'form_key': window.FORM_KEY,'scope': scope, 'scopeId': scopeId},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.valid == 0) {
alert({content: 'Error: can\'t fix it'});
} else if (data.valid == 1) {
alert({content: 'Frontend fixed, please refresh your cache'});
}
});
},
_resyncSubscribers: function (listId) {
var resyncSubscribersUrl = this.options.resyncSubscribersUrl;
$.ajax({
url: resyncSubscribersUrl,
data: {'form_key': window.FORM_KEY, 'listId': listId},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.valid == 0) {
alert({content: 'Error: can\'t resync your subscribers'});
} else if (data.valid == 1) {
alert({content: 'All subscribers marked for resync'});
}
});
},
_resyncProducts: function (mailchimpStoreId) {
var resyncProductsUrl = this.options.resyncProductsUrl;
$.ajax({
url: resyncProductsUrl,
data: {'form_key': window.FORM_KEY, 'mailchimpStoreId': mailchimpStoreId},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.valid == 0) {
alert({content: 'Error: can\'t resync your products'});
} else if (data.valid == 1) {
alert({content: 'All products marked for resync'});
}
});
},
_createWebhook: function (apiKey, listId) {
var createWebhookUrl = this.options.createWebhookUrl;
var scope = this.options.scope;
var scopeId = this.options.scopeId;
$.ajax({
url: createWebhookUrl,
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, 'listId': listId, 'scope': scope, 'scopeId': scopeId},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.valid == 0) {
alert({content: 'Error: can\'t create WebHook. Your WebHook is already created or your web is private'});
} else if (data.valid == 1) {
alert({content: 'WebHook created'});
}
});
},
_loadStores: function (apiKey) {
var self = this;
var storeUrl = this.options.storeUrl;
// remove all items in list combo
$('#mailchimp_general_monkeystore').empty();
// get the selected apikey
$('#mailchimp_general_monkeystore').append($(' ', {
value: -1,
text: 'Select one Mailchimp Store'
}));
$('#mailchimp_general_monkeylist').append($(' ', {
value: -1,
text: 'Select one Mailchimp Store'
}));
// get the list for this apikey via ajax
$.ajax({
url: storeUrl,
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, 'encrypt': 0},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.valid == 1) {
var unique = data.stores.length;
$.each(data.stores, function (i, item) {
if (unique == 1) {
$('#mailchimp_general_monkeystore').append($(' ', {
value: item.id,
text: item.name,
selected: "selected"
}));
} else {
$('#mailchimp_general_monkeystore').append($(' ', {
value: item.id,
text: item.name
}));
}
});
if ($('#mailchimp_general_monkeystore option').length > 1) {
$('#row_mailchimp_general_monkeystore').find('.note').hide();
} else {
$('#row_mailchimp_general_monkeystore').find('.note').show();
}
self._loadDetails();
} else {
if (data.errormsg != '') {
alert({content: data.errormsg});
} else {
alert({content: "API Key Invalid"});
}
}
});
},
_showSupport: function () {
alert({content: "By leveraging remote diagnostics for the Mailchimp for Magento plugin, our technical team can pinpoint and resolve syncing issues while ensuring that no sensitive data is involved in the troubleshooting process."});
},
_showRegistationDetails: function () {
var registerUrl = this.options.registerUrl;
var detailsUrl = this.options.detailsUrl;
var accountdata = {};
var apiKey = $('#mailchimp_general_apikey').val();
var scope = this.options.scope;
var scopeId = this.options.scopeId;
var selectedStore = $('#mailchimp_general_monkeystore').find(':selected').val();
var encrypt = 0;
if (apiKey == '******') {
encrypt = 3;
}
$.ajax({
url: detailsUrl,
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "store": selectedStore, 'encrypt': encrypt, "scope": scope, "scopeId": scopeId},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
$.each(data, function (i, item) {
if (item.hasOwnProperty('label')) {
$('#mailchimp_general_account_details_ul').append('' + item.label + ' ' + item.value + ' ');
} else if (item.hasOwnProperty('code')) {
accountdata[item.code] = {'value': item.value, 'html': item.html};
}
});
var outputtext = ""
for (const key in accountdata) {
if (accountdata.hasOwnProperty(key)) {
outputtext += '' + accountdata[key]['html'] + ' ' + accountdata[key]['value'] + ' ';
}
}
outputtext += '
';
confirmation({
content: "Confirm your data " + outputtext,
actions: {
confirm: function () {
$.ajax({
url: registerUrl,
dataType: 'json',
data: {
'form_key': window.FORM_KEY,
'apikey': apiKey,
"data": accountdata,
'scope': scope,
'scopeId': scopeId
},
type: 'POST',
showLoader: true
}).done(function (data) {
if (data.error == 0) {
alert({content: 'You confirm, thanks ' + data.token});
} else {
alert({content: "Something went wrong!"});
}
});
},
cancel: function () {
$('#mailchimp_general_monkeystore option[value="-1"]').attr('selected', 'selected');
$('#mailchimp_general_monkeylist').empty();
}
}
}
);
}
)
},
_switchsupport: function (supportenabled) {
var scope = this.options.scope;
var scopeId = this.options.scopeId;
var switchurl = this.options.switchurl;
$.ajax({
url: switchurl,
data: {'form_key': window.FORM_KEY, 'scope': scope, 'scopeId': scopeId,'onoff': supportenabled},
dataType: 'json',
type: 'POST',
showLoader: true
}).done(function (data) {
if (data.error == 1) {
alert({content: data.message});
$('#mailchimp_general_enable_support option[value="0"]').prop('selected', 'selected');
}
})
},
_loadDetails: function () {
var registerUrl = this.options.registerUrl;
var detailsUrl = this.options.detailsUrl;
var interestUrl = this.options.getInterestUrl;
var apiKey = $('#mailchimp_general_apikey').val();
var selectedStore = $('#mailchimp_general_monkeystore').find(':selected').val();
var encrypt = 0;
var accountdata = {};
var scope = this.options.scope;
var scopeId = this.options.scopeId;
if (apiKey == '******') {
encrypt = 3;
}
$('#mailchimp_general_account_details_ul').empty();
$('#mailchimp_general_monkeylist').empty();
$.ajax({
url: detailsUrl,
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "store": selectedStore, 'encrypt': encrypt, 'scope': scope, 'scopeId': scopeId},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
$.each(data, function (i, item) {
if (item.hasOwnProperty('label')) {
$('#mailchimp_general_account_details_ul').append('' + item.label + ' ' + item.value + ' ');
} else if (item.hasOwnProperty('code')) {
accountdata[item.code] = {'value': item.value,'html':item.html};
}
});
if (data.list_id) {
$('#mailchimp_general_monkeylist').append($(' ', {
value: data.list_id,
text: data.list_name,
selected: "selected"
}));
}
var selectedList = data.list_id;
$('#mailchimp_general_interest').empty();
$.ajax({
url: interestUrl,
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "list": selectedList, "encrypt": encrypt},
type: 'GET',
dataType: 'json',
showLoader: true
}).done(function (data) {
if (data.error == 0) {
if (data.data.length) {
$.each(data.data, function (i, item) {
$('#mailchimp_general_interest').append($(' ', {
value: item.id,
text: item.title
}));
});
} else {
$('#mailchimp_general_interest').append($(' ', {
label: '---No Data---'
}));
}
}
});
if ($('#mailchimp_general_monkeystore').find(':selected').val() <= 0) {
return;
}
var outputtext = ""
for (const key in accountdata) {
if (accountdata.hasOwnProperty(key)) {
outputtext += ''+accountdata[key]['html'] + ' ' + accountdata[key]['value']+' ';
}
}
outputtext += '
';
confirmation( {
content: "Confirm your data "+outputtext,
actions: {
confirm: function () {
$.ajax({
url: registerUrl,
dataType: 'json',
data: {'form_key': window.FORM_KEY, 'apikey': apiKey, "data": accountdata,'scope': scope, 'scopeId': scopeId},
type: 'POST',
showLoader: true
}).done(function (data) {
if (data.error == 0) {
alert({content: 'You confirm, thanks '+data.token});
} else {
alert({content: "Something went wrong!"});
}
});
},
cancel: function () {
$('#mailchimp_general_monkeystore option[value="-1"]').attr('selected', 'selected');
$('#mailchimp_general_monkeylist').empty();
}
}
}
);
});
}
});
return $.mage.configmonkeyapikey;
}
);
================================================
FILE: view/adminhtml/web/js/mailchimpconfirmation.js
================================================
/**
* Ebizmarts_MailChimp Magento JS component
*
* @category Ebizmarts
* @package Ebizmarts_MailChimp
* @author Ebizmarts Team
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
define(
[
'jquery',
'Magento_Ui/js/modal/confirm',
'Magento_Ui/js/modal/alert'
], function ($ , confirmation, alert) {
'use strict';
window.mailchimpdeleteconfirmation = function (ajaxurl) {
var message = 'Are you sure you want to do this?';
confirmation( {
content: message,
actions: {
confirm: function () {
$.ajax({
url: ajaxurl,
data: {form_key: window.FORM_KEY},
type: 'POST',
success: function (retdata) {
if (retdata.valid == 0) {
alert({
content: 'Error: ' + data.message
});
}
else if (retdata.valid == 1) {
alert({
content: 'Operation OK'
});
}
}
}).done(function (a) {
console.log(a);
});
}
}
});
return false;
}
}
);
================================================
FILE: view/frontend/layout/checkout_onepage_success.xml
================================================
================================================
FILE: view/frontend/layout/default.xml
================================================
Ebizmarts_MailChimp::footer.phtml
================================================
FILE: view/frontend/layout/mailchimp_cart_loadquote.xml
================================================
================================================
FILE: view/frontend/layout/newsletter_manage_index.xml
================================================
================================================
FILE: view/frontend/requirejs-config.js
================================================
/**
* Ebizmarts_MailChimp Magento JS component
*
* @category Ebizmarts
* @package Ebizmarts_MailChimp
* @author Ebizmarts Team
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
var config = {
"map": {
"*": {
campaigncatcher: 'Ebizmarts_MailChimp/js/campaigncatcher'
}
}
};
================================================
FILE: view/frontend/templates/catcher.phtml
================================================
"}}'>
================================================
FILE: view/frontend/templates/checkout/order/success.phtml
================================================
getInterest();
//echo $interest;
?>
= $block->escapeHtml($block->getMessageBefore()) ?>
= $block->escapeHtml($block->getMessageAfter()) ?>
================================================
FILE: view/frontend/templates/footer.phtml
================================================
= $block->escapeHtml(__('Newsletter')) ?>
= $block->escapeHtml(__('Subscribe')) ?>
================================================
FILE: view/frontend/templates/form/newsletter.phtml
================================================
getInterest();
?>
= $block->escapeHtml($i['interest']['title']) ?>
escapeHtml('selected'); } ?>>= $block->escapeHtml($c['name']) ?>
================================================
FILE: view/frontend/templates/loadquote.phtml
================================================
================================================
FILE: view/frontend/templates/mailchimpjs.phtml
================================================
getJsUrl();
?>
================================================
FILE: view/frontend/web/js/campaigncatcher.js
================================================
/**
* Ebizmarts_MailChimp Magento JS component
*
* @category Ebizmarts
* @package Ebizmarts_MailChimp
* @author Ebizmarts Team
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
define(
[
'jquery',
'mage/cookies'
],
function ($) {
"use strict";
$.widget('mage.campaigncatcher', {
"options": {
"checkCampaignUrl": ""
},
_init: function () {
var self = this;
$(document).ready(function () {
var path = location;
var urlparams = null;
var isGet = path.search.search('\\?');
var mc_cid = null;
var isMailchimp = false;
var checkCampaignUrl = self.options.checkCampaignUrl;
if(isGet != -1) {
urlparams = self.getUrlVars();
urlparams.forEach(function (item) {
if (item.key=='utm_source') {
var reg = /^mailchimp$/;
if (reg.exec(item.value)) {
isMailchimp = true;
}
} else {
if (item.key=='mc_cid') {
mc_cid = item.value;
}
}
});
} else {
urlparams = path.href.split('/');
var utmIndex = $.inArray('utm_source', urlparams);
var mccidIndex = $.inArray('mc_cid', urlparams);
if (utmIndex != -1) {
var value = urlparams[utmIndex + 1];
var reg = /^mailchimp$/;
if (reg.exec(value)) {
isMailchimp = true;
}
} else {
if (mccidIndex != -1) {
mc_cid = urlparams[mccidIndex + 1];
}
}
}
if (mc_cid && !isMailchimp) {
$.ajax({
url: checkCampaignUrl + 'mc_cid/' + mc_cid + '/',
type: 'GET',
dataType: 'json',
cache: true,
showLoader: false
}).done(function (data) {
if (data.valid==0) {
$.mage.cookies.clear('mailchimp_campaign_id');
$.mage.cookies.set('mailchimp_landing_page', location);
} else if (data.valid==1) {
$.mage.cookies.set('mailchimp_campaign_id' , mc_cid);
$.mage.cookies.set('mailchimp_landing_page', location);
}
});
}
if (isMailchimp) {
$.mage.cookies.clear('mailchimp_campaign_id');
$.mage.cookies.set('mailchimp_landing_page', location);
}
});
},
getUrlVars: function() {
var vars = [];
var i = 0;
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[i] = {'value':value,'key':key};
i++;
});
return vars;
}
});
return $.mage.campaigncatcher;
}
);