[
  {
    "path": "Block/Adminhtml/Customer/Edit/Tabs/Mailchimp.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/29/17 1:55 PM\n * @file: Mailchimp.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Customer\\Edit\\Tabs;\n\nuse Magento\\Customer\\Controller\\RegistryConstants;\nuse Magento\\Ui\\Component\\Layout\\Tabs\\TabInterface;\nuse Magento\\Backend\\Block\\Widget\\Form;\nuse Magento\\Backend\\Block\\Widget\\Form\\Generic;\n\nclass Mailchimp extends \\Magento\\Backend\\Block\\Template implements TabInterface\n{\n    /**\n     * @var \\Magento\\Store\\Model\\System\\Store\n     */\n    protected $_systemStore;\n    /**\n     * @var \\Magento\\Framework\\Registry\n     */\n    protected $_coreRegistry;\n\n    /**\n     * Mailchimp constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param \\Magento\\Framework\\Data\\FormFactory $formFactory\n     * @param \\Magento\\Store\\Model\\System\\Store $systemStore\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\Data\\FormFactory $formFactory,\n        \\Magento\\Store\\Model\\System\\Store $systemStore,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n        $this->_coreRegistry = $registry;\n        $this->_systemStore = $systemStore;\n        parent::__construct($context, $data);\n    }\n\n    public function getCustomerId()\n    {\n        return $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);\n    }\n\n    /**\n     * @return \\Magento\\Framework\\Phrase\n     */\n    public function getTabLabel()\n    {\n        return __('MailChimp');\n    }\n\n    /**\n     * @return \\Magento\\Framework\\Phrase\n     */\n    public function getTabTitle()\n    {\n        return __('MailChimp');\n    }\n\n    /**\n     * @return bool\n     */\n    public function canShowTab()\n    {\n        if ($this->getCustomerId()) {\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * @return bool\n     */\n    public function isHidden()\n    {\n        if ($this->getCustomerId()) {\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * Tab class getter\n     *\n     * @return string\n     */\n    public function getTabClass()\n    {\n        return '';\n    }\n\n    /**\n     * Return URL link to Tab content\n     *\n     * @return string\n     */\n    public function getTabUrl()\n    {\n        return '';\n    }\n\n    /**\n     * Tab should be loaded trough Ajax call\n     *\n     * @return bool\n     */\n    public function isAjaxLoaded()\n    {\n        return false;\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/Customer/Edit/Tabs/View/Customer.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/29/17 2:49 PM\n * @file: Customer.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Customer\\Edit\\Tabs\\View;\n\nclass Customer extends \\Magento\\Backend\\Block\\Template\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $subscriberFactory;\n\n    /**\n     * @var \\Magento\\Framework\\Registry\n     */\n    protected $registry;\n\n    /**\n     * Customer constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Magento\\Framework\\Registry $registry,\n        array $data\n    ) {\n    \n        parent::__construct($context, $data);\n        $this->helper               = $helper;\n        $this->subscriberFactory    = $subscriberFactory;\n        $this->registry             = $registry;\n    }\n\n    public function getInterest()\n    {\n        $subscriber = $this->subscriberFactory->create();\n        $customerId = $this->registry->registry(\\Magento\\Customer\\Controller\\RegistryConstants::CURRENT_CUSTOMER_ID);\n        $subscriber->loadByCustomerId($customerId);\n        return $this->helper->getSubscriberInterest($subscriber->getSubscriberId(), $subscriber->getStoreId());\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/Stores/Edit/Form.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/10/17 4:04 PM\n * @file: Form.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit;\n\nuse Magento\\Backend\\Block\\Widget\\Form\\Generic;\n\nclass Form extends Generic\n{\n    protected function _prepareForm()\n    {\n        /** @var \\Magento\\Framework\\Data\\Form $form */\n        $form = $this->_formFactory->create(\n            [\n                'data' => [\n                    'id'    => 'edit_form',\n                    'action' => $this->getData('action'),\n                    'method' => 'post'\n                ]\n            ]\n        );\n        $form->setUseContainer(true);\n        $this->setForm($form);\n\n        return parent::_prepareForm();\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/Stores/Edit/Tab/Address.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/12/17 5:07 PM\n * @file: Address.php\n */\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit\\Tab;\n\nuse Magento\\Backend\\Block\\Widget\\Form\\Generic;\nuse Magento\\Backend\\Block\\Widget\\Tab\\TabInterface;\nuse Magento\\Backend\\Block\\Template\\Context;\nuse Magento\\Framework\\Registry;\nuse Magento\\Framework\\Data\\FormFactory;\n\nclass Address extends Generic implements TabInterface\n{\n    /**\n     * @var \\Magento\\Directory\\Model\\Config\\Source\\Country\n     */\n    protected $_country;\n\n    /**\n     * Address constructor.\n     * @param Context $context\n     * @param Registry $registry\n     * @param FormFactory $formFactory\n     * @param \\Magento\\Directory\\Model\\Config\\Source\\Country $country\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\Data\\FormFactory $formFactory,\n        \\Magento\\Directory\\Model\\Config\\Source\\Country $country,\n        array $data = []\n    ) {\n    \n        $this->_country = $country;\n        parent::__construct($context, $registry, $formFactory, $data);\n    }\n\n    protected function _prepareForm()\n    {\n        $model  = $this->_coreRegistry->registry('mailchimp_stores');\n        $form   = $this->_formFactory->create();\n        $form->setHtmlIdPrefix('stores_');\n        $form->setFieldNameSuffix('stores');\n        $fieldset = $form->addFieldset(\n            'base_fieldset',\n            ['legend' => __('Address')]\n        );\n        if ($model->getId()) {\n            $fieldset->addField(\n                'id',\n                'hidden',\n                ['name' => 'id']\n            );\n        }\n        $fieldset->addField(\n            'address_address_one',\n            'text',\n            [\n                'name'        => 'address_address_one',\n                'label'    => __('Street'),\n                'required'     => true\n            ]\n        );\n        $fieldset->addField(\n            'address_address_two',\n            'text',\n            [\n                'name'        => 'address_address_two',\n                'label'    => __('Street'),\n                'required'     => false\n            ]\n        );\n        $fieldset->addField(\n            'address_city',\n            'text',\n            [\n                'name'        => 'address_city',\n                'label'    => __('City'),\n                'required'     => true\n            ]\n        );\n        $fieldset->addField(\n            'address_postal_code',\n            'text',\n            [\n                'name'        => 'address_postal_code',\n                'label'    => __('Postal Code'),\n                'required'     => false\n            ]\n        );\n        $country = $this->_country->toOptionArray();\n        $countryArray = [''=> __('Select one')];\n        foreach ($country as $c) {\n            $countryArray[$c['value']] = $c['label'];\n        }\n        $fieldset->addField(\n            'address_country_code',\n            'select',\n            [\n                'name'        => 'address_country_code',\n                'label'    => __('Country'),\n                'required'     => true,\n                'options'   => $countryArray\n            ]\n        );\n\n        $data = $model->getData();\n        $form->setValues($data);\n        $this->setForm($form);\n\n        return parent::_prepareForm();\n    }\n    public function getTabLabel()\n    {\n        return __('Store Address Info');\n    }\n    public function getTabTitle()\n    {\n        return __('Store Address Info');\n    }\n    public function canShowTab()\n    {\n        return true;\n    }\n    public function isHidden()\n    {\n        return false;\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/Stores/Edit/Tab/Info.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/12/17 11:03 AM\n * @file: Info.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit\\Tab;\n\nuse Magento\\Backend\\Block\\Widget\\Form\\Generic;\nuse Magento\\Backend\\Block\\Widget\\Tab\\TabInterface;\nuse Magento\\Backend\\Block\\Template\\Context;\nuse Magento\\Framework\\Registry;\nuse Magento\\Framework\\Data\\FormFactory;\n\nclass Info extends Generic implements TabInterface\n{\n    /**\n     * @var \\Magento\\Config\\Model\\Config\\Source\\Locale\\Timezone\n     */\n    protected $_timezone;\n    /**\n     * @var \\Magento\\Config\\Model\\Config\\Source\\Yesno\n     */\n    protected $_yesno;\n    /**\n     * @var \\Magento\\Config\\Model\\Config\\Source\\Locale\\Currency\n     */\n    protected $_currency;\n    /**\n     * @var \\Magento\\Config\\Model\\Config\\Source\\Locale\n     */\n    protected $_locale;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Config\\Source\\ApiKey\n     */\n    protected $_apikey;\n\n    /**\n     * Info constructor.\n     * @param Context $context\n     * @param Registry $registry\n     * @param FormFactory $formFactory\n     * @param \\Magento\\Config\\Model\\Config\\Source\\Locale\\Timezone $timezone\n     * @param \\Magento\\Config\\Model\\Config\\Source\\Yesno $yesno\n     * @param \\Magento\\Config\\Model\\Config\\Source\\Locale\\Currency $currency\n     * @param \\Magento\\Config\\Model\\Config\\Source\\Locale $locale\n     * @param \\Ebizmarts\\MailChimp\\Model\\Config\\Source\\ApiKey $apiKey\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\Data\\FormFactory $formFactory,\n        \\Magento\\Config\\Model\\Config\\Source\\Locale\\Timezone $timezone,\n        \\Magento\\Config\\Model\\Config\\Source\\Yesno $yesno,\n        \\Magento\\Config\\Model\\Config\\Source\\Locale\\Currency $currency,\n        \\Magento\\Config\\Model\\Config\\Source\\Locale $locale,\n        \\Ebizmarts\\MailChimp\\Model\\Config\\Source\\ApiKey $apiKey,\n        array $data = []\n    ) {\n    \n        $this->_timezone    = $timezone;\n        $this->_yesno       = $yesno;\n        $this->_currency    = $currency;\n        $this->_locale      = $locale;\n        $this->_apikey      = $apiKey;\n        parent::__construct($context, $registry, $formFactory, $data);\n    }\n\n    protected function _prepareForm()\n    {\n        $model  = $this->_coreRegistry->registry('mailchimp_stores');\n        $form   = $this->_formFactory->create();\n        $form->setHtmlIdPrefix('stores_');\n        $form->setFieldNameSuffix('stores');\n\n        $fieldset = $form->addFieldset(\n            'base_fieldset',\n            ['legend' => __('General')]\n        );\n        if ($model->getId()) {\n            $fieldset->addField(\n                'id',\n                'hidden',\n                ['name' => 'id']\n            );\n            $fieldset->addField(\n                'apikey',\n                'hidden',\n                ['name' => 'apikey']\n            );\n            $fieldset->addField(\n                'storeid',\n                'hidden',\n                ['name' => 'storeid']\n            );\n        } else {\n            $this->_apikey->getAllApiKeys();\n            $apikey = $this->_apikey->toOptionArray();\n            $apikeyArray = [];\n            foreach ($apikey as $a) {\n                $apikeyArray[$a['value']] = $a['label'];\n            }\n            $url = $this->_urlBuilder->getUrl('mailchimp/stores/getList');\n            $fieldset->addField(\n                'apikey',\n                'select',\n                [\n                    'name'      => 'apikey',\n                    'label'     => __('Apikey'),\n                    'required'  => true,\n                    'options'   => $apikeyArray,\n                ]\n            );\n            $listArray = [''=>__('Select first an ApiKey')];\n            $fieldset->addField(\n                'list_id',\n                'select',\n                [\n                    'name'      => 'list_id',\n                    'label'     => __('List'),\n                    'required'  => true,\n                    'options'   => $listArray,\n                ]\n            );\n        }\n\n        $fieldset->addField(\n            'name',\n            'text',\n            [\n                'name'        => 'name',\n                'label'    => __('Name'),\n                'required'     => true\n            ]\n        );\n\n        $fieldset->addField(\n            'domain',\n            'text',\n            [\n                'name'        => 'domain',\n                'label'    => __('Domain'),\n                'required'     => true\n            ]\n        );\n\n        $fieldset->addField(\n            'email_address',\n            'text',\n            [\n                'name'        => 'email_address',\n                'label'    => __('Email'),\n                'required'     => true\n            ]\n        );\n        $currency = $this->_currency->toOptionArray();\n        $currencyArray = [''=> __('Select one')];\n        foreach ($currency as $c) {\n            $currencyArray[$c['value']] = $c['label'];\n        }\n        $fieldset->addField(\n            'currency_code',\n            'select',\n            [\n                'name'      => 'currency_code',\n                'label'     => __('Currency'),\n                'required'  => true,\n                'options'   => $currencyArray\n            ]\n        );\n        $locale = $this->_locale->toOptionArray();\n        $localeArray = [''=> __('Select one')];\n        foreach ($locale as $l) {\n            $localeArray[$l['value']] = $l['label'];\n        }\n\n        $fieldset->addField(\n            'primary_locale',\n            'select',\n            [\n                'name'      => 'primary_locale',\n                'label'     => __('Locale'),\n                'required'  => true,\n                'options'   => $localeArray\n            ]\n        );\n        $timezone = $this->_timezone->toOptionArray();\n        $timezoneArray = [''=> __('Select one')];\n        foreach ($timezone as $t) {\n            $timezoneArray[$t['value']] = $t['label'];\n        }\n        $fieldset->addField(\n            'timezone',\n            'select',\n            [\n                'name'        => 'timezone',\n                'label'    => __('TimeZone'),\n                'required'     => true,\n                'options'   => $timezoneArray\n            ]\n        );\n        $fieldset->addField(\n            'phone',\n            'text',\n            [\n                'name'        => 'phone',\n                'label'    => __('Phone'),\n                'required'     => true\n            ]\n        );\n\n        $data = $model->getData();\n        $form->setValues($data);\n        $this->setForm($form);\n\n        return parent::_prepareForm();\n    }\n    public function getTabLabel()\n    {\n        return __('Store Info');\n    }\n    public function getTabTitle()\n    {\n        return __('Store Info');\n    }\n    public function canShowTab()\n    {\n        return true;\n    }\n    public function isHidden()\n    {\n        return false;\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/Stores/Edit/Tabs.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/12/17 11:01 AM\n * @file: Tabs.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit;\n\nuse Magento\\Backend\\Block\\Widget\\Tabs as WidgetTabs;\n\nclass Tabs extends WidgetTabs\n{\n    /**\n     * Class constructor\n     *\n     * @return void\n     */\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setId('stores_edit_tabs');\n        $this->setDestElementId('edit_form');\n        $this->setTitle(__('Mailchimp Store Information'));\n    }\n\n    /**\n     * @return $this\n     */\n    protected function _beforeToHtml()\n    {\n        $this->addTab(\n            'stores_info',\n            [\n                'label' => __('General'),\n                'title' => __('General'),\n                'content' => $this->getLayout()->createBlock(\n                    \\Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit\\Tab\\Info::class\n                )->toHtml(),\n                'active' => true\n            ]\n        );\n        $this->addTab(\n            'stores_address',\n            [\n                'label' => __('Address'),\n                'title' => __('Address'),\n                'content' => $this->getLayout()->createBlock(\n                    \\Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit\\Tab\\Address::class\n                )->toHtml(),\n                'active' => false\n            ]\n        );\n\n        return parent::_beforeToHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/Stores/Edit.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/10/17 1:08 PM\n * @file: Edit.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores;\n\nuse Magento\\Backend\\Block\\Widget\\Form\\Container;\nuse Magento\\Backend\\Block\\Widget\\Context;\nuse Magento\\Framework\\Registry;\n\nclass Edit extends Container\n{\n    /**\n     * @var Registry\n     */\n    protected $_coreRegistry;\n    /**\n     * Edit constructor.\n     * @param Context $context\n     * @param Registry $registry\n     * @param array $data\n     */\n    public function __construct(\n        Context $context,\n        Registry $registry,\n        array $data = []\n    ) {\n    \n        $this->_coreRegistry = $registry;\n        parent::__construct($context, $data);\n    }\n    protected function _construct()\n    {\n        $this->_objectId = 'id';\n        $this->_controller = 'adminhtml_stores';\n        $this->_blockGroup = 'Ebizmarts_MailChimp';\n\n        parent::_construct();\n\n        $this->buttonList->update('save', 'label', __('Save'));\n        $this->buttonList->add(\n            'saveandcontinue',\n            [\n                'label' => __('Save and Continue Edit'),\n                'class' => 'save',\n                'data_attribute' => [\n                    'mage-init' => [\n                        'button' => [\n                            'event' => 'saveAndContinueEdit',\n                            'target' => '#edit_form'\n                        ]\n                    ]\n                ]\n            ],\n            -100\n        );\n        $this->buttonList->update('delete', 'label', __('Delete'));\n    }\n\n    /**\n     * Retrieve text for header element depending on loaded news\n     *\n     * @return string\n     */\n    public function getHeaderText()\n    {\n        $storeRegistry = $this->_coreRegistry->registry('mailchimp_stores');\n        if ($storeRegistry->getId()) {\n            $storeTitle = $this->escapeHtml($storeRegistry->getTitle());\n            return __(\"Edit Store '%1'\", $storeTitle);\n        } else {\n            return __('Add Store');\n        }\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/Account.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass Account extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $values = $element->getValues();\n        $html = '<div id=\"mailchimp_general_account_details\">';\n        $html .= '<ul class=\"checkboxes\" id=\"mailchimp_general_account_details_ul\">';\n        if ($values) {\n            foreach ($values as $dat) {\n                if ($dat['value']!=='') {\n                    $html .= \"<li>{$dat['label']}: {$dat['value']}</li>\";\n                } else {\n                    $html .= \"<li>{$dat['label']}</li>\";\n                }\n            }\n        }\n\n        $html .= '</ul>';\n        $html .= '</div>';\n\n        return $html;\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/CreateAbandonedCart.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass CreateAbandonedCart extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    protected $_template    = 'system/config/create_abandonedcart_automation.phtml';\n\n    private $_url     = \"https://admin.mailchimp.com/#/create-campaign/explore/abandonedCart\";\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n\n        $label = $originalData['button_label'];\n\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->authorizeRequestUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return parent::_toHtml();\n        ;\n    }\n    public function authorizeRequestUrl()\n    {\n        return $this->_url;\n    }\n}"
  },
  {
    "path": "Block/Adminhtml/System/Config/CreateWebhook.php",
    "content": "<?php\n/**\n * Created by PhpStorm.\n * User: gonzalo\n * Date: 3/12/18\n * Time: 2:12 PM\n */\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass CreateWebhook extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n\n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/createwebhook.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'button_url' => $this->getAjaxCheckUrl(),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n\n    public function getButtonHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $label = $originalData['button_label'];\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->getAjaxCreateWebhookUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return $this->_toHtml();\n    }\n    public function getAjaxCreateWebhookUrl()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = [];\n        if (isset($params['website'])) {\n            $scope = ['website'=>$params['website']];\n        } elseif (isset($params['store'])) {\n            $scope = ['store'=>$params['store']];\n        }\n        return $this->_urlBuilder->getUrl('mailchimp/ecommerce/CreateWebhook', $scope);\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/Date.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 9/30/16 2:38 PM\n * @file: Date.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass Date extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    public function render(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $element->setDateFormat(\\Magento\\Framework\\Stdlib\\DateTime::DATE_INTERNAL_FORMAT);\n        $element->setTimeFormat(null);\n        return parent::render($element);\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/DeleteStore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/20/17 3:25 PM\n * @file: ResetErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass DeleteStore extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n    \n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/deletestore.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'button_url' => $this->getAjaxCheckUrl(),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n\n    public function getButtonHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $label = $originalData['button_label'];\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->getAjaxCheckUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return $this->_toHtml();\n    }\n    public function getAjaxCheckUrl()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = [];\n        if (isset($params['website'])) {\n            $scope = ['website'=>$params['website']];\n        } elseif (isset($params['store'])) {\n            $scope = ['store'=>$params['store']];\n        }\n        return $this->_urlBuilder->getUrl('mailchimp/ecommerce/DeleteStore', $scope);\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/Fieldset/Hint.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Fieldset;\n\nclass Hint extends \\Magento\\Backend\\Block\\Template implements\n    \\Magento\\Framework\\Data\\Form\\Element\\Renderer\\RendererInterface\n{\n    /**\n     * @var string\n     */\n    protected $_template = 'Ebizmarts_MailChimp::system/config/fieldset/hint.phtml';\n    /**\n     * @var \\Magento\\Framework\\App\\ProductMetadataInterface\n     */\n    private $_metaData;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var \\Magento\\Backend\\Block\\Template\\Context\n     */\n    private $_context;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Config\\ModuleVersion\n     */\n    private $_moduleVersion;\n\n    /**\n     * Hint constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Magento\\Framework\\App\\ProductMetadataInterface $productMetaData\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\Config\\ModuleVersion $moduleVersion\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Magento\\Framework\\App\\ProductMetadataInterface $productMetaData,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\Config\\ModuleVersion $moduleVersion,\n        array $data = []\n    ) {\n        parent::__construct($context, $data);\n        $this->_metaData = $productMetaData;\n        $this->_helper = $helper;\n        $this->_moduleVersion   = $moduleVersion;\n        $this->_context = $context;\n    }\n    /**\n     * @param \\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element\n     * @return mixed\n     */\n    public function render(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        return $this->toHtml();\n    }\n\n    public function getModuleVersion()\n    {\n        return $this->_moduleVersion->getModuleVersion('Ebizmarts_MailChimp');\n    }\n    public function getHasApiKey()\n    {\n        $apikey = $this->_helper->getApiKey($this->_context->getStoreManager()->getStore()->getId());\n        if ($apikey) {\n            return true;\n        } else {\n            return false;\n        }\n    }\n    public function getScope()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = 'default';\n        if (isset($params['website'])) {\n            $scope = 'website';\n        } elseif (isset($params['store'])) {\n            $scope = 'store';\n        }\n        return $scope;\n    }\n    public function getScopeId()\n    {\n        $params = $this->getRequest()->getParams();\n        $scopeId = 0;\n        if (isset($params['website'])) {\n            $scopeId = $params['website'];\n        } elseif (isset($params['store'])) {\n            $scopeId = $params['store'];\n        }\n        return $scopeId;\n    }\n    public function getRegisterToken()\n    {\n        $scopeId = $this->getScopeId();\n        $scope = $this->getScope();\n        $token = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_STATISTICS_TOKEN, $scopeId, $scope);\n        return $token;\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/FixMailchimpJS.php",
    "content": "<?php\n/**\n * Created by PhpStorm.\n * User: gonzalo\n * Date: 3/12/18\n * Time: 2:12 PM\n */\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass FixMailchimpJS extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n\n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/fixmailchimpjs.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/Form/Field/CustomerMap.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/27/17 12:01 PM\n * @file: CustomerMap.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Form\\Field;\n\nclass CustomerMap extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\\FieldArray\\AbstractFieldArray\n{\n    /**\n     * @var VarsMap\n     */\n    protected $_varsRenderer=null;\n    protected $_mailchimpRenderer=null;\n\n    protected function _getVarsRenderer()\n    {\n        if (!$this->_varsRenderer) {\n            $this->_varsRenderer = $this->getLayout()->createBlock(\n                \\Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Form\\Field\\VarsMap::class,\n                '',\n                ['data' => ['is_render_to_js_template' => true]]\n            );\n            $this->_varsRenderer->setClass('customer_field_select');\n        }\n        return $this->_varsRenderer;\n    }\n    protected function _getMailchimpRenderer()\n    {\n        if (!$this->_mailchimpRenderer) {\n            $this->_mailchimpRenderer = $this->getLayout()->createBlock(\n                \\Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Form\\Field\\MailchimpMap::class,\n                '',\n                ['data' => ['is_render_to_js_template' => true]]\n            );\n            $this->_mailchimpRenderer->setClass('mailchimp_field_select');\n        }\n        return $this->_mailchimpRenderer;\n    }\n\n    protected function _prepareToRender()\n    {\n//        $this->addColumn('mailchimp', ['label' => __('Mailchimp')]);\n        $this->addColumn(\n            'mailchimp_field_id',\n            ['label' => __('Mailchimp'), 'renderer' => $this->_getMailchimpRenderer()]\n        );\n        $this->addColumn(\n            'customer_field_id',\n            ['label' => __('Magento'), 'renderer' => $this->_getVarsRenderer()]\n        );\n        $this->_addAfter = false;\n        $this->_addButtonLabel = __('Add');\n    }\n    protected function _prepareArrayRow(\\Magento\\Framework\\DataObject $row)\n    {\n        $optionExtraAttr = [];\n        $optionExtraAttr['option_' . $this->_getVarsRenderer()->calcOptionHash($row->getData('customer_field_id'))] =\n            'selected=\"selected\"';\n        $optionExtraAttr['option_' . $this->_getMailchimpRenderer()->calcOptionHash(\n            $row->getData('mailchimp_field_id')\n        )\n        ] =\n            'selected=\"selected\"';\n        $row->setData(\n            'option_extra_attrs',\n            $optionExtraAttr\n        );\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/Form/Field/MailchimpMap.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/9/18 1:17 PM\n * @file: MailchimpMap.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Form\\Field;\n\nclass MailchimpMap extends \\Magento\\Framework\\View\\Element\\Html\\Select\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $_storeManager;\n    /**\n     * @var \\Magento\\Framework\\App\\RequestInterface\n     */\n    protected $_request;\n\n    /**\n     * MailchimpMap constructor.\n     * @param \\Magento\\Framework\\View\\Element\\Context $context\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\View\\Element\\Context $context,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManager,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n\n        parent::__construct($context, $data);\n        $this->_helper          = $helper;\n        $this->_storeManager    = $storeManager;\n        $this->_request         = $context->getRequest();\n    }\n\n    protected function _getMailchimpTags()\n    {\n        $ret = [];\n        $storeId = (int) $this->_request->getParam(\"store\", 0);\n        if ($this->_request->getParam('website', 0)) {\n            $scope = 'website';\n            $storeId = $this->_request->getParam('website', 0);\n        } elseif ($this->_request->getParam('store', 0)) {\n            $scope = 'stores';\n            $storeId = $this->_request->getParam('store', 0);\n        } else {\n            $scope = 'default';\n        }\n\n        $api = $this->_helper->getApi($storeId, $scope);\n        try {\n            $merge = $api->lists->mergeFields->getAll(\n                $this->_helper->getConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST,\n                    $storeId,\n                    $scope\n                ),\n                null,\n                null,\n                \\Ebizmarts\\MailChimp\\Helper\\Data::MAX_MERGEFIELDS\n            );\n            if (is_array($merge) && key_exists('merge_fields', $merge)) {\n                foreach ($merge['merge_fields'] as $item) {\n                    $ret[$item['tag']] = $item['tag'] . ' (' . $item['name'] . ' : ' . $item['type'] . ')';\n                }\n            }\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log($e->getFriendlyMessage());\n        }\n        return $ret;\n    }\n    public function setInputName($value)\n    {\n        return $this->setName($value);\n    }\n\n    /**\n     * Render block HTML\n     *\n     * @return string\n     */\n    public function _toHtml()\n    {\n        if (!$this->getOptions()) {\n            foreach ($this->_getMailchimpTags() as $attId => $attLabel) {\n                $this->addOption($attId, $this->escapeHtmlAttr($attLabel));\n            }\n        }\n        return parent::_toHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/Form/Field/VarsMap.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/27/17 3:41 PM\n * @file: VarsMap.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Form\\Field;\n\nclass VarsMap extends \\Magento\\Framework\\View\\Element\\Html\\Select\n{\n    /**\n     * @var \\Magento\\Customer\\Model\\ResourceModel\\Attribute\\CollectionFactory\n     */\n    private $_attCollection;\n    /**\n     * VarsMap constructor.\n     * @param \\Magento\\Framework\\View\\Element\\Context $context\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\Attribute\\CollectionFactory $attCollection\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\View\\Element\\Context $context,\n        \\Magento\\Customer\\Model\\ResourceModel\\Attribute\\CollectionFactory $attCollection,\n        array $data = []\n    ) {\n\n        parent::__construct($context, $data);\n        $this->_attCollection = $attCollection;\n    }\n    protected function _getAddressAtt()\n    {\n        $ret = [];\n        $ret['default_shipping##zip']     = __('Shipping Zip Code');\n        $ret['default_shipping##country'] = __('Shipping Country');\n        $ret['default_shipping##city']    = __('Shipping City');\n        $ret['default_shipping##state']   = __('Shipping State');\n        $ret['default_shipping##telephone']   = __('Shipping Telephone');\n        $ret['default_shipping##company']   = __('Shipping Company');\n        $ret['default_shipping##street']   = __('Shipping Street');\n\n        $ret['default_billing##zip']      = __('Billing Zip Code');\n        $ret['default_billing##country']  = __('Billing Country');\n        $ret['default_billing##city']     = __('Billing City');\n        $ret['default_billing##state']    = __('Billing State');\n        $ret['default_billing##telephone']   = __('Billing Telephone');\n        $ret['default_billing##company']   = __('Billing Company');\n        $ret['default_billing##street']   = __('Billing Street');\n\n        return $ret;\n    }\n\n    protected function _getBindableAttributes()\n    {\n        $systemAtt = $this->_getCustomerAtt();\n        $extraAtt = $this->_getAddressAtt();\n\n        // Note: We cannot use array_merge here because we need to hold\n        // numeric indexes as they are\n        $ret = $systemAtt + $extraAtt;\n\n        natsort($ret);\n        return $ret;\n    }\n\n    protected function _getCustomerAtt()\n    {\n        $ret = [];\n        $collection = $this->_attCollection->create();\n        /**\n         * @var $item \\Magento\\Customer\\Model\\Attribute\n         */\n        foreach ($collection as $item) {\n            $ret[$item->getId()] = $item->getFrontendLabel();\n        }\n\n        natsort($ret);\n        return $ret;\n    }\n\n    public function setInputName($value)\n    {\n        return $this->setName($value);\n    }\n\n    /**\n     * Render block HTML\n     *\n     * @return string\n     */\n    public function _toHtml()\n    {\n        if (!$this->getOptions()) {\n            foreach ($this->_getBindableAttributes() as $attId => $attLabel) {\n                $this->addOption($attId, $this->escapeHtmlAttr($attLabel));\n            }\n        }\n        return parent::_toHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/OauthWizard.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass OauthWizard extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    protected $_template    = 'system/config/oauth_wizard.phtml';\n\n    private $_authorizeUri     = \"https://login.mailchimp.com/oauth2/authorize\";\n    private $_accessTokenUri   = \"https://login.mailchimp.com/oauth2/token\";\n    private $_redirectUri      = \"https://ebizmarts.com/magento/mc-magento2/oauth2/complete.php\";\n    private $_clientId         = 390007044048;\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n\n        $label = $originalData['button_label'];\n\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->authorizeRequestUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return parent::_toHtml();\n        ;\n    }\n    public function authorizeRequestUrl()\n    {\n\n        $url = $this->_authorizeUri;\n        $redirectUri = urlencode($this->_redirectUri);\n\n        return \"{$url}?redirect_uri={$redirectUri}&response_type=code&client_id={$this->_clientId}\";\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/ResetErrors.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/20/17 3:25 PM\n * @file: ResetErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass ResetErrors extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n    \n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/reseterrors.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'button_url' => $this->getAjaxCheckUrl(),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n\n    public function getButtonHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $label = $originalData['button_label'];\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->getAjaxCheckUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return $this->_toHtml();\n    }\n    public function getAjaxCheckUrl()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = [];\n        if (isset($params['website'])) {\n            $scope = ['website'=>$params['website']];\n        } elseif (isset($params['store'])) {\n            $scope = ['store'=>$params['store']];\n        }\n        return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetLocalErrors', $scope);\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/ResetErrorsNoRetry.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/20/17 3:25 PM\n * @file: ResetErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass ResetErrorsNoRetry extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n    \n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/reseterrorsnoretry.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'button_url' => $this->getAjaxCheckUrl(),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n\n    public function getButtonHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $label = $originalData['button_label'];\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->getAjaxCheckUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return $this->_toHtml();\n    }\n    public function getAjaxCheckUrl()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = [];\n        if (isset($params['website'])) {\n            $scope = ['website'=>$params['website']];\n        } elseif (isset($params['store'])) {\n            $scope = ['store'=>$params['store']];\n        }\n        return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetLocalErrorsNoRetry', $scope);\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/ResetStore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/20/17 3:25 PM\n * @file: ResetErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass ResetStore extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n    \n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/resetstore.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'button_url' => $this->getAjaxCheckUrl(),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n\n    public function getButtonHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $label = $originalData['button_label'];\n        $this->addData([\n            'button_label' => __($label),\n            'button_url'   => $this->getAjaxCheckUrl(),\n            'html_id' => $element->getHtmlId(),\n        ]);\n        return $this->_toHtml();\n    }\n    public function getAjaxCheckUrl()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = [];\n        if (isset($params['website'])) {\n            $scope = ['website'=>$params['website']];\n        } elseif (isset($params['store'])) {\n            $scope = ['store'=>$params['store']];\n        }\n        return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetStore', $scope);\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/ResyncProducts.php",
    "content": "<?php\n/**\n * Created by PhpStorm.\n * User: gonzalo\n * Date: 3/12/18\n * Time: 2:12 PM\n */\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass ResyncProducts extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n\n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/resyncproducts.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Adminhtml/System/Config/ResyncSubscriber.php",
    "content": "<?php\n/**\n * Created by PhpStorm.\n * User: gonzalo\n * Date: 3/12/18\n * Time: 2:12 PM\n */\nnamespace Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config;\n\nclass ResyncSubscriber extends \\Magento\\Config\\Block\\System\\Config\\Form\\Field\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * ResetErrors constructor.\n     * @param \\Magento\\Backend\\Block\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Backend\\Block\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data = []\n    ) {\n\n        $this->_helper = $helper;\n        parent::__construct($context, $data);\n    }\n\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->setTemplate('system/config/resyncsubscriber.phtml');\n    }\n\n    protected function _getElementHtml(\\Magento\\Framework\\Data\\Form\\Element\\AbstractElement $element)\n    {\n        $originalData = $element->getOriginalData();\n        $this->addData(\n            [\n                'button_label' => __($originalData['button_label']),\n                'html_id' => $element->getHtmlId(),\n            ]\n        );\n        return $this->_toHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Catcher.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/25/17 3:35 PM\n * @file: Catcher.php\n */\nnamespace Ebizmarts\\MailChimp\\Block;\n\nuse Magento\\Framework\\View\\Element\\Template;\n\nclass Catcher extends Template\n{\n    /**\n     * @var string $_template\n     */\n    protected $_template = \"catcher.phtml\";\n\n    // write your methods here...\n}\n"
  },
  {
    "path": "Block/Checkout/Success.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/13/17 4:41 PM\n * @file: Success.php\n */\nnamespace Ebizmarts\\MailChimp\\Block\\Checkout;\n\nclass Success extends \\Magento\\Framework\\View\\Element\\Template\n{\n    /**\n     * @var \\Magento\\Checkout\\Model\\Session\n     */\n    protected $_checkoutSession;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $_subscriberFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory\n     */\n    protected $_interestGroupFactory;\n    /**\n     * @var \\Magento\\Framework\\View\\Element\\Template\\Context\n     */\n    protected $_context;\n\n    /**\n     * Success constructor.\n     * @param \\Magento\\Framework\\View\\Element\\Template\\Context $context\n     * @param \\Magento\\Checkout\\Model\\Session $checkoutSession\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\View\\Element\\Template\\Context $context,\n        \\Magento\\Checkout\\Model\\Session $checkoutSession,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory,\n        array $data\n    ) {\n    \n        parent::__construct($context, $data);\n        $this->_checkoutSession     = $checkoutSession;\n        $this->_helper              = $helper;\n        $this->_subscriberFactory   = $subscriberFactory;\n        $this->_interestGroupFactory= $interestGroupFactory;\n        $this->_context             = $context;\n    }\n\n    public function getInterest()\n    {\n        $order = $this->_checkoutSession->getLastRealOrder();\n        /**\n         * @var $subscriber \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        $subscriber = $this->_subscriberFactory->create();\n        $subscriber->loadByEmail($order->getCustomerEmail());\n\n        return $this->_helper->getSubscriberInterest($subscriber->getSubscriberId(), $subscriber->getStoreId());\n    }\n    protected function getValues($category)\n    {\n        $rc =[];\n        foreach ($category as $c) {\n            $rc[] = ['value'=>$c['id'],'label'=>$c['name']];\n        }\n        return $rc;\n    }\n    public function getMessageBefore()\n    {\n        return $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_INTEREST_SUCCESS_HTML_BEFORE);\n    }\n    public function getMessageAfter()\n    {\n        return $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_INTEREST_SUCCESS_HTML_AFTER);\n    }\n    public function getFormUrl()\n    {\n        $order = $this->_checkoutSession->getLastRealOrder();\n        return $this->_helper->getSuccessInterestUrl($order->getStoreId());\n    }\n    public function _toHtml()\n    {\n        if (!$this->_helper->isMailChimpEnabled($this->_context->getStoreManager()->getStore()->getId())) {\n            return \"\";\n        }\n        return parent::_toHtml();\n    }\n}\n"
  },
  {
    "path": "Block/Loadquote.php",
    "content": "<?php\n/**\n * Loadquote\n *\n * @copyright Copyright © 2017 Ebizmarts Corp.. All rights reserved.\n * @author    info@ebizmarts.com\n */\n\nnamespace Ebizmarts\\MailChimp\\Block;\n\nuse Magento\\Framework\\View\\Element\\Template;\n\nclass Loadquote extends Template\n{\n    /**\n     * @var string $_template\n     */\n    protected $_template = \"loadquote.phtml\";\n\n    // write your methods here...\n}\n"
  },
  {
    "path": "Block/Mailchimpjs.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/8/17 12:00 PM\n * @file: Mailchimpjs.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block;\n\nuse Magento\\Store\\Model\\ScopeInterface;\n\nclass Mailchimpjs extends \\Magento\\Framework\\View\\Element\\Template\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $_storeManager;\n\n    /**\n     * Mailchimpjs constructor.\n     * @param \\Magento\\Framework\\View\\Element\\Template\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\View\\Element\\Template\\Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data\n    ) {\n        parent::__construct($context, $data);\n        $this->_helper          = $helper;\n        $this->_storeManager    = $context->getStoreManager();\n    }\n\n    public function getJsUrl()\n    {\n        $storeId = $this->_storeManager->getStore()->getId();\n\n        $url = $this->_scopeConfig->getValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_JS_URL, ScopeInterface::SCOPE_STORES,\n            $storeId\n        );\n        $active = $this->_scopeConfig->getValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ACTIVE, ScopeInterface::SCOPE_STORES,\n            $storeId\n        );\n\n        // if we have URL cached or integration is disabled\n        // then avoid initialization of Mailchimp Helper and all linked classes (~30 classes)\n        if ($active && !$url) {\n            $url = $this->_helper->getJsUrl($storeId);\n        }\n\n        return $url;\n    }\n}\n"
  },
  {
    "path": "Block/Newsletter.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/23/17 4:40 PM\n * @file: Newsletter.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Block;\n\nclass Newsletter extends \\Magento\\Framework\\View\\Element\\Template\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $subscriberFactory;\n    /**\n     * @var \\Magento\\Customer\\Model\\Session\n     */\n    protected $customerSession;\n\n    /**\n     * Newsletter constructor.\n     * @param \\Magento\\Framework\\View\\Element\\Template\\Context $context\n     * @param \\Magento\\Customer\\Model\\Session $customerSession\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\View\\Element\\Template\\Context $context,\n        \\Magento\\Customer\\Model\\Session $customerSession,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        array $data\n    ) {\n    \n        parent::__construct($context, $data);\n        $this->_helper  = $helper;\n        $this->subscriberFactory = $subscriberFactory;\n        $this->customerSession = $customerSession;\n    }\n\n    public function getInterest()\n    {\n        $subscriber = $this->subscriberFactory->create();\n        $subscriber->loadByCustomerId($this->customerSession->getCustomerId());\n//        $subscriber = $this->getSubscriptionObject();\n        return $this->_helper->getSubscriberInterest($subscriber->getSubscriberId(), $subscriber->getStoreId());\n    }\n    public function getFormUrl()\n    {\n        return  $this->getUrl('mailchimp/accountmanage/save');\n    }\n}\n"
  },
  {
    "path": "Block/Subscribe.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Block;\n\nuse Magento\\Framework\\View\\Element\\Template;\nuse \\Ebizmarts\\MailChimp\\Helper\\Data as MailchimpHelper;\n\nclass Subscribe extends \\Magento\\Newsletter\\Block\\Subscribe\n{\n    /**\n     * @var Template\\Context\n     */\n    protected $context;\n    /**\n     * @var MailchimpHelper\n     */\n    protected $helper;\n\n    /**\n     * @param Template\\Context $context\n     * @param MailchimpHelper $helper\n     * @param array $data\n     */\n    public function __construct(\n        Template\\Context $context,\n        MailchimpHelper $helper,\n        array $data = []\n    )\n    {\n        parent::__construct($context, $data);\n        $this->context = $context;\n        $this->helper = $helper;\n    }\n\n    public function getPopupUrl()\n    {\n\n        $storeId = $this->context->getStoreManager()->getStore()->getId();\n        return $this->helper->getConfigValue(MailchimpHelper::XML_POPUP_URL,$storeId);\n    }\n}"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\n## [102.3.78](https://github.com/mailchimp/mc-magento2/tree/102.3.78)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.77...102.3.78)\n\n**Fixed bugs:**\n\n- Error when delete the current mailchimp store and access the configuration [\\#2268](https://github.com/mailchimp/mc-magento2/issues/2268)\n- New order/cart send product as new [\\#2262](https://github.com/mailchimp/mc-magento2/issues/2262)\n- Products permanently stuck in SYNCERROR or NEEDTORESYNC [\\#2256](https://github.com/mailchimp/mc-magento2/issues/2256)\n- Array to string conversion warning [\\#2250](https://github.com/mailchimp/mc-magento2/issues/2250)\n\n## [102.3.77](https://github.com/mailchimp/mc-magento2/tree/102.3.77)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.76...102.3.77)\n\n**Implemented enhancements:**\n\n- Send an event every time visit an abandoned cart [\\#2233](https://github.com/mailchimp/mc-magento2/issues/2233)\n\n**Fixed bugs:**\n\n- Ebizmarts\\MailChimp\\Model\\Api\\Product.php can break during iteration [\\#2239](https://github.com/mailchimp/mc-magento2/issues/2239)\n- Incorrect DATETIME value: '' [\\#2227](https://github.com/mailchimp/mc-magento2/issues/2227)\n\n## [102.3.76](https://github.com/mailchimp/mc-magento2/tree/102.3.76)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.75...102.3.76)\n\n**Implemented enhancements:**\n\n- Feature Request: Store customers email in logs for abandoned baskets. [\\#2084](https://github.com/mailchimp/mc-magento2/issues/2084)\n\n**Fixed bugs:**\n\n- Error cleaning the mailchimp\\_statistics table [\\#2210](https://github.com/mailchimp/mc-magento2/issues/2210)\n\n## [102.3.75](https://github.com/mailchimp/mc-magento2/tree/102.3.75)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.74...102.3.75)\n\n**Implemented enhancements:**\n\n- Add total amount of subscribers to the registration [\\#2199](https://github.com/mailchimp/mc-magento2/issues/2199)\n- Add data to the registration [\\#2192](https://github.com/mailchimp/mc-magento2/issues/2192)\n\n## [102.3.74](https://github.com/mailchimp/mc-magento2/tree/102.3.74)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.73...102.3.74)\n\n**Implemented enhancements:**\n\n- Add flag to sync not salable products [\\#2181](https://github.com/mailchimp/mc-magento2/issues/2181)\n\n## [102.3.73](https://github.com/mailchimp/mc-magento2/tree/102.3.73)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.72...102.3.73)\n\n**Implemented enhancements:**\n\n- Change the way that the statistics are synced [\\#2167](https://github.com/mailchimp/mc-magento2/issues/2167)\n\n## [102.3.72](https://github.com/mailchimp/mc-magento2/tree/102.3.72)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.71...102.3.72)\n\n**Implemented enhancements:**\n\n- Add support for grouped products [\\#2156](https://github.com/mailchimp/mc-magento2/issues/2156)\n\n## [102.3.71](https://github.com/mailchimp/mc-magento2/tree/102.3.71)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.70...102.3.71)\n\n**Implemented enhancements:**\n\n- Add the bundle product itself to the lines of the cart [\\#2142](https://github.com/mailchimp/mc-magento2/issues/2142)\n- Add the bundle product itself to the lines of the order [\\#2136](https://github.com/mailchimp/mc-magento2/issues/2136)\n\n\n## [102.3.70](https://github.com/mailchimp/mc-magento2/tree/102.3.70)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.69...102.3.70)\n\n**Implemented enhancements:**\n\n- Add clean period for mailchimp\\_notification table [\\#2118](https://github.com/mailchimp/mc-magento2/issues/2118)\n- Add bundle products support [\\#2112](https://github.com/mailchimp/mc-magento2/issues/2112)\n\n**Fixed bugs:**\n\n- Add translation for options mergevar [\\#2124](https://github.com/mailchimp/mc-magento2/issues/2124)\n\n## [102.3.69](https://github.com/mailchimp/mc-magento2/tree/HEAD)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.68...102.3.69)\n\n**Fixed bugs:**\n\n- Huge memory usage from ebizmarts\\_generate\\_statistics cron [\\#2098](https://github.com/mailchimp/mc-magento2/issues/2098)\n\n# [102.3.68](https://github.com/mailchimp/mc-magento2/tree/102.3.68)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.67...102.3.68)\n\n**Fixed bugs:**\n\n- SyncStatistics error when the data in mailchimp\\_notification is not a valid json [\\#2083](https://github.com/mailchimp/mc-magento2/issues/2083)\n\n## [102.3.67](https://github.com/mailchimp/mc-magento2/tree/102.3.67)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.66...102.3.67)\n\n**Fixed bugs:**\n\n- Cron is taking long time \\(special price related\\) [\\#2063](https://github.com/mailchimp/mc-magento2/issues/2063)\n- 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)\n\n## [102.3.66](https://github.com/mailchimp/mc-magento2/tree/102.3.66)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.65...102.3.66)\n\n**Implemented enhancements:**\n\n- Include the Billing and Shipping street in the maps fields [\\#2043](https://github.com/mailchimp/mc-magento2/issues/2043)\n- Generate support data [\\#2041](https://github.com/mailchimp/mc-magento2/issues/2041)\n- Put a config to sync only customers with orders [\\#2035](https://github.com/mailchimp/mc-magento2/issues/2035)\n\n## [102.3.65](https://github.com/mailchimp/mc-magento2/tree/102.3.65)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.64...102.3.65)\n\n**Implemented enhancements:**\n\n- missing i18n translation [\\#1983](https://github.com/mailchimp/mc-magento2/issues/1983)\n\n**Fixed bugs:**\n\n- Merge field value is deleted on the Magento store, but not on Mailchimp [\\#1388](https://github.com/mailchimp/mc-magento2/issues/1388)\n- Wrong total revenue in MailChimp [\\#395](https://github.com/mailchimp/mc-magento2/issues/395)\n\n## [102.3.64](https://github.com/mailchimp/mc-magento2/tree/102.3.64)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.63...102.3.64)\n\n**Fixed bugs:**\n\n- Manage deleted and not salable products [\\#2003](https://github.com/mailchimp/mc-magento2/issues/2003)\n- Configuration page in Magento's backend takes a long time to load in certain cases [\\#2002](https://github.com/mailchimp/mc-magento2/issues/2002)\n\n## [102.3.63](https://github.com/mailchimp/mc-magento2/tree/102.3.63)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.62...103.3.63)\n\n**Implemented enhancements:**\n\n- Add the date to the error grid [\\#1972](https://github.com/mailchimp/mc-magento2/issues/1972)\n\n**Fixed bugs:**\n\n- Order status change is not synced when done through webapi [\\#1985](https://github.com/mailchimp/mc-magento2/issues/1985)\n- Column not found: 1054 Unknown column 'mailchimp\\_sync' in 'order clause' [\\#1981](https://github.com/mailchimp/mc-magento2/issues/1981)\n\n## [102.3.62](https://github.com/mailchimp/mc-magento2/tree/102.3.62)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.61...102.3.62)\n\n**Fixed bugs:**\n\n- Bad financial status in mailchimp [\\#1962](https://github.com/mailchimp/mc-magento2/issues/1962)\n\n\n## [101.2.61](https://github.com/mailchimp/mc-magento2/tree/102.3.61)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.60...102.3.61)\n\n**Implemented enhancements:**\n\n- Put the inventory\\_quantity = 0 when delete a product in magento [\\#1945](https://github.com/mailchimp/mc-magento2/issues/1945)\n\n**Fixed bugs:**\n\n- Doesn't search for customer activity for modified orders [\\#1951](https://github.com/mailchimp/mc-magento2/issues/1951)\n- Abandoned cart button doesn't load the cart when click on it [\\#1939](https://github.com/mailchimp/mc-magento2/issues/1939)\n\n## [102.3.60](https://github.com/mailchimp/mc-magento2/tree/102.3.60)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.59...102.3.60)\n\n**Fixed bugs:**\n\n- The token change and can't retrieve the cart from the abandoned cart email [\\#1930](https://github.com/mailchimp/mc-magento2/issues/1930)\n- Abs fail when discount amount is null [\\#1921](https://github.com/mailchimp/mc-magento2/issues/1921)\n- Error table prefix [\\#1920](https://github.com/mailchimp/mc-magento2/issues/1920)\n- Check in webhook cron if the listid is OK when get the groups [\\#1914](https://github.com/mailchimp/mc-magento2/issues/1914)\n\n## [102.3.58](https://github.com/mailchimp/mc-magento2/tree/102.3.58)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.57...102.3.58)\n\n**Implemented enhancements:**\n\n- Add controls to the webhook cron to exclude stores with no mailchimp store [\\#1880](https://github.com/mailchimp/mc-magento2/issues/1880)\n- Use the activity API end point to fill the campaign id [\\#1866](https://github.com/mailchimp/mc-magento2/issues/1866)\n\n**Fixed bugs:**\n\n- 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)\n- SQL Error on config page right after installation [\\#1865](https://github.com/mailchimp/mc-magento2/issues/1865)\n- Trinidad & Tobago country incorrectly synced [\\#1863](https://github.com/mailchimp/mc-magento2/issues/1863)\n- Unescaped output  [\\#1841](https://github.com/mailchimp/mc-magento2/issues/1841)\n- Cannot save some customers [\\#1840](https://github.com/mailchimp/mc-magento2/issues/1840)\n- Error \"Resource Not Found for Api Call:\" when try to access batches grid [\\#1834](https://github.com/mailchimp/mc-magento2/issues/1834)\n- Magento subscription email sent despite 'Magento always managed emails' set to 'No' [\\#1311](https://github.com/mailchimp/mc-magento2/issues/1311)\n\n\n## [102.3.57](https://github.com/mailchimp/mc-magento2/tree/102.3.57)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.56...102.3.57)\n\n**Fixed bugs:**\n\n- The order is not marked as modified when cancel [\\#1822](https://github.com/mailchimp/mc-magento2/issues/1822)\n- Unable to assign a customer to another website [\\#1818](https://github.com/mailchimp/mc-magento2/issues/1818)\n\n## [102.3.56](https://github.com/mailchimp/mc-magento2/tree/102.3.56)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.55...102.3.56)\n\n**Implemented enhancements:**\n\n- MailChimp Customer Tab Empty [\\#1804](https://github.com/mailchimp/mc-magento2/issues/1804)\n\n## [102.3.55](https://github.com/mailchimp/mc-magento2/tree/102.3.55)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.54...102.3.55)\n\n**Fixed bugs:**\n\n- Checkout is broken (error in the etc/di.xml) [\\#1790](https://github.com/mailchimp/mc-magento2/issues/1790)\n\n## [102.3.54](https://github.com/mailchimp/mc-magento2/tree/102.3.54)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.53...102.3.54)\n\n**Implemented enhancements:**\n\n- Performance: Excessive SQL usage in Sales and Products Grid [\\#1759](https://github.com/mailchimp/mc-magento2/issues/1759)\n- Remove unused code in Heper/Data.php [\\#1753](https://github.com/mailchimp/mc-magento2/issues/1753)\n\n**Fixed bugs:**\n\n- Upgrade to 103.4.53 caused UPDATE on over 60% of the existing \\(old\\) orders [\\#1772](https://github.com/mailchimp/mc-magento2/issues/1772)\n- ebizmarts\\_ecommerce job unchecks \"Use Default Value\" checkbox for some product attributes [\\#1758](https://github.com/mailchimp/mc-magento2/issues/1758)\n- Check if the Abandoned cart is enabled, the ecommerce must be enabled [\\#1745](https://github.com/mailchimp/mc-magento2/issues/1745)\n\n## [102.3.53](https://github.com/mailchimp/mc-magento2/tree/102.3.53)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.52...102.3.53)\n\n**Fixed bugs:**\n\n- Cannot upgrade to latest version due to patch error [\\#1732](https://github.com/mailchimp/mc-magento2/issues/1732)\n\n## [102.3.52](https://github.com/mailchimp/mc-magento2/tree/102.3.52)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.51...102.3.52)\n\n**Implemented enhancements:**\n\n- Optimize the product grid to avoid access the ecommerce table [\\#1714](https://github.com/mailchimp/mc-magento2/issues/1714)\n- Optimize the order grid to avoid access the ecommerce table [\\#1708](https://github.com/mailchimp/mc-magento2/issues/1708)\n- 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)\n- Add links to campaign and member in mailchimp in the order grid [\\#1690](https://github.com/mailchimp/mc-magento2/issues/1690)\n\n**Fixed bugs:**\n\n- The sync of orders fails if the order has no billing address [\\#1720](https://github.com/mailchimp/mc-magento2/issues/1720)\n\n\n## [102.3.51](https://github.com/mailchimp/mc-magento2/tree/102.3.51)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.50...102.3.51)\n\n**Implemented enhancements:**\n\n- Put tracking\\_number when the order is shipped [\\#1667](https://github.com/mailchimp/mc-magento2/issues/1667)\n- Create a grid to show our cronjobs in the cron\\_schedule  [\\#1648](https://github.com/mailchimp/mc-magento2/issues/1648)\n- Create JS code that automatically enables ecommerce syncing when abandoned cart syncing is disabled [\\#1633](https://github.com/mailchimp/mc-magento2/issues/1633)\n\n**Fixed bugs:**\n\n- Invoice and shipment pluging doesn't work [\\#1668](https://github.com/mailchimp/mc-magento2/issues/1668)\n- Error fetching store ID row in batch grid [\\#1656](https://github.com/mailchimp/mc-magento2/issues/1656)\n- Duplicate entries in the stores grid [\\#1650](https://github.com/mailchimp/mc-magento2/issues/1650)\n- Resync subscribers and Resync products always resyncs default store [\\#1640](https://github.com/mailchimp/mc-magento2/issues/1640)\n- 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)\n- Bad class name [\\#1613](https://github.com/mailchimp/mc-magento2/issues/1613)\n- Fail phpcs test [\\#1607](https://github.com/mailchimp/mc-magento2/issues/1607)\n\n## [102.3.50](https://github.com/mailchimp/mc-magento2/tree/102.3.50)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.49...102.3.50)\n\n**Implemented enhancements:**\n\n- Clean the error table automatically based on a configuration setting [\\#1577](https://github.com/mailchimp/mc-magento2/issues/1577)\n- Slow-query optimization for product special prices [\\#1569](https://github.com/mailchimp/mc-magento2/issues/1569)\n- Create grid in admin that shows batch information [\\#1465](https://github.com/mailchimp/mc-magento2/issues/1465)\n\n**Fixed bugs:**\n\n- The carts are not deleted from mailchimp when are converted in an order [\\#1595](https://github.com/mailchimp/mc-magento2/issues/1595)\n- Add a button to fix the chimpstatic js in the frontend [\\#1584](https://github.com/mailchimp/mc-magento2/issues/1584)\n\n## [102.3.49](https://github.com/mailchimp/mc-magento2/tree/102.3.49)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.48...102.3.49)\n\n**Implemented enhancements:**\n\n- Query optimization for special prices [\\#1535](https://github.com/mailchimp/mc-magento2/issues/1535)\n\n**Fixed bugs:**\n\n- Wrong query when load the configuration page and use db prefix [\\#1557](https://github.com/mailchimp/mc-magento2/issues/1557)\n- The subcribe at the bottom doesn't work [\\#1551](https://github.com/mailchimp/mc-magento2/issues/1551)\n- \"Magento always manage emails\" configuration blocking default Magento newsletter confirm email sending [\\#1545](https://github.com/mailchimp/mc-magento2/issues/1545)\n- Wrong column name in mailchimp\\_stores [\\#1533](https://github.com/mailchimp/mc-magento2/issues/1533)\n\n## [102.3.48](https://github.com/mailchimp/mc-magento2/tree/102.3.48) (2022-08-18)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.47...102.3.48)\n\n**Implemented enhancements:**\n\n- Point the wiki to the github wiki [\\#1522](https://github.com/mailchimp/mc-magento2/issues/1522)\n\n**Fixed bugs:**\n\n- Observer name \"sales\\_order\\_save\\_after\" is too generic. [\\#1516](https://github.com/mailchimp/mc-magento2/issues/1516)\n- Error saving configuration when install the extension for the first time [\\#1510](https://github.com/mailchimp/mc-magento2/issues/1510)\n\n## [102.3.47](https://github.com/mailchimp/mc-magento2/tree/102.3.47) (2022-08-15)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.46...102.3.47)\n\n**Implemented enhancements:**\n\n- 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)\n- Change the footer subscribe button and open a popup with the mailchimp form to subscribe [\\#1487](https://github.com/mailchimp/mc-magento2/issues/1487)\n- Large mailchimp\\_sync\\_ecommerce table with unused registers [\\#1475](https://github.com/mailchimp/mc-magento2/issues/1475)\n\n**Fixed bugs:**\n\n- Custom boolean customer attribute not synced correctly to Mailchimp [\\#1474](https://github.com/mailchimp/mc-magento2/issues/1474)\n- Migrate the update data to the patches approach [\\#1472](https://github.com/mailchimp/mc-magento2/issues/1472)\n\n## [102.3.46](https://github.com/mailchimp/mc-magento2/tree/102.3.46) (2022-07-19)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.45...102.3.46)\n\n**Implemented enhancements:**\n\n- Rewrite \"This MailChimp account is not connected to Magento\" label to make it more clear [\\#1448](https://github.com/mailchimp/mc-magento2/issues/1448)\n- Add a synchorization column in the customer grid [\\#1439](https://github.com/mailchimp/mc-magento2/issues/1439)\n- Add a synchorization column in the product grid [\\#1438](https://github.com/mailchimp/mc-magento2/issues/1438)\n- Add button on backend to create the abandoned cart automation [\\#1432](https://github.com/mailchimp/mc-magento2/issues/1432)\n\n**Fixed bugs:**\n\n- Missing fields in Cart.php on db call [\\#1460](https://github.com/mailchimp/mc-magento2/issues/1460)\n- Wrong field map value when is null [\\#1425](https://github.com/mailchimp/mc-magento2/issues/1425)\n- Can't get the response file from a batch [\\#1414](https://github.com/mailchimp/mc-magento2/issues/1414)\n- Unmark the modified flag in the ecommerce table when an object is synced [\\#1408](https://github.com/mailchimp/mc-magento2/issues/1408)\n- Don't use Zend\\_Db\\_Select::COLUMNS [\\#1405](https://github.com/mailchimp/mc-magento2/issues/1405)\n\n## [102.3.45](https://github.com/mailchimp/mc-magento2/tree/102.3.45)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.44...102.3.45)\n\n**Implemented enhancements:**\n\n- Query optimization for ecommerce table [\\#1391](https://github.com/mailchimp/mc-magento2/issues/1391)\n- Add the possibility  to send the company as a merge field [\\#1369](https://github.com/mailchimp/mc-magento2/issues/1369)\n- Make uninstall [\\#1347](https://github.com/mailchimp/mc-magento2/issues/1347)\n- Performance Issue During Product Import [\\#1309](https://github.com/mailchimp/mc-magento2/issues/1309)\n\n**Fixed bugs:**\n\n- Subscribers are not added to mailchimp [\\#1359](https://github.com/mailchimp/mc-magento2/issues/1359)\n- The sync fails when an order contains a deleted product [\\#1330](https://github.com/mailchimp/mc-magento2/issues/1330)\n- Problem syncing country with customer address [\\#1329](https://github.com/mailchimp/mc-magento2/issues/1329)\n- Chimpstatic wrong url when change the mailchimp store [\\#1322](https://github.com/mailchimp/mc-magento2/issues/1322)\n- Error creating the webhook, wrong webhook url [\\#1316](https://github.com/mailchimp/mc-magento2/issues/1316)\n\n## [102.3.44](https://github.com/mailchimp/mc-magento2/tree/102.3.44)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.43...102.3.44)\n\n**Implemented enhancements:**\n\n- Add option in the error grid to link to the register with error [\\#1279](https://github.com/mailchimp/mc-magento2/issues/1279)\n\n**Fixed bugs:**\n\n- Incorrect image url with some extensions \\(p.e. cloudinary extension\\) [\\#1288](https://github.com/mailchimp/mc-magento2/issues/1288)\n- Modify order totals to $0 when order is cancelled [\\#1272](https://github.com/mailchimp/mc-magento2/issues/1272)\n- 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)\n- Deleting error records causes database lockup [\\#1242](https://github.com/mailchimp/mc-magento2/issues/1242)\n- 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)\n- 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)\n- Error retrieving the response of a batch from mailchimp [\\#1204](https://github.com/mailchimp/mc-magento2/issues/1204)\n- Avoid duplicate entries in the stores grid [\\#1217](https://github.com/mailchimp/mc-magento2/issues/1217)\n- Unable to create a new Mailchimp Store in admin [\\#1208](https://github.com/mailchimp/mc-magento2/issues/1208)\n\n## [102.3.43](https://github.com/mailchimp/mc-magento2/tree/102.3.43)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.42...102.3.43)\n\n**Implemented enhancements:**\n\n- Add a button in the admin to resync all products [\\#1184](https://github.com/mailchimp/mc-magento2/issues/1184)\n- Missing indexes on mailchimp\\_errors [\\#1162](https://github.com/mailchimp/mc-magento2/issues/1162)\n- Ignore modified items when flagging store as synced [\\#1140](https://github.com/mailchimp/mc-magento2/issues/1140)\n- Only fetch specific columns from sales\\_order [\\#1134](https://github.com/mailchimp/mc-magento2/issues/1134)\n- Error table never getting cleaned up [\\#1107](https://github.com/mailchimp/mc-magento2/issues/1107)\n\n**Fixed bugs:**\n\n- Change the low value for date sync to a valid one [\\#1192](https://github.com/mailchimp/mc-magento2/issues/1192)\n- Exclude the bundle and grouped products for the product collection [\\#1191](https://github.com/mailchimp/mc-magento2/issues/1191)\n- 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)\n- Mark products as modified when use import products from the admin [\\#1167](https://github.com/mailchimp/mc-magento2/issues/1167)\n- Issue with \"Magento Always Manage Emails\" when Unsubscribing from a Customer Account [\\#1157](https://github.com/mailchimp/mc-magento2/issues/1157)\n- errors in cron related to ebizmarts\\_webhooks [\\#1152](https://github.com/mailchimp/mc-magento2/issues/1152)\n- Ecommerce order send loop [\\#1112](https://github.com/mailchimp/mc-magento2/issues/1112)\n- Allow more than 10 interest inside a group [\\#1103](https://github.com/mailchimp/mc-magento2/issues/1103)\n- observer name that breaks Magento 2 DOM XML [\\#1102](https://github.com/mailchimp/mc-magento2/issues/1102)\n- CSP Whitelist Support [\\#1097](https://github.com/mailchimp/mc-magento2/issues/1097)\n- Infinite loop on customer account creation if email present in newsletter subscribers list [\\#1090](https://github.com/mailchimp/mc-magento2/issues/1090)\n- Ecommerce Cron error \"Requested country is not available.\" [\\#1084](https://github.com/mailchimp/mc-magento2/issues/1084)\n- Subscribing for a second time does not work. [\\#1078](https://github.com/mailchimp/mc-magento2/issues/1078)\n\n## [102.3.42](https://github.com/mailchimp/mc-magento2/tree/102.3.42)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.41...102.3.42)\n\n**Implemented enhancements:**\n\n- Create custom field mapping [\\#1025](https://github.com/mailchimp/mc-magento2/issues/1025)\n\n**Fixed bugs:**\n\n- Subscribing for a second time does not work. [\\#1078](https://github.com/mailchimp/mc-magento2/issues/1078)\n- Invalid date format when use mysql 8 [\\#1066](https://github.com/mailchimp/mc-magento2/issues/1066)\n- Unable to capture the order for a campaign [\\#1065](https://github.com/mailchimp/mc-magento2/issues/1065)\n- Notice: Undefined index: image\\_url Model/Api/Product.php [\\#1059](https://github.com/mailchimp/mc-magento2/issues/1059)\n- Multistore product sync wrong name  [\\#1055](https://github.com/mailchimp/mc-magento2/issues/1055)\n\n## [102.3.41](https://github.com/mailchimp/mc-magento2/tree/102.3.41)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.40...102.3.41)\n\n**Implemented enhancements:**\n\n- Coupon Codes \\(Promo Codes\\) Do Not Send to Mailchimp With Order Data [\\#1032](https://github.com/mailchimp/mc-magento2/issues/1032)\n\n**Fixed bugs:**\n\n- \"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)\n- Fallback to JQueryUI Compat activated. [\\#1034](https://github.com/mailchimp/mc-magento2/issues/1034)\n- Abandoned Cart revenue not showing on Mailchimp account [\\#1033](https://github.com/mailchimp/mc-magento2/issues/1033)\n\n## [102.3.40](https://github.com/mailchimp/mc-magento2/tree/102.3.40)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.39...102.3.40)\n\n**Implemented enhancements:**\n\n- Add magento 2.4 compatibility [\\#1027](https://github.com/mailchimp/mc-magento2/issues/1027)\n\n## [102.3.39](https://github.com/mailchimp/mc-magento2/tree/102.3.39)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.38...102.3.39)\n\n**Implemented enhancements:**\n\n- Licensing? [\\#996](https://github.com/mailchimp/mc-magento2/issues/996)\n\n**Fixed bugs:**\n\n- Typo in campaigncatcher.js causing Javascript error [\\#1015](https://github.com/mailchimp/mc-magento2/issues/1015)\n- The mailchimp groups are not shown correctly in the customer account [\\#1009](https://github.com/mailchimp/mc-magento2/issues/1009)\n- Improper call to interest-categories in the webhook processing [\\#1002](https://github.com/mailchimp/mc-magento2/issues/1002)\n- MapFields not getting synced when configured in storeView. [\\#998](https://github.com/mailchimp/mc-magento2/issues/998)\n- Eternal Spinning gif after invalid API key has been entered in the configuration [\\#990](https://github.com/mailchimp/mc-magento2/issues/990)\n- Syncing customer group changed some customers group id to 0 [\\#989](https://github.com/mailchimp/mc-magento2/issues/989)\n- Issue syncing DOB merge field [\\#987](https://github.com/mailchimp/mc-magento2/issues/987)\n- JS error on product page with slow internet [\\#912](https://github.com/mailchimp/mc-magento2/issues/912)\n\n## [102.3.38](https://github.com/mailchimp/mc-magento2/tree/102.3.38)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.37...102.3.38)\n\n**Implemented enhancements:**\n\n- Optimize MailChimp JS block [\\#895](https://github.com/mailchimp/mc-magento2/issues/895)\n- Optimize MailChimp JS block [\\#891](https://github.com/mailchimp/mc-magento2/pull/891) ([andrey-legayev](https://github.com/andrey-legayev))\n\n**Fixed bugs:**\n\n- Incorrect import in Webhook controller [\\#976](https://github.com/mailchimp/mc-magento2/issues/976)\n- The street line 3 is not synced in orders [\\#963](https://github.com/mailchimp/mc-magento2/issues/963)\n- Loading screen stuck when attempting to save the API key. [\\#940](https://github.com/mailchimp/mc-magento2/issues/940)\n- \\[Performance Issue\\] HTTP calls to mailchimp on every page request and config cache flush [\\#939](https://github.com/mailchimp/mc-magento2/issues/939)\n- Strong check for interest groups [\\#932](https://github.com/mailchimp/mc-magento2/issues/932)\n- Take the first date value from storeview scope. [\\#931](https://github.com/mailchimp/mc-magento2/issues/931)\n- Bad management of the groups in the webhooks [\\#926](https://github.com/mailchimp/mc-magento2/issues/926)\n- Error grid, bad data when try to sort for one field 3 times [\\#922](https://github.com/mailchimp/mc-magento2/issues/922)\n- 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)\n- JS error on product page with slow internet [\\#912](https://github.com/mailchimp/mc-magento2/issues/912)\n- Invalid API key error when attempting to update settings. [\\#906](https://github.com/mailchimp/mc-magento2/issues/906)\n- Typo in Ecommerce cron when mark an object with error [\\#900](https://github.com/mailchimp/mc-magento2/issues/900)\n- Error in cron when split databases [\\#887](https://github.com/mailchimp/mc-magento2/issues/887)\n- Make changes to pass code sniffer [\\#881](https://github.com/mailchimp/mc-magento2/issues/881)\n- Fix catching campaign with enabled Varnish FPC [\\#874](https://github.com/mailchimp/mc-magento2/issues/874)\n- Fix incorrect import in Webhook controller [\\#973](https://github.com/mailchimp/mc-magento2/pull/973) ([ihor-sviziev](https://github.com/ihor-sviziev))\n\n## [102.3.37](https://github.com/mailchimp/mc-magento2/tree/102.3.37)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.36...102.3.37)\n\n**Implemented enhancements:**\n\n- Make strong check for the API key [\\#849](https://github.com/mailchimp/mc-magento2/issues/849)\n- Add alt text to the order grid in the mailchimp sync image [\\#810](https://github.com/mailchimp/mc-magento2/issues/810)\n- Send the merge\\_fields for customers [\\#790](https://github.com/mailchimp/mc-magento2/issues/790)\n\n**Fixed bugs:**\n\n- Do not add anything to frontend if module disabled [\\#866](https://github.com/mailchimp/mc-magento2/issues/866)\n- Made sure a missing \"simple\\_sku\" won't break the entire sync [\\#862](https://github.com/mailchimp/mc-magento2/issues/862)\n- Not all batches are saved when multi store enabled [\\#857](https://github.com/mailchimp/mc-magento2/issues/857)\n- Mark orders with error to not try to re-sync [\\#841](https://github.com/mailchimp/mc-magento2/issues/841)\n- PayPal Express orders sync fails - Last name is NULL [\\#840](https://github.com/mailchimp/mc-magento2/issues/840)\n- Bad management of old batches [\\#821](https://github.com/mailchimp/mc-magento2/issues/821)\n- Bad batches management [\\#817](https://github.com/mailchimp/mc-magento2/issues/817)\n- Bad way to test if the json\\_encode fails [\\#805](https://github.com/mailchimp/mc-magento2/issues/805)\n- Rename delete customer account option [\\#801](https://github.com/mailchimp/mc-magento2/issues/801)\n- Orders with no products are not marked as synced [\\#797](https://github.com/mailchimp/mc-magento2/issues/797)\n- Re sync the subscriber when the customer is modified [\\#786](https://github.com/mailchimp/mc-magento2/issues/786)\n- Use always the md5 of the customer email to identify the customer [\\#782](https://github.com/mailchimp/mc-magento2/issues/782)\n- Error when select a website scope in config [\\#773](https://github.com/mailchimp/mc-magento2/issues/773)\n- Change the Resync Customers button [\\#768](https://github.com/mailchimp/mc-magento2/issues/768)\n-  ebizmarts\\_ecommerce has an error [\\#767](https://github.com/mailchimp/mc-magento2/issues/767)\n- Unhandled `Magento\\Framework\\Serialize\\Serializer\\Json::\\(un\\)serialize` calls [\\#758](https://github.com/mailchimp/mc-magento2/issues/758)\n\n## [102.3.36](https://github.com/mailchimp/mc-magento2/tree/102.3.36)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.35...102.3.36)\n\n**Implemented enhancements:**\n\n- Take the version from the composer.json [\\#759](https://github.com/mailchimp/mc-magento2/issues/759)\n\n## [102.3.35](https://github.com/mailchimp/mc-magento2/tree/102.3.35)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/102.3.34...101.2.35)\n\n**Implemented enhancements:**\n\n- Show the amount of list subscribers [\\#740](https://github.com/mailchimp/mc-magento2/issues/740)\n- Wrong error message in order grid [\\#710](https://github.com/mailchimp/mc-magento2/issues/710)\n- Add a button to re sync customers [\\#702](https://github.com/mailchimp/mc-magento2/issues/702)\n- Encrypt sensitive data [\\#701](https://github.com/mailchimp/mc-magento2/issues/701)\n- Some exceptions are not added into logs, making it hard to find the error message. [\\#700](https://github.com/mailchimp/mc-magento2/issues/700)\n\n**Fixed bugs:**\n\n- Remove error message when resend an item with error [\\#719](https://github.com/mailchimp/mc-magento2/issues/719)\n- Error message 'Resource Not Found' on creating new customers [\\#715](https://github.com/mailchimp/mc-magento2/issues/715)\n- Don't delete the cart from ecommerce table when the order is made [\\#706](https://github.com/mailchimp/mc-magento2/issues/706)\n- Success unsubscription, if subscribe again doesn't send confirm subscription emails [\\#696](https://github.com/mailchimp/mc-magento2/issues/696)\n- Customer and subscriber with same email sent to mailchimp with different id [\\#692](https://github.com/mailchimp/mc-magento2/issues/692)\n- Order is not marked to resync when the credit memo comes via magento API [\\#687](https://github.com/mailchimp/mc-magento2/issues/687)\n- Order is not marked to resync when the invoice comes via magento API [\\#682](https://github.com/mailchimp/mc-magento2/issues/682)\n- Order is not marked to resync when the shipment comes via magento API [\\#678](https://github.com/mailchimp/mc-magento2/issues/678)\n- Multistore with different Mailchimp account wrong synchronization on customer delete/unsubcribe from magento admin [\\#674](https://github.com/mailchimp/mc-magento2/issues/674)\n- MySQL error during setup:upgrade after module install \\(with split database Magento EE feature enabled\\) [\\#664](https://github.com/mailchimp/mc-magento2/issues/664)\n\n## [102.3.34](https://github.com/mailchimp/mc-magento2/tree/102.3.34)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.3.33...102.3.34)\n\n**Implemented enhancements:**\n\n- Add link to Terms of service [\\#641](https://github.com/mailchimp/mc-magento2/issues/641)\n- Delete the Cart register in the sync\\_commerce table when confirm the order [\\#626](https://github.com/mailchimp/mc-magento2/issues/626)\n- Add some other logs [\\#602](https://github.com/mailchimp/mc-magento2/issues/602)\n- Clean the maichimp\\_sync\\_batches table [\\#598](https://github.com/mailchimp/mc-magento2/issues/598)\n- Avoid getByEmail calls when sending Orders and Carts to Mailchimp [\\#468](https://github.com/mailchimp/mc-magento2/issues/468)\n- Put a column in the order grid to show if the order was synced [\\#140](https://github.com/mailchimp/mc-magento2/issues/140)\n\n**Fixed bugs:**\n\n- Change the version numeration to meet the magento marketplace requirements [\\#649](https://github.com/mailchimp/mc-magento2/issues/649)\n- Save the email in the quote only with the agreement from the customer [\\#645](https://github.com/mailchimp/mc-magento2/issues/645)\n- Not send the carts until the store is completely synced [\\#636](https://github.com/mailchimp/mc-magento2/issues/636)\n- Defer the load of the mailchimp js [\\#630](https://github.com/mailchimp/mc-magento2/issues/630)\n- No first and lastname when the order is from a guest [\\#609](https://github.com/mailchimp/mc-magento2/issues/609)\n- Subscriber not sent if country state is empty. [\\#593](https://github.com/mailchimp/mc-magento2/issues/593)\n- Ecommerce cronjob stuck on customers with no address \\(error occurs\\) [\\#400](https://github.com/mailchimp/mc-magento2/issues/400)\n\n\n## [1.3.33](https://github.com/mailchimp/mc-magento2/tree/1.3.33)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.32...1.3.33)\n\n**Implemented enhancements:**\n\n- 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)\n- Add possibility to send the product's price including taxes [\\#532](https://github.com/mailchimp/mc-magento2/issues/532)\n- Sync performance in large stores [\\#502](https://github.com/mailchimp/mc-magento2/issues/502)\n- Clean the table mailchimp\\_webhook\\_request [\\#486](https://github.com/mailchimp/mc-magento2/issues/486)\n- Add option to not send Promo Codes and Promo Rules [\\#481](https://github.com/mailchimp/mc-magento2/issues/481)\n- Ask for confirmation when removing mailchimp store [\\#480](https://github.com/mailchimp/mc-magento2/issues/480)\n- add magento 2.3 compatibility [\\#494](https://github.com/mailchimp/mc-magento2/pull/494) ([gonzaloebiz](https://github.com/gonzaloebiz))\n\n**Fixed bugs:**\n\n- Spelling error in order status sent to mailchimp [\\#574](https://github.com/mailchimp/mc-magento2/issues/574)\n- 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)\n- No campaign assigned to orders [\\#554](https://github.com/mailchimp/mc-magento2/issues/554)\n- Missing Customer Fields Mapping [\\#553](https://github.com/mailchimp/mc-magento2/issues/553)\n- Customers generate entries in the mailchimp\\_sycn\\_ecommerce with related\\_id = null [\\#541](https://github.com/mailchimp/mc-magento2/issues/541)\n- Re sync the parent product when modifiy a child one [\\#537](https://github.com/mailchimp/mc-magento2/issues/537)\n- Could not resolve host: xx.api.mailchimp.com [\\#523](https://github.com/mailchimp/mc-magento2/issues/523)\n- Incorrect price in configurable product [\\#513](https://github.com/mailchimp/mc-magento2/issues/513)\n- No timezone saved when create a new Mailchimp store [\\#512](https://github.com/mailchimp/mc-magento2/issues/512)\n- Cart not updated in a Abandoned Cart Series [\\#498](https://github.com/mailchimp/mc-magento2/issues/498)\n- \"Unable to unserialize value \" when run the ecommerce cron process [\\#473](https://github.com/mailchimp/mc-magento2/issues/473)\n- multi-site Customer Fields Mapping not syncing correctly [\\#471](https://github.com/mailchimp/mc-magento2/issues/471)\n- Previously unsubscribed guest/customer is not resubscribed when selecting groups on success page [\\#365](https://github.com/mailchimp/mc-magento2/issues/365)\n\n## [1.0.31](https://github.com/mailchimp/mc-magento2/tree/1.0.31)\n\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.30...1.0.31)\n\n**Implemented enhancements:**\n\n- Add a combo in the Customer Fields Mapping with the MailChimp defined tags [\\#423](https://github.com/mailchimp/mc-magento2/issues/423)\n\n**Fixed bugs:**\n\n- Error of serialization when processing webhook data [\\#455](https://github.com/mailchimp/mc-magento2/issues/455)\n- Don't use serialize function directly [\\#451](https://github.com/mailchimp/mc-magento2/issues/451)\n- Error when a product has SKU = null [\\#448](https://github.com/mailchimp/mc-magento2/issues/448)\n- Send the product id in the order when is a configurable [\\#445](https://github.com/mailchimp/mc-magento2/issues/445)\n- 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)\n- Wrong parent id in the cart [\\#432](https://github.com/mailchimp/mc-magento2/issues/432)\n- Abandoned cart email queue in Mailchimp dashboard not getting reset on placing the order [\\#431](https://github.com/mailchimp/mc-magento2/issues/431)\n- Collissions with mailchimp cookies [\\#429](https://github.com/mailchimp/mc-magento2/issues/429)\n- Subscriber which was added in MailChimp doesn't have storeId in Magento2 [\\#427](https://github.com/mailchimp/mc-magento2/issues/427)\n- Product Image does not show on abandoned cart email template / order details  [\\#425](https://github.com/mailchimp/mc-magento2/issues/425)\n- Total orders\\_count and total\\_spent sent incorrectly in order [\\#420](https://github.com/mailchimp/mc-magento2/issues/420)\n- NULL price when special price is not set, but special price dates are set  [\\#416](https://github.com/mailchimp/mc-magento2/issues/416)\n- field \\[operations.item:2\\] : Schema describes object, array found instead [\\#409](https://github.com/mailchimp/mc-magento2/issues/409)\n- Empty data in the batch json for custom products types [\\#406](https://github.com/mailchimp/mc-magento2/issues/406)\n- After syncing data with MailChimp the wrong products are show for my stores [\\#404](https://github.com/mailchimp/mc-magento2/issues/404)\n- Fix unique type validation in di.xml [\\#450](https://github.com/mailchimp/mc-magento2/pull/450) ([ihor-sviziev](https://github.com/ihor-sviziev))\n\n## [1.0.30](https://github.com/mailchimp/mc-magento2/tree/1.0.30) (2018-09-18)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.29...1.0.30)\n\n**Implemented enhancements:**\n\n- Adding extra logging on import parts of the Cronjob [\\#393](https://github.com/mailchimp/mc-magento2/issues/393)\n- Add an option to choose between send MailChimp or Magento mails [\\#372](https://github.com/mailchimp/mc-magento2/issues/372)\n- Log batch totals for each run [\\#361](https://github.com/mailchimp/mc-magento2/issues/361)\n-  Add debug information [\\#359](https://github.com/mailchimp/mc-magento2/issues/359)\n- High CPU load when API not available [\\#325](https://github.com/mailchimp/mc-magento2/issues/325)\n\n**Fixed bugs:**\n\n- MailChimp breaks order processing when it's done through CLI [\\#378](https://github.com/mailchimp/mc-magento2/issues/378)\n- Disabled in Admin Panel Mailchimp block Magento default newsletter flow. [\\#339](https://github.com/mailchimp/mc-magento2/issues/339)\n- Special prices management in Magento Enterprise [\\#391](https://github.com/mailchimp/mc-magento2/issues/391)\n- Failed to open stream: No such file or directory [\\#388](https://github.com/mailchimp/mc-magento2/issues/388)\n- Promo rules are not updated [\\#370](https://github.com/mailchimp/mc-magento2/issues/370)\n- Error in the configuration when selecting other website than default [\\#368](https://github.com/mailchimp/mc-magento2/issues/368)\n- Orders not synced when products in the order not already synced [\\#366](https://github.com/mailchimp/mc-magento2/issues/366)\n- Wrong website set on customer [\\#357](https://github.com/mailchimp/mc-magento2/issues/357)\n- Issue with coupons for free shipping [\\#355](https://github.com/mailchimp/mc-magento2/issues/355)\n- Error downloading response from error grid when batch not exist [\\#351](https://github.com/mailchimp/mc-magento2/issues/351)\n- Unable to set custom Env.php API Credentials  [\\#345](https://github.com/mailchimp/mc-magento2/issues/345)\n- Webhook processing fails when list id does not match any list configured in Magento [\\#337](https://github.com/mailchimp/mc-magento2/issues/337)\n- Sending modified products in order or cart [\\#335](https://github.com/mailchimp/mc-magento2/issues/335)\n- Base table or view not found Magento 2.2.4 [\\#321](https://github.com/mailchimp/mc-magento2/issues/321)\n- Unknown column 'at\\_special\\_from\\_date\\_default.value' in 'on clause' [\\#309](https://github.com/mailchimp/mc-magento2/issues/309)\n\n## [1.0.29](https://github.com/mailchimp/mc-magento2/tree/1.0.29) (2018-05-31)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.28...1.0.29)\n\n**Implemented enhancements:**\n\n- Add check before renaming 'address\\_address1' table column [\\#283](https://github.com/mailchimp/mc-magento2/pull/283) ([rob-aimes](https://github.com/rob-aimes))\n\n**Fixed bugs:**\n\n- No cron\\_groups.xml is defined [\\#316](https://github.com/mailchimp/mc-magento2/issues/316)\n- Wrong url for a generic product of configurable producs [\\#313](https://github.com/mailchimp/mc-magento2/issues/313)\n- No image url when the product and the parent has no image [\\#307](https://github.com/mailchimp/mc-magento2/issues/307)\n- web\\_hooks error somewhere - first/last name being required [\\#302](https://github.com/mailchimp/mc-magento2/issues/302)\n- In the mailchimpstore grid not all the apikeys are taken [\\#295](https://github.com/mailchimp/mc-magento2/issues/295)\n- Error getting interest groups [\\#293](https://github.com/mailchimp/mc-magento2/issues/293)\n- Multistore with different Mailchimp accounts not saving correctly [\\#289](https://github.com/mailchimp/mc-magento2/issues/289)\n- Exception is thrown when Promotion is marked for removal [\\#280](https://github.com/mailchimp/mc-magento2/issues/280)\n- Webhook cronjob fails when updating customer [\\#278](https://github.com/mailchimp/mc-magento2/issues/278)\n- Cron Ecommerce: cannot create batches data because update existed products in orders or carts [\\#277](https://github.com/mailchimp/mc-magento2/issues/277)\n- Cancelled or pending orders added to revenue in mailchimp [\\#274](https://github.com/mailchimp/mc-magento2/issues/274)\n- Bad registers are generated in mailchimp\\_sync\\_ecommerce table [\\#267](https://github.com/mailchimp/mc-magento2/issues/267)\n- PHP warning in Helper/Data.php line 340 [\\#266](https://github.com/mailchimp/mc-magento2/issues/266)\n- Subscriber fields not updated when Ecommerce Data not enabled [\\#258](https://github.com/mailchimp/mc-magento2/issues/258)\n- The instest groups are not reloaded when the list changes [\\#257](https://github.com/mailchimp/mc-magento2/issues/257)\n- The user can select non existing group in admin [\\#256](https://github.com/mailchimp/mc-magento2/issues/256)\n- Don't process stores with no mailchimp store [\\#255](https://github.com/mailchimp/mc-magento2/issues/255)\n- Error when attempting to edit a customer from the backend [\\#240](https://github.com/mailchimp/mc-magento2/issues/240)\n- 2.2 Error Importing Configuration [\\#223](https://github.com/mailchimp/mc-magento2/issues/223)\n- No Abandoned Cart Data Sent [\\#220](https://github.com/mailchimp/mc-magento2/issues/220)\n- 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)\n- Change cron group id to 'mailchimp'. [\\#282](https://github.com/mailchimp/mc-magento2/pull/282) ([jhruehl](https://github.com/jhruehl))\n- fix decodeArrayFieldValue error [\\#265](https://github.com/mailchimp/mc-magento2/pull/265) ([gundamkid](https://github.com/gundamkid))\n\n## [1.0.28](https://github.com/mailchimp/mc-magento2/tree/1.0.28) (2018-03-27)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.27...1.0.28)\n\n**Implemented enhancements:**\n\n- Not necessary mailchimp/script/get requests [\\#248](https://github.com/mailchimp/mc-magento2/issues/248)\n- Add a button to create the webhooks [\\#229](https://github.com/mailchimp/mc-magento2/issues/229)\n- Add get Api credentials button using oauth. [\\#207](https://github.com/mailchimp/mc-magento2/issues/207)\n- Special price management [\\#194](https://github.com/mailchimp/mc-magento2/issues/194)\n- Use a checkbox on Checkout to determine Opt-in status. [\\#36](https://github.com/mailchimp/mc-magento2/issues/36)\n\n**Fixed bugs:**\n\n- Wrong product marked as modified in ecommerce table [\\#253](https://github.com/mailchimp/mc-magento2/issues/253)\n- Don't delete the batch\\_id when modify a register [\\#246](https://github.com/mailchimp/mc-magento2/issues/246)\n- Invalid argument supplied for foreach\\(\\) [\\#243](https://github.com/mailchimp/mc-magento2/issues/243)\n- Missing argument on call to \\_updateSyncData\\(\\) [\\#241](https://github.com/mailchimp/mc-magento2/issues/241)\n- MailChimp js file loaded each time the page loads [\\#232](https://github.com/mailchimp/mc-magento2/issues/232)\n- Mark non existing batchs as canceled [\\#216](https://github.com/mailchimp/mc-magento2/issues/216)\n- Modified carts are not re synced [\\#212](https://github.com/mailchimp/mc-magento2/issues/212)\n- Try to get result for not existing batch [\\#210](https://github.com/mailchimp/mc-magento2/issues/210)\n- Wrong error management [\\#204](https://github.com/mailchimp/mc-magento2/issues/204)\n- When modify a simple product, the variant is empty [\\#202](https://github.com/mailchimp/mc-magento2/issues/202)\n- Abandoned cart email product price has range starting at $0 when using configurable products [\\#197](https://github.com/mailchimp/mc-magento2/issues/197)\n- Error due to customer data race condition [\\#112](https://github.com/mailchimp/mc-magento2/issues/112)\n- Update default.xml [\\#180](https://github.com/mailchimp/mc-magento2/pull/180) ([jhruehl](https://github.com/jhruehl))\n- 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))\n\n## [1.0.27](https://github.com/mailchimp/mc-magento2/tree/1.0.27) (2018-01-30)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.26...1.0.27)\n\n**Implemented enhancements:**\n\n- Send categories in product vendor attribute [\\#129](https://github.com/mailchimp/mc-magento2/issues/129)\n\n**Fixed bugs:**\n\n- Merge Names not synching [\\#188](https://github.com/mailchimp/mc-magento2/issues/188)\n- Error in ebizmarts\\_ecommerce after upgrading to 1.0.26 [\\#186](https://github.com/mailchimp/mc-magento2/issues/186)\n- Installation error when the database has a prefix [\\#184](https://github.com/mailchimp/mc-magento2/issues/184)\n\n## [1.0.26](https://github.com/mailchimp/mc-magento2/tree/1.0.26) (2018-01-24)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.25...1.0.26)\n\n**Implemented enhancements:**\n\n- Copy suggestions for List Group enhancement [\\#173](https://github.com/mailchimp/mc-magento2/issues/173)\n- Add support for List Groups [\\#122](https://github.com/mailchimp/mc-magento2/issues/122)\n- Magento 2.2 compatibility [\\#116](https://github.com/mailchimp/mc-magento2/issues/116)\n- Add mergevars [\\#110](https://github.com/mailchimp/mc-magento2/issues/110)\n\n**Fixed bugs:**\n\n- MailChimp connected sites List Settings syncing seemingly forever [\\#66](https://github.com/mailchimp/mc-magento2/issues/66)\n- Products are not marked as modified in the sync\\_ecommerce table [\\#177](https://github.com/mailchimp/mc-magento2/issues/177)\n- Child product update when parent has not been sent yet [\\#160](https://github.com/mailchimp/mc-magento2/issues/160)\n- Guest Abandoned Carts failing to load when accessing from automation. [\\#153](https://github.com/mailchimp/mc-magento2/issues/153)\n- Guest Abandoned Carts not associating email address at checkout [\\#152](https://github.com/mailchimp/mc-magento2/issues/152)\n- Sync only works, if eCommerce is enabled [\\#150](https://github.com/mailchimp/mc-magento2/issues/150)\n- Intallation error in EE when the database is already splitted [\\#149](https://github.com/mailchimp/mc-magento2/issues/149)\n- Compatibility with Magento Enterprise Edition 2.1.x [\\#144](https://github.com/mailchimp/mc-magento2/issues/144)\n- Send duplicates promo codes [\\#121](https://github.com/mailchimp/mc-magento2/issues/121)\n- Mark customer as modified when any data was modified [\\#118](https://github.com/mailchimp/mc-magento2/issues/118)\n- Error when the webhook is created [\\#117](https://github.com/mailchimp/mc-magento2/issues/117)\n- Exception when running cron [\\#114](https://github.com/mailchimp/mc-magento2/issues/114)\n- Cron error \"Requested country is not available.\" [\\#58](https://github.com/mailchimp/mc-magento2/issues/58)\n- Fix for broken admin grid in production [\\#176](https://github.com/mailchimp/mc-magento2/pull/176) ([duckchip](https://github.com/duckchip))\n- Module Dependancy [\\#126](https://github.com/mailchimp/mc-magento2/pull/126) ([valguss](https://github.com/valguss))\n\n## [1.0.25](https://github.com/mailchimp/mc-magento2/tree/1.0.25) (2017-11-06)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.24...1.0.25)\n\n**Implemented enhancements:**\n\n- Add support for Promo Rules and Promo Codes [\\#100](https://github.com/mailchimp/mc-magento2/issues/100)\n- Total subscribers in admin display the total subscriber of the account [\\#94](https://github.com/mailchimp/mc-magento2/issues/94)\n- Performance cron ebizmarts\\_ecommerce [\\#93](https://github.com/mailchimp/mc-magento2/issues/93)\n\n**Fixed bugs:**\n\n- The cart url for abandoned cart not work [\\#111](https://github.com/mailchimp/mc-magento2/issues/111)\n- Store is always syncing [\\#97](https://github.com/mailchimp/mc-magento2/issues/97)\n- Module doesn't install if database uses a prefix [\\#95](https://github.com/mailchimp/mc-magento2/issues/95)\n\n## [1.0.24](https://github.com/mailchimp/mc-magento2/tree/1.0.24) (2017-09-18)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.23...1.0.24)\n\n**Implemented enhancements:**\n\n- Major Admin Order Grid Slowdown [\\#88](https://github.com/mailchimp/mc-magento2/issues/88)\n\n**Fixed bugs:**\n\n- Error installation when use split database [\\#85](https://github.com/mailchimp/mc-magento2/issues/85)\n- Incorrect cart url [\\#84](https://github.com/mailchimp/mc-magento2/issues/84)\n- Incorrect image url [\\#82](https://github.com/mailchimp/mc-magento2/issues/82)\n- Change $this-\\>\\_helper-\\>\\_\\_\\(\\) to \\_\\_\\(\\) [\\#80](https://github.com/mailchimp/mc-magento2/pull/80) ([rikardwissing](https://github.com/rikardwissing))\n\n## [1.0.23](https://github.com/mailchimp/mc-magento2/tree/1.0.23) (2017-09-01)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.22...1.0.23)\n\n**Fixed bugs:**\n\n- Guest subscribers issue - STOREID is null [\\#75](https://github.com/mailchimp/mc-magento2/issues/75)\n- Website scope always taking list from default configuration [\\#68](https://github.com/mailchimp/mc-magento2/issues/68)\n- Requested product doesn't exist [\\#67](https://github.com/mailchimp/mc-magento2/issues/67)\n- Bad ajax call [\\#65](https://github.com/mailchimp/mc-magento2/issues/65)\n- 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)\n- Display appropriate thumbnails for items [\\#43](https://github.com/mailchimp/mc-magento2/issues/43)\n- New customers are not added to MailChimp [\\#42](https://github.com/mailchimp/mc-magento2/issues/42)\n- remove the use of data helper from InstallSchema [\\#70](https://github.com/mailchimp/mc-magento2/pull/70) ([BlackIkeEagle](https://github.com/BlackIkeEagle))\n\n## [1.0.22](https://github.com/mailchimp/mc-magento2/tree/1.0.22) (2017-07-26)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.21...1.0.22)\n\n## [1.0.21](https://github.com/mailchimp/mc-magento2/tree/1.0.21) (2017-07-14)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.20...1.0.21)\n\n## [1.0.20](https://github.com/mailchimp/mc-magento2/tree/1.0.20) (2017-07-12)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.19...1.0.20)\n\n## [1.0.19](https://github.com/mailchimp/mc-magento2/tree/1.0.19) (2017-07-12)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.18...1.0.19)\n\n## [1.0.18](https://github.com/mailchimp/mc-magento2/tree/1.0.18) (2017-06-29)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.17...1.0.18)\n\n**Implemented enhancements:**\n\n- Add a commit call when use a connection directly [\\#53](https://github.com/mailchimp/mc-magento2/issues/53)\n\n**Fixed bugs:**\n\n- Reset the errors when no more mailchimp store are connected [\\#54](https://github.com/mailchimp/mc-magento2/issues/54)\n\n## [1.0.17](https://github.com/mailchimp/mc-magento2/tree/1.0.17) (2017-06-21)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.16...1.0.17)\n\n**Fixed bugs:**\n\n- Error in mc.js when change the mailchimp store [\\#51](https://github.com/mailchimp/mc-magento2/issues/51)\n- Prevent sending customers to other store views even when they belong to the same website [\\#48](https://github.com/mailchimp/mc-magento2/issues/48)\n\n## [1.0.16](https://github.com/mailchimp/mc-magento2/tree/1.0.16) (2017-06-19)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.15...1.0.16)\n\n**Implemented enhancements:**\n\n- Limit the process of the webhooks [\\#47](https://github.com/mailchimp/mc-magento2/issues/47)\n\n**Fixed bugs:**\n\n- Invalid product url on simple products not visible [\\#49](https://github.com/mailchimp/mc-magento2/issues/49)\n\n## [1.0.15](https://github.com/mailchimp/mc-magento2/tree/1.0.15) (2017-06-05)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.14...1.0.15)\n\n**Implemented enhancements:**\n\n- List MC account and List  [\\#22](https://github.com/mailchimp/mc-magento2/issues/22)\n- Add the download response link to error grid [\\#8](https://github.com/mailchimp/mc-magento2/issues/8)\n- Process the webhooks in a separate cron process [\\#46](https://github.com/mailchimp/mc-magento2/issues/46)\n- Show the list in the configuration page [\\#41](https://github.com/mailchimp/mc-magento2/issues/41)\n- Add actions to webhooks [\\#40](https://github.com/mailchimp/mc-magento2/issues/40)\n- Add webhooks [\\#39](https://github.com/mailchimp/mc-magento2/issues/39)\n- Request: Move MailChimp Store above Account Details on the Configuration page [\\#31](https://github.com/mailchimp/mc-magento2/issues/31)\n- Autoselect store when only one exists [\\#28](https://github.com/mailchimp/mc-magento2/issues/28)\n- Change the configuration to use jquery and ajax [\\#27](https://github.com/mailchimp/mc-magento2/issues/27)\n- Installation of MC.js pixel [\\#18](https://github.com/mailchimp/mc-magento2/issues/18)\n\n**Fixed bugs:**\n\n- Ecomm Data uploaded to MailChimp should display if reselecting a connected store. [\\#32](https://github.com/mailchimp/mc-magento2/issues/32)\n- Account no longer syncing [\\#26](https://github.com/mailchimp/mc-magento2/issues/26)\n- Multiple stores not showing in Configuration dropdown [\\#25](https://github.com/mailchimp/mc-magento2/issues/25)\n- MC Account information displayed in Configuration does not change when API key is toggled. [\\#24](https://github.com/mailchimp/mc-magento2/issues/24)\n- Remove old warning message on Configuration [\\#23](https://github.com/mailchimp/mc-magento2/issues/23)\n- In the MailChimp Store, the street is not saved [\\#21](https://github.com/mailchimp/mc-magento2/issues/21)\n- Pull all lists for dropdown when creating a store [\\#20](https://github.com/mailchimp/mc-magento2/issues/20)\n- Use \"MailChimp\" instead of \"Mailchimp\" [\\#19](https://github.com/mailchimp/mc-magento2/issues/19)\n- Change the order \\# when sync [\\#45](https://github.com/mailchimp/mc-magento2/issues/45)\n- Not mark the already synced element like errors [\\#44](https://github.com/mailchimp/mc-magento2/issues/44)\n- Avoid error when for some reason the process cancel [\\#38](https://github.com/mailchimp/mc-magento2/issues/38)\n- Review the Customer process [\\#37](https://github.com/mailchimp/mc-magento2/issues/37)\n- Problem when receive the response of batch [\\#35](https://github.com/mailchimp/mc-magento2/issues/35)\n- Add ACL permissions [\\#34](https://github.com/mailchimp/mc-magento2/issues/34)\n- Sorting MailChimp Stores grid by email more than once causes display issues [\\#33](https://github.com/mailchimp/mc-magento2/issues/33)\n- Enable not saving on a MailChimp store level [\\#29](https://github.com/mailchimp/mc-magento2/issues/29)\n- Invalid product image url when the product not have any image [\\#17](https://github.com/mailchimp/mc-magento2/issues/17)\n- Newly added products not synced. [\\#13](https://github.com/mailchimp/mc-magento2/issues/13)\n- Store information not passing to MailChimp [\\#12](https://github.com/mailchimp/mc-magento2/issues/12)\n- Purchases made via campaign not attributed to the campaign [\\#11](https://github.com/mailchimp/mc-magento2/issues/11)\n- APIKey management and store creation [\\#10](https://github.com/mailchimp/mc-magento2/issues/10)\n\n## [1.0.14](https://github.com/mailchimp/mc-magento2/tree/1.0.14) (2017-05-04)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.9...1.0.14)\n\n## [1.0.9](https://github.com/mailchimp/mc-magento2/tree/1.0.9) (2017-05-03)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.8...1.0.9)\n\n## [1.0.8](https://github.com/mailchimp/mc-magento2/tree/1.0.8) (2017-05-03)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.7...1.0.8)\n\n## [1.0.7](https://github.com/mailchimp/mc-magento2/tree/1.0.7) (2017-05-02)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.6...1.0.7)\n\n## [1.0.6](https://github.com/mailchimp/mc-magento2/tree/1.0.6) (2017-04-24)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.5...1.0.6)\n\n## [1.0.5](https://github.com/mailchimp/mc-magento2/tree/1.0.5) (2017-04-21)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.4...1.0.5)\n\n## [1.0.4](https://github.com/mailchimp/mc-magento2/tree/1.0.4) (2017-03-22)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.3...1.0.4)\n\n**Fixed bugs:**\n\n- The error grid don't paginate [\\#9](https://github.com/mailchimp/mc-magento2/issues/9)\n- Add the mailchimp\\_store\\_id to all auxiliar tables [\\#7](https://github.com/mailchimp/mc-magento2/issues/7)\n- The reset errors button not work [\\#6](https://github.com/mailchimp/mc-magento2/issues/6)\n- Error in mailchimp\\_errors table [\\#5](https://github.com/mailchimp/mc-magento2/issues/5)\n- Products not syncing [\\#3](https://github.com/mailchimp/mc-magento2/issues/3)\n\n## [1.0.3](https://github.com/mailchimp/mc-magento2/tree/1.0.3) (2017-03-18)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.2...1.0.3)\n\n**Fixed bugs:**\n\n- Clean error don't work [\\#4](https://github.com/mailchimp/mc-magento2/issues/4)\n\n## [1.0.2](https://github.com/mailchimp/mc-magento2/tree/1.0.2) (2017-03-17)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.1...1.0.2)\n\n## [1.0.1](https://github.com/mailchimp/mc-magento2/tree/1.0.1) (2017-03-16)\n[Full Changelog](https://github.com/mailchimp/mc-magento2/compare/1.0.0...1.0.1)\n\n## [1.0.0](https://github.com/mailchimp/mc-magento2/tree/1.0.0) (2017-03-16)\n\n\n\\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "### Contribution requirements\n\n1. Contributions must adhere to [Magento coding standards](http://devdocs.magento.com/guides/v2.0/coding-standards/bk-coding-standards.html).\n2. 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.\n3. Commits must be accompanied by meaningful commit messages. (include a **closes** in the commit that close the issue)\n4. 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).\n5. 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.\n"
  },
  {
    "path": "Controller/Adminhtml/Batch/GetResponse.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/3/17 3:28 PM\n * @file: Getresponse.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Batch;\n\nuse Magento\\Framework\\Controller\\ResultFactory;\n\nclass GetResponse extends \\Magento\\Backend\\App\\Action\n{\n    const MAX_RETRIES = 5;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory\n     */\n    protected $_batchFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Result\n     */\n    protected $_result;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Framework\\Filesystem\\Driver\\File\n     */\n    protected $_driver;\n\n    /**\n     * Getresponse constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $errorsFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Result $result\n     * @param \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatchesFactory $_batchFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Result $result,\n        \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n    ) {\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_batchFactory        = $_batchFactory;\n        $this->_result              = $result;\n        $this->_helper              = $helper;\n        $this->_driver              = $driver;\n    }\n\n    public function execute()\n    {\n        $batchId    = $this->getRequest()->getParam('id');\n        $batches = $this->_batchFactory->create();\n        $batches->getResource()->load($batches, $batchId);\n        $batchId = $batches->getBatchId();\n        $fileContent = [];\n        $counter = 0;\n        do {\n            $counter++;\n            $files = $this->_result->getBatchResponse($batchId, $batches->getStoreId());\n            if ($files===false) {\n                $fileContent = \"Response was deleted from MailChimp servers\";\n                break;\n            }\n            foreach ($files as &$file) {\n                $items = json_decode($this->_driver->fileGetContents($file));\n                foreach ($items as &$item) {\n                    $content = [\n                        'status_code' => $item->status_code,\n                        'operation_id' => $item->operation_id,\n                        'response' => json_decode($item->response)\n                    ];\n                    $fileContent[] = $content;\n                }\n                $this->_driver->deleteFile($file);\n            }\n            $baseDir = $this->_helper->getBaseDir();\n            if ($this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                \\Ebizmarts\\MailChimp\\Model\\Api\\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId)) {\n                $this->_driver->deleteDirectory(\n                    $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    \\Ebizmarts\\MailChimp\\Model\\Api\\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId\n                );\n            }\n        } while (!count($fileContent) && $counter<self::MAX_RETRIES);\n        $resultJson =$this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setHeader('Content-disposition', 'attachment; filename='.$batchId.'.json');\n        $resultJson->setHeader('Content-type', 'application/json');\n        $data = json_encode($fileContent, JSON_PRETTY_PRINT);\n        $resultJson->setJsonData($data);\n        return $resultJson;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::batch_grid');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Batch/Index.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/28/16 4:58 PM\n * @file: Index.php\n */\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Batch;\n\nclass Index extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var \\Magento\\Framework\\View\\Result\\PageFactory\n     */\n    protected $resultPageFactory;\n\n    /**\n     * Index constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n    ) {\n\n        $this->resultPageFactory = $resultPageFactory;\n        return parent::__construct($context);\n    }\n    public function execute()\n    {\n        $page = $this->resultPageFactory->create();\n        $page->getConfig()->getTitle()->prepend(__('Mailchimp Batches'));\n        return $page;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::batch_grid');\n    }\n}\n\n\n"
  },
  {
    "path": "Controller/Adminhtml/Carts/Index.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Carts;\n\nclass Index extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var \\Magento\\Framework\\View\\Result\\PageFactory\n     */\n    protected $resultPageFactory;\n\n    /**\n     * Index constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n    ) {\n        $this->resultPageFactory = $resultPageFactory;\n\n        parent::__construct($context);\n    }\n    public function execute()\n    {\n        $page = $this->resultPageFactory->create();\n        $page->getConfig()->getTitle()->prepend(__('Mailchimp Carts'));\n        return $page;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::carts_grid');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Cron/Index.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/28/16 4:58 PM\n * @file: Index.php\n */\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Cron;\n\nclass Index extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var \\Magento\\Framework\\View\\Result\\PageFactory\n     */\n    protected $resultPageFactory;\n\n    /**\n     * Index constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n    ) {\n\n        $this->resultPageFactory = $resultPageFactory;\n        return parent::__construct($context);\n    }\n    public function execute()\n    {\n        $page = $this->resultPageFactory->create();\n        $page->getConfig()->getTitle()->prepend(__('Mailchimp Cron'));\n        return $page;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::cron_grid');\n    }\n}\n\n\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/CreateWebhook.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/12/18 4:14 PM\n * @file: CreateWebhook.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\n\nclass CreateWebhook extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n\n    /**\n     * DeleteStore constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $config\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $config\n    ) {\n\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->storeManager         = $storeManagerInterface;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        $apiKey = $params['apikey'];\n        $listId = $params['listId'];\n        $scope = $params['scope'];\n        $scopeId = $params['scopeId'];\n\n        if ($apiKey=='******') {\n            $apiKey = $this->helper->getApiKey($scopeId, $scope);\n        }\n\n        $return = $this->helper->createWebHook($apiKey, $listId, $scope, $scopeId);\n        if (isset($return['message'])) {\n            $valid = 0;\n            $message = $return['message'];\n        }\n        $resultJson = $this->resultJsonFactory->create();\n\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"CreateWebhook\", $ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/DeleteStore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\n\nclass DeleteStore extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\n     */\n    protected $_config;\n\n    /**\n     * DeleteStore constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $config\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $config\n    ) {\n\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->storeManager         = $storeManagerInterface;\n        $this->_config              = $config;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        if (isset($params['website'])) {\n            $scope = 'website';\n            $storeId = $params['website'];\n        } elseif (isset($params['store'])) {\n            $scope = 'store';\n            $storeId = $params['store'];\n        } else {\n            //$storeId = $this->storeManager->getDefaultStoreView()->getWebsiteId();\n            $storeId = 0;\n            $scope = 'default';\n        }\n\n        $mailchimpStore = $this->helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $storeId,\n            $scope\n        );\n        $resultJson = $this->resultJsonFactory->create();\n        try {\n            $this->helper->deleteStore($mailchimpStore);\n            $this->_config->deleteConfig(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE, $scope, $storeId);\n        } catch (ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"DeleteStore\",$ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/FixMailchimpJS.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory;\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\n\nclass FixMailchimpJS extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\n     */\n    protected $config;\n    protected $typeList;\n\n    /**\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $config\n     * @param \\Magento\\Framework\\App\\Cache\\TypeListInterface $typeList\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $config,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $typeList,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->config               = $config;\n        $this->typeList             = $typeList;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n\n        $params = $this->getRequest()->getParams();\n        $this->helper->log($params);\n        $scope = $params['scope'];\n        $scopeId = $params['scopeId'];\n        if ($scope == 'store') {\n            $scope = 'stores';\n        }\n        $this->helper->log(\"Scope $scope id $scopeId\");\n        $resultJson = $this->resultJsonFactory->create();\n        try {\n            $this->config->deleteConfig(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_JS_URL, $scope, $scopeId);\n        } catch(ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"FixMailchimpJS\", $ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/GetInterest.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/23/18 10:05 AM\n * @file: GetInterest.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\n\nclass GetInterest extends Action\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    protected $_storeManager;\n\n    /**\n     * GetInterest constructor.\n     * @param Context $context\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        Context $context,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_helper                  = $helper;\n        $this->_storeManager        = $storeManager;\n    }\n\n    /**\n     * @return mixed\n     */\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $rc = [];\n        $error = 0;\n        if (array_key_exists('apikey', $param) && array_key_exists('list', $param)) {\n            $apiKey = $param['apikey'];\n            $list  = $param['list'];\n            $encrypt = $param['encrypt'];\n            try {\n                if ($encrypt == 3) {\n                    $api = $this->_helper->getApi($this->_storeManager->getStore()->getId());\n                } else {\n                    $api = $this->_helper->getApiByApiKey($apiKey, $encrypt);\n                }\n\n                $result = $api->lists->interestCategory->getAll($list, null, null, 200);\n                if (is_array($result['categories']) && count($result['categories'])) {\n                    $rc = $result['categories'];\n                }\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n                $error = 1;\n            }\n        }\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setData(['error' => $error, 'data' => $rc]);\n        return $resultJson;\n    }\n\n    /**\n     * @return mixed\n     */\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/Getaccountdetails.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/5/17 3:40 PM\n * @file: GetAccountDetails.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse \\Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\n\nclass Getaccountdetails extends Action\n{\n    /**\n     * @var MailChimpHelper\n     */\n    protected $_helper;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    protected $_storeManager;\n\n    /**\n     * @param Context $context\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param MailChimpHelper $helper\n     */\n    public function __construct(\n        Context $context,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        MailChimpHelper $helper\n    ) {\n\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_helper                  = $helper;\n        $this->_storeManager        = $storeManager;\n    }\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $apiKey = $param['apikey'];\n        $store  = $param['store'];\n        $encrypt = $param['encrypt'];\n        $scope = $param['scope'];\n        $scopeId = $param['scopeId'];\n        try {\n            if ($encrypt == 3) {\n                $api = $this->_helper->getApi($this->_storeManager->getStore()->getId());\n            } else {\n                $api = $this->_helper->getApiByApiKey($apiKey, $encrypt);\n            }\n            $apiInfo = $api->root->info();\n            $options = [];\n            if (isset($apiInfo['account_name'])) {\n                $options['account_name'] = ['code' => 'account_name','html' => __('Account Name'),'value' => $apiInfo['account_name']];\n                $options['email'] = ['code' => 'email','html' => __('email'),'value' => $apiInfo['email']];\n                $options['first_name'] = ['code'=> 'first_name','html' => __('First Name'),'value' => $apiInfo['first_name']];\n                $options['last_name'] = ['code'=>'last_name','html' => __('Last Name'),'value' => $apiInfo['last_name']];\n                $options['pricing_plan_type'] = ['code'=>'pricing_plan_type','html' => __('Pricing Plan'),'value' => $apiInfo['pricing_plan_type']];\n                $options['username'] = ['code'=>'username','html' => __('User name:'), 'value' => $apiInfo['account_name']];\n                $options['account_id'] = ['code'=> 'account_id','html' => __('Account id:'), 'value' => $apiInfo['account_id']];\n                $options['total_subscribers'] = ['label' => __('Total Account Subscribers:'), 'value' => $apiInfo['total_subscribers']];\n                $options['total_account_subscribers'] = ['code' => 'total_subscribers', 'html' => __('Total Account Subscribers:'), 'value' => $apiInfo['total_subscribers']];\n                $token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope);\n                if ($store != -1) {\n                    $storeData = $api->ecommerce->stores->get($store);\n                    $options['list_id'] = $storeData['list_id'];\n                    $list = $api->lists->getLists($storeData['list_id']);\n                    $options['list_name'] = $list['name'];\n                    $options['total_list_subscribers'] = ['label' => __('Total List Subscribers:'), 'value' => $list['stats']['member_count']];\n                    $options['token'] = ['label' => __('Registration ID:'), 'value' => $token];\n                    $options['subtitle'] = ['label' => __('Ecommerce Data uploaded to MailChimp:'), 'value' => ''];\n                    $totalCustomers = $api->ecommerce->customers->getAll($store, 'total_items');\n                    $options['total_customers'] = ['label' => __('Total customers:'), 'value' => $totalCustomers['total_items']];\n                    $totalProducts = $api->ecommerce->products->getAll($store, 'total_items');\n                    $options['total_products'] = ['label' => __('Total products:'), 'value' => $totalProducts['total_items']];\n                    $totalOrders = $api->ecommerce->orders->getAll($store, 'total_items');\n                    $options['total_orders'] = ['label' => __('Total orders:'), 'value' => $totalOrders['total_items']];\n                    $totalCarts = $api->ecommerce->carts->getAll($store, 'total_items');\n                    $options['total_carts'] = ['label' => __('Total Carts:'), 'value' => $totalCarts['total_items']];\n                    $options['notsaved'] = ['label' => __('Ecommerce disabled, save configuration to enable.'), 'value' => ''];\n                } else {\n                    $options['nostore'] = ['label' => __('Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized).'), 'value' => ''];\n                }\n            }\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log($e->getFriendlyMessage());\n            $options['error'] = ['label' => 'Error', 'value' => __('--- Invalid API Key ---')];\n        }\n\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setData($options);\n        return $resultJson;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/Register.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Directory\\Helper\\Data as DirectoryHelper;\nuse Magento\\Framework\\App\\Config\\ScopeConfigInterface;\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse Magento\\Store\\Model\\StoreManager;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Config\\Model\\ResourceModel\\Config;\nuse Ebizmarts\\MailChimp\\Helper\\Data as Helper;\nuse Ebizmarts\\MailChimp\\Helper\\Http as MailChimpHttp;\n\nclass Register extends Action\n{\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var Helper\n     */\n    protected $_helper;\n    /**\n     * @var MailChimpHttp\n     */\n    protected $_http;\n    /**\n     * @var Config\n     */\n    protected $_config;\n    /**\n     * @var StoreManager\n     */\n    protected $_storeManager;\n    /**\n     * @var DirectoryHelper\n     */\n    protected $_directoryHelper;\n\n    /**\n     * @param Context $context\n     * @param Helper $helper\n     * @param MailChimpHttp $http\n     * @param Config $config\n     * @param StoreManager $storeManager\n     * @param DirectoryHelper $directoryHelper\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function __construct(\n        Context $context,\n        Helper $helper,\n        MailChimpHttp $http,\n        Config $config,\n        StoreManager $storeManager,\n        DirectoryHelper $directoryHelper\n    )\n    {\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_helper = $helper;\n        $this->_http = $http;\n        $this->_http->setUrl($helper->getConfigValue(Helper::XML_REGISTER_URL).'/register');\n        $this->_config = $config;\n        $this->_storeManager = $storeManager;\n        $this->_directoryHelper = $directoryHelper;\n    }\n    public function execute()\n    {\n        $params = $this->getRequest()->getParams();\n        $scope = $params['scope'];\n        $scopeId = $params['scopeId'];\n        $registerData = [];\n        $error = true;\n        $token = $this->_helper->getConfigValue(Helper::XML_STATISTICS_TOKEN,$scopeId, $scope);\n        foreach ($params['data'] as $index => $value) {\n            $registerData[$index] = $value['value'];\n        }\n        $registerData['store_url'] = stripslashes($this->_storeManager->getStore($scopeId)->getBaseUrl());\n        $registerData['city'] = $this->_helper->getConfigValue(\\Magento\\Store\\Model\\Information::XML_PATH_STORE_INFO_CITY,$scopeId, $scope);\n        $registerData['country'] = $this->_directoryHelper->getDefaultCountry($scopeId);\n        $registerDataJson = json_encode($registerData);\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        if ($token) {\n            $ret = $this->_http->patch($token, $registerDataJson);\n        } else {\n            $ret = $this->_http->post($registerDataJson);\n        }\n        $ret = json_decode($ret,true);\n        if ( !$ret['error']) {\n            $error = false;\n            $token = $ret['token'];\n            $this->_helper->saveConfigValue(Helper::XML_STATISTICS_TOKEN, $token,  $scopeId, $scope);\n        }\n        $resultJson->setData(['error' => $error, 'token' => $token]);\n        return $resultJson;\n\n    }\n    /**\n     * @return mixed\n     */\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/ResetLocalErrors.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass ResetLocalErrors extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n\n    /**\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->storeManager         = $storeManagerInterface;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        if (isset($params['website'])) {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $params['website'],\n                'website'\n            );\n            $storeId = $params['website'];\n        } elseif (isset($params['store'])) {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $params['store'],\n                'store'\n            );\n            $storeId = $params['store'];\n        } else {\n            $storeId = $this->storeManager->getStore()->getId();\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $storeId\n            );\n        }\n\n        $resultJson = $this->resultJsonFactory->create();\n        try {\n            $this->syncHelper->resetErrors($mailchimpStore, $storeId, true);\n        } catch (ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"ResetLocalErrors\",$ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/ResetLocalErrorsNoRetry.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass ResetLocalErrorsNoRetry extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n\n    /**\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->storeManager         = $storeManagerInterface;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        if (isset($params['website'])) {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $params['website'],\n                'website'\n            );\n            $storeId = $params['website'];\n        } elseif (isset($params['store'])) {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $params['store'],\n                'store'\n            );\n            $storeId = $params['store'];\n        } else {\n            $storeId = $this->storeManager->getStore()->getId();\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $storeId\n            );\n        }\n\n        $resultJson = $this->resultJsonFactory->create();\n        try {\n            $this->syncHelper->resetErrors($mailchimpStore, $storeId, false);\n        } catch (ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"ResetLocalErrorNoRetry\",$ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/ResetStore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\n\nclass ResetStore extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n\n    /**\n     * ResetLocalErrors constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->storeManager         = $storeManagerInterface;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        if (isset($params['website'])) {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $params['website'],\n                'website'\n            );\n        } elseif (isset($params['store'])) {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $params['store'],\n                'store'\n            );\n        } else {\n            $mailchimpStore = $this->helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $this->storeManager->getStore()\n            );\n        }\n\n        try {\n            $resultJson = $this->resultJsonFactory->create();\n        } catch (ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"ResetStore\",$ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/ResyncProducts.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\nclass ResyncProducts extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $helper;\n\n    /**\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param SyncHelper $syncHelper\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        SyncHelper $syncHelper,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->syncHelper           = $syncHelper;\n        $this->storeManager         = $storeManagerInterface;\n        $this->helper = $helper;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        $mailchimpStore = $params['mailchimpStoreId'];\n        $resultJson = $this->resultJsonFactory->create();\n        try {\n            $this->syncHelper->resyncProducts($mailchimpStore);\n        } catch (ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"ResyncProducts\",  $ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/ResyncSubscribers.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/21/17 5:07 PM\n * @file: ResetLocalErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Framework\\Controller\\Result\\JsonFactory;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass ResyncSubscribers extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var JsonFactory\n     */\n    protected $resultJsonFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $storeManager;\n\n    /**\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param JsonFactory $resultJsonFactory\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        JsonFactory $resultJsonFactory,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManagerInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n\n        parent::__construct($context);\n        $this->resultJsonFactory    = $resultJsonFactory;\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->storeManager         = $storeManagerInterface;\n    }\n\n    public function execute()\n    {\n        $valid = 1;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        $mailchimpList = $params['listId'];\n        $resultJson = $this->resultJsonFactory->create();\n        try {\n            $this->syncHelper->resyncAllSubscribers($mailchimpList);\n        } catch (ValidatorException $e) {\n            $valid = 0;\n            $message = $e->getMessage();\n        }\n        $ret = [\n            'valid' => (int)$valid,\n            'message' => $message,\n        ];\n        $this->helper->buttonPressed(\"ResyncSubscribers\",  $ret);\n        return $resultJson->setData($ret);\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Ecommerce/SyncLog.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Ecommerce;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailchimpHelper;\nuse Ebizmarts\\MailChimp\\Helper\\Http as MailChimpHttp;\n\n\nclass SyncLog extends Action\n{\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var MailChimpHttp\n     */\n    protected $_http;\n    /**\n     * @var MailchimpHelper\n     */\n    protected $_helper;\n    public function __construct(\n        Context $context,\n        MailchimpHelper $mailchimpHelper,\n        MailchimpHttp $mailchimpHttp\n    )\n    {\n        parent::__construct($context);\n        $this->_resultFactory = $context->getResultFactory();\n        $this->_helper = $mailchimpHelper;\n        $this->_http = $mailchimpHttp;\n        $this->_url = $mailchimpHelper->getConfigValue(MailchimpHelper::XML_REGISTER_URL);\n    }\n    public function execute()\n    {\n        $error = 0;\n        $message = '';\n        $params = $this->getRequest()->getParams();\n        $scope = $params['scope'];\n        $scopeId = $params['scopeId'];\n        $onoff = $params['onoff'];\n        $token = $this->_helper->getConfigValue(MailchimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope);\n        if ($token) {\n            if ($onoff) {\n                $this->_http->setUrl($this->_url . '/switchon');\n            } else {\n                $this->_http->setUrl($this->_url . '/switchoff');\n            }\n            $response = $this->_http->put($token, null);\n            $res = json_decode($response, true);\n            if (key_exists('error',$res)) {\n                $error = $res['error'];\n                $message = $res['message'];\n            }\n        } else {\n            $error = 1;\n            $message = 'First register your copy';\n        }\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setData(['error' => $error, 'message' => $message]);\n        return $resultJson;\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Errors/Getresponse.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/3/17 3:28 PM\n * @file: Getresponse.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Errors;\n\nuse Magento\\Framework\\Controller\\ResultFactory;\n\nclass Getresponse extends \\Magento\\Backend\\App\\Action\n{\n    const MAX_RETRIES = 5;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory\n     */\n    protected $_errorsFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Result\n     */\n    protected $_result;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Framework\\Filesystem\\Driver\\File\n     */\n    protected $_driver;\n\n    /**\n     * Getresponse constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $errorsFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Result $result\n     * @param \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $errorsFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Result $result,\n        \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n    ) {\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_errorsFactory       = $errorsFactory;\n        $this->_result              = $result;\n        $this->_helper              = $helper;\n        $this->_driver              = $driver;\n    }\n\n    public function execute()\n    {\n        $errorId    = $this->getRequest()->getParam('id');\n        $errors = $this->_errorsFactory->create();\n        $errors->getResource()->load($errors, $errorId);\n        $batchId = $errors->getBatchId();\n        $fileContent = [];\n        $counter = 0;\n        do {\n            $counter++;\n            $files = $this->_result->getBatchResponse($batchId, $errors->getStoreId());\n            if ($files===false) {\n                $fileContent = \"Response was deleted from MailChimp servers\";\n                break;\n            }\n            foreach ($files as $file) {\n                $items = json_decode($this->_driver->fileGetContents($file));\n                foreach ($items as $item) {\n                    $content = [\n                        'status_code' => $item->status_code,\n                        'operation_id' => $item->operation_id,\n                        'response' => json_decode($item->response)\n                    ];\n                    $fileContent[] = $content;\n                }\n                $this->_driver->deleteFile($file);\n            }\n            $baseDir = $this->_helper->getBaseDir();\n            if ($this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                \\Ebizmarts\\MailChimp\\Model\\Api\\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId)) {\n                $this->_driver->deleteDirectory(\n                    $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    \\Ebizmarts\\MailChimp\\Model\\Api\\Result::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId\n                );\n            }\n        } while (!count($fileContent) && $counter<self::MAX_RETRIES);\n        $resultJson =$this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setHeader('Content-disposition', 'attachment; filename='.$batchId.'.json');\n        $resultJson->setHeader('Content-type', 'application/json');\n        $data = json_encode($fileContent, JSON_PRETTY_PRINT);\n        $resultJson->setJsonData($data);\n        return $resultJson;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::error_grid');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Errors/Index.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/28/16 4:58 PM\n * @file: Index.php\n */\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Errors;\n\nclass Index extends \\Magento\\Backend\\App\\Action\n{\n    /**\n     * @var \\Magento\\Framework\\View\\Result\\PageFactory\n     */\n    protected $resultPageFactory;\n\n    /**\n     * Index constructor.\n     * @param \\Magento\\Backend\\App\\Action\\Context $context\n     * @param \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n     */\n    public function __construct(\n        \\Magento\\Backend\\App\\Action\\Context $context,\n        \\Magento\\Framework\\View\\Result\\PageFactory $resultPageFactory\n    ) {\n\n        $this->resultPageFactory = $resultPageFactory;\n        return parent::__construct($context);\n    }\n    public function execute()\n    {\n        $page = $this->resultPageFactory->create();\n        $page->getConfig()->getTitle()->prepend(__('Mailchimp Errors'));\n        return $page;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::error_grid');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Lists/Get.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/20/17 3:20 PM\n * @file: Get.php\n */\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Lists;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\n\nclass Get extends Action\n{\n    const MAX_LISTS = 200;\n\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var \\Magento\\Framework\\Encryption\\Encryptor\n     */\n    protected $encryptor;\n\n    /**\n     * Get constructor.\n     * @param Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Framework\\Encryption\\Encryptor $encryptor\n     */\n    public function __construct(\n        Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\Encryption\\Encryptor $encryptor\n    ) {\n\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_helper                  = $helper;\n        $this->encryptor                = $encryptor;\n    }\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $apiKey = $this->encryptor->decrypt($param['apikey']);\n        $result = [];\n        try {\n            $api = $this->_helper->getApiByApiKey($apiKey);\n            $lists = $api->lists->getLists(null, null, null, self::MAX_LISTS);\n            foreach ($lists['lists'] as $list) {\n                $result['lists'][] = ['id' => $list['id'], 'name' => $list['name']];\n            }\n            $result['valid'] = 1;\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $result['valid'] = 0;\n            $result['errormsg'] = $e->getTitle();\n            $this->_helper->log($e->getFriendlyMessage());\n        }\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setData($result);\n        return $resultJson;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Orders/Campaign.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Orders;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\UrlInterface;\nuse Magento\\Sales\\Model\\OrderRepository;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\n\nclass Campaign extends Action\n{\n    /**\n     * @var MailChimpHelper\n     */\n    private $helper;\n    /**\n     * @var OrderRepository\n     */\n    private $orderRepository;\n    /**\n     * @var UrlInterface\n     */\n    private $urlBuilder;\n\n    /**\n     * @param Context $context\n     * @param MailChimpHelper $helper\n     * @param OrderRepository $orderRepository\n     * @param UrlInterface $urlBuilder\n     */\n    public function __construct(\n        Context $context,\n        MailChimpHelper $helper,\n        OrderRepository $orderRepository,\n        UrlInterface $urlBuilder\n    ) {\n        parent::__construct($context);\n        $this->helper = $helper;\n        $this->orderRepository = $orderRepository;\n        $this->urlBuilder = $urlBuilder;\n    }\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $orderId = $this->getRequest()->getParam('orderId');\n        $order = $this->orderRepository->get($orderId);\n        $api = $this->helper->getApi($order->getStoreId());\n        try {\n            $campaign = $api->campaigns->get($order->getMailchimpCampaignId());\n            $webId = $campaign['web_id'];\n            $url = $this->urlBuilder->getUrl('https://admin.mailchimp.com/reports/summary') . \"?id=$webId\";\n            $this->_redirect($url);\n        } catch(\\Exception $e) {\n            $this->messageManager->addErrorMessage($e->getMessage());\n            $this->_redirect($this->urlBuilder->getUrl('sales/order'));\n        }\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::mailchimp_access');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Orders/Member.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Orders;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\UrlInterface;\nuse Magento\\Sales\\Model\\OrderRepository;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\n\nclass Member extends Action\n{\n    /**\n     * @var MailChimpHelper\n     */\n    private $helper;\n    /**\n     * @var OrderRepository\n     */\n    private $orderRepository;\n    /**\n     * @var UrlInterface\n     */\n    private $urlBuilder;\n\n    /**\n     * @param Context $context\n     * @param MailChimpHelper $helper\n     * @param OrderRepository $orderRepository\n     * @param UrlInterface $urlBuilder\n     */\n    public function __construct(\n        Context $context,\n        MailChimpHelper $helper,\n        OrderRepository $orderRepository,\n        UrlInterface $urlBuilder\n    ) {\n        parent::__construct($context);\n        $this->helper = $helper;\n        $this->orderRepository = $orderRepository;\n        $this->urlBuilder = $urlBuilder;\n    }\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $orderId = $this->getRequest()->getParam('orderId');\n        $order = $this->orderRepository->get($orderId);\n        $api = $this->helper->getApi($order->getStoreId());\n        try {\n            $email = $order->getCustomerEmail();\n            $listId = $this->helper->getDefaultList($order->getStoreId());\n            $member = $api->lists->members->get($listId, hash('md5', strtolower($email)));\n            $memberId = $member['contact_id'];\n            $url = $this->urlBuilder->getUrl('https://admin.mailchimp.com/audience/contact-profile') . \"?contact_id=$memberId\";\n            $this->_redirect($url);\n        } catch(\\Exception $e) {\n            $this->messageManager->addErrorMessage($e->getMessage());\n            $this->_redirect($this->urlBuilder->getUrl('sales/order'));\n        }\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::mailchimp_access');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Stores/Delete.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/17/17 12:03 PM\n * @file: Delete.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores;\n\nclass Delete extends \\Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores\n{\n    public function execute()\n    {\n        $resultRedirect = $this->resultRedirectFactory->create();\n        $storeId = (int) $this->getRequest()->getParam('id');\n        if ($storeId) {\n            $storeModel = $this->_mailchimpStoresFactory->create();\n            $storeModel->getResource()->load($storeModel, $storeId);\n            try {\n                $api = $this->_mhelper->getApiByApiKey($storeModel->getApikey(), true);\n                $api->ecommerce->stores->delete($storeModel->getStoreid());\n                $this->messageManager->addSuccess(__('You deleted the store.'));\n                return $resultRedirect->setPath('mailchimp/stores');\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->messageManager->addError(__('Store could not be deleted.'.$e->getMessage()));\n                $this->_mhelper->log($e->getFriendlyMessage());\n                return $resultRedirect->setPath('mailchimp/stores/edit', ['id'=>$storeId]);\n            }\n        }\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Stores/Edit.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/5/17 1:23 PM\n * @file: Edit.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores;\n\nuse Ebizmarts\\MailChimp\\Model\\MailChimpStoresFactory;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Registry;\nuse Magento\\Framework\\View\\Result\\PageFactory;\n\nclass Edit extends \\Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores\n{\n\n    public function execute()\n    {\n        $storeId = $this->getRequest()->getParam('id');\n        /** @var \\Ebizmarts\\MailChimp\\Model\\MailChimpStores $model */\n        $model = $this->_mailchimpStoresFactory->create();\n\n        if ($storeId) {\n            $model->getResource()->load($model, $storeId);\n            if (!$model->getId()) {\n                $this->messageManager->addError(__('This store no longer exists.'));\n                $this->_redirect('*/*/');\n                return;\n            }\n        }\n\n        // Restore previously entered form data from session\n        $data = $this->_session->getStoreData(true);\n        if (isset($data['name'])) {\n            $data['name'] = preg_replace('/ \\(Warning: not connected\\)/', '', $data['name']);\n        }\n        if (!empty($data)) {\n            $model->setData($data);\n        }\n        if (isset($model['name'])) {\n            $model['name'] = preg_replace('/ \\(Warning: not connected\\)/', '', $model['name']);\n        }\n        $this->_coreRegistry->register('mailchimp_stores', $model);\n\n        /** @var \\Magento\\Backend\\Model\\View\\Result\\Page $resultPage */\n        $resultPage = $this->_resultPageFactory->create();\n        $resultPage->setActiveMenu('Ebizmarts_MailChimp::main_menu');\n        $resultPage->getConfig()->getTitle()->prepend(__('Mailchimp Store'));\n\n        return $resultPage;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Stores/Get.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/20/17 3:20 PM\n * @file: Get.php\n */\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\n\nclass Get extends Action\n{\n    const MAX_STORES = 200;\n\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_mhelper;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n\n    /**\n     * Get constructor.\n     * @param Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_mhelper                  = $helper;\n    }\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $apiKey = $param['apikey'];\n        $encrypt = $param['encrypt'];\n        try {\n            $api = $this->_mhelper->getApiByApiKey($apiKey, $encrypt);\n            $stores = $api->ecommerce->stores->get(null, null, null, self::MAX_STORES);\n            $result = [];\n            $result['valid'] = 1;\n            $result['stores'] = [];\n            foreach ($stores['stores'] as $store) {\n                if ($store['platform'] == \\Ebizmarts\\MailChimp\\Helper\\Data::PLATFORM) {\n                    if ($store['list_id']=='') {\n                        continue;\n                    }\n                    $list = $api->lists->getLists($store['list_id']);\n                    $result['stores'][] = [\n                        'id' => $store['id'],\n                        'name' => $store['name'],\n                        'list_name' => $list['name'],\n                        'list_id' => $store['list_id']\n                    ];\n                    $result['valid'] = 1;\n                }\n            }\n        } catch (\\Mailchimp_Error $e) {\n            $this->_mhelper->log($e->getFriendlyMessage());\n            $result['valid'] = 0;\n            $result['errormsg'] = $e->getTitle();\n        }\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setData($result);\n        return $resultJson;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::config_mailchimp');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Stores/Index.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/24/17 10:38 AM\n * @file: Index.php\n */\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores;\n\nuse Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores;\n\nclass Index extends Stores\n{\n    public function execute()\n    {\n        $this->_mhelper->loadStores();\n        $page = $this->_resultPageFactory->create();\n        $page->getConfig()->getTitle()->prepend(__('Mailchimp Stores'));\n        return $page;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_grid');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Stores/Save.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/17/17 11:05 AM\n * @file: Save.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores;\n\nclass Save extends \\Ebizmarts\\MailChimp\\Controller\\Adminhtml\\Stores\n{\n    public function execute()\n    {\n        $isPost = $this->getRequest()->getPost();\n        if ($isPost) {\n            $resultRedirect = $this->resultRedirectFactory->create();\n            $returnToEdit = (bool)$this->getRequest()->getParam('back', false);\n            $storeModel = $this->_mailchimpStoresFactory->create();\n            $formData = $this->getRequest()->getParam('stores');\n            $storeId = isset($formData['id']) ? $formData['id'] : null;\n            if ($storeId) {\n                $storeModel->getResource()->load($storeModel, $storeId);\n            }\n            try {\n                $formData['storeid'] = $this->_updateMailchimp($formData);\n                $formData['platform'] = \\Ebizmarts\\MailChimp\\Helper\\Data::PLATFORM;\n                $storeModel->setData($formData);\n                $storeModel->getResource()->save($storeModel);\n                if ($returnToEdit) {\n                    if (!$storeId) {\n                        $storeId = $storeModel->getId();\n                    }\n                    return $resultRedirect->setPath('mailchimp/stores/edit', ['id'=>$storeId]);\n                } else {\n                    return $resultRedirect->setPath('mailchimp/stores');\n                }\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->messageManager->addErrorMessage(__('Store could not be saved.'.$e->getMessage()));\n                $this->_mhelper->log($e->getFriendlyMessage());\n                return $resultRedirect->setPath('mailchimp/stores/edit', ['id'=>$storeId]);\n            }\n        }\n    }\n    protected function _updateMailchimp($formData)\n    {\n        $api = $this->_mhelper->getApiByApiKey($formData['apikey'], true);\n        // set the address\n        $address = [];\n        $address['address1']    = $formData['address_address_one'];\n        $address['address2']    = $formData['address_address_two'];\n        $address['city']        = $formData['address_city'];\n        $address['province']    = '';\n        $address['province_code'] = '';\n        $address['postal_code'] = $formData['address_postal_code'];\n        $address['country']     = '';\n        $address['country_code'] = $formData['address_country_code'];\n        $emailAddress   = $formData['email_address'];\n        $currencyCode   = $formData['currency_code'];\n        $primaryLocale  = $formData['primary_locale'];\n        $timeZone       = $formData['timezone'];\n        $phone          = $formData['phone'];\n        $name           = $formData['name'];\n        $domain         = $formData['domain'];\n        $storeId = isset($formData['storeid']) ? $formData['storeid'] : null;\n        $is_sync = null;\n\n        if ($storeId) {\n            $api->ecommerce->stores->edit(\n                $storeId,\n                \\Ebizmarts\\MailChimp\\Helper\\Data::PLATFORM,\n                $domain,\n                $name,\n                $emailAddress,\n                $currencyCode,\n                null,\n                $primaryLocale,\n                $timeZone,\n                $phone,\n                $address,\n                $is_sync\n            );\n        } else {\n            $date = $this->_mhelper->getDateMicrotime();\n            $mailchimpStoreId = hash('md5', $name. '_' . $date);\n            //$mailchimpStoreId = md5($name. '_' . $date);\n            $is_sync = true;\n            $ret =$api->ecommerce->stores->add(\n                $mailchimpStoreId,\n                $formData['list_id'],\n                $name,\n                $currencyCode,\n                \\Ebizmarts\\MailChimp\\Helper\\Data::PLATFORM,\n                $domain,\n                $emailAddress,\n                null,\n                $primaryLocale,\n                $timeZone,\n                $phone,\n                $address,\n                $is_sync\n            );\n            $formData['storeid'] = $mailchimpStoreId;\n        }\n        return $formData['storeid'];\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_edit');\n    }\n}\n"
  },
  {
    "path": "Controller/Adminhtml/Stores.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/12/17 11:35 AM\n * @file: Stores.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Adminhtml;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Registry;\nuse Magento\\Framework\\View\\Result\\PageFactory;\nuse Ebizmarts\\MailChimp\\Model\\MailChimpStoresFactory;\n\nclass Stores extends Action\n{\n    /**\n     * @var Registry\n     */\n    protected $_coreRegistry;\n    /**\n     * @var PageFactory\n     */\n    protected $_resultPageFactory;\n    /**\n     * @var MailChimpStoresFactory\n     */\n    protected $_mailchimpStoresFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_mhelper;\n\n    /**\n     * Stores constructor.\n     * @param Context $context\n     * @param Registry $registry\n     * @param PageFactory $resultPageFactory\n     * @param MailChimpStoresFactory $storesFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        Context $context,\n        Registry $registry,\n        PageFactory $resultPageFactory,\n        MailChimpStoresFactory $storesFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n\n        parent::__construct($context);\n        $this->_coreRegistry            = $registry;\n        $this->_resultPageFactory       = $resultPageFactory;\n        $this->_mailchimpStoresFactory  = $storesFactory;\n        $this->_mhelper                  = $helper;\n    }\n    public function execute()\n    {\n        return 1;\n    }\n    protected function _isAllowed()\n    {\n        return $this->_authorization->isAllowed('Ebizmarts_MailChimp::stores_grid');\n    }\n}\n"
  },
  {
    "path": "Controller/Campaign/Check.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 1/19/19 12:36 PM\n * @file: Check.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Campaign;\n\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\n\nclass Check extends \\Magento\\Framework\\App\\Action\\Action\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    protected $_storeManager;\n\n    /**\n     * Get constructor.\n     * @param Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n    ) {\n\n        parent::__construct($context);\n        $this->_resultFactory       = $context->getResultFactory();\n        $this->_helper              = $helper;\n        $this->_storeManager        = $storeManager;\n    }\n\n    public function execute()\n    {\n        $param = $this->getRequest()->getParams();\n        $mc_cid = null;\n        if (key_exists('mc_cid', $param)) {\n            $mc_cid = $param['mc_cid'];\n            $magentoStoreId = $this->_storeManager->getStore()->getId();\n            $api = $this->_helper->getApi($magentoStoreId);\n            try {\n                $campaign =$api->campaigns->get($mc_cid);\n                $mailchimpList = $this->_helper->getConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST,\n                    $magentoStoreId\n                );\n                if ($mailchimpList == $campaign['recipients']['list_id']) {\n                    $valid = 1;\n                } else {\n                    $valid = 0;\n                }\n            } catch (\\Exception $e) {\n                $valid = 0;\n            }\n        } else {\n            $valid = 0;\n        }\n        $resultJson = $this->_resultFactory->create(ResultFactory::TYPE_JSON);\n        $resultJson->setData(['valid' => $valid]);\n        return $resultJson;\n    }\n}\n"
  },
  {
    "path": "Controller/Cart/Loadquote.php",
    "content": "<?php\n/**\n * Index\n *\n * @copyright Copyright © 2017 Ebizmarts Corp.. All rights reserved.\n * @author    info@ebizmarts.com\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Cart;\n\nuse Magento\\Framework\\App\\Action\\Action;\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse Magento\\Framework\\View\\Result\\PageFactory;\nuse Magento\\Framework\\App\\Action\\Context;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Loadquote extends Action\n{\n    /**\n     * @var PageFactory\n     */\n    protected $pageFactory;\n    /**\n     * @var \\Magento\\Quote\\Model\\QuoteFactory\n     */\n    protected $_quote;\n    /**\n     * @var \\Magento\\Customer\\Model\\Session\n     */\n    protected $_customerSession;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Framework\\Url\n     */\n    protected $_urlHelper;\n    /**\n     * @var \\Magento\\Framework\\Message\\ManagerInterface\n     */\n    protected $_message;\n    /**\n     * @var \\Magento\\Customer\\Model\\Url\n     */\n    protected $_customerUrl;\n    /**\n     * @var \\Magento\\Checkout\\Model\\Session\n     */\n    protected $_checkoutSession;\n\n    /**\n     * @param Context $context\n     * @param PageFactory $pageFactory\n     * @param \\Magento\\Quote\\Model\\QuoteFactory $quote\n     * @param \\Magento\\Customer\\Model\\Session $customerSession\n     * @param \\Magento\\Checkout\\Model\\Session $checkoutSession\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Framework\\Url $urlHelper\n     * @param \\Magento\\Customer\\Model\\Url $customerUrl\n     */\n    public function __construct(\n        Context $context,\n        PageFactory $pageFactory,\n        \\Magento\\Quote\\Model\\QuoteFactory $quote,\n        \\Magento\\Customer\\Model\\Session $customerSession,\n        \\Magento\\Checkout\\Model\\Session $checkoutSession,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Framework\\Url $urlHelper,\n        \\Magento\\Customer\\Model\\Url $customerUrl\n    ) {\n\n        $this->pageFactory      = $pageFactory;\n        $this->_quote           = $quote;\n        $this->_customerSession = $customerSession;\n        $this->_helper          = $helper;\n        $this->syncHelper       = $syncHelper;\n        $this->_urlHelper       = $urlHelper;\n        $this->_message         = $context->getMessageManager();\n        $this->_customerUrl     = $customerUrl;\n        $this->_checkoutSession = $checkoutSession;\n        parent::__construct($context);\n    }\n\n    /**\n     * Index Action\n     *\n     * @return \\Magento\\Framework\\View\\Result\\Page\n     */\n    public function execute()\n    {\n        /** @var \\Magento\\Framework\\View\\Result\\Page $resultPage */\n        $resultPage = $this->pageFactory->create();\n        $params     = $this->getRequest()->getParams();\n        if (isset($params['id'])) {\n            $quote = $this->_quote->create();\n            $quote->getResource()->load($quote, $params['id']);\n            $magentoStoreId = $quote->getStoreId();\n            $mailchimpStoreId = $this->_helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $magentoStoreId\n            );\n            $syncCommerce = $this->syncHelper->getChimpSyncEcommerce(\n                $mailchimpStoreId,\n                $params['id'],\n                \\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE\n            );\n            if (!isset($params['token']) || $params['token'] != $syncCommerce->getMailchimpToken()) {\n                // @error\n                $this->_message->addErrorMessage(__(\"You can't access this cart\"));\n                $url = $this->_urlHelper->getUrl(\n                    $this->_helper->getConfigValue(\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::XML_ABANDONEDCART_PAGE,\n                        $magentoStoreId\n                    )\n                );\n                $this->_redirect($url);\n            } else {\n                if (isset($params['mc_cid'])) {\n                    $url = $this->_urlHelper->getUrl(\n                        $this->_helper->getConfigValue(\n                            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_ABANDONEDCART_PAGE,\n                            $magentoStoreId\n                        ),\n                        ['mc_cid'=> $params['mc_cid']]\n                    );\n                    $quote->setData('mailchimp_campaign_id', $params['mc_cid']);\n                } else {\n                    $url = $this->_urlHelper->getUrl(\n                        $this->_helper->getConfigValue(\n                            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_ABANDONEDCART_PAGE,\n                            $magentoStoreId\n                        )\n                    );\n                }\n                $quote->setData('mailchimp_abandonedcart_flag', true);\n\n                $quote->getResource()->save($quote);\n                $this->_helper->sendCartEvent($quote);\n                if (!$quote->getCustomerId()) {\n                    $this->_checkoutSession->setQuoteId($quote->getId());\n                    $this->_redirect($url);\n                } else {\n                    if ($this->_customerSession->isLoggedIn()) {\n                        $this->_redirect($url);\n                    } else {\n                        $this->_message->addNoticeMessage(__(\"Login to complete your order\"));\n                        if (isset($params['mc_cid'])) {\n                            $url = $this->_urlHelper->getUrl(\n                                $this->_customerUrl->getLoginUrl(),\n                                ['mc_cid'=>$params['mc_cid']]\n                            );\n                        } else {\n                            $url = $this->_customerUrl->getLoginUrl();\n                        }\n                        $this->_redirect($url);\n                    }\n                }\n            }\n        }\n        return $resultPage;\n    }\n}\n"
  },
  {
    "path": "Controller/Checkout/Success.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/20/17 5:06 PM\n * @file: Success.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\Checkout;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Success extends \\Magento\\Framework\\App\\Action\\Action\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Checkout\\Model\\Session\n     */\n    protected $_checkoutSession;\n    /**\n     * @var \\Magento\\Framework\\View\\Result\\PageFactory\n     */\n    protected $_pageFactory;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $_subscriberFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory\n     */\n    protected $_interestGroupFactory;\n\n    /**\n     * @param \\Magento\\Framework\\App\\Action\\Context $context\n     * @param \\Magento\\Framework\\View\\Result\\PageFactory $pageFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Checkout\\Model\\Session $checkoutSession\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n     */\n    public function __construct(\n        \\Magento\\Framework\\App\\Action\\Context $context,\n        \\Magento\\Framework\\View\\Result\\PageFactory $pageFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Checkout\\Model\\Session $checkoutSession,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n    ) {\n        $this->_pageFactory         =$pageFactory;\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->_checkoutSession     = $checkoutSession;\n        $this->_subscriberFactory   = $subscriberFactory;\n        $this->_interestGroupFactory= $interestGroupFactory;\n        parent::__construct($context);\n    }\n\n    public function execute()\n    {\n        $params     = $this->getRequest()->getParams();\n        $order = $this->_checkoutSession->getLastRealOrder();\n        /**\n         * @var $subscriber \\Magento\\Newsletter\\Model\\Subscriber\n         * @var $interestGroup \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroup\n         */\n        $subscriber = $this->_subscriberFactory->create();\n        $interestGroup = $this->_interestGroupFactory->create();\n        try {\n            $subscriber->loadByEmail($order->getCustomerEmail());\n            if ($subscriber->getEmail()==$order->getCustomerEmail()) {\n                if ($subscriber->getStatus()==\\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED) {\n                    $subscriber->subscribe($subscriber->getEmail());\n                }\n                $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                $interestGroup->setGroupdata($this->_helper->serialize($params));\n                $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                $interestGroup->setStoreId($subscriber->getStoreId());\n                $interestGroup->setUpdatedAt($this->_helper->getGmtDate());\n                $interestGroup->getResource()->save($interestGroup);\n                $listId = $this->_helper->getGeneralList($order->getStoreId());\n                $this->_updateSubscriber($listId, $subscriber->getId(), $this->_helper->getGmtDate(), '', 1);\n            } else {\n                $this->_subscriberFactory->create()->subscribe($order->getCustomerEmail());\n                $subscriber->loadByEmail($order->getCustomerEmail());\n                $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                $interestGroup->setGroupdata($this->_helper->serialize($params));\n                $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                $interestGroup->setStoreId($subscriber->getStoreId());\n                $interestGroup->setUpdatedAt($this->_helper->getGmtDate());\n                $interestGroup->getResource()->save($interestGroup);\n            }\n        } catch (\\Exception $e) {\n            $this->_helper->log($e->getMessage());\n        }\n        $this->messageManager->addSuccessMessage(__('Thanks for sharing your interest with us'));\n        $this->_redirect($this->_helper->getBaserUrl(\n            $order->getStoreId(),\n            \\Magento\\Framework\\UrlInterface::URL_TYPE_WEB\n        ));\n    }\n    protected function _updateSubscriber(\n        $listId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null\n    ) {\n        $this->syncHelper->saveEcommerceData(\n            $listId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER,\n            $sync_delta,\n            $sync_error,\n            $sync_modified\n        );\n    }\n}\n"
  },
  {
    "path": "Controller/WebHook/Index.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/23/17 3:36 PM\n * @file: Index.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Controller\\WebHook;\n\nuse Magento\\Framework\\App\\Action\\Action;\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse Magento\\Framework\\View\\Result\\PageFactory;\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Framework\\App\\CsrfAwareActionInterface;\nuse Magento\\Framework\\App\\Request\\InvalidRequestException;\nuse Magento\\Framework\\App\\RequestInterface;\nuse Magento\\Framework\\Controller\\ResultInterface;\n\nclass Index extends Action implements CsrfAwareActionInterface\n{\n    const WEBHOOK__PATH = 'mailchimp/webhook/index';\n    /**\n     * @var ResultFactory\n     */\n    protected $_resultFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequestFactory\n     */\n    protected $_chimpWebhookRequestFactory;\n    private $_remoteAddress;\n\n    /**\n     * Index constructor.\n     * @param Context $context\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequestFactory $chimpWebhookRequestFactory\n     * @param \\Magento\\Framework\\HTTP\\PhpEnvironment\\RemoteAddress $remoteAddress\n     */\n    public function __construct(\n        Context $context,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequestFactory $chimpWebhookRequestFactory,\n        \\Magento\\Framework\\HTTP\\PhpEnvironment\\RemoteAddress $remoteAddress\n    ) {\n    \n        parent::__construct($context);\n        $this->_resultFactory              = $context->getResultFactory();\n        $this->_helper                      = $helper;\n        $this->_chimpWebhookRequestFactory  = $chimpWebhookRequestFactory;\n        $this->_remoteAddress               = $remoteAddress;\n    }\n    /**\n     * @inheritDoc\n     */\n    public function createCsrfValidationException(\n        RequestInterface $request\n    ): ?InvalidRequestException {\n        return null;\n    }\n    /**\n     * @inheritDoc\n     */\n    public function validateForCsrf(RequestInterface $request): ?bool\n    {\n        return true;\n    }\n\n    public function execute()\n    {\n        $requestKey = $this->getRequest()->getParam('wkey');\n        /**\n         * @var ResultInterface $result\n         */\n        $result = $this->_resultFactory->create(ResultFactory::TYPE_RAW);\n        $result->setContents('');\n        if (!$requestKey) {\n            $this->_helper->log('No wkey parameter from ip: '.$this->_remoteAddress->getRemoteAddress());\n            $result->setHttpResponseCode(403);\n            return $result;\n        }\n        $key = $this->_helper->getWebhooksKey();\n        if ($key!=$requestKey) {\n            $this->_helper->log('wkey parameter is invalid from ip: '.$this->_remoteAddress->getRemoteAddress());\n            $result->setHttpResponseCode(403);\n            return $result;\n        }\n        if ($this->getRequest()->getPost('type')) {\n            $request = $this->getRequest()->getPost();\n            if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_WEBHOOK_ACTIVE) ||\n                $request['type']==\\Ebizmarts\\MailChimp\\Cron\\Webhook::TYPE_SUBSCRIBE) {\n                try {\n                    $chimpRequest = $this->_chimpWebhookRequestFactory->create();\n                    $chimpRequest->setType($request['type']);\n                    $chimpRequest->setFiredAt($request['fired_at']);\n                    $chimpRequest->setDataRequest($this->_helper->serialize($request['data']));\n                    $chimpRequest->setProcessed(false);\n                    $chimpRequest->getResource()->save($chimpRequest);\n                    $result->setHttpResponseCode(200);\n                } catch(\\Exception $e) {\n                    $this->_helper->log($e->getMessage());\n                    $this->_helper->log($request['data']);\n                    $result->setHttpResponseCode(403);\n                }\n            }\n        } else {\n            $this->_helper->log('An empty request comes from ip: '.$this->_remoteAddress->getRemoteAddress());\n            $result->setHttpResponseCode(200);\n        }\n        return $result;\n    }\n}\n"
  },
  {
    "path": "Cron/BatchesClean.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 22/11/18 10:02 AM\n * @file: BatchesClean.php\n */\nnamespace Ebizmarts\\MailChimp\\Cron;\n\nclass BatchesClean\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches\n     */\n    protected $mailChimpSyncBatches;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors\n     */\n    protected $mailChimpErrors;\n\n    /**\n     * BatchesClean constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches $mailChimpSyncBatches\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors $chimpErrors\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches $mailChimpSyncBatches,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors $chimpErrors\n    ) {\n        $this->helper               = $helper;\n        $this->mailChimpSyncBatches = $mailChimpSyncBatches;\n        $this->mailChimpErrors      = $chimpErrors;\n    }\n    public function execute()\n    {\n        try {\n            $connection = $this->mailChimpSyncBatches->getResource()->getConnection();\n            $tableName = $this->mailChimpSyncBatches->getResource()->getMainTable();\n            $quoteInto = $connection->quoteInto(\n                'status IN(\"completed\",\"canceled\") and ( date_add(modified_date, interval ? month) < now() OR modified_date IS NULL)',\n                1\n            );\n            $connection->delete($tableName, $quoteInto);\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n        }\n\n        try {\n            $connection = $this->mailChimpSyncBatches->getResource()->getConnection();\n            $tableName = $this->mailChimpSyncBatches->getResource()->getMainTable();\n            $select = $connection->select();\n            $select->from($tableName, ['batch_id']);\n            $existingBatchIds = $connection->fetchCol($select);\n            $connection = $this->mailChimpErrors->getResource()->getConnection();\n            $tableName = $this->mailChimpErrors->getResource()->getMainTable();\n            if ($existingBatchIds) {\n                $connection->delete($tableName, [\n                    'batch_id NOT IN (?)' => $existingBatchIds,\n                ]);\n            } else {\n                $connection->delete($tableName);\n            }\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "Cron/Ecommerce.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/1/16 10:02 AM\n * @file: Ecommerce.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Cron;\n\nclass Ecommerce\n{\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    private $_storeManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Product\n     */\n    private $_apiProduct;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Result\n     */\n    private $_apiResult;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Customer\n     */\n    private $_apiCustomer;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Order\n     */\n    private $_apiOrder;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Cart\n     */\n    private $_apiCart;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatchesFactory\n     */\n    private $_mailChimpSyncBatchesFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n     */\n    private $_chimpSyncEcommerce;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Subscriber\n     */\n    private $_apiSubscribers;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\PromoCodes\n     */\n    private $_apiPromoCodes;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\PromoRules\n     */\n    private $_apiPromoRules;\n    /**\n     * @var \\Magento\\Framework\\Filesystem\\DirectoryList\n     */\n    private $_dir;\n\n    /**\n     * Ecommerce constructor.\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Product $apiProduct\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Result $apiResult\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Customer $apiCustomer\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Order $apiOrder\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Cart $apiCart\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Subscriber $apiSubscriber\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\PromoCodes $apiPromoCodes\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\PromoRules $apiPromoRules\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatchesFactory $mailChimpSyncBatchesFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimpSyncEcommerce\n     * @param \\Magento\\Framework\\Filesystem\\DirectoryList $dir\n     */\n    public function __construct(\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Product $apiProduct,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Result $apiResult,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Customer $apiCustomer,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Order $apiOrder,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Cart $apiCart,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Subscriber $apiSubscriber,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\PromoCodes $apiPromoCodes,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\PromoRules $apiPromoRules,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatchesFactory $mailChimpSyncBatchesFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimpSyncEcommerce,\n        \\Magento\\Framework\\Filesystem\\DirectoryList $dir\n    ) {\n\n        $this->_storeManager    = $storeManager;\n        $this->_helper          = $helper;\n        $this->_apiProduct      = $apiProduct;\n        $this->_mailChimpSyncBatchesFactory = $mailChimpSyncBatchesFactory;\n        $this->_apiResult       = $apiResult;\n        $this->_apiCustomer     = $apiCustomer;\n        $this->_apiOrder        = $apiOrder;\n        $this->_apiCart         = $apiCart;\n        $this->_apiSubscribers  = $apiSubscriber;\n        $this->_chimpSyncEcommerce  = $chimpSyncEcommerce;\n        $this->_apiPromoCodes   = $apiPromoCodes;\n        $this->_apiPromoRules   = $apiPromoRules;\n        $this->_dir             = $dir;\n    }\n\n    public function execute()\n    {\n\n        $connection = $this->_chimpSyncEcommerce->getResource()->getConnection();\n        $tableName = $this->_chimpSyncEcommerce->getResource()->getMainTable();\n        $connection->delete(\n            $tableName,\n            'batch_id is null and mailchimp_sync_modified != 1 and mailchimp_sync_error is null'\n        );\n\n        foreach ($this->_storeManager->getStores() as $storeId => $val) {\n            if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ACTIVE, $storeId)) {\n                if (!$this->_ping($storeId)) {\n                    $this->_helper->log('MailChimp is not available');\n                    return;\n                }\n                $this->_storeManager->setCurrentStore($storeId);\n                $listId = $this->_helper->getGeneralList($storeId);\n                $mailchimpStoreId = $this->_helper->getConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                    $storeId\n                );\n                if ($mailchimpStoreId != -1 && $mailchimpStoreId != '') {\n                    $this->_apiResult->processResponses($storeId, true, $mailchimpStoreId);\n                    $batchId = $this->_processStore($storeId, $mailchimpStoreId, $listId);\n                    if ($batchId) {\n                        $connection->update(\n                            $tableName,\n                            [\n                                'batch_id' => $batchId,\n                                'mailchimp_sync_modified' => 0,\n                                'mailchimp_sync_delta' => $this->_helper->getGmtDate()\n                            ],\n                            \"batch_id is null and mailchimp_store_id = '$mailchimpStoreId' and mailchimp_sync_error is null\"\n                        );\n                        $connection->update(\n                            $tableName,\n                            [\n                                'batch_id' => $batchId,\n                                'mailchimp_sync_modified' => 0,\n                                'mailchimp_sync_delta' => $this->_helper->getGmtDate()],\n                            \"batch_id is null and mailchimp_store_id = '$listId' and mailchimp_sync_error is null\"\n                        );\n                    }\n                }\n            }\n        }\n        $syncs = [];\n        foreach ($this->_storeManager->getStores() as $storeId => $val) {\n            $mailchimpStoreId = $this->_helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $storeId\n            );\n            if ($mailchimpStoreId != -1 && $mailchimpStoreId != '') {\n                $dateSync = $this->_helper->getMCMinSyncDateFlag($storeId);\n                if (isset($syncs[$mailchimpStoreId])) {\n                    if ($syncs[$mailchimpStoreId] && $syncs[$mailchimpStoreId]['datesync'] < $dateSync) {\n                        $syncs[$mailchimpStoreId]['datesync'] = $dateSync;\n                        $syncs[$mailchimpStoreId]['storeid'] = $storeId;\n                    }\n                } elseif ($dateSync) {\n                    $syncs[$mailchimpStoreId]['datesync'] = $dateSync;\n                    $syncs[$mailchimpStoreId]['storeid'] = $storeId;\n                } else {\n                    $syncs[$mailchimpStoreId] = false;\n                }\n            }\n        }\n        foreach ($syncs as $mailchimpStoreId => $val) {\n            $flag = $this->_helper->getMCMinSyncDateFlagByMailchimpStore(\n                $mailchimpStoreId,\n                0,\n                'default'\n            );\n            if ($val && !$flag) {\n                $this->updateSyncFlagData($val['storeid'], $mailchimpStoreId);\n            }\n        }\n    }\n\n    protected function _processStore($storeId, $mailchimpStoreId, $listId)\n    {\n        $batchId = null;\n        $countCustomers = 0;\n        $countProducts = 0;\n        $countOrders = 0;\n        $batchArray = [];\n        $this->_helper->resetCounters($storeId);\n        $results = $this->_apiSubscribers->sendSubscribers($storeId, $listId);\n        if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ECOMMERCE_ACTIVE, $storeId)) {\n            $this->_helper->log('Generate Products payload');\n            $products = $this->_apiProduct->_sendProducts($storeId);\n            $countProducts = count($products);\n            $results = array_merge($results, $products);\n\n            if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ALL_CUSTOMERS, $storeId)) {\n                $this->_helper->log('Generate Customers payload');\n                $customers = $this->_apiCustomer->sendCustomers($storeId);\n                $countCustomers = count($customers);\n                $results = array_merge($results, $customers);\n            }\n            $this->_helper->log('Generate Orders payload');\n            $orders = $this->_apiOrder->sendOrders($storeId);\n            $countOrders = count($orders);\n            $results = array_merge($results, $orders);\n\n            if ($this->_helper->getMCMinSyncDateFlag($storeId)) {\n                $this->_helper->log('Generate Carts payload');\n                $carts = $this->_apiCart->createBatchJson($storeId);\n                $results = array_merge($results, $carts);\n            } else {\n                $this->_helper->log('No Carts will be synced until the store is completely synced');\n            }\n            if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_SEND_PROMO, $storeId)) {\n                $this->_helper->log('Generate Rules payload');\n                $rules = $this->_apiPromoRules->sendRules($storeId);\n                $results = array_merge($results, $rules);\n\n                $this->_helper->log('Generate Coupons payload');\n                $coupons = $this->_apiPromoCodes->sendCoupons($storeId);\n                $results = array_merge($results, $coupons);\n            }\n        }\n\n        if (!empty($results)) {\n            list($OKOperations, $BadOperations) = $this->encodeOperations($results);\n            $batchArray['operations'] = $OKOperations;\n            try {\n\n                if (!count($batchArray['operations'])) {\n                    $this->_helper->log('An empty operation was detected');\n                } else {\n                    $api = $this->_helper->getApi($storeId);\n                    $batchResponse = $api->batchOperation->add($batchArray);\n                    if (!isset($batchResponse['id'])) {\n                        $this->_helper->log('error in the call to batch');\n                    } else {\n                        $batchCounters = $this->_helper->getCounters();\n                        $syncBatches = $this->_mailChimpSyncBatchesFactory->create();\n                        $syncBatches->setStoreId($storeId);\n                        $syncBatches->setBatchId($batchResponse['id']);\n                        $syncBatches->setStatus(\\Ebizmarts\\MailChimp\\Helper\\Data::BATCH_PENDING);\n                        $syncBatches->setMailchimpStoreId($mailchimpStoreId);\n                        $syncBatches->setModifiedDate($this->_helper->getGmtDate());\n                        if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ALL_CUSTOMERS, $storeId)) {\n                            $syncBatches->setCustomersNewCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::CUS_NEW]);\n                            $syncBatches->setCustomersModifiedCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::CUS_MOD]);\n                        }\n                        $syncBatches->setSubscribersNewCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::SUB_NEW]);\n                        $syncBatches->setProductsNewCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::PRO_NEW]);\n                        $syncBatches->setCartsNewCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::QUO_NEW]);\n                        $syncBatches->setOrdersNewCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::ORD_NEW]);\n                        $syncBatches->setSubscribersModifiedCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::SUB_MOD]);\n                        $syncBatches->setProductsModifiedCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::PRO_MOD]);\n                        $syncBatches->setCartsModifiedCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::QUO_MOD]);\n                        $syncBatches->setOrdersModifiedCount($batchCounters[\\Ebizmarts\\MailChimp\\Helper\\Data::ORD_MOD]);\n                        $syncBatches->getResource()->save($syncBatches);\n                        $batchId = $batchResponse['id'];\n                        $this->_showResume($batchId, $storeId);\n                    }\n                }\n                if (count($BadOperations)) {\n                    $this->markWithError($BadOperations, $mailchimpStoreId, $listId);\n                }\n\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n            }\n        } else {\n            $this->_helper->log(\"Nothing to sync for store $storeId\");\n        }\n        $countTotal = $this->_helper->getTotalNewItemsSent();\n        $syncing = $this->_helper->getMCMinSyncDateFlag($storeId);\n        if ($countTotal == 0 && $syncing) {\n            $this->_helper->saveMCMinSyncing(\n                null,\n                date('Y-m-d'),\n                $storeId\n            );\n        }\n\n        return $batchId;\n    }\n\n    /**\n     * @param $storeId\n     * @param $mailchimpStoreId\n     */\n    protected function updateSyncFlagData($storeId, $mailchimpStoreId)\n    {\n        $this->apiUpdateSyncFlag($storeId, $mailchimpStoreId);\n        $this->_helper->saveMCMinSyncing(\n            $mailchimpStoreId,\n            date('Y-m-d'),\n            0,\n            'default'\n        );\n    }\n\n    /**\n     * @param $storeId\n     * @param $mailchimpStoreId\n     */\n    protected function apiUpdateSyncFlag($storeId, $mailchimpStoreId)\n    {\n        try {\n            $api = $this->_helper->getApi($storeId);\n            $api->ecommerce->stores->edit(\n                $mailchimpStoreId,\n                null,\n                null,\n                null,\n                null,\n                null,\n                null,\n                null,\n                null,\n                null,\n                null,\n                false\n            );\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log('MailChimp error when updating syncing flag for store ' . $storeId);\n            $this->_helper->log($e->getFriendlyMessage());\n        }\n    }\n    protected function _ping($storeId)\n    {\n        try {\n            $api = $this->_helper->getApi($storeId);\n            $api->root->info();\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log($e->getFriendlyMessage());\n            return false;\n        }\n        return true;\n    }\n    protected function _showResume($batchId, $storeId)\n    {\n        $this->_helper->log(\"Sent batch $batchId for store $storeId\");\n        $this->_helper->log($this->_helper->getCounters());\n    }\n\n    protected function _saveRequest($resquest)\n    {\n        $pathLog = $this->_dir->getPath('log').DIRECTORY_SEPARATOR.'Request'.$this->_helper->getGmtTimeStamp().'.log';\n        error_log(var_export($resquest, true), 3, $pathLog);\n        $this->_helper->log(\"Request with error was saved in $pathLog\");\n    }\n\n    protected function encodeOperations($operations)\n    {\n        $OKOperations = [];\n        $BadOperations = [];\n        $batchJson = json_encode($operations);\n        $jsonLastErrorGeneral  = json_last_error();\n        $jsonLastErrorMsgGeneral = json_last_error_msg();\n        if ($jsonLastErrorGeneral) {\n            $this->_helper->log(\"Encode error\");\n            foreach ($operations as $opIndex => $operation) {\n                $jsonEncode = json_encode($operation);\n                $jsonLastErrorItem = json_last_error();\n                if ($jsonLastErrorItem) {\n                    $jsonLastErrorMsgItem = json_last_error_msg();\n                    $this->_helper->log(\"\");\n                    $this->_helper->log(\"json_encode error: $jsonLastErrorMsgItem, operation:\");\n                    $this->_saveRequest($operation);\n                    /*remove failing operation*/\n                    $BadOperations[] = $operation;\n                    unset($operations[$opIndex]);\n                } else {\n                    $OKOperations[] = $operation;\n                }\n            }\n        } else {\n            $OKOperations = $operations;\n        }\n        return [$OKOperations, $BadOperations];\n    }\n    protected function markWithError($operations, $mailchimpStoreId, $listId)\n    {\n        $type = null;\n        $relatedId = null;\n        $types = [\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER\n        ];\n        $connection = $this->_chimpSyncEcommerce->getResource()->getConnection();\n        $tableName = $this->_chimpSyncEcommerce->getResource()->getMainTable();\n        foreach ($operations as $operation) {\n            if (is_array($operation)) {\n                if (array_key_exists('operation_id', $operation)) {\n                    $operationId = explode(\"_\", $operation['operation_id']);\n                    if (isset($operationId[0])) {\n                        $type = $operationId[0];\n                        if (!in_array($type, $types)) {\n                            $type = '';\n                        } else {\n                            if ($type == \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER) {\n                                $storeId = $listId;\n                            } else {\n                                $storeId = $mailchimpStoreId;\n                            }\n                        }\n                    }\n                    if (isset($operationId[2])) {\n                        $relatedId = $operationId[2];\n                    }\n                    if ($type && $relatedId) {\n                        $connection->update(\n                            $tableName,\n                            [\n                            'batch_id' => -1,\n                            'mailchimp_sync_modified' => 0,\n                            'mailchimp_sync_delta' => $this->_helper->getGmtDate(),\n                            'mailchimp_sync_error' => __('Json error'),\n                            'mailchimp_sent' => \\Ebizmarts\\MailChimp\\Helper\\Data::NOTSYNCED\n                            ],\n                            \"batch_id is null and mailchimp_store_id = '$storeId' and type ='$type' and related_id = $relatedId\"\n                        );\n                    }\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Cron/ErrorsClean.php",
    "content": "<?php\n\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 15/09/22 10:02 AM\n * @file: ErrorsClean.php\n */\nnamespace Ebizmarts\\MailChimp\\Cron;\n\nclass ErrorsClean\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors\n     */\n    protected $chimpErrors;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    protected $storeManager;\n    const LIMIT = 1000;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors $chimpErrors\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors $chimpErrors,\n        \\Magento\\Store\\Model\\StoreManager $storeManager\n    )\n    {\n        $this->helper = $helper;\n        $this->chimpErrors = $chimpErrors;\n        $this->storeManager = $storeManager;\n    }\n    public function execute()\n    {\n        foreach ($this->storeManager->getStores() as $storeId => $val)\n        {\n            $period = $this->helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_CLEAN_ERROR_MONTHS, $storeId);\n            if ($period > 0) {\n                try {\n                    $this->helper->log(\"Cleaning errors for store [$storeId] older than $period months\");\n                    $this->chimpErrors->deleteByStorePeriod($storeId,$period,self::LIMIT);\n                } catch (\\Exception $e) {\n                    $this->helper->log($e->getMessage());\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "Cron/GenerateStatistics.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Cron;\n\nuse Magento\\Store\\Model\\StoreManager;\nuse Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface;\nuse Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory as CustomerCollectionFactory;\nuse Magento\\Catalog\\Model\\ResourceModel\\Product\\CollectionFactory as ProductCollectionFactory;\nuse Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory as OrderCollectionFactory;\nuse Magento\\Cron\\Model\\ResourceModel\\Schedule\\CollectionFactory as ScheduleCollectionFactory;\nuse Magento\\Framework\\App\\ProductMetadataInterface;\nuse Ebizmarts\\MailChimp\\Helper\\Data;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches\\CollectionFactory as MailChimpSyncBatchesCollectionFactory;\nuse Ebizmarts\\MailChimp\\Model\\Config\\ModuleVersion;\n\nclass GenerateStatistics\n{\n    /**\n     * @var Data\n     */\n    protected $helper;\n    /**\n     * @var StoreManager\n     */\n    protected $storeManager;\n    /**\n     * @var CustomerCollectionFactory\n     */\n    protected $customerCollectionFactory;\n    /**\n     * @var ProductCollectionFactory\n     */\n    protected $productCollectionFactory;\n    /**\n     * @var OrderCollectionFactory\n     */\n    protected $orderCollectionFactory;\n    /**\n     * @var MailChimpSyncBatchesCollectionFactory\n     */\n    protected $mailChimpSyncBatchesCollectionFactory;\n    /**\n     * @var ScheduleCollectionFactory\n     */\n    protected $scheduleCollectionFactory;\n    /**\n     * @var ProductMetadataInterface\n     */\n    protected $productMetadata;\n    /**\n     * @var ModuleVersion\n     */\n    protected $moduleVersion;\n    /**\n     * @var TimezoneInterface\n     */\n    protected $locale;\n    protected $deleteAction = [\n        0 => 'Unsubscribe',\n        1 => 'Delete',\n    ];\n    public function __construct(\n        Data $helper,\n        StoreManager $storeManager,\n        CustomerCollectionFactory $customerCollectionFactory,\n        ProductCollectionFactory $productCollectionFactory,\n        OrderCollectionFactory $orderCollectionFactory,\n        MailchimpSyncBatchesCollectionFactory $mailchimpSyncBatchesCollectionFactory,\n        ScheduleCollectionFactory $scheduleCollectionFactory,\n        ProductMetadataInterface $productMetadata,\n        ModuleVersion $moduleVersion,\n        TimezoneInterface $locale\n    )\n    {\n        $this->helper = $helper;\n        $this->storeManager = $storeManager;\n        $this->customerCollectionFactory = $customerCollectionFactory;\n        $this->productCollectionFactory = $productCollectionFactory;\n        $this->orderCollectionFactory = $orderCollectionFactory;\n        $this->mailChimpSyncBatchesCollectionFactory = $mailchimpSyncBatchesCollectionFactory;\n        $this->scheduleCollectionFactory = $scheduleCollectionFactory;\n        $this->productMetadata = $productMetadata;\n        $this->moduleVersion = $moduleVersion;\n        $this->locale = $locale;\n    }\n    public function execute()\n    {\n        $data = [];\n        $data['storeURL'] = $this->storeManager->getStore()->getBaseUrl();\n        $data['time'] = $this->helper->getGmtDate();\n        foreach ($this->storeManager->getStores() as $storeId => $val)\n        {\n            if ($this->helper->isMailChimpEnabled($storeId)) {\n                $mailChimpStoreId = $this->helper->getConfigValue(Data::XML_MAILCHIMP_STORE, $storeId);\n                $storeStatistics = [];\n                // Get currents mailchimp totals (orders, products, customers)\n                $storeStatistics['mailchimp'] = $this->getMailchimpTotals($storeId);\n                $storeStatistics['magento'] = $this->getMagentoTotals($storeId);\n                $data['statistics']['store'][$storeId] = $storeStatistics;\n                $data['batches']['store'][$storeId] = $this->getBatches($storeId, $mailChimpStoreId);\n            }\n        }\n        $data['jobs'] = $this->getJobs();\n        if (!empty($data)) {\n            $this->helper->saveNotification($data);\n        }\n    }\n    private function getMagentoTotals($storeId)\n    {\n        $options = [];\n        $customerCollection = $this->customerCollectionFactory->create();\n        $customerCollection->addFieldToFilter('store_id', ['eq'=>$storeId]);\n        $customerCollection->getSelect()->reset(\\Magento\\Framework\\DB\\Select::COLUMNS)->columns(['entity_id','store_id']);\n        $totalCustomers = $customerCollection->getSize();\n        $options['total_customers'] = $totalCustomers;\n        unset($customerCollection);\n\n        $productCollection = $this->productCollectionFactory->create();\n        $productCollection->addStoreFilter($storeId);\n        $productCollection->getSelect()->reset(\\Magento\\Framework\\DB\\Select::COLUMNS)->columns(['entity_id']);\n        $totalProducts = $productCollection->getSize();\n        $options['total_products'] = $totalProducts;\n        unset($productCollection);\n\n        $orderCollection = $this->orderCollectionFactory->create();\n        $orderCollection->addFieldToFilter('store_id', ['eq' => $storeId]);\n        $orderCollection->getSelect()->reset(\\Magento\\Framework\\DB\\Select::COLUMNS)->columns(['entity_id']);\n        $totalOrders = $orderCollection->getSize();\n        $options['total_orders'] = $totalOrders;\n        unset($orderCollection);\n        $storeUrl = stripslashes($this->storeManager->getStore($storeId)->getUrl());\n        $options['store_url'] = stripslashes($storeUrl);\n        // get all de configuration\n        $config = [];\n        $config['general']['active'] = $this->helper->getConfigValue(Data::XML_PATH_ACTIVE, $storeId);\n        $config['general']['store'] = $this->helper->getConfigValue(Data::XML_MAILCHIMP_STORE, $storeId);\n        $config['general']['list'] = $this->helper->getConfigValue(Data::XML_PATH_LIST, $storeId);\n        $config['general']['popup_form'] = $this->helper->getConfigValue(Data::XML_POPUP_FORM, $storeId);\n        if ($config['general']['popup_form']) {\n            $config['general']['popup_url'] = $this->helper->getConfigValue(Data::XML_POPUP_URL, $storeId);\n        }\n        $config['general']['magento_email'] = $this->helper->getConfigValue(Data::XML_MAGENTO_MAIL, $storeId);\n        $config['general']['two-way_sync'] = $this->helper->getConfigValue(Data::XML_PATH_WEBHOOK_ACTIVE, $storeId);\n        if ( $config['general']['two-way_sync']) {\n            $config['general']['delete_action'] = $this->deleteAction[$this->helper->getConfigValue(Data::XML_PATH_WEBHOOK_DELETE)];\n        }\n        $config['general']['enable_log'] = $this->helper->getConfigValue(Data::XML_PATH_LOG,$storeId);\n        $config['general']['field_mapping'] = $this->helper->getConfigValue(Data::XML_MERGEVARS, $storeId);\n        $config['general']['mapping'] = $this->helper->getMapFields($storeId, false);\n        $config['general']['interest'] = $this->helper->getConfigValue(Data::XML_INTEREST, $storeId);\n        $config['general']['show_groups'] = $this->helper->getConfigValue(Data::XML_INTEREST_IN_SUCCESS);\n        if ($config['general']['show_groups']) {\n            $config['general']['group_description'] = $this->helper->getConfigValue(Data::XML_INTEREST_SUCCESS_HTML_BEFORE, $storeId);\n            $config['general']['succes_message'] = $this->helper->getConfigValue(Data::XML_INTEREST_SUCCESS_HTML_AFTER, $storeId);\n        }\n        $config['general']['timeout'] = $this->helper->getConfigValue(Data::XML_PATH_TIMEOUT, $storeId);\n        $config['ecommerce']['enabled'] = $this->helper->getConfigValue(Data::XML_PATH_ECOMMERCE_ACTIVE, $storeId);\n        $config['ecommerce']['sync_all_customers'] = $this->helper->getConfigValue(Data::XML_PATH_ALL_CUSTOMERS, $storeId);\n        $config['ecommerce']['subscribe_all_customers'] = $this->helper->getConfigValue(Data::XML_ECOMMERCE_OPTIN, $storeId);\n        $config['ecommerce']['first_date'] = $this->helper->getConfigValue(Data::XML_ECOMMERCE_FIRSTDATE, $storeId);\n        $config['ecommerce']['send_promo'] = $this->helper->getConfigValue(Data::XML_SEND_PROMO, $storeId);\n        $config['ecommerce']['include_taxes'] = $this->helper->getConfigValue(Data::XML_INCLUDING_TAXES, $storeId);\n        $config['ecommerce']['campaign_attribution'] = $this->helper->getConfigValue(Data::XML_CAMPAIGN_ACTION, $storeId);\n        $config['ecommerce']['monts_to_clear_error_table'] = $this->helper->getConfigValue(Data::XML_CLEAN_ERROR_MONTHS, $storeId);\n        $config['ac']['enabled'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_ACTIVE, $storeId);\n        $config['ac']['first_date'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_FIRSTDATE, $storeId);\n        $config['ac']['redirect_page'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_PAGE, $storeId);\n        $config['ac']['save_email'] = $this->helper->getConfigValue(Data::XML_ABANDONEDCART_EMAIL, $storeId);\n        $options['config'] = $config;\n        $options['magento_version'] = $this->productMetadata->getVersion();\n        $options['mc2-version'] = $this->moduleVersion->getModuleVersion('Ebizmarts_MailChimp');\n        try {\n            $options['lib-version'] = $this->moduleVersion->getLibVersion('ebizmarts/mailchimp-lib');\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n        }\n        $options['time_zone'] = $this->locale->getConfigTimezone(\\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORE, $storeId);\n        return $options;\n    }\n    private function getMailchimpTotals($storeId)\n    {\n        $mailchimpList = $this->helper->getGeneralList($storeId);\n        $mailChimpStoreId = $this->helper->getConfigValue(Data::XML_MAILCHIMP_STORE, $storeId);\n        $api = $this->helper->getApi($storeId);\n        $apiInfo = $api->root->info();\n        $options = [];\n        $options ['store']  = $mailChimpStoreId;\n        if (isset($apiInfo['account_name'])) {\n            $options['webhooks'] = $this->getWebhooks($api, $mailchimpList);\n            $options['username'] =$apiInfo['account_name'];\n            $options['total_subscribers'] = $apiInfo['total_subscribers'];\n            if ($storeId != -1) {\n                $storeData = $api->ecommerce->stores->get($mailChimpStoreId);\n                $options['list_id'] = $storeData['list_id'];\n                $list = $api->lists->getLists($storeData['list_id']);\n                $options['list_name'] = $list['name'];\n                $options['total_list_subscribers'] = $list['stats']['member_count'];\n                $totalCustomers = $api->ecommerce->customers->getAll($mailChimpStoreId, 'total_items');\n                $options['total_customers'] = $totalCustomers['total_items'];\n                $totalProducts = $api->ecommerce->products->getAll($mailChimpStoreId, 'total_items');\n                $options['total_products'] = $totalProducts['total_items'];\n                $totalOrders = $api->ecommerce->orders->getAll($mailChimpStoreId, 'total_items');\n                $options['total_orders'] = $totalOrders['total_items'];\n                $totalCarts = $api->ecommerce->carts->getAll($mailChimpStoreId, 'total_items');\n                $options['total_carts'] = $totalCarts['total_items'];\n                $options['currency_code'] = $storeData['currency_code'];\n                $options['money_format'] = $storeData['money_format'];\n                $options['primary_locale'] = $storeData['primary_locale'];\n                $options['timezone'] = $storeData['timezone'];\n                $options['is_syncing'] = $storeData['is_syncing'];\n                $contact = [];\n                $contact['email_address'] = $storeData['email_address'];\n                $contact['phone_number'] = $storeData['phone'];\n                $contact['address'] = $storeData['address'];\n                $options['contact'] = $contact;\n            } else {\n                $options['nostore'] = ['label' => __('Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized)'), 'value' => ''];\n            }\n        }\n        return $options;\n    }\n    private function getWebhooks($api, $listId)\n    {\n        $ret = [];\n        $webhooks = $api->lists->webhooks->getAll($listId);\n        foreach ($webhooks['webhooks'] as $webhook) {\n            $item =[];\n            $item['url'] = $webhook['url'];\n            $item['events'] = $webhook['events'];\n            $item['sources'] = $webhook['sources'];\n            $ret[] = $item;\n        }\n        return $ret;\n    }\n    private function getBatches($storeId,$mailchimpStoreId)\n    {\n        $batches = [];\n        $collection = $this->mailChimpSyncBatchesCollectionFactory->create();\n        $collection\n            ->addFieldToFilter('store_id', ['eq' => $storeId])\n            ->addFieldToFilter('mailchimp_store_id', ['eq' => $mailchimpStoreId]);\n        $collection->setOrder('modified_date', 'DESC');\n        $collection->getSelect()->limit(10);\n        foreach ($collection as $item) {\n            $batch = [];\n            $batch['id'] = $item['batch_id'];\n            $batch['mailchimp_store_id'] = $item['mailchimp_store_id'];\n            $batch['date'] = $item['modified_date'];\n            $batch['status'] = $item['status'];\n            $counters = [];\n            $counters['carts_new'] = $item['carts_new_count'];\n            $counters['order_new'] = $item['orders_new_count'];\n            $counters['products_new'] = $item['products_new_count'];\n            $counters['customers_new'] = $item['customers_new_count'];\n            $counters['subscribers_new'] = $item['subscribers_new_count'];\n            $counters['carts_modified'] = $item['carts_modified_count'];\n            $counters['customers_modified'] = $item['customers_modified_count'];\n            $counters['orders_modified'] = $item['orders_modified_count'];\n            $counters['products_modified'] = $item['products_modified_count'];\n            $counters['subscribers_modified'] = $item['subscribers_modified_count'];\n            $batch['counters'] = $counters;\n            $batches[] = $batch;\n        }\n        return $batches;\n    }\n    private function getJobs()\n    {\n        $jobs = [];\n        $collection = $this->scheduleCollectionFactory->create();\n        $collection->addFieldToFilter('job_code', ['eq'=> 'ebizmarts_ecommerce']);\n        $collection->setOrder('scheduled_at', 'DESC');\n        $collection->getSelect()->limit(10);\n        foreach ($collection as $item) {\n            $job =[];\n            $job['job_code'] = $item['job_code'];\n            $job['status'] = $item['status'];\n            $job['messages'] = $item['messages'];\n            $job['scheduled_at'] = $item['scheduled_at'];\n            $job['executed_at'] = $item['executed_at'];\n            $job['finished_at'] = $item['finished_at'];\n            $jobs[] = $job;\n        }\n        $collection = $this->scheduleCollectionFactory->create();\n        $collection->addFieldToFilter('job_code', ['eq'=> 'ebizmarts_webhooks']);\n        $collection->setOrder('scheduled_at', 'DESC');\n        $collection->getSelect()->limit(10);\n        foreach ($collection as $item) {\n            $job =[];\n            $job['job_code'] = $item['job_code'];\n            $job['status'] = $item['status'];\n            $job['messages'] = $item['messages'];\n            $job['scheduled_at'] = $item['scheduled_at'];\n            $job['executed_at'] = $item['executed_at'];\n            $job['finished_at'] = $item['finished_at'];\n            $jobs[] = $job;\n        }\n        return $jobs;\n    }\n}\n"
  },
  {
    "path": "Cron/SyncStatistics.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Cron;\n\nuse Magento\\Store\\Model\\StoreManager;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailchimpNotification\\CollectionFactory as MailchimpNotificationCollectionFactory;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailchimpNotification;\nuse Ebizmarts\\MailChimp\\Model\\MailchimpNotificationFactory;\nuse Ebizmarts\\MailChimp\\Helper\\Http as MailChimpHttp;\n\nclass SyncStatistics\n{\n    /**\n     * @var MailChimpHelper\n     */\n    private $helper;\n    /**\n     * @var MailchimpNotificationCollectionFactory\n     */\n    private $mailchimpNotificationCollectionFactory;\n    /**\n     * @var MailchimpNotificationFactory\n     */\n    private $mailchimpNotificationFactory;\n    /**\n     * @var MailchimpNotification\n     */\n    private $mailchimpNotification;\n    /**\n     * @var MailChimpHttp\n     */\n    private $mailchimpHttp;\n    private $storeManager;\n    const MAX_NOTIFICATIONS = 200;\n    const MAX_BATCH_SIZE = 25;\n\n    public function __construct(\n        MailChimpHelper $helper,\n        MailchimpNotificationCollectionFactory $mailchimpNotificationCollectionFactory,\n        MailchimpNotificationFactory $mailchimpNotificationFactory,\n        MailchimpNotification $mailchimpNotification,\n        MailchimpHttp $mailchimpHttp,\n        StoreManager $storeManager\n    )\n    {\n        $this->helper = $helper;\n        $this->mailchimpNotificationCollectionFactory = $mailchimpNotificationCollectionFactory;\n        $this->mailchimpNotificationFactory = $mailchimpNotificationFactory;\n        $this->mailchimpNotification = $mailchimpNotification;\n        $this->mailchimpHttp = $mailchimpHttp;\n        $mailchimpHttp->setUrl($helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL));\n        $this->storeManager = $storeManager;\n    }\n    public function execute()\n    {\n        $count = 0;\n        $batch = [];\n        $this->helper->log(\"SyncStatistics\");\n        if ($this->helper->isSupportEnabled())\n        {\n            $scopeId = $this->storeManager->getDefaultStoreView()->getId();\n            $scope = 'default';\n            $token = $this->helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $scopeId, $scope);\n            if (!$token) {\n                $this->helper->log(\"You must first register your copy to sync statistics\");\n                $this->cleanData();\n                return;\n            }\n            $this->mailchimpHttp->setUrl($this->helper->getConfigValue(MailChimpHelper::XML_REGISTER_URL).'/logenabled');\n            $response = $this->mailchimpHttp->get($token);\n            $res = json_decode($response, true);\n            if (key_exists('error',$res) && $res['error']) {\n                $this->helper->log(\"Something went wrong while syncing statistics\");\n                $this->cleanData();\n                return;\n            } elseif (key_exists('enabled',$res) && !$res['enabled']) {\n                $this->helper->log(\"You are not authorized to sync statistics\");\n                $this->cleanData();\n                return;\n            }\n            $this->helper->log(\"Processing sync statistics\");\n            $url = $this->helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL).\"/$token\";\n            $this->mailchimpHttp->setUrl($url);\n            $collection = $this->getCollection();\n            /**\n             * @var $collectionItem \\Ebizmarts\\MailChimp\\Model\\MailChimpNotification\n             */\n            foreach ($collection as $collectionItem)\n            {\n                if (!($count%self::MAX_BATCH_SIZE)&&$count) {\n                    if ($this->syncData($batch)) {\n                        $batch = [];\n                        $batch[$collectionItem->getId()] = $collectionItem->getNotificationData();\n                        $count++;\n                    } else {\n                        $batch = [];\n                        break;\n                    }\n                } else {\n                    $batch[$collectionItem->getId()] = $collectionItem->getNotificationData();\n                    $count++;\n                }\n            }\n            if (count($batch)) {\n                $this->syncData($batch);\n            }\n            $this->helper->log(\"Sync statistics $count registers processed\");\n        } else {\n            $this->helper->log(\"Sync statistics not enabled\");\n        }\n        $this->cleanData();\n    }\n    private function getCollection()\n    {\n        $collection = $this->mailchimpNotificationCollectionFactory->create();\n        $collection->addFieldToFilter('processed', 0);\n        $collection->setOrder('generated_at', 'ASC');\n        $collection->getSelect()->limit(self::MAX_NOTIFICATIONS);;\n\n        return $collection;\n    }\n    private function syncData($data)\n    {\n        $batch = [];\n        $continue = true;\n        foreach ($data as $id => $notification) {\n            $json = [];\n            try {\n                $jsonData = json_decode($notification, true, 50, JSON_THROW_ON_ERROR);\n            } catch (\\Exception $e) {\n                $this->helper->log($e->getMessage());\n                $mailchimpNotification = $this->mailchimpNotificationFactory->create();\n                $mailchimpNotification->getResource()->load($mailchimpNotification, $id);\n                $mailchimpNotification->setProcessed(true);\n                $mailchimpNotification->setSyncedAt($this->helper->getGmtDate());\n                $mailchimpNotification->getResource()->save($mailchimpNotification);\n                continue;\n            }\n            $json['data'] = $jsonData;\n            $json['id'] = $id;\n            $batch[] = $json;\n        }\n        $post = json_encode($batch);\n        try {\n            $response = $this->mailchimpHttp->post($post);\n            $rjson = json_decode($response, true);\n            if (is_array($rjson)) {\n                foreach ($rjson as $r) {\n                    if (is_array($r) && array_key_exists('id', $r)) {\n                        $id = $r['id'];\n                        if (!$r['error']) {\n                            $mailchimpNotification = $this->mailchimpNotificationFactory->create();\n                            $mailchimpNotification->getResource()->load($mailchimpNotification, $id);\n                            $mailchimpNotification->setProcessed(true);\n                            $mailchimpNotification->setSyncedAt($this->helper->getGmtDate());\n                            $mailchimpNotification->getResource()->save($mailchimpNotification);\n                        }\n                    } else {\n                        $this->helper->log(\"Sync notification failed to sync\");\n                        $this->helper->log($r);\n                    }\n                }\n            } else {\n                switch ($this->mailchimpHttp->extractResponse($response)) {\n                    case MailchimpHttp::ERROR_GENERIC:\n                        break;\n                    case MailChimpHttp::ERROR_AUTH:\n                        $continue = false;\n                        break;\n                    case MailChimpHttp::ERROR_JSON:\n                        $this->helper->log(\"Invalid JSON, syncing process will continue regardless\");\n                        break;\n                }\n            }\n        } catch (\\Exception $e) {\n            $this->helper->log('Exception '.$e->getMessage());\n            return false;\n        }\n        return $continue;\n    }\n    private function cleanData()\n    {\n        $days = $this->helper->getConfigValue(MailChimpHelper::XML_CLEAN_SUPPORT_PERIOD);\n        try {\n            $connection = $this->mailchimpNotification->getConnection();\n            $tableName = $this->mailchimpNotification->getMainTable();\n            $quoteInto = $connection->quoteInto('processed = 1 or date_add(generated_at, interval ? day) <= NOW()', $days);\n            $connection->delete($tableName, $quoteInto);\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "Cron/Webhook.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/30/17 8:34 PM\n * @file: Webhook.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Cron;\n\n\nclass Webhook\n{\n    const ACTION_DELETE         = 'delete';\n    const ACTION_UNSUBSCRIBE    = 'unsub';\n\n    const TYPE_SUBSCRIBE        = 'subscribe';\n    const TYPE_UNSUBSCRIBE      = 'unsubscribe';\n    const TYPE_CLEANED          = 'cleaned';\n    const TYPE_UPDATE_EMAIL     = 'upemail';\n    const TYPE_PROFILE          = 'profile';\n    const BATCH_LIMIT           = 50;\n    const NOT_PROCESSED         = 0;\n    const PROCESSED_OK          = 1;\n    const PROCESSED_WITH_ERROR  = 2;\n    const DATA_WITH_ERROR       = 3;\n    const DATA_NOT_CONVERTED    = 4;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $_subscriberFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\CollectionFactory\n     */\n    protected $_webhookCollection;\n    /**\n     * @var \\Magento\\Customer\\Model\\CustomerFactory\n     */\n    protected $_customer;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory\n     */\n    protected $interestGroupFactory;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    protected $storeManager;\n    protected $groups = [];\n\n    /**\n     * Webhook constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\CollectionFactory $webhookCollection\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param \\Magento\\Customer\\Model\\CustomerFactory $customer\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\CollectionFactory $webhookCollection,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        \\Magento\\Customer\\Model\\CustomerFactory $customer\n    ) {\n\n        $this->_helper              = $helper;\n        $this->_subscriberFactory   = $subscriberFactory;\n        $this->_webhookCollection   = $webhookCollection;\n        $this->_customer            = $customer;\n        $this->interestGroupFactory = $interestGroupFactory;\n        $this->storeManager         = $storeManager;\n    }\n    public function execute()\n    {\n        $this->processWebhooks();\n    }\n    public function processWebhooks()\n    {\n        $this->_loadGroups();\n        /**\n         * @var $collection \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\Collection\n         */\n        $collection = $this->_webhookCollection->create();\n        $collection->addFieldToFilter('processed', ['eq'=>self::NOT_PROCESSED]);\n        $collection->getSelect()->limit(self::BATCH_LIMIT);\n        /**\n         * @var $item \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequest\n         */\n        foreach ($collection as $item) {\n            try {\n                $data = $this->_helper->unserialize($item->getDataRequest());\n                $stores = $this->_helper->getMagentoStoreIdsByListId($data['list_id']);\n                if (count($stores)) {\n                    switch ($item->getType()) {\n                        case self::TYPE_SUBSCRIBE:\n                            $this->_subscribe($data);\n                            break;\n                        case self::TYPE_UNSUBSCRIBE:\n                            $this->_unsubscribe($data);\n                            break;\n                        case self::TYPE_CLEANED:\n                            $this->_clean($data);\n                            break;\n                        case self::TYPE_UPDATE_EMAIL:\n                            $this->_updateEmail($data);\n                            break;\n                        case self::TYPE_PROFILE:\n                            $this->_profile($data);\n                    }\n                    $processed = self::PROCESSED_OK;\n                } else {\n                    $processed = self::PROCESSED_WITH_ERROR;\n                }\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n                $processed = self::PROCESSED_WITH_ERROR;\n            }\n            $item->setProcessed($processed);\n            $item->getResource()->save($item);\n        }\n    }\n    protected function _subscribe($data)\n    {\n        $listId = $data['list_id'];\n        $email  = $data['email'];\n        $subscribers = $this->_helper->loadListSubscribers($listId, $email);\n        /**\n         * @var $sub \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        if ($subscribers->count()) {\n            foreach ($subscribers as $sub) {\n                if ($sub->getSubscriberStatus() != \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED) {\n                    $sub->setSubscriberStatus(\\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED);\n                    $sub->getResource()->save($sub);\n                }\n            }\n        } else {\n            $storeIds = $this->_helper->getMagentoStoreIdsByListId($listId);\n            if (count($storeIds) > 0) {\n                foreach ($storeIds as $storeId) {\n                    $sub = $this->_subscriberFactory->create();\n                    $sub->setStoreId($storeId);\n                    $sub->setSubscriberEmail($email);\n                    $this->_subscribeMember($sub, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED);\n                }\n            } else {\n                $sub = $this->_subscriberFactory->create();\n                $sub->setSubscriberEmail($email);\n                $this->_subscribeMember($sub, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED);\n            }\n        }\n    }\n    protected function _unsubscribe($data)\n    {\n        $listId = $data['list_id'];\n        $email  = $data['email'];\n        $subscribers = $this->_helper->loadListSubscribers($listId, $email);\n        /**\n         * @var $sub \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        foreach ($subscribers as $sub) {\n            try {\n                $action = isset($data['action']) ? $data['action'] : self::ACTION_DELETE;\n                switch ($action) {\n                    case self::ACTION_DELETE:\n                        if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_WEBHOOK_DELETE)) {\n                            $sub->getResource()->delete($sub);\n                        } elseif ($sub->getSubscriberStatus()!=\\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED) {\n                            $this->_subscribeMember($sub, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED);\n                        }\n                        break;\n                    case self::ACTION_UNSUBSCRIBE:\n                        if ($sub->getSubscriberStatus()!=\\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED) {\n                            $this->_subscribeMember($sub, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED);\n                        }\n                        break;\n                }\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n            }\n        }\n    }\n    protected function _clean($data)\n    {\n        $subscribers = $this->_helper->loadListSubscribers($data['list_id'], $data['email']);\n        /**\n         * @var $sub \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        foreach ($subscribers as $sub) {\n            $sub->getResource()->delete($sub);\n        }\n    }\n    protected function _updateEmail($data)\n    {\n        $oldEmail = $data['old_email'];\n        $newEmail = $data['new_email'];\n        $listId   = $data['list_id'];\n        $oldSubscribers = $this->_helper->loadListSubscribers($listId, $oldEmail);\n        $newSubscribers = $this->_helper->loadListSubscribers($listId, $newEmail);\n        /**\n         * @var $sub \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        if (!$newSubscribers->count()) {\n            if ($oldSubscribers->count()) {\n                foreach ($oldSubscribers as $sub) {\n                    $sub->setSubscriberEmail($newEmail);\n                    $sub->getResource()->save($sub);\n                }\n            } else {\n                $sub = $this->_subscriberFactory->create();\n                $sub->setSubscriberEmail($newEmail);\n                $this->_subscribeMember($sub, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED);\n            }\n        }\n    }\n    protected function _profile($data)\n    {\n        $listId = $data['list_id'];\n        $email = $data['email'];\n        $customers = $this->_helper->loadListCustomers($listId, $email);\n        if ($customers->count() > 0) {\n            /**\n             * @var $customer  \\Magento\\Customer\\Model\\Customer\n             */\n            foreach ($customers as $c) {\n                $customer = $this->_customer->create();\n                $customer->getResource()->load($customer, $c->getEntityId());\n                $this->_processMerges($customer,$data);\n                $customer->getResource()->save($customer);\n            }\n        } else {\n            $subscribers = $this->_helper->loadListSubscribers($listId, $email);\n            if ($subscribers->count() == 0) {\n                $subscriber = $this->_subscriberFactory->create();\n                $subscriber->setSubscriberEmail($email);\n\n                $stores = $this->_helper->getMagentoStoreIdsByListId($listId);\n                if (count($stores)) {\n                    $subscriber->setStoreId($stores[0]);\n                    try {\n                        $api = $this->_helper->getApi($stores[0]);\n                        $member = $api->lists->members->get($listId, hash('md5', strtolower($email)));\n                        if ($member) {\n                            if ($member['status'] == \\Mailchimp::SUBSCRIBED) {\n                                $this->_subscribeMember($subscriber, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED);\n                            } elseif ($member['status'] == \\Mailchimp::UNSUBSCRIBED) {\n                                $this->_subscribeMember($subscriber, \\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED);\n                            }\n                        }\n                    } catch (\\Mailchimp_Error $e) {\n                        $this->_helper->log($e->getFriendlyMessage());\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * @param \\Magento\\Customer\\Model\\Customer $customer\n     * @param $data\n     */\n    protected function _processMerges(\\Magento\\Customer\\Model\\Customer $customer, $data)\n    {\n        $mapFields = $this->_helper->getMapFields($customer->getStoreId());\n        foreach($data['merges'] as $key=> $value) {\n            if (!empty($value)) {\n                if ($key=='GROUPINGS') {\n                    $groups = ['group' => []];\n                    foreach($value as $item) {\n                        if (!empty($item['groups'])) {\n                            $groups['group'][$item['unique_id']] = $this->_getGroups($item['groups'],$item['unique_id']);\n                        }\n                    }\n                    $serializedGroups = $this->_helper->serialize($groups);\n                    $subscriber = $this->_subscriberFactory->create();\n                    $subscriber->loadByCustomerId($customer->getId());\n                    $interestGroup = $this->interestGroupFactory->create();\n                    if ($subscriber->getEmail()==$customer->getEmail()) {\n                        $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                        $interestGroup->setGroupdata($serializedGroups);\n                        $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                        $interestGroup->setStoreId($subscriber->getStoreId());\n                        $interestGroup->setUpdatedAt($this->_helper->getGmtDate());\n                        $interestGroup->getResource()->save($interestGroup);\n                        $listId = $this->_helper->getGeneralList($subscriber->getStoreId());\n                    } else {\n                        $this->_subscriberFactory->create()->subscribe($customer->getEmail());\n                        $subscriber->loadByEmail($customer->getEmail());\n                        $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                        $interestGroup->setGroupdata($serializedGroups);\n                        $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                        $interestGroup->setStoreId($subscriber->getStoreId());\n                        $interestGroup->setUpdatedAt($this->_helper->getGmtDate());\n                        $interestGroup->getResource()->save($interestGroup);\n                    }\n                } else {\n                    if (is_array($mapFields)) {\n                        foreach ($mapFields as $map) {\n                            if ($map['mailchimp'] == $key) {\n                                if (!$map['isAddress'] && $map['customer_field'] != \"dob\" && strpos($map['customer_field'], '##') !== false) {\n                                    if (count($map['options'])) {\n                                        foreach ($map['options'] as $option) {\n                                            if ($option['label'] == $value) {\n                                                $customer->setData($map['customer_field'], $option['value']);\n                                            }\n                                        }\n                                    } else {\n                                        $customer->setData($map['customer_field'], $value);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @param string $status\n     * @throws \\Exception\n     */\n    protected function _subscribeMember(\\Magento\\Newsletter\\Model\\Subscriber $subscriber, int $status)\n    {\n        $subscriber->setImportMode(true);\n        $subscriber->setStatus($status);\n        $subscriber->setSubscriberConfirmCode($subscriber->randomSequence());\n        $subscriber->setIsStatusChanged(true);\n        $subscriber->getResource()->save($subscriber);\n    }\n    protected function _loadGroups()\n    {\n        foreach ($this->storeManager->getStores() as $storeId => $val) {\n            if (!$this->_helper->isMailChimpEnabled($storeId)) {\n                continue;\n            }\n            $listId =$this->_helper->getDefaultList($storeId);\n            if (!$listId||$listId==-1) {\n                $this->_helper->log(\"ListId [$listId] is invalid for Store [$storeId]\");\n                continue;\n            } else {\n                $api = $this->_helper->getApi($storeId);\n                try {\n                    $interestsCat = $api->lists->interestCategory->getAll($listId, null, null, 200);\n                    if (isset($interestsCat['categories'])) {\n                        foreach ($interestsCat['categories'] as $cat) {\n                            $interests = $api->lists->interestCategory->interests->getAll($listId, $cat['id'], null, null, 200);\n                            $this->groups = array_merge_recursive($this->groups, $interests['interests']);\n                        }\n                    }\n                } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                    $error = $e->getMessage();\n                    $this->_helper->log(\"Error: [$error] for store [$storeId]\");\n                }\n            }\n        }\n    }\n    protected function _getGroups($groups, $cat)\n    {\n        $rc = [];\n        $gr = explode(\",\",$groups);\n        foreach ($gr as $g) {\n            foreach ($this->groups as $group) {\n                if (trim($g)==$group['name']&&$group['category_id']==$cat) {\n                    $rc[$group['id']] = $group['id'];\n                    break;\n                }\n            }\n        }\n        return $rc;\n    }\n}\n"
  },
  {
    "path": "Cron/WebhookClean.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 22/11/18 10:02 AM\n * @file: WebhookClean.php\n */\nnamespace Ebizmarts\\MailChimp\\Cron;\n\nclass WebhookClean\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequest\n     */\n    protected $webhooks;\n\n    /**\n     * WebhookClean constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequest $webhookRequest\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequest $webhookRequest\n    ) {\n        $this->helper   = $helper;\n        $this->webhooks = $webhookRequest;\n    }\n    public function execute()\n    {\n        try {\n            $connection = $this->webhooks->getResource()->getConnection();\n            $tableName = $this->webhooks->getResource()->getMainTable();\n            $quoteInto = $connection->quoteInto('processed = ? and date_add(fired_at, interval 1 month) < now()', 1);\n            $connection->delete($tableName, $quoteInto);\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "Helper/Data.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Helper;\n\nuse Magento\\Framework\\App\\ResourceConnection;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Magento\\Store\\Model\\Store;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Model\\MailchimpNotificationFactory as MailchimpNotificationFactory;\n\nclass Data extends \\Magento\\Framework\\App\\Helper\\AbstractHelper\n{\n    const XML_PATH_ACTIVE            = 'mailchimp/general/active';\n    const XML_PATH_APIKEY            = 'mailchimp/general/apikey';\n    const XML_PATH_APIKEY_LIST       = 'mailchimp/general/apikeylist';\n    const XML_PATH_MAXLISTAMOUNT     = 'mailchimp/general/maxlistamount';\n    const XML_PATH_LIST              = 'mailchimp/general/monkeylist';\n    const XML_PATH_WEBHOOK_ACTIVE    = 'mailchimp/general/webhook_active';\n    const XML_PATH_WEBHOOK_DELETE    = 'mailchimp/general/webhook_delete';\n    const XML_PATH_LOG               = 'mailchimp/general/log';\n    const XML_PATH_TIMEOUT           = 'mailchimp/general/timeout';\n\n    const XML_PATH_MAPPING           = 'mailchimp/general/mapping';\n    const XML_MAILCHIMP_STORE        = 'mailchimp/general/monkeystore';\n    const XML_MAILCHIMP_JS_URL       = 'mailchimp/general/mailchimpjsurl';\n    const XML_PATH_CONFIRMATION_FLAG = 'newsletter/subscription/confirm';\n    const XML_PATH_STORE             = 'mailchimp/ecommerce/store';\n    const XML_PATH_ECOMMERCE_ACTIVE  = 'mailchimp/ecommerce/active';\n    const XML_PATH_ALL_CUSTOMERS     = 'mailchimp/ecommerce/all_customers';\n    const XML_PATH_SYNC_DATE         = 'mailchimp/general/mcminsyncdateflag';\n    const XML_ECOMMERCE_OPTIN        = 'mailchimp/ecommerce/customer_optin';\n    const XML_ECOMMERCE_FIRSTDATE    = 'mailchimp/ecommerce/firstdate';\n    const XML_ABANDONEDCART_ACTIVE   = 'mailchimp/abandonedcart/active';\n    const XML_ABANDONEDCART_FIRSTDATE   = 'mailchimp/abandonedcart/firstdate';\n    const XML_ABANDONEDCART_PAGE     = 'mailchimp/abandonedcart/page';\n    const XML_PATH_IS_SYNC           = 'mailchimp/general/issync';\n    const XML_ABANDONEDCART_EMAIL    = 'mailchimp/abandonedcart/save_email_in_quote';\n    const XML_MERGEVARS              = 'mailchimp/general/map_fields';\n    const XML_INTEREST               = 'mailchimp/general/interest';\n    const XML_INTEREST_IN_SUCCESS    = 'mailchimp/general/interest_in_success';\n    const XML_INTEREST_SUCCESS_HTML_BEFORE  = 'mailchimp/general/interest_success_html_before';\n    const XML_INTEREST_SUCCESS_HTML_AFTER   = 'mailchimp/general/interest_success_html_after';\n    const XML_MAGENTO_MAIL           = 'mailchimp/general/magentoemail';\n    const XML_SEND_PROMO             = 'mailchimp/ecommerce/send_promo';\n    const XML_SYNC_SALABLE             = 'mailchimp/ecommerce/syncsalable';\n    const XML_INCLUDING_TAXES        = 'mailchimp/ecommerce/including_taxes';\n    const XML_CAMPAIGN_ACTION        = 'mailchimp/ecommerce/campaign_action';\n    const XML_POPUP_FORM             = 'mailchimp/general/popup_form';\n    const XML_POPUP_URL              = 'mailchimp/general/popup_url';\n    const XML_CLEAN_ERROR_MONTHS     = 'mailchimp/ecommerce/clean_errors_months';\n    const XML_ENABLE_SUPPORT         = 'mailchimp/general/enable_support';\n    const SYNC_TOKEN                 = 'mailchimp/statistics/token';\n    const SYNC_NOTIFICATION_URL       = 'mailchimp/statistics/notification_url';\n    const XML_CLEAN_SUPPORT_PERIOD    = 'mailchimp/general/clean_support_period';\n    const XML_REGISTER_URL            = 'mailchimp/statistics/register_url';\n    const XML_STATISTICS_TOKEN        = 'mailchimp/register/token';\n    const ORDER_STATE_OK             = 'complete';\n\n    const GUEST_GROUP                = 'NOT LOGGED IN';\n    const IS_CUSTOMER   = \"CUS\";\n    const IS_PRODUCT    = \"PRO\";\n    const IS_ORDER      = \"ORD\";\n    const IS_QUOTE      = \"QUO\";\n    const IS_SUBSCRIBER = \"SUB\";\n    const IS_PROMO_RULE = \"PRL\";\n    const IS_PROMO_CODE = \"PCD\";\n\n    const PLATFORM      = 'Magento2';\n    const MAXSTORES     = 200;\n\n    const SUB_MOD       = \"SubscriberModified\";\n    const SUB_NEW       = \"SubscriberNew\";\n    const PRO_MOD       = \"ProductModified\";\n    const PRO_NEW       = \"ProductNew\";\n    const PRO_DELETED = \"ProductDeleted\";\n    const CUS_MOD       = \"CustomerModified\";\n    const CUS_NEW       = \"CustomerNew\";\n    const ORD_MOD       = \"OrderModified\";\n    const ORD_NEW       = \"OrderNew\";\n    const QUO_MOD       = \"QuoteModified\";\n    const QUO_NEW       = \"QuoteNew\";\n\n    const SYNCED        = 1;\n    const NEEDTORESYNC  = 2;\n    const WAITINGSYNC   = 3;\n    const SYNCERROR     = 4;\n    const NOTSYNCED = 5;\n\n    const NEVERSYNC     = 0;\n\n    const BATCH_CANCELED = 'canceled';\n    const BATCH_COMPLETED = 'completed';\n    const BATCH_PENDING = 'pending';\n    const BATCH_ERROR = 'error';\n\n    const MAX_MERGEFIELDS = 100;\n\n    protected $counters = [];\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    private $_storeManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Logger\\Logger\n     */\n    private $_mlogger;\n    /**\n     * @var \\Magento\\Customer\\Model\\GroupRegistry\n     */\n    private $_groupRegistry;\n    /**\n     * @var \\Magento\\Framework\\App\\Config\\ScopeConfigInterface\n     */\n    private $_scopeConfig;\n    /**\n     * @var \\Magento\\Framework\\App\\RequestInterface\n     */\n    protected $_request;\n    /**\n     * @var \\Magento\\Framework\\App\\State\n     */\n    private $_state;\n    /**\n     * @var \\Magento\\Framework\\Module\\ModuleList\\Loader\n     */\n    private $_loader;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\n     */\n    private $_config;\n    /**\n     * @var \\Mailchimp\n     */\n    private $_api;\n\n    /**\n     * @var \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CustomerRepository\n     */\n    private $_customer;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches\n     */\n    private $_syncBatches;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpStoresFactory\n     */\n    private $_mailChimpStoresFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpStores\n     */\n    private $_mailChimpStores;\n    /**\n     * @var \\Magento\\Framework\\Encryption\\Encryptor\n     */\n    private $_encryptor;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\CollectionFactory\n     */\n    private $_subscriberCollection;\n    /**\n     * @var \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory\n     */\n    private $_customerCollection;\n    private $_addressRepositoryInterface;\n    /**\n     * @var \\Magento\\Framework\\DB\\Adapter\\AdapterInterface\n     */\n    private $connection;\n    /**\n     * @var \\Magento\\Framework\\App\\ResourceConnection\n     */\n    private $_resource;\n    /**\n     * @var \\Magento\\Framework\\App\\Cache\\TypeListInterface\n     */\n    private $_cacheTypeList;\n    /**\n     * @var \\Magento\\Customer\\Model\\ResourceModel\\Attribute\\CollectionFactory\n     */\n    private $_attCollection;\n    /**\n     * @var \\Magento\\Customer\\Model\\CustomerFactory\n     */\n    protected $_customerFactory;\n    /**\n     * @var \\Magento\\Directory\\Api\\CountryInformationAcquirerInterface\n     */\n    protected $_countryInformation;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory\n     */\n    protected $_interestGroupFactory;\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\DateTime\\DateTime\n     */\n    protected $_date;\n    /**\n     * @var \\Magento\\Framework\\App\\DeploymentConfig\n     */\n    protected $_deploymentConfig;\n    /**\n     * @var \\Magento\\Framework\\Serialize\\Serializer\\Json\n     */\n    protected $_serializer;\n    /**\n     * @var \\Magento\\Directory\\Model\\CountryFactory\n     */\n    protected $countryFactory;\n    /**\n     * @var \\Magento\\Framework\\Locale\\Resolver\n     */\n    protected $resolver;\n    /**\n     * @var MailchimpNotificationFactory\n     */\n    protected $mailchimpNotificationFactory;\n\n    private $customerAtt    = null;\n    private $addressAtt     = null;\n    private $_mapFields     = null;\n\n    /**\n     * @param \\Magento\\Framework\\App\\Helper\\Context $context\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n     * @param \\Ebizmarts\\MailChimp\\Model\\Logger\\Logger $logger\n     * @param \\Magento\\Customer\\Model\\GroupRegistry $groupRegistry\n     * @param \\Magento\\Framework\\App\\State $state\n     * @param \\Magento\\Framework\\Module\\ModuleList\\Loader $loader\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $config\n     * @param \\Mailchimp $api\n     * @param \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\CustomerRepository $customer\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches $syncBatches\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpStoresFactory $mailChimpStoresFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpStores $mailChimpStores\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\Attribute\\CollectionFactory $attCollection\n     * @param \\Magento\\Framework\\Encryption\\Encryptor $encryptor\n     * @param \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\CollectionFactory $subscriberCollection\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory $customerCollection\n     * @param \\Magento\\Customer\\Api\\AddressRepositoryInterface $addressRepositoryInterface\n     * @param \\Magento\\Customer\\Model\\CustomerFactory $customerFactory\n     * @param \\Magento\\Directory\\Api\\CountryInformationAcquirerInterface $countryInformation\n     * @param ResourceConnection $resource\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n     * @param \\Magento\\Framework\\Serialize\\Serializer\\Json $serializer\n     * @param \\Magento\\Framework\\App\\DeploymentConfig $deploymentConfig\n     * @param \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date\n     * @param \\Magento\\Directory\\Model\\CountryFactory $countryFactory\n     * @param \\Magento\\Framework\\Locale\\Resolver $resolver\n     * @param MailchimpNotificationFactory $mailchimpNotificationFactory\n     */\n    public function __construct(\n        \\Magento\\Framework\\App\\Helper\\Context $context,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManager,\n        \\Ebizmarts\\MailChimp\\Model\\Logger\\Logger $logger,\n        \\Magento\\Customer\\Model\\GroupRegistry $groupRegistry,\n        \\Magento\\Framework\\App\\State $state,\n        \\Magento\\Framework\\Module\\ModuleList\\Loader $loader,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $config,\n        \\Mailchimp $api,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList,\n        \\Magento\\Customer\\Model\\ResourceModel\\CustomerRepository $customer,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches $syncBatches,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpStoresFactory $mailChimpStoresFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpStores $mailChimpStores,\n        \\Magento\\Customer\\Model\\ResourceModel\\Attribute\\CollectionFactory $attCollection,\n        \\Magento\\Framework\\Encryption\\Encryptor $encryptor,\n        \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\CollectionFactory $subscriberCollection,\n        \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory $customerCollection,\n        \\Magento\\Customer\\Api\\AddressRepositoryInterface $addressRepositoryInterface,\n        \\Magento\\Customer\\Model\\CustomerFactory $customerFactory,\n        \\Magento\\Directory\\Api\\CountryInformationAcquirerInterface $countryInformation,\n        \\Magento\\Framework\\App\\ResourceConnection $resource,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory,\n        \\Magento\\Framework\\Serialize\\Serializer\\Json $serializer,\n        \\Magento\\Framework\\App\\DeploymentConfig $deploymentConfig,\n        \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date,\n        \\Magento\\Directory\\Model\\CountryFactory $countryFactory,\n        \\Magento\\Framework\\Locale\\Resolver $resolver,\n        MailchimpNotificationFactory $mailchimpNotificationFactory\n    ) {\n\n        $this->_storeManager  = $storeManager;\n        $this->_mlogger       = $logger;\n        $this->_groupRegistry = $groupRegistry;\n        $this->_scopeConfig   = $context->getScopeConfig();\n        $this->_request       = $context->getRequest();\n        $this->_state         = $state;\n        $this->_loader        = $loader;\n        $this->_config        = $config;\n        $this->_api           = $api;\n        $this->_customer      = $customer;\n        $this->_syncBatches             = $syncBatches;\n        $this->_mailChimpStores         = $mailChimpStores;\n        $this->_mailChimpStoresFactory  = $mailChimpStoresFactory;\n        $this->_encryptor               = $encryptor;\n        $this->_subscriberCollection    = $subscriberCollection;\n        $this->_customerCollection      = $customerCollection;\n        $this->_addressRepositoryInterface = $addressRepositoryInterface;\n        $this->_resource                = $resource;\n        $this->connection               = $resource->getConnection();\n        $this->_cacheTypeList           = $cacheTypeList;\n        $this->_attCollection           = $attCollection;\n        $this->_customerFactory         = $customerFactory;\n        $this->_countryInformation      = $countryInformation;\n        $this->_interestGroupFactory    = $interestGroupFactory;\n        $this->_serializer              = $serializer;\n        $this->_deploymentConfig        = $deploymentConfig;\n        $this->_date                    = $date;\n        $this->countryFactory           = $countryFactory;\n        $this->mailchimpNotificationFactory = $mailchimpNotificationFactory;\n        $this->resolver                 = $resolver;\n        parent::__construct($context);\n    }\n\n    /**\n     * @param null $store\n     * @return mixed\n     */\n    public function isMailChimpEnabled($store = null)\n    {\n        return $this->getConfigValue(self::XML_PATH_ACTIVE, $store);\n    }\n    public function isSupportEnabled()\n    {\n        return $this->getConfigValue(self::XML_ENABLE_SUPPORT);\n    }\n    /**\n     * @param null $store\n     * @return mixed\n     */\n    public function isDoubleOptInEnabled($store = null)\n    {\n        return $this->getConfigValue(self::XML_PATH_CONFIRMATION_FLAG, $store);\n    }\n\n    /**\n     * @param null $store\n     * @return mixed\n     */\n    public function getApiKey($store = null, $scope = null)\n    {\n        $apiKey =$this->getConfigValue(self::XML_PATH_APIKEY, $store, $scope);\n        return $this->_encryptor->decrypt($apiKey);\n    }\n    public function getTimeOut($store=null, $scope=null)\n    {\n        return $this->getConfigValue(self::XML_PATH_TIMEOUT, $store, $scope);\n    }\n\n    /**\n     * @param null $store\n     * @return \\Mailchimp\n     */\n    public function getApi($store = null, $scope = null)\n    {\n        $apiKey = $this->getApiKey($store, $scope);\n        $timeOut = $this->getTimeOut($store,$scope);\n        $this->_api->setApiKey($apiKey);\n        $this->_api->setHelper($this);\n        $this->_api->setStoreURL($this->_storeManager->getStore($store)->getBaseUrl());\n        $this->_api->setUserAgent('Mailchimp4Magento' . (string)$this->getModuleVersion());\n        if ($timeOut) {\n            $this->_api->setTimeOut($timeOut);\n        }\n        return $this->_api;\n    }\n    private function getBindableAttributes()\n    {\n        $systemAtt = $this->getCustomerAtts();\n        $extraAtt = $this->getAddressAtt();\n\n        // Note: We cannot use array_merge here because we need to hold\n        // numeric indexes as they are\n        $ret = $systemAtt + $extraAtt;\n\n        return $ret;\n    }\n    private function getCustomerAtts()\n    {\n        $ret = [];\n        if (!$this->customerAtt) {\n            $collection = $this->_attCollection->create();\n            /**\n             * @var $item \\Magento\\Customer\\Model\\Attribute\n             */\n            foreach ($collection as $item) {\n                try {\n                    if ($item->usesSource()) {\n                        $options = $item->getSource()->getAllOptions();\n                    } else {\n                        $options = [];\n                    }\n                } catch (\\Exception $e) {\n                    $options = [];\n                }\n                $isDate = ($item->getBackendModel()==\\Magento\\Eav\\Model\\Entity\\Attribute\\Backend\\Datetime::class) ? 1:0;\n                $isAddress = (\n                    $item->getBackendModel()==\\Magento\\Customer\\Model\\Customer\\Attribute\\Backend\\Billing::class ||\n                    $item->getBackendModel()==\\Magento\\Customer\\Model\\Customer\\Attribute\\Backend\\Shipping::class) ? 1:0;\n                $ret[$item->getId()] = [\n                    'attCode' => $item->getAttributeCode(),\n                    'isDate' =>$isDate,\n                    'isAddress' => $isAddress,\n                    'options'=>$options\n                ] ;\n            }\n\n            $this->customerAtt = $ret;\n        }\n        return $this->customerAtt;\n    }\n    private function getAddressAtt()\n    {\n        $ret = [];\n        if (!$this->addressAtt) {\n            $elements = [\n                'default_shipping##zip',\n                'default_shipping##country',\n                'default_shipping##city',\n                'default_shipping##state',\n                'default_shipping##telephone',\n                'default_shipping##company',\n                'default_shipping##street',\n                'default_billing##zip',\n                'default_billing##country',\n                'default_billing##city',\n                'default_billing##state',\n                'default_billing##telephone',\n                'default_billing##company',\n                'default_billing##street'\n            ];\n\n            foreach($elements as $item) {\n                $ret[$item] = [\n                    'attCode'   => $item,\n                    'isDate'    => false,\n                    'isAddress' => false,\n                    'options'   => []\n                ];\n            }\n\n            $this->addressAtt = $ret;\n        }\n\n        return $this->addressAtt;\n    }\n    public function resetMapFields()\n    {\n        $this->_mapFields = null;\n    }\n    public function getMapFields($storeId = null, $options=true)\n    {\n        if (!$this->_mapFields) {\n            $customerAtt = $this->getBindableAttributes();\n            $data = $this->getConfigValue(self::XML_MERGEVARS, $storeId);\n            try {\n                $data = $this->unserialize($data);\n                if (is_array($data)) {\n                    foreach ($data as $customerFieldId => $mailchimpName) {\n                        $this->_mapFields[] = [\n                            'mailchimp' => strtoupper($mailchimpName),\n                            'customer_field' => $customerAtt[$customerFieldId]['attCode'],\n                            'isDate' => $customerAtt[$customerFieldId]['isDate'],\n                            'isAddress' => $customerAtt[$customerFieldId]['isAddress'],\n                            'options' => $options ? $customerAtt[$customerFieldId]['options'] : false\n                        ];\n                    }\n                }\n            } catch (\\Exception $e) {\n                $this->log($e->getMessage());\n            }\n        }\n        return $this->_mapFields;\n    }\n    public function getDateFormat()\n    {\n        return 'm/d/Y';\n    }\n\n    /**\n     * @param $apiKey\n     * @param bool $encrypted\n     * @return \\Mailchimp\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function getApiByApiKey($apiKey, $encrypted = false)\n    {\n        if ($encrypted) {\n            $this->_api->setApiKey($this->_encryptor->decrypt($apiKey));\n        } else {\n            $this->_api->setApiKey($apiKey);\n        }\n        $this->_api->setUserAgent('Mailchimp4Magento' . (string)$this->getModuleVersion());\n        $this->_api->setHelper($this);\n        $this->_api->setStoreURL($this->_storeManager->getStore()->getBaseUrl());\n        return $this->_api;\n    }\n\n    /**\n     * @param $path\n     * @param null $storeId\n     * @return mixed\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function getConfigValue($path, $storeId = null, $scope = null)\n    {\n        if ($scope) {\n            $value = $this->_scopeConfig->getValue($path, $scope, $storeId);\n        } else {\n            $value = $this->_scopeConfig->getValue($path, \\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORES, $storeId);\n        }\n        return $value;\n    }\n    public function deleteConfig($path, $storeId = null, $scope = null)\n    {\n        $this->_config->deleteConfig($path, $scope, $storeId);\n    }\n\n    public function saveConfigValue($path, $value, $storeId = null, $scope = null)\n    {\n        if ($scope) {\n            $this->_config->saveConfig($path, $value, $scope, $storeId);\n        } else {\n            $this->_config->saveConfig($path, $value, \\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORES, $storeId);\n        }\n        $this->_cacheTypeList->cleanType('config');\n    }\n    public function saveMCMinSyncing($mailchimpStoreId, $value, $storeId = null, $scope = null)\n    {\n        if ($mailchimpStoreId) {\n            $this->saveConfigValue(self::XML_PATH_IS_SYNC . \"/$mailchimpStoreId\", $value, $storeId, $scope);\n        } else {\n            $this->saveConfigValue(self::XML_PATH_IS_SYNC, $value, $storeId, $scope);\n        }\n    }\n    public function getCartUrl($storeId, $cartId, $token)\n    {\n        $rc = $this->_storeManager->getStore($storeId)->getUrl(\n            'mailchimp/cart/loadquote',\n            [\n                'id' => $cartId,\n                'token' => $token,\n                '_nosid' => true,\n                '_secure' => true\n            ]\n        );\n        return $rc;\n    }\n    public function getRedemptionUrl($storeId, $couponId, $token)\n    {\n        $rc = $this->_storeManager->getStore($storeId)->getUrl(\n            'mailchimp/cart/loadcoupon',\n            [\n                'id' => $couponId,\n                'token' => $token,\n                '_nosid' => true,\n                '_secure' => true\n            ]\n        );\n        return $rc;\n    }\n    public function getSuccessInterestUrl($storeId)\n    {\n        $rc = $this->_storeManager->getStore($storeId)->getUrl(\n            'mailchimp/checkout/success',\n            [\n                '_nosid' => true,\n                '_secure' => true\n            ]\n        );\n        return $rc;\n    }\n    /**\n     * @param null $store\n     * @return mixed\n     */\n    public function getDefaultList($store = null)\n    {\n        return $this->getConfigValue(self::XML_PATH_LIST, $store);\n    }\n\n    /**\n     * @return \\Psr\\Log\\LoggerInterface\n     */\n    public function getLogger()\n    {\n        return $this->_logger;\n    }\n\n    /**\n     * @param $message\n     * @param null $store\n     */\n    public function log($message, $store = null, $file = null)\n    {\n        if ($this->getConfigValue(self::XML_PATH_LOG, $store)) {\n            $this->_mlogger->mailchimpLog($message, $file);\n        }\n    }\n    public function saveNotification($data)\n    {\n        $mailchimpNotification = $this->mailchimpNotificationFactory->create();\n        $mailchimpNotification->setNotificationData(json_encode($data));\n        $mailchimpNotification->setProcessed(false);\n        $mailchimpNotification->getResource()->save($mailchimpNotification);\n\n    }\n    /**\n     * @return string\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function getModuleVersion()\n    {\n        $modules = $this->_loader->load();\n        $v = \"\";\n        if (isset($modules['Ebizmarts_MailChimp'])) {\n            $v = $modules['Ebizmarts_MailChimp']['setup_version'];\n        }\n        return $v;\n    }\n    public function deleteStore($mailchimpStore)\n    {\n        try {\n//            $storeId = $this->getConfigValue(self::XML_MAILCHIMP_STORE);\n            $this->getApi()->ecommerce->stores->delete($mailchimpStore);\n            $this->cancelAllPendingBatches($mailchimpStore);\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->log($e->getFriendlyMessage());\n        } catch (Exception $e) {\n            $this->log($e->getMessage());\n        }\n    }\n    public function markAllBatchesAs($mailchimpStore, $fromStatus, $toStatus)\n    {\n        $connection = $this->_syncBatches->getResource()->getConnection();\n        $tableName = $this->_syncBatches->getResource()->getMainTable();\n        $connection->update(\n            $tableName,\n            ['status' => $toStatus],\n            \"mailchimp_store_id = '\" . $mailchimpStore . \"' and status = '\" . $fromStatus . \"'\"\n        );\n    }\n\n    public function cancelAllPendingBatches($mailchimpStore)\n    {\n        $this->markAllBatchesAs($mailchimpStore, self::BATCH_PENDING, self::BATCH_CANCELED);\n    }\n\n    public function restoreAllCanceledBatches($mailchimpStore)\n    {\n        $this->markAllBatchesAs($mailchimpStore, self::BATCH_CANCELED, self::BATCH_PENDING);\n    }\n\n    public function getMCStoreName($storeId)\n    {\n        return $this->_storeManager->getStore($storeId)->getFrontendName();\n    }\n    public function getBaserUrl($storeId, $type)\n    {\n        return $this->_storeManager->getStore($storeId)->getBaseUrl($type, true);\n    }\n    public function createStore($listId = null, $storeId)\n    {\n        if ($listId) {\n            //generate store id\n            $date = date('Y-m-d-His');\n            $baseUrl = $this->_storeManager->getStore($storeId)->getName();\n            $mailchimpStoreId = hash('md5', parse_url($baseUrl, PHP_URL_HOST) . '_' . $date);\n            $currencyCode = $this->_storeManager->getStore($storeId)->getDefaultCurrencyCode();\n            $name = $this->getMCStoreName($storeId);\n\n            //create store in mailchimp\n            try {\n                $this->getApi()->ecommerce->stores->add(\n                    $mailchimpStoreId,\n                    $listId,\n                    $name,\n                    $currencyCode,\n                    self::PLATFORM\n                );\n                return $mailchimpStoreId;\n            } catch (\\Mailchimp_Error $e) {\n                $this->log($e->getFriendlyMessage());\n            } catch (Exception $e) {\n                return null;\n            }\n        }\n        return null;\n    }\n    public function getMCMinSyncDateFlag($storeId = null)\n    {\n        $syncDate = $this->getConfigValue(self::XML_PATH_IS_SYNC, $storeId);\n        if ($syncDate=='') {\n            $syncDate = '1900-01-01';\n        }\n        return $syncDate;\n    }\n    public function getMCMinSyncDateFlagByMailchimpStore($mailchimpStoreId = null, $storeId = null, $scope = null)\n    {\n        $syncDate = $this->getConfigValue(self::XML_PATH_IS_SYNC. \"/$mailchimpStoreId\", $storeId, $scope);\n        return $syncDate;\n    }\n    public function getBaseDir()\n    {\n        return BP;\n    }\n\n    /**\n     * @param \\Magento\\Customer\\Model\\Customer $customer\n     * @param $storeId\n     * @param null $email\n     * @return array|null\n     */\n    public function getMergeVars(\\Magento\\Customer\\Model\\Customer $customer, $storeId)\n    {\n        $mergeVars = [];\n        $mapFields = $this->getMapFields($storeId);\n        if (is_array($mapFields)) {\n            foreach ($mapFields as $map) {\n                $value = null;\n                if (strpos($map['customer_field'], '##') !== false) {\n                    $parts = explode('##', $map['customer_field']);\n                    $attributeCode = $parts[0];\n                    $fieldName = $parts[1];\n                    $customerAddress = $customer->getPrimaryAddress($attributeCode);\n                    if ($customerAddress !== false) {\n                        if ($fieldName!='company') {\n                            $addressData = $this->_getAddressValues($customerAddress);\n                            if (!empty($addressData[$fieldName])) {\n                                $value = $addressData[$fieldName];\n                            }\n                        } else {\n                            $value = $customerAddress->getCompany();\n                        }\n                    }\n                }\n                else {\n                    $value = $customer->getData($map['customer_field']);\n                    if (!is_null($value)) {\n                        if ($map['isDate']) {\n                            $format = $this->getDateFormat();\n                            if ($map['customer_field'] == 'dob') {\n                                $format = substr($format, 0, 3);\n                            }\n                            $value = date($format, strtotime($value));\n                        } elseif ($map['isAddress']) {\n                            $customerAddress = $customer->getPrimaryAddress($map['customer_field']);\n                            $value = [];\n                            if ($customerAddress !== false) {\n                                $value = $this->_getAddressValues($customerAddress);\n                            }\n                        } elseif (count($map['options'])) {\n                            foreach ($map['options'] as $option) {\n                                if ($option['value'] == $value) {\n                                    $value = __($option['label']);\n                                    break;\n                                }\n                            }\n                        }\n                    }\n                }\n\n                if (!empty($value)) {\n                    $mergeVars[$map['mailchimp']] = $value;\n                } else {\n                    $mergeVars[$map['mailchimp']] = '';\n                }\n            }\n        }\n        return (!empty($mergeVars)) ? $mergeVars : null;\n    }\n\n\n    /**\n     * @param \\Magento\\Customer\\Model\\Address\\AbstractAddress $value\n     * @return array\n     */\n    private function _getAddressValues(\\Magento\\Customer\\Model\\Address\\AbstractAddress $address)\n    {\n        $addressData = [];\n        if ($address) {\n            $street = $address->getStreet();\n            if (count($street) > 1) {\n                $addressData[\"street\"] = $street[0].' '.$street[1];\n            } else {\n                if (!empty($street[0])) {\n                    $addressData[\"street\"] = $street[0];\n                }\n            }\n            if ($address->getCity()) {\n                $addressData[\"city\"] = $address->getCity();\n            }\n            if ($address->getRegion()) {\n                $addressData[\"state\"] = $address->getRegion();\n            } else {\n                $addressData[\"state\"] = \"\";\n            }\n\n            if ($address->getPostcode()) {\n                $addressData[\"zip\"] = $address->getPostcode();\n            }\n            if ($address->getCountry()) {\n                $country = $this->countryFactory->create()->loadByCode($address->getCountryId());\n                $addressData[\"country\"] = $country->getName('en_US');\n            }\n            if ($address->getTelephone()) {\n                $addressData['telephone'] = $address->getTelephone();\n            }\n        }\n        return $addressData;\n    }\n\n    public function getMergeVarsBySubscriber(\\Magento\\Newsletter\\Model\\Subscriber $subscriber, $email = null)\n    {\n        $mergeVars = [];\n        $storeId = $subscriber->getStoreId();\n        $webSiteId = $this->getWebsiteId($subscriber->getStoreId());\n        if (!$email) {\n            $email = $subscriber->getEmail();\n        }\n        try {\n            /**\n             * @var $customer \\Magento\\Customer\\Model\\Customer\n             */\n            $customer = $this->_customerFactory->create();\n            $customer->setWebsiteId($webSiteId);\n            $customer->loadByEmail($email);\n            if ($customer->getData('email') == $email) {\n                $mergeVars = $this->getMergeVars($customer, $storeId);\n            }\n        } catch (\\Exception $e) {\n            $this->log($e->getMessage());\n        }\n        return $mergeVars;\n    }\n\n    /**\n     * @param \\Magento\\Customer\\Model\\Customer $customer\n     * @param $email\n     * @return array|null\n     */\n    public function getMergeVarsByCustomer(\\Magento\\Customer\\Model\\Customer $customer, $email)\n    {\n        return $this->getMergeVars($customer, $customer->getData('store_id'));\n    }\n\n    public function getGeneralList($storeId)\n    {\n        return $this->getConfigValue(self::XML_PATH_LIST, $storeId);\n    }\n\n    public function getListForMailChimpStore($mailchimpStoreId, $apiKey)\n    {\n        try {\n            $api = $this->getApiByApiKey($apiKey);\n            $store = $api->ecommerce->stores->get($mailchimpStoreId);\n            if (isset($store['list_id'])) {\n                return $store['list_id'];\n            }\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->log($e->getFriendlyMessage());\n        }\n        return null;\n    }\n\n    public function getDateMicrotime()\n    {\n        $microtime = explode(' ', microtime());\n        $msec = $microtime[0];\n        $msecArray = explode('.', $msec);\n        $date = date('Y-m-d-H-i-s') . '-' . $msecArray[1];\n        return $date;\n    }\n    public function loadStores()\n    {\n\n        $mcUserName = [];\n        $allStores = [];\n        $connection = $this->_mailChimpStores->getResource()->getConnection();\n        $tableName = $this->_mailChimpStores->getResource()->getMainTable();\n        $connection->truncateTable($tableName);\n        $keys = $this->getAllApiKeys();\n        foreach ($keys as $apiKey) {\n            if (!$apiKey || $apiKey =='') {\n                continue;\n            }\n            $this->_api->setApiKey(trim($apiKey));\n            $this->_api->setUserAgent('Mailchimp4Magento' . (string)$this->getModuleVersion());\n            $this->_api->setHelper($this);\n\n            try {\n                $apiStores = $this->_api->ecommerce->stores->get(null, null, null, self::MAXSTORES);\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->log($e->getFriendlyMessage());\n                continue;\n            }\n\n            foreach ($apiStores['stores'] as $store) {\n                if ($store['platform']!=self::PLATFORM||in_array($store['id'],$allStores)) {\n                    continue;\n                }\n                if (isset($store['connected_site'])) {\n                    $name = $store['name'];\n                } else {\n                    $name = $store['name'].' (Warning: not connected)';\n                }\n                $allStores[] = $store['id'];\n                $mstore = $this->_mailChimpStoresFactory->create();\n                $mstore->setApikey($this->_encryptor->encrypt(trim($apiKey)));\n                $mstore->setStoreid($store['id']);\n                $mstore->setListId($store['list_id']);\n                $mstore->setName($name);\n                $mstore->setPlatform($store['platform']);\n                $mstore->setIsSync($store['is_syncing']);\n                $mstore->setEmailAddress($store['email_address']);\n                $mstore->setDomain($store['domain']);\n                $mstore->setCurrencyCode($store['currency_code']);\n                $mstore->setPrimaryLocale($store['primary_locale']);\n                $mstore->setTimezone($store['timezone']);\n                $mstore->setPhone($store['phone']);\n                $mstore->setAddressAddressOne($store['address']['address1']);\n                $mstore->setAddressAddressTwo($store['address']['address2']);\n                $mstore->setAddressCity($store['address']['city']);\n                $mstore->setAddressProvince($store['address']['province']);\n                $mstore->setAddressProvinceCode($store['address']['province_code']);\n                $mstore->setAddressPostalCode($store['address']['postal_code']);\n                $mstore->setAddressCountry($store['address']['country']);\n                $mstore->setAddressCountryCode($store['address']['country_code']);\n                if (!isset($mcUserName[$apiKey])) {\n                    $mcInfo = $this->_api->root->info();\n                    $mcUserName[$apiKey] = $mcInfo['account_name'];\n                }\n                try {\n                    $listInfo = $this->_api->lists->getLists($store['list_id']);\n                    if (isset($listInfo['name'])) {\n                        $mstore->setListName($listInfo['name']);\n                        $mstore->setMcAccountName($mcUserName[$apiKey]);\n                        $mstore->getResource()->save($mstore);\n                    }\n                } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                    $this->log($e->getFriendlyMessage());\n                }\n            }\n        }\n    }\n    public function saveJsUrl($storeId, $scope = null, $mailChimpStoreId = null)\n    {\n        if (!$scope) {\n            $scope = \\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORES;\n        }\n        if ($this->getConfigValue(self::XML_PATH_ACTIVE, $storeId, $scope)) {\n            try {\n                $api = $this->getApi($storeId);\n                $storeData = $api->ecommerce->stores->get($mailChimpStoreId);\n                if (isset($storeData['connected_site']['site_script']['url'])) {\n                    $url = $storeData['connected_site']['site_script']['url'];\n                    $this->_config->saveConfig(\n                        self::XML_MAILCHIMP_JS_URL,\n                        $url,\n                        $scope,\n                        $storeId\n                    );\n                }\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->log($e->getFriendlyMessage());\n            }\n        }\n\n    }\n    public function getJsUrl($storeId)\n    {\n        $url = $this->getConfigValue(self::XML_MAILCHIMP_JS_URL, $storeId);\n        if ($this->getConfigValue(self::XML_PATH_ACTIVE, $storeId) && !$url) {\n            $mailChimpStoreId = $this->getConfigValue(self::XML_MAILCHIMP_STORE, $storeId);\n            try {\n                $api = $this->getApi($storeId);\n                $storeData = $api->ecommerce->stores->get($mailChimpStoreId);\n                if (isset($storeData['connected_site']['site_script']['url'])) {\n                    $url = $storeData['connected_site']['site_script']['url'];\n                    $this->_config->saveConfig(\n                        self::XML_MAILCHIMP_JS_URL,\n                        $url,\n                        \\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORES,\n                        $storeId\n                    );\n                }\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->log($e->getFriendlyMessage());\n            }\n        }\n        return $url;\n    }\n\n    public function getWebhooksKey()\n    {\n        $keys =explode(\"\\n\", $this->_encryptor->exportKeys());\n        $crypt = hash('md5', (string)$keys[0]);\n        $key = substr($crypt, 0, (strlen($crypt) / 2));\n\n        return $key;\n    }\n\n    public function createWebHook($apikey, $listId, $scope=null, $scopeId=null)\n    {\n        $events = [\n            'subscribe' => true,\n            'unsubscribe' => true,\n            'profile' => true,\n            'cleaned' => true,\n            'upemail' => true,\n            'campaign' => false\n        ];\n        $sources = [\n            'user' => true,\n            'admin' => true,\n            'api' => true\n        ];\n        try {\n            $api = $this->getApiByApiKey($apikey);\n            $hookUrl = $this->_getUrl(\\Ebizmarts\\MailChimp\\Controller\\WebHook\\Index::WEBHOOK__PATH, [\n                '_scope' => $scopeId,\n                'wkey' => $this->getWebhooksKey(),\n                '_nosid' => true,\n                '_secure' => true]);\n            // the urlencode of the hookUrl not work\n            $ret = $api->lists->webhooks->add($listId, $hookUrl, $events, $sources);\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->log($e->getFriendlyMessage());\n            $ret ['message']= $e->getMessage();\n        }\n        return $ret;\n    }\n    public function deleteWebHook($apikey, $listId)\n    {\n        if (empty($listId)) {\n            return;\n        }\n        try {\n            $api = $this->getApiByApiKey($apikey);\n            $webhooks = $api->lists->webhooks->getAll($listId);\n            $hookUrl = $this->_getUrl(\\Ebizmarts\\MailChimp\\Controller\\WebHook\\Index::WEBHOOK__PATH, [\n                '_nosid' => true,\n                '_secure' => true]);\n            if (isset($webhooks['webhooks'])) {\n                foreach ($webhooks['webhooks'] as $wh) {\n                    if ($wh['url'] == $hookUrl) {\n                        $api->lists->webhooks->delete($listId, $wh['id']);\n                    }\n                }\n            }\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->log($e->getFriendlyMessage());\n        }\n    }\n\n    /**\n     * @param $listId\n     * @param $mail\n     * @return \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\Collection\n     */\n    public function loadListSubscribers($listId, $mail)\n    {\n        $collection = null;\n        $storeIds = $this->getMagentoStoreIdsByListId($listId);\n        $storeIds[] = 0;\n        if (count($storeIds) > 0) {\n            $collection = $this->_subscriberCollection->create();\n            $collection\n                ->addFieldToFilter('store_id', ['in'=>$storeIds])\n                ->addFieldToFilter('subscriber_email', ['eq'=>$mail]);\n        }\n        return $collection;\n    }\n    public function getMagentoStoreIdsByListId($listId)\n    {\n        $storeIds = [];\n        foreach ($this->_storeManager->getStores() as $storeId => $val) {\n            if ($this->isMailChimpEnabled($storeId)) {\n                $storeListId = $this->getConfigValue(self::XML_PATH_LIST, $storeId);\n                if ($storeListId == $listId) {\n                    $storeIds[] = $storeId;\n                }\n            }\n        }\n        return $storeIds;\n    }\n\n    /**\n     * @param $listId\n     * @param $email\n     * @return \\Magento\\Customer\\Model\\ResourceModel\\Customer\\Collection\n     */\n    public function loadListCustomers($listId, $email)\n    {\n        $customer = null;\n        $storeIds = $this->getMagentoStoreIdsByListId($listId);\n        if (count($storeIds) > 0) {\n            $customer = $this->_customerCollection->create();\n            $customer\n                ->addFieldToSelect('entity_id')\n                ->addFieldToFilter('store_id', ['in' => $storeIds])\n                ->addFieldToFilter('email', ['eq' => $email]);\n        }\n        return $customer;\n    }\n\n    /**\n     * @param $tableName\n     * @param string $conn\n     * @return string\n     */\n    public function getTableName($tableName, $conn = ResourceConnection::DEFAULT_CONNECTION)\n    {\n        $connection = $this->_resource->getConnection($conn);\n        $tablePrefix = $this->_resource->getTablePrefix();\n        if ($tablePrefix && strpos($tableName, $tablePrefix) !== 0) {\n            $tableName = $tablePrefix . $tableName;\n        }\n        return $connection->getTableName($tableName, $conn);\n    }\n    public function getWebsiteId($storeId)\n    {\n        return $this->_storeManager->getStore($storeId)->getWebsiteId();\n    }\n    public function getInterest($storeId)\n    {\n        $rc = [];\n        $interest = $this->getConfigValue(self::XML_INTEREST, $storeId);\n        if ($interest!='') {\n            $interest = explode(\",\", $interest);\n        } else {\n            $interest = [];\n        }\n        try {\n            $api = $this->getApi($storeId);\n            $listId = $this->getConfigValue(self::XML_PATH_LIST, $storeId);\n            $allInterest = $api->lists->interestCategory->getAll($listId, null, null, 200);\n            if (is_array($allInterest) &&\n                array_key_exists('categories', $allInterest) &&\n                is_array($allInterest['categories'])) {\n                foreach ($allInterest['categories'] as $item) {\n                    if (in_array($item['id'], $interest)) {\n                        $rc[$item['id']]['interest'] =\n                            ['id' => $item['id'], 'title' => $item['title'], 'type' => $item['type']];\n                    }\n                }\n                foreach ($interest as $interestId) {\n                    $mailchimpInterest = $api->lists->interestCategory->interests->getAll($listId, $interestId, null, null, 200);\n                    foreach ($mailchimpInterest['interests'] as $mi) {\n                        $rc[$mi['category_id']]['category'][$mi['display_order']] =\n                            ['id' => $mi['id'], 'name' => $mi['name'], 'checked' => false];\n                    }\n                }\n            } else {\n                $this->log(__('Error retrieving interest groups for store ').$storeId);\n                $rc = [];\n            }\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->log($e->getFriendlyMessage());\n        }\n        return $rc;\n    }\n    public function getSubscriberInterest($subscriberId, $storeId, $interest = null)\n    {\n        if (!$interest) {\n            $interest = $this->getInterest($storeId);\n        }\n        /**\n         * @var $interestGroup \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroup\n         */\n        $interestGroup = $this->_interestGroupFactory->create();\n        $interestGroup->getBySubscriberIdStoreId($subscriberId, $storeId);\n        $serialized = $interestGroup->getGroupdata();\n        if ($serialized&&is_array($interest)&&count($interest)) {\n            try {\n                $groups = $this->unserialize($serialized);\n                if (isset($groups['group'])) {\n                    foreach ($groups['group'] as $key => $value) {\n                        if (array_key_exists($key, $interest)) {\n                            if (is_array($value)) {\n                                foreach ($value as $groupId) {\n                                    foreach ($interest[$key]['category'] as $gkey => $gvalue) {\n                                        if ($gvalue['id'] == $groupId) {\n                                            $interest[$key]['category'][$gkey]['checked'] = true;\n                                        } elseif (!isset($interest[$key]['category'][$gkey]['checked'])) {\n                                            $interest[$key]['category'][$gkey]['checked'] = false;\n                                        }\n                                    }\n                                }\n                            } else {\n                                foreach ($interest[$key]['category'] as $gkey => $gvalue) {\n                                    if ($gvalue['id'] == $value) {\n                                        $interest[$key]['category'][$gkey]['checked'] = true;\n                                    } else {\n                                        $interest[$key]['category'][$gkey]['checked'] = false;\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->log($e->getMessage());\n            }\n        }\n        return $interest;\n    }\n    public function getGmtDate($format = null)\n    {\n        return $this->_date->gmtDate($format);\n    }\n    public function getGmtTimeStamp()\n    {\n        return $this->_date->gmtTimestamp();\n    }\n    public function getAllApiKeys()\n    {\n        $apiKeys = [];\n        foreach ($this->_storeManager->getStores() as $storeId => $val) {\n            $apiKey = $this->getApiKey($storeId);\n            if (!in_array($apiKey, $apiKeys)) {\n                $apiKeys[] = $apiKey;\n            }\n        }\n        return $apiKeys;\n    }\n    public function modifyCounter($index, $increment = 1)\n    {\n        if (array_key_exists($index, $this->counters)) {\n            $this->counters[$index] = $this->counters[$index] + $increment;\n        } else {\n            $this->counters[$index] = 1;\n        }\n    }\n    public function resetCounters($storeId = null)\n    {\n        $this->counters = [];\n        $this->counters = [\n            self::SUB_NEW => 0,\n            self::SUB_MOD => 0,\n            self::ORD_NEW => 0,\n            self::ORD_MOD => 0,\n            self::PRO_NEW => 0,\n            self::PRO_DELETED => 0,\n            self::PRO_MOD => 0,\n            self::QUO_NEW => 0,\n            self::QUO_MOD => 0\n        ];\n        if ($this->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ALL_CUSTOMERS, $storeId)) {\n            $this->counters [self::CUS_NEW] = 0;\n            $this->counters [self::CUS_MOD] = 0;\n        }\n\n    }\n    public function getCounters()\n    {\n        return $this->counters;\n    }\n    public function getTotalNewItemsSent()\n    {\n        $totalAmount = 0;\n        $itemArray = [self::ORD_NEW, self::SUB_NEW, self::PRO_NEW, self::CUS_NEW, self::QUO_NEW];\n\n        foreach ($itemArray as $item) {\n            if (array_key_exists($item, $this->counters)) {\n                $totalAmount += $this->counters[$item];\n            }\n        }\n\n        return $totalAmount;\n    }\n    public function serialize($data)\n    {\n        return $this->_serializer->serialize($data);\n    }\n    public function unserialize($string)\n    {\n        return $this->_serializer->unserialize($string);\n    }\n    public function isEmailSavingEnabled($storeId)\n    {\n        return $this->_scopeConfig->isSetFlag(\n            self::XML_ABANDONEDCART_EMAIL,\n            \\Magento\\Store\\Model\\ScopeInterface::SCOPE_STORES,\n            $storeId\n        );\n    }\n    public function decrypt($value)\n    {\n        return $this->_encryptor->decrypt($value);\n    }\n    public function encrypt($value)\n    {\n        return $this->_encryptor->encrypt($value);\n    }\n    public function buttonPressed($button, $result)\n    {\n        $data = [];\n        $data['storeURL'] = $this->_storeManager->getStore()->getBaseUrl();\n        $data['time'] = $this->getGmtDate();\n        $data['button']['action'] = $button;\n        $data['button']['result'] = $result;\n        $this->saveNotification($data);\n\n    }\n    public function switchLog($on)\n    {\n        $storeId = $this->_storeManager->getDefaultStoreView()->getId();\n        $scope = 'default';\n        $token = $this->getConfigValue(self::XML_STATISTICS_TOKEN, $storeId, $scope);\n    }\n    /**\n     * @param \\Magento\\Quote\\Model\\Quote $quote\n     * @return void\n     */\n    public function sendCartEvent($quote)\n    {\n        $storeId = $quote->getStoreId();\n        $api = $this->getApi($storeId);\n        $list = $this->getDefaultList($storeId);\n        $customerMailchimpId = hash('md5', strtolower($quote->getCustomerEmail()));\n        $properties = [];\n        $properties['quote_id'] = $quote->getId();\n        $properties['store_id'] = $this->getConfigValue(self::XML_MAILCHIMP_STORE, $storeId);\n        $properties['customer_email'] = $quote->getCustomerEmail();\n        $properties['total'] = $quote->getGrandTotal();\n        $properties['currency'] = $quote->getQuoteCurrencyCode();\n        $properties['customer_id'] = $quote->getCustomerId();\n        $api->lists->members->memberEvent->add($list, $customerMailchimpId, \"abandoned_cart_visit\",$properties,false,$this->getGmtDate());\n    }\n}\n"
  },
  {
    "path": "Helper/Http.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Helper;\n\nuse Ebizmarts\\MailChimp\\Model\\HTTP\\Client\\Curl;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\n\nclass Http\n{\n    const NO_ERROR = 0;\n    const ERROR_JSON = 1;\n    const ERROR_AUTH = 2;\n    const ERROR_GENERIC = 3;\n    /**\n     * @var Curl\n     */\n    protected $curl;\n    protected $url;\n    /**\n     * @var MailChimpHelper\n     */\n    protected $helper;\n    public function __construct(\n        Curl $curl,\n        MailChimpHelper $helper\n    ) {\n        $this->curl = $curl;\n        $this->url = $helper->getConfigValue(MailChimpHelper::SYNC_NOTIFICATION_URL);\n        $token = $helper->getConfigValue(MailChimpHelper::SYNC_TOKEN);\n        $headers = ['Authorization' => 'Bearer ' . $token,\n            'Content-Type' => 'application/json'\n        ];\n        $this->curl->setOption(CURLOPT_RETURNTRANSFER, true);\n        $this->curl->setHeaders($headers);\n        $this->helper = $helper;\n    }\n    public function setUrl($url)\n    {\n        $this->url = $url;\n        $token = $this->helper->getConfigValue(MailChimpHelper::SYNC_TOKEN);\n        $headers = ['Authorization' => 'Bearer ' . $token,\n            'Content-Type' => 'application/json'\n        ];\n        $this->curl->setOption(CURLOPT_RETURNTRANSFER, true);\n        $this->curl->setHeaders($headers);\n    }\n    public function post($body)\n    {\n        $this->curl->post($this->url , $body);\n        $response = $this->curl->getBody();\n        return $response;\n    }\n    public function patch($id,$body)\n    {\n        $this->curl->patch($this->url .'/'. $id , $body);\n        $response = $this->curl->getBody();\n        return $response;\n    }\n    public function get($id)\n    {\n        $this->curl->get($this->url .'/'. $id);\n        $response = $this->curl->getBody();\n        return $response;\n    }\n    public function put($id,$body)\n    {\n        $this->curl->put($this->url .'/'. $id , $body);\n        $response = $this->curl->getBody();\n        return $response;\n    }\n    public function extractResponse($response)\n    {\n        try {\n            $data = json_decode($response, true);\n            if (is_null($data) || json_last_error() !== JSON_ERROR_NONE) {\n                return self::ERROR_JSON;\n            }\n            if (key_exists('error', $data)) {\n                if (!$data['error']) {\n                    return self::NO_ERROR;\n                } else {\n                    $this->helper->log(\"Error found\");\n                    $this->helper->log($response);\n                    $this->helper->log($data['message']);\n                    return self::ERROR_AUTH;\n                }\n            }\n        } catch (\\Exception $e) {\n            $this->helper->log(\"Exception found\");\n            $this->helper->log($response);\n            $this->helper->log($e->getMessage());\n            return self::ERROR_GENERIC;\n        }\n        return self::ERROR_GENERIC;\n    }\n}\n"
  },
  {
    "path": "Helper/Sync.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Helper;\n\nuse Magento\\Framework\\App\\Helper\\AbstractHelper;\nuse Magento\\Framework\\App\\Helper\\Context;\nuse Magento\\Framework\\Exception\\ValidatorException;\nuse Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory;\nuse Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce;\nuse Ebizmarts\\MailChimp\\Model\\MailChimpErrors;\n\nclass Sync extends AbstractHelper\n{\n    /**\n     * @var MailChimpSyncEcommerceFactory\n     */\n    private $chimpSyncEcommerceFactory;\n    /**\n     * @var MailChimpErrors\n     */\n    private $mailChimpErrors;\n    /**\n     * @var MailChimpSyncEcommerce\n     */\n    private $chimpSyncEcommerce;\n\n    /**\n     * @param Context $context\n     * @param MailChimpSyncEcommerceFactory $chimpSyncEcommerceFactory\n     * @param MailChimpErrors $mailChimpErrors\n     * @param MailChimpSyncEcommerce $chimpSyncEcommerce\n     */\n    public function __construct(\n        Context $context,\n        MailChimpSyncEcommerceFactory $chimpSyncEcommerceFactory,\n        MailChimpErrors $mailChimpErrors,\n        MailChimpSyncEcommerce $chimpSyncEcommerce\n    ) {\n        $this->chimpSyncEcommerceFactory = $chimpSyncEcommerceFactory;\n        $this->mailChimpErrors = $mailChimpErrors;\n        $this->chimpSyncEcommerce = $chimpSyncEcommerce;\n        parent::__construct($context);\n    }\n    public function saveEcommerceData(\n        $storeId,\n        $entityId,\n        $type,\n        $date = null,\n        $error = null,\n        $modified = null,\n        $deleted = null,\n        $token = null,\n        $sent = null,\n        $isResult = false\n    ) {\n        if (!empty($entityId)) {\n            $chimpSyncEcommerce = $this->getChimpSyncEcommerce($storeId, $entityId, $type);\n            if ($chimpSyncEcommerce->getRelatedId() == $entityId ||\n                !$chimpSyncEcommerce->getRelatedId() && $modified != 1) {\n                if ($isResult && $chimpSyncEcommerce->getMailchimpSyncModified()) {\n                    return;\n                }\n                $chimpSyncEcommerce->setMailchimpStoreId($storeId);\n                $chimpSyncEcommerce->setType($type);\n                $chimpSyncEcommerce->setRelatedId($entityId);\n                if ($modified!==null) {\n                    $chimpSyncEcommerce->setMailchimpSyncModified($modified);\n                } else {\n                    $chimpSyncEcommerce->setMailchimpSyncModified(0);\n                }\n                if ($date) {\n                    $chimpSyncEcommerce->setMailchimpSyncDelta($date);\n                }\n                if ($error) {\n                    $chimpSyncEcommerce->setMailchimpSyncError($error);\n                }\n                if ($deleted) {\n                    $chimpSyncEcommerce->setMailchimpSyncDeleted($deleted);\n                    $chimpSyncEcommerce->setMailchimpSyncModified(0);\n                }\n                if ($token) {\n                    $chimpSyncEcommerce->setMailchimpToken($token);\n                }\n                if ($sent) {\n                    $chimpSyncEcommerce->setMailchimpSent($sent);\n                }\n                $chimpSyncEcommerce->getResource()->save($chimpSyncEcommerce);\n            }\n        }\n    }\n    public function getChimpSyncEcommerce($storeId, $id, $type)\n    {\n        $chimp = $this->chimpSyncEcommerceFactory->create();\n        return $chimp->getByStoreIdType($storeId, $id, $type);\n    }\n    public function markEcommerceAsDeleted($relatedId, $type, $relatedDeletedId = null)\n    {\n        $this->chimpSyncEcommerce->markAllAsDeleted($relatedId, $type, $relatedDeletedId);\n    }\n    public function markEcommorceAsNotDeleted($relatedId, $type)\n    {\n        $this->chimpSyncEcommerce->markEcommorceAsNotDeleted($relatedId, $type);\n    }\n    public function ecommerceDeleteAllByIdType($id, $type, $mailchimpStoreId)\n    {\n        $this->chimpSyncEcommerce->deleteAllByIdType($id, $type, $mailchimpStoreId);\n    }\n    public function deleteAllByBatchId($batchId)\n    {\n        $this->chimpSyncEcommerce->deleteAllByBatchid($batchId);\n    }\n    public function markRegisterAsModified($registerId, $type)\n    {\n        if (!empty($registerId)) {\n            $this->chimpSyncEcommerce->markAllAsModified($registerId, $type);\n        }\n    }\n    public function deleteByTypeAndId($type, $id, $mailchimpStoreId)\n    {\n        $this->chimpSyncEcommerce->deleteByTypeAndId($type, $id, $mailchimpStoreId);\n    }\n    public function markAllAsModifiedByIds($mailchimpStoreId, $ids, $type)\n    {\n        $this->chimpSyncEcommerce->markAllAsModifiedByIds($mailchimpStoreId, $ids, $type);\n    }\n    public function resyncAllSubscribers($mailchimpList)\n    {\n        $connection = $this->chimpSyncEcommerce->getResource()->getConnection();\n        $tableName = $this->chimpSyncEcommerce->getResource()->getMainTable();\n        $connection->update(\n            $tableName,\n            ['mailchimp_sync_modified' => 1],\n            \"type = '\" . \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER . \"' and mailchimp_store_id = '$mailchimpList'\"\n        );\n    }\n    public function resyncProducts($mailchimpList)\n    {\n        $connection = $this->chimpSyncEcommerce->getResource()->getConnection();\n        $tableName = $this->chimpSyncEcommerce->getResource()->getMainTable();\n        $connection->update(\n            $tableName,\n            ['mailchimp_sync_modified' => 1],\n            \"type = '\" . \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT . \"' and mailchimp_store_id = '$mailchimpList'\"\n        );\n    }\n\n    public function resetErrors($mailchimpStore, $storeId, $retry)\n    {\n        try {\n            // clean the errors table\n            $connection = $this->mailChimpErrors->getResource()->getConnection();\n            $tableName = $this->mailChimpErrors->getResource()->getMainTable();\n            $connection->delete($tableName, \"mailchimp_store_id = '\".$mailchimpStore.\"'\");\n            // clean the syncecommerce table with errors\n            if ($retry) {\n                $connection = $this->chimpSyncEcommerce->getResource()->getConnection();\n                $tableName = $this->chimpSyncEcommerce->getResource()->getMainTable();\n                $connection->delete(\n                    $tableName,\n                    \"mailchimp_store_id = '\" . $mailchimpStore . \"' and mailchimp_sync_error is not null\"\n                );\n            }\n        } catch (\\Zend_Db_Exception $e) {\n            throw new ValidatorException(__($e->getMessage()));\n        }\n    }\n}\n"
  },
  {
    "path": "Helper/VarsMap.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/30/17 10:35 AM\n * @file: VarsMap.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Helper;\n\nclass VarsMap extends \\Magento\\Framework\\App\\Helper\\AbstractHelper\n{\n    /**\n     * @var Data\n     */\n    protected $_helper;\n    protected $mathRandom;\n\n    /**\n     * VarsMap constructor.\n     * @param \\Magento\\Framework\\App\\Helper\\Context $context\n     * @param \\Magento\\Framework\\Math\\Random $mathRandom\n     * @param Data $helper\n     */\n    public function __construct(\n        \\Magento\\Framework\\App\\Helper\\Context $context,\n        \\Magento\\Framework\\Math\\Random $mathRandom,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n    \n        $this->_helper      = $helper;\n        $this->mathRandom   = $mathRandom;\n        parent::__construct($context);\n    }\n    public function makeArrayFieldValue($value)\n    {\n        $value = $this->unserializeValue($value);\n        $value = $this->encodeArrayFieldValue($value);\n        return $value;\n    }\n    public function makeStorableArrayFieldValue($value)\n    {\n        $value = is_array($value) ? $this->decodeArrayFieldValue($value) : $value;\n        $value = $this->serializeValue($value);\n        return $value;\n    }\n\n    /**\n     * @param $value\n     * @return bool\n     */\n    protected function isEncodedArrayFieldValue($value)\n    {\n        if (!is_array($value)) {\n            return false;\n        }\n        unset($value['__empty']);\n        foreach ($value as $row) {\n            if (!is_array($row)\n                || !array_key_exists('customer_field_id', $row)\n                || !array_key_exists('mailchimp_field_id', $row)\n            ) {\n                return false;\n            }\n        }\n        return true;\n    }\n    protected function decodeArrayFieldValue(array $value)\n    {\n        $result = [];\n        unset($value['__empty']);\n        foreach ($value as $row) {\n            if (!is_array($row)\n                || !array_key_exists('customer_field_id', $row)\n                || !array_key_exists('mailchimp_field_id', $row)\n            ) {\n                continue;\n            }\n            $customer_field_id = $row['customer_field_id'];\n            $mailchimp_field_id = $row['mailchimp_field_id'];\n            $result[$customer_field_id] = $mailchimp_field_id;\n        }\n        return $result;\n    }\n    protected function serializeValue($value)\n    {\n        $rc = '';\n        if (is_array($value)) {\n            $data = [];\n            foreach ($value as $customerFiledId => $mailchimpName) {\n                if (!array_key_exists($customerFiledId, $data)) {\n                    $data[$customerFiledId] = $mailchimpName;\n                }\n            }\n            try {\n                $rc = $this->_helper->serialize($data);\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n            }\n        }\n        return $rc;\n    }\n    protected function unserializeValue($value)\n    {\n        $rc = [];\n        if (is_string($value) && !empty($value)) {\n            try {\n                $rc = $this->_helper->unserialize($value);\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n            }\n        }\n        return $rc;\n    }\n    protected function encodeArrayFieldValue(array $value)\n    {\n        $result = [];\n        foreach ($value as $customerFieldId => $mailchimpName) {\n            $resultId = $this->mathRandom->getUniqueHash('_');\n            $result[$resultId] = ['mailchimp_field_id' => $mailchimpName ,'customer_field_id' => $customerFieldId];\n        }\n        return $result;\n    }\n}\n"
  },
  {
    "path": "ISSUE_TEMPLATE.md",
    "content": "# Issue reporting guidelines\n\nTo 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.\n\nBefore creating an issue, please do the following:\n\n* Make sure the behavior you are reporting is really a bug, not a feature.\n* Check the existing [issues](https://github.com/mailchimp/mc-magento2/issues) to make sure you are not duplicating somebody’s work.\n* 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.\n\nIf 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.\n\n## Title\n\nTitle 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.\n\nGood example would be:\n\n> Unable to place order with Virtual product and PayPal.\n\nUnclear example:\n\n> Can't checkout.\n\n## Issue Description\n\n### Preconditions\n\nDescribing 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.\n\nExample:\n\n    1. Magento CE 2.1.7 without sample data is installed.\n    2. mc-magento2 1.0.21.\n    3. Test category is set up.\n    4. Virtual Product is created and assigned to the Test Category.\n    ...\n\n### Steps to reproduce\n\nThis 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.\n\nPrecisely 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.\n\nExample:\n\n    1. Navigate to storefront as a guest.\n    2. Open Test Category.\n    3. Click \"Add to Cart\" on the Virtual Product.\n    4. Open mini shopping cart and click \"Proceed to Checkout\".\n    ...\n\n### Actual and Expected result\n\nTo 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.\n\nExample:\n\n    Expected result:\n    Order is placed successfully, customer is redirected to the success page.\n    Actual result:\n    \"Place order\" button is not visible, order cannot be placed.\n\n### Additional information\n\nAdditional 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.\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "\nOpen Software License (\"OSL\") v. 3.0\n\nThis 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:\n\nLicensed under the Open Software License version 3.0\n\n   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:\n\n         1. to reproduce the Original Work in copies, either alone or as part of a collective work;\n\n         2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works (\"Derivative Works\") based upon the Original Work;\n\n         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;\n\n         4. to perform the Original Work publicly; and\n\n         5. to display the Original Work publicly.\n\n   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.\n\n   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.\n\n   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.\n\n   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).\n\n   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.\n\n   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.\n\n   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.\n\n   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).\n\n  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.\n\n  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.\n\n  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.\n\n  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.\n\n  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.\n\n  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.\n\n  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 <insert your license name here>\" 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."
  },
  {
    "path": "Model/Api/Cart.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/7/17 12:42 PM\n * @file: Cart.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\nuse \\Magento\\GroupedProduct\\Model\\Product\\Type\\Grouped as GroupedProductType;\n\nclass Cart\n{\n\n    const BATCH_LIMIT = 100;\n\n    protected $_firstDate;\n    protected $_counter;\n    protected $_batchId;\n    protected $_api = null;\n    protected $_token = null;\n\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Quote\\Model\\ResourceModel\\Quote\\CollectionFactory\n     */\n    protected $_quoteCollection;\n    /**\n     * @var \\Magento\\Customer\\Model\\CustomerFactory\n     */\n    protected $_customerFactory;\n    /**\n     * @var Product\n     */\n    protected $_apiProduct;\n    /**\n     * @var \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory\n     */\n    protected $_orderCollectionFactory;\n    /**\n     * @var Customer\n     */\n    protected $_apiCustomer;\n    /**\n     * @var \\Magento\\Directory\\Model\\CountryFactory\n     */\n    protected $_countryFactory;\n    /**\n     * @var \\Magento\\Framework\\Url\n     */\n    protected $_urlHelper;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Quote\\Model\\ResourceModel\\Quote\\CollectionFactory $quoteColletcion\n     * @param \\Magento\\Customer\\Model\\CustomerFactory $customerFactory\n     * @param Product $apiProduct\n     * @param Customer $apiCustomer\n     * @param \\Magento\\Directory\\Model\\CountryFactory $countryFactory\n     * @param \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollectionFactory\n     * @param \\Magento\\Framework\\Url $urlHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Quote\\Model\\ResourceModel\\Quote\\CollectionFactory $quoteColletcion,\n        \\Magento\\Customer\\Model\\CustomerFactory $customerFactory,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Product $apiProduct,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Customer $apiCustomer,\n        \\Magento\\Directory\\Model\\CountryFactory $countryFactory,\n        \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollectionFactory,\n        \\Magento\\Framework\\Url $urlHelper\n    ) {\n\n        $this->_helper                  = $helper;\n        $this->syncHelper               = $syncHelper;\n        $this->_quoteCollection         = $quoteColletcion;\n        $this->_customerFactory         = $customerFactory;\n        $this->_apiProduct              = $apiProduct;\n        $this->_apiCustomer             = $apiCustomer;\n        $this->_orderCollectionFactory  = $orderCollectionFactory;\n        $this->_countryFactory          = $countryFactory;\n        $this->_urlHelper               = $urlHelper;\n    }\n\n        /**\n         * @param $mailchimpStoreId\n         * @param $magentoStoreId\n         * @return array\n         */\n    public function createBatchJson($magentoStoreId)\n    {\n        $allCarts = [];\n        if (!$this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_ABANDONEDCART_ACTIVE,\n            $magentoStoreId\n        )\n        ) {\n            return $allCarts;\n        }\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $magentoStoreId\n        );\n\n        $this->_firstDate = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_ABANDONEDCART_FIRSTDATE,\n            $magentoStoreId\n        );\n        if (!$this->_firstDate) {\n            $this->_firstDate = $this->_helper->getMCMinSyncDateFlagByMailchimpStore(\n                $mailchimpStoreId,\n                0,\n                'default'\n            );\n        }\n        $this->_counter = 0;\n\n        $date = $this->_helper->getDateMicrotime();\n        $this->_batchId =  \\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE.'_'.$date;\n        // get all the carts converted in orders (must be deleted on mailchimp)\n        $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId));\n        // get all the carts modified but not converted in orders\n        $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId));\n        // get new carts\n        $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId));\n        return $allCarts;\n    }\n\n    /**\n     * @param $mailchimpStoreId\n     * @param $magentoStoreId\n     * @return array\n     */\n    protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId)\n    {\n        $allCarts = [];\n        $convertedCarts = $this->_getQuoteCollection();\n        // get only the converted quotes\n        $convertedCarts->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);\n        $convertedCarts->addFieldToFilter('is_active', ['eq' => 0]);\n        $convertedCarts->getSelect()->reset(\\Zend_Db_Select::COLUMNS)->columns(['entity_id','customer_email']);\n        //join with mailchimp_ecommerce_sync_data table to filter by sync data.\n        $convertedCarts->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE.\"'\n            AND m4m.mailchimp_store_id = '\" . $mailchimpStoreId . \"'\",\n            ['m4m.*']\n        );\n        // be sure that the quotes are already in mailchimp and not deleted\n        $convertedCarts->getSelect()->where(\"m4m.mailchimp_sync_deleted is null and m4m.related_id is not null\");\n        // limit the collection\n        $convertedCarts->getSelect()->limit(self::BATCH_LIMIT);\n        /**\n         * @var $cart \\Magento\\Quote\\Model\\Quote\n         */\n        foreach ($convertedCarts as $cart) {\n            $cartId = $cart->getEntityId();\n            // we need to delete all the carts associated with this email\n            $allCartsForEmail = $this->_getAllCartsByEmail(\n                $cart->getCustomerEmail(),\n                $mailchimpStoreId,\n                $magentoStoreId\n            );\n            /**\n             * @var $cartForEmail \\Magento\\Quote\\Model\\Quote\n             */\n            foreach ($allCartsForEmail as $cartForEmail) {\n                $alreadySentCartId = $cartForEmail->getEntityId();\n                if ($alreadySentCartId != $cartId) {\n                    $allCarts[$this->_counter]['method'] = 'DELETE';\n                    $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' .\n                        $alreadySentCartId;\n                    $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId;\n                    $allCarts[$this->_counter]['body'] = '';\n                    $this->_updateQuote(\n                        $mailchimpStoreId,\n                        $alreadySentCartId,\n                        null,\n                        null,\n                        null,\n                        1\n                    );\n                    $this->_counter += 1;\n                }\n            }\n\n            $allCartsForEmail->clear();\n            $allCarts[$this->_counter]['method'] = 'DELETE';\n            $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId;\n            $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId;\n            $allCarts[$this->_counter]['body'] = '';\n            $this->_updateQuote(\n                $mailchimpStoreId,\n                $cartId,\n                null,\n                null,\n                null,\n                1\n            );\n            $this->_counter += 1;\n        }\n\n        return $allCarts;\n    }\n\n    /**\n     * @param $mailchimpStoreId\n     * @param $magentoStoreId\n     * @return array\n     */\n    protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId)\n    {\n        $allCarts = [];\n        $modifiedCarts = $this->_getQuoteCollection();\n        // select carts with no orders\n        $modifiedCarts->addFieldToFilter('is_active', ['eq'=>1]);\n        // select carts for the current Magento store id\n        $modifiedCarts->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);\n        $modifiedCarts->getSelect()->reset(\\Zend_Db_Select::COLUMNS)->columns(['entity_id','customer_id','customer_email','mailchimp_campaign_id','quote_currency_code','grand_total']);\n\n        //join with mailchimp_ecommerce_sync_data table to filter by sync data.\n        $modifiedCarts->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE.\"'\n            AND m4m.mailchimp_store_id = '\" . $mailchimpStoreId . \"'\",\n            ['m4m.*']\n        );\n        // be sure that the quotes are already in mailchimp and not deleted\n        $modifiedCarts->getSelect()->where(\n            \"(m4m.mailchimp_sync_deleted is null or m4m.mailchimp_sync_deleted = 0)\".\n            \" AND m4m.mailchimp_sync_modified = 1\"\n        );\n        // limit the collection\n        $modifiedCarts->getSelect()->limit(self::BATCH_LIMIT);\n        /**\n         * @var $cart \\Magento\\Quote\\Model\\Quote\n         */\n        foreach ($modifiedCarts as $cart) {\n            $this->_token = $cart->getMailchimpToken();\n            $cartId = $cart->getEntityId();\n            /**\n             * @var $customer \\Magento\\Customer\\Model\\Customer\n             */\n            $customer = $this->_customerFactory->create();\n            $customer->setWebsiteId($this->_helper->getWebsiteId($magentoStoreId));\n            $customer->loadByEmail($cart->getCustomerEmail());\n\n            if ($customer->getEmail() != $cart->getCustomerEmail()) {\n                $allCartsForEmail = $this->_getAllCartsByEmail(\n                    $cart->getCustomerEmail(),\n                    $mailchimpStoreId,\n                    $magentoStoreId\n                );\n                /**\n                 * @var $cartForEmail \\Magento\\Quote\\Model\\Quote\n                 */\n                foreach ($allCartsForEmail as $cartForEmail) {\n                    $alreadySentCartId = $cartForEmail->getEntityId();\n                    if ($alreadySentCartId != $cartId) {\n                        $allCarts[$this->_counter]['method'] = 'DELETE';\n                        $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' .\n                            $alreadySentCartId;\n                        $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId;\n                        $allCarts[$this->_counter]['body'] = '';\n                        $this->_updateQuote(\n                            $mailchimpStoreId,\n                            $alreadySentCartId,\n                            null,\n                            null,\n                            null,\n                            1\n                        );\n                        $this->_counter += 1;\n                    }\n                }\n\n                $allCartsForEmail->clear();\n            }\n            // avoid carts abandoned as guests when customer email associated to a registered customer.\n            if (!$cart->getCustomerId() && $customer->getEmail()==$cart->getCustomerEmail()) {\n                $this->_updateQuote($mailchimpStoreId, $cartId);\n                continue;\n            }\n\n            // send the products that not already sent\n            try {\n                $productData = $this->_apiProduct->sendQuoteModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);\n            } catch (\\Exception $e) {\n                $error = $e->getMessage();\n                $this->_helper->log($error);\n                $this->_updateQuote($mailchimpStoreId, $cartId);\n                continue;\n            }\n            if (count($productData)) {\n                foreach ($productData as $p) {\n                    $allCarts[$this->_counter] = $p;\n                    $this->_counter += 1;\n                }\n            }\n\n            if (count($cart->getAllVisibleItems())) {\n                $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId);\n                if ($cartJson!==false) {\n                    if (!empty($cartJson)) {\n                        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::QUO_MOD);\n                        $allCarts[$this->_counter]['method'] = 'PATCH';\n                        $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId .\n                            '/carts/' . $cartId;\n                        $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId;\n                        $allCarts[$this->_counter]['body'] = $cartJson;\n                        $this->_counter += 1;\n                        $this->_updateQuote($mailchimpStoreId, $cartId);\n                    } else {\n                        $this->_updateQuote(\n                            $mailchimpStoreId,\n                            $cartId,\n                            $this->_helper->getGmtDate(),\n                            \"Cart is empty\",\n                            0\n                        );\n                    }\n                } else {\n                    $this->_updateQuote(\n                        $mailchimpStoreId,\n                        $cartId,\n                        $this->_helper->getGmtDate(),\n                        \"Json error\",\n                        0\n                    );\n                }\n            }\n        }\n        return $allCarts;\n    }\n\n    /**\n     * @param $mailchimpStoreId\n     * @return array\n     */\n    protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId)\n    {\n        $allCarts = [];\n        $newCarts = $this->_getQuoteCollection();\n        $newCarts->addFieldToFilter('is_active', ['eq'=>1]);\n        $newCarts->addFieldToFilter('customer_email', ['notnull'=>true]);\n        $newCarts->addFieldToFilter('items_count', ['gt'=>0]);\n        // select carts for the current Magento store id\n        $newCarts->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);\n        // filter by first date if exists.\n        if ($this->_firstDate) {\n            $newCarts->addFieldToFilter('created_at', ['gt' => $this->_firstDate]);\n        }\n        $newCarts->getSelect()->reset(\\Zend_Db_Select::COLUMNS)->columns(['entity_id','customer_id','customer_email','mailchimp_campaign_id','updated_at','quote_currency_code','grand_total']);\n\n        //join with mailchimp_ecommerce_sync_data table to filter by sync data.\n        $newCarts->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.entity_id and m4m.type = '\" . \\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE . \"'\n            AND m4m.mailchimp_store_id = '\" . $mailchimpStoreId . \"'\",\n            ['m4m.*']\n        );\n        // be sure that the quotes are already in mailchimp and not deleted\n        $newCarts->getSelect()->where(\"m4m.mailchimp_sync_delta IS NULL\");\n        // limit the collection\n        $newCarts->getSelect()->limit(self::BATCH_LIMIT);\n        /**\n         * @var $cart \\Magento\\Quote\\Model\\Quote\n         */\n        foreach ($newCarts as $cart) {\n            $this->_token = null;\n            $cartId = $cart->getEntityId();\n            $orderCollection = $this->_getOrderCollection();\n            $orderCollection->addFieldToFilter('main_table.customer_email', ['eq' => $cart->getCustomerEmail()])\n                ->addFieldToFilter('main_table.updated_at', ['from' => $cart->getUpdatedAt()]);\n            //if cart is empty or customer has an order made after the abandonment skip current cart.\n            if (!count($cart->getAllVisibleItems()) || $orderCollection->getSize()) {\n                $this->_updateQuote($mailchimpStoreId, $cartId);\n                continue;\n            }\n            $customer = $this->_customerFactory->create();\n            $customer->setWebsiteId($this->_helper->getWebsiteId($magentoStoreId));\n            $customer->loadByEmail($cart->getCustomerEmail());\n\n            if ($customer->getEmail() != $cart->getCustomerEmail()) {\n                $allCartsForEmail = $this->_getAllCartsByEmail(\n                    $cart->getCustomerEmail(),\n                    $mailchimpStoreId,\n                    $magentoStoreId\n                );\n                foreach ($allCartsForEmail as $cartForEmail) {\n                    $alreadySentCartId = $cartForEmail->getEntityId();\n                    $allCarts[$this->_counter]['method'] = 'DELETE';\n                    $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' .\n                        $alreadySentCartId;\n                    $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId;\n                    $allCarts[$this->_counter]['body'] = '';\n                    $this->_updateQuote(\n                        $mailchimpStoreId,\n                        $alreadySentCartId,\n                        null,\n                        null,\n                        null,\n                        1\n                    );\n                    $this->_counter += 1;\n                }\n\n                $allCartsForEmail->clear();\n            }\n\n            // don't send the carts for guest customers who are registered\n            if (!$cart->getCustomerId() && $customer->getEmail()==$cart->getCustomerEmail()) {\n                $this->_updateQuote(\n                    $mailchimpStoreId,\n                    $cartId,\n                    $this->_helper->getGmtDate(),\n                    null,\n                    0\n                );\n                continue;\n            }\n\n            // send the products that not already sent\n            try {\n                $productData = $this->_apiProduct->sendQuoteModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);\n            } catch (\\Exception $e) {\n                $error = $e->getMessage();\n                $this->_updateQuote($mailchimpStoreId, $cartId, $this->_helper->getGmtDate(), $error, 0);\n                continue;\n            }\n            if (count($productData)) {\n                foreach ($productData as $p) {\n                    $allCarts[$this->_counter] = $p;\n                    $this->_counter += 1;\n                }\n            }\n\n            $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId);\n            if ($cartJson!==false) {\n                if (!empty($cartJson)) {\n                    $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::QUO_NEW);\n                    $allCarts[$this->_counter]['method'] = 'POST';\n                    $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts';\n                    $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId;\n                    $allCarts[$this->_counter]['body'] = $cartJson;\n                    $this->_updateQuote($mailchimpStoreId, $cartId);\n                    $this->_counter += 1;\n                } else {\n                    $this->_updateQuote(\n                        $mailchimpStoreId,\n                        $cartId,\n                        $this->_helper->getGmtDate(),\n                        \"Cart is empty\",\n                        0\n                    );\n                }\n            } else {\n                $this->_updateQuote(\n                    $mailchimpStoreId,\n                    $cartId,\n                    $this->_helper->getGmtDate(),\n                    \"Json error\",\n                    0\n                );\n            }\n        }\n\n        return $allCarts;\n    }\n\n    /**\n     * Get all existing carts in the current store view for a given email address.\n     *\n     * @param $email\n     * @param $mailchimpStoreId\n     * @param $magentoStoreId\n     * @return object\n     */\n    protected function _getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId)\n    {\n        $allCartsForEmail = $this->_getQuoteCollection();\n        $allCartsForEmail->addFieldToFilter('is_active', ['eq' => 1]);\n        $allCartsForEmail->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);\n        $allCartsForEmail->addFieldToFilter('customer_email', ['eq' => $email]);\n        $allCartsForEmail->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE.\"'\n            AND m4m.mailchimp_store_id = '\" . $mailchimpStoreId . \"'\",\n            ['m4m.*']\n        );\n        // be sure that the quotes are already in mailchimp and not deleted\n        $allCartsForEmail->getSelect()->where(\"m4m.mailchimp_sync_deleted = 0\");\n        return $allCartsForEmail;\n    }\n\n    /**\n     * @param $cart\n     * @param $mailchimpStoreId\n     * @param $magentoStoreId\n     * @return string\n     */\n    protected function _makeCart(\\Magento\\Quote\\Model\\Quote $cart, $mailchimpStoreId, $magentoStoreId)\n    {\n        $campaignId = $cart->getMailchimpCampaignId();\n        $oneCart = [];\n        $oneCart['id'] = $cart->getEntityId();\n        $oneCart['customer'] = $this->_getCustomer($cart, $mailchimpStoreId, $magentoStoreId);\n        if ($campaignId) {\n            $oneCart['campaign_id'] = $campaignId;\n        }\n\n        $oneCart['checkout_url'] = $this->_getCheckoutUrl($cart, $magentoStoreId);\n        $oneCart['currency_code'] = $cart->getQuoteCurrencyCode();\n        $oneCart['order_total'] = $cart->getGrandTotal();\n        $oneCart['tax_total'] = 0;\n        $lines = [];\n        // get all items on the cart\n        $items = $cart->getAllVisibleItems();\n        $itemCount = 0;\n        /**\n         * @var $item \\Magento\\Quote\\Model\\Quote\\Item\n         */\n        foreach ($items as $item) {\n            $line = [];\n            if ($item->getProductType()==\\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE) {\n                $variant = null;\n                if ($item->getOptionByCode('simple_product')) {\n                    $variant = $item->getOptionByCode('simple_product')->getProduct();\n                }\n\n                if (!$variant) {\n                    continue;\n                }\n\n                $variantId = $variant->getId();\n            } elseif ($item->getProductType() == \\Magento\\Bundle\\Model\\Product\\Type::TYPE_CODE) {\n                $itemCount++;\n                $lines[] = [\n                    \"id\" => (string)$itemCount,\n                    \"product_id\" => $item->getProductId(),\n                    \"product_variant_id\" => $item->getProductId().'-min',\n                    \"quantity\" => (int)$item->getQtyOrdered(),\n                    \"price\" => 0\n                ];\n                $bundleProducts = $cart->getAllItems();\n                foreach ($bundleProducts as $bundleProduct) {\n                    if ($bundleProduct->getParentItemId() == $item->getItemId()) {\n                        $itemCount++;\n                        $lines[] = [\n                            \"id\" => (string)$itemCount,\n                            \"product_id\" => $bundleProduct-> getProductId(),\n                            \"product_variant_id\" => $bundleProduct-> getProductId(),\n                            \"quantity\" => (int)$bundleProduct->getQtyOrdered(),\n                            \"price\" => $bundleProduct->getPrice()\n                        ];\n                    }\n                }\n                continue;\n            } else {\n                $variantId = $item->getProductId();\n            }\n\n            //id can not be 0 so we add 1 to $itemCount before setting the id.\n            $itemCount++;\n            $line['id'] = (string)$itemCount;\n            $line['product_id'] = $item->getProductId();\n            $line['product_variant_id'] = $variantId;\n            $line['quantity'] = (int)$item->getQty();\n            $line['price'] = $item->getPrice();\n            $lines[] = $line;\n        }\n\n        $jsonData = \"\";\n        if ($itemCount) {\n            $oneCart['lines'] = $lines;\n            //enconde to JSON\n            $jsonData = json_encode($oneCart);\n            if ($jsonData === false) {\n                $jsonErrormsg = json_last_error_msg();\n                $this->_helper->log(\"\");\n                $this->_helper->log(\"$jsonErrormsg on cart [\".$cart->getId().\"]\");\n            }\n        }\n        return $jsonData;\n    }\n    /**\n     * @param \\Magento\\Quote\\Model\\Quote $cart\n     * @return string\n     */\n    protected function _getCheckoutUrl(\\Magento\\Quote\\Model\\Quote $cart, $storeId)\n    {\n        if (!$this->_token) {\n            $this->_token = hash('md5', rand(0, 9999999));\n        }\n        $url = $this->_helper->getCartUrl($storeId, $cart->getId(), $this->_token);\n        return $url;\n    }\n    protected function _getCustomer(\\Magento\\Quote\\Model\\Quote $cart, $mailchimpStoreId, $magentoStoreId)\n    {\n        $customer = [\n            'id' => hash('md5', strtolower($cart->getCustomerEmail())),\n            'email_address' => $cart->getCustomerEmail(),\n            'opt_in_status' => $this->_apiCustomer->getOptin($magentoStoreId)\n        ];\n\n        $firstName = $cart->getCustomerFirstname();\n        if ($firstName) {\n            $customer[\"first_name\"] = $firstName;\n        }\n\n        $lastName = $cart->getCustomerLastname();\n        if ($lastName) {\n            $customer[\"last_name\"] = $lastName;\n        }\n\n        $billingAddress = $cart->getBillingAddress();\n        if ($billingAddress) {\n            $street = $billingAddress->getStreet();\n            $address = [];\n            if ($street[0]) {\n                $address['address1'] = $street[0];\n            }\n\n            if (count($street) > 1) {\n                $address['address1'] = $street[1];\n            }\n\n            if ($billingAddress->getCity()) {\n                $address['city'] = $billingAddress->getCity();\n            }\n\n            if ($billingAddress->getRegion()) {\n                $address['province'] = $billingAddress->getRegion();\n            }\n\n            if ($billingAddress->getRegionCode()) {\n                $address['province_code'] = $billingAddress->getRegionCode();\n            }\n\n            if ($billingAddress->getPostcode()) {\n                $address['postal_code'] = $billingAddress->getPostcode();\n            }\n\n            if ($billingAddress->getCountryId()) {\n                /**\n                 * @var $country \\Magento\\Directory\\Model\\Country\n                 */\n                $country = $this->_countryFactory->create()->loadByCode($billingAddress->getCountryId());\n                $address['shipping_address']['country'] = $country->getName('en_US');\n                $address['shipping_address']['country_code'] = $billingAddress->getCountryId();\n            }\n\n            if (count($address)) {\n                $customer['address'] = $address;\n            }\n        }\n\n        //company\n//        if ($billingAddress->getCompany()) {\n//            $customer[\"company\"] = $billingAddress->getCompany();\n//        }\n\n        return $customer;\n    }\n\n    /**\n     * @return \\Magento\\Quote\\Model\\ResourceModel\\Quote\\Collection\n     */\n    protected function _getQuoteCollection()\n    {\n        return $this->_quoteCollection->create();\n    }\n\n    /**\n     * @return \\Magento\\Sales\\Model\\ResourceModel\\Order\\Collection\n     */\n    protected function _getOrderCollection()\n    {\n        return $this->_orderCollectionFactory->create();\n    }\n\n    /**\n     * @param $storeId\n     * @param $entityId\n     * @param $sync_delta\n     * @param $sync_error\n     * @param $sync_modified\n     * @param $sync_deleted\n     */\n    protected function _updateQuote(\n        $storeId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null,\n        $sync_deleted = null\n    ) {\n        $this->syncHelper->saveEcommerceData(\n            $storeId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE,\n            $sync_delta,\n            $sync_error,\n            $sync_modified,\n            $sync_deleted,\n            $this->_token\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Api/Customer.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/1/16 12:00 PM\n * @file: Customer.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Magento\\Directory\\Model\\CountryFactory;\nuse Magento\\Framework\\Exception\\State\\ExpiredException;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\nclass Customer\n{\n    const MAX           = 100;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory\n     */\n    protected $_collection;\n    /**\n     * @var \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory\n     */\n    protected $_orderCollection;\n    /**\n     * @var CountryFactory\n     */\n    protected $_countryFactory;\n    /**\n     * @var \\Magento\\Customer\\Model\\CustomerFactory\n     */\n    protected $_customerFactory;\n    /**\n     * @var \\Magento\\Customer\\Model\\Address\n     */\n    protected $_address;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $subscriberFactory;\n\n    /**\n     * @var string\n     */\n    protected $_batchId;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Customer\\Model\\CustomerFactory $customerFactory\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory $collection\n     * @param \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollection\n     * @param CountryFactory $countryFactory\n     * @param \\Magento\\Customer\\Model\\Address $address\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Customer\\Model\\CustomerFactory $customerFactory,\n        \\Magento\\Customer\\Model\\ResourceModel\\Customer\\CollectionFactory $collection,\n        \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollection,\n        \\Magento\\Directory\\Model\\CountryFactory $countryFactory,\n        \\Magento\\Customer\\Model\\Address $address,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n    ) {\n\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->_collection          = $collection;\n        $this->_orderCollection     = $orderCollection;\n        $this->_batchId             = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER. '_' .\n            $this->_helper->getGmtTimeStamp();\n        $this->_address             = $address;\n        $this->_customerFactory     = $customerFactory;\n        $this->_countryFactory      = $countryFactory;\n        $this->subscriberFactory    = $subscriberFactory;\n    }\n    public function sendCustomers($storeId)\n    {\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $storeId\n        );\n        $listId = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST, $storeId);\n        $collection = $this->_collection->create();\n        $collection->addFieldToFilter('store_id', ['eq'=>$storeId]);\n        $collection->getSelect()->reset(\\Zend_Db_Select::COLUMNS)->columns(['entity_id','store_id']);\n        $collection->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = e.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER.\n            \"' and m4m.mailchimp_store_id = '\".$mailchimpStoreId.\"'\",\n            ['m4m.*']\n        );\n        $collection->getSelect()->where(\"m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1\");\n        $collection->getSelect()->limit(self::MAX);\n        $counter = 0;\n        $customerArray = [];\n        $this->_helper->resetMapFields();\n\n        foreach ($collection as $item) {\n            $customer = $this->_customerFactory->create();\n            $customer->getResource()->load($customer, $item->getId());\n            $data           = $this->_buildCustomerData($customer);\n            $customerJson   = '';\n\n            $customerJson = json_encode($data);\n            if ($customerJson!==false) {\n                if (!empty($customerJson)) {\n                    if ($item->getMailchimpSyncModified() == 1) {\n                        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::CUS_MOD);\n                    } else {\n                        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::CUS_NEW);\n                    }\n                    $customerMailchimpId = hash('md5', strtolower($customer->getEmail()));\n                    $customerArray[$counter]['method'] = \"PUT\";\n                    $customerArray[$counter]['path'] = \"/ecommerce/stores/\" . $mailchimpStoreId . \"/customers/\" .\n                        $customerMailchimpId;\n                    $customerArray[$counter]['operation_id'] = $this->_batchId . '_' . $customer->getId();\n                    $customerArray[$counter]['body'] = $customerJson;\n                    $counter++;\n                    if (!$this->isSubscriber($customer)) {\n                        $subscriberData = $this->buildSubscriberData($customer);\n                        $subscriberJson = json_encode($subscriberData);\n                        if ($subscriberJson !==false) {\n                            $customerArray[$counter]['method'] = \"PATCH\";\n                            $customerArray[$counter]['path'] = \"/lists/\" . $listId . \"/members/\" .\n                                $customerMailchimpId;\n                            $customerArray[$counter]['operation_id'] = $this->_batchId . '_' .\n                                $customer->getId().'_SUB';\n                            $customerArray[$counter]['body'] = $subscriberJson;\n                            $counter++;\n                        }\n                    }\n                    //update customers delta\n                    $this->_updateCustomer($mailchimpStoreId, $customer->getId());\n                } else {\n                    $this->_updateCustomer(\n                        $mailchimpStoreId,\n                        $customer->getId(),\n                        $this->_helper->getGmtDate(),\n                        'Customer with no data',\n                        0\n                    );\n                }\n            } else {\n                $this->_updateCustomer(\n                    $mailchimpStoreId,\n                    $customer->getId(),\n                    $this->_helper->getGmtDate(),\n                    json_last_error_msg(),\n                    0\n                );\n            }\n        }\n        return $customerArray;\n    }\n    /**\n     * @param \\Magento\\Customer\\Model\\Customer $customer\n     * @return mixed\n     */\n    protected function buildSubscriberData(\\Magento\\Customer\\Model\\Customer $customer)\n    {\n        $data = [];\n        $data[\"merge_fields\"] = $this->_helper->getMergeVars($customer, $customer->getData('store_id'));\n        return $data;\n    }\n    protected function isSubscriber(\\Magento\\Customer\\Model\\Customer $customer)\n    {\n        $subscriber = $this->subscriberFactory->create();\n        $subscriber->loadByEmail($customer->getEmail());\n        if ($subscriber->getEmail() == $customer->getEmail()) {\n            if ($subscriber->getStatus() === \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    /**\n     * @param \\Magento\\Customer\\Model\\Customer $customer\n     * @return array\n     */\n    protected function _buildCustomerData(\\Magento\\Customer\\Model\\Customer $customer)\n    {\n        $point = 0;\n        $data = [];\n        $data[\"id\"] = hash('md5', strtolower($customer->getEmail()));\n        $data[\"email_address\"] = $customer->getEmail() ? $customer->getEmail() : '';\n        $data[\"first_name\"] = $customer->getFirstname() ? $customer->getFirstname() : '';\n        $data[\"last_name\"] = $customer->getLastname() ? $customer->getLastname() : '';\n        $data[\"opt_in_status\"] = $this->getOptin();\n        // customer order data\n        $orderCollection = $this->_orderCollection->create();\n        $orderCollection->addFieldToFilter('state', [\n            ['neq',\\Magento\\Sales\\Model\\Order::STATE_CANCELED],\n            ['neq',\\Magento\\Sales\\Model\\Order::STATE_CLOSED]])\n            ->addAttributeToFilter('customer_id', ['eq' => $customer->getId()]);\n        $totalOrders = 0;\n        $totalAmountSpent = 0;\n        /**\n         * @var $customerOrder \\Magento\\Sales\\Model\\Order\n         */\n        foreach ($orderCollection as $customerOrder) {\n            $totalOrders++;\n            $totalAmountSpent += $customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded()\n                - $customerOrder->getTotalCanceled();\n        }\n        $data['orders_count']   = $totalOrders;\n        $data['total_spent']    = $totalAmountSpent;\n        $address = $customer->getDefaultBillingAddress();\n        if ($address) {\n            $customerAddress = [];\n            if ($street = $address->getStreet()) {\n                $street = $address->getStreet();\n                if ($street[0]) {\n                    $customerAddress[\"address1\"] = $street[0];\n                }\n                if (count($street) > 1) {\n                    $customerAddress[\"address2\"] = $street[1];\n                }\n            }\n            if ($address->getCity()) {\n                $customerAddress[\"city\"] = $address->getCity();\n            }\n            if ($address->getRegion()) {\n                $customerAddress[\"province\"] = $address->getRegion();\n            }\n            if ($address->getRegionCode()) {\n                $customerAddress[\"province_code\"] = $address->getRegionCode();\n            }\n            if ($address->getPostcode()) {\n                $customerAddress[\"postal_code\"] = $address->getPostcode();\n            }\n            if ($address->getCountryId()) {\n                /**\n                 * @var $country \\Magento\\Directory\\Model\\Country\n                 */\n                $country = $this->_countryFactory->create()->loadByCode($address->getCountryId());\n                $customerAddress[\"country\"] = preg_replace('/\\&/', 'and',$country->getName('en_US'));\n                $customerAddress[\"country_code\"] = $address->getCountryId();\n            }\n            if (count($customerAddress)) {\n                $data[\"address\"] = $customerAddress;\n            }\n        }\n        return $data;\n    }\n\n    public function getOptin($storeId = 0)\n    {\n        if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_ECOMMERCE_OPTIN, $storeId)) {\n            $optin = true;\n        } else {\n            $optin = false;\n        }\n        return $optin;\n    }\n    protected function _updateCustomer(\n        $storeId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null\n    ) {\n        $this->syncHelper->saveEcommerceData(\n            $storeId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER,\n            $sync_delta,\n            $sync_error,\n            $sync_modified,\n            null,\n            null,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::WAITINGSYNC\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Api/Order.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/21/16 3:51 PM\n * @file: Order.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Magento\\SalesRule\\Model\\RuleRepository;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\nuse Magento\\Bundle\\Model\\Product\\Type as ProductTypeBundle;\n\nclass Order\n{\n    const BATCH_LIMIT = 50;\n    const PAID = 'paid';\n    const PARTIALLY_PAID = 'partially_paid';\n    const SHIPPED = 'shipped';\n    const PARTIALLY_SHIPPED = 'partially_shipped';\n    const PENDING = 'pending';\n    const REFUNDED = 'refunded';\n    const PARTIALLY_REFUNDED = 'partially_refunded';\n    const CANCELED = 'cancelled';\n    const COMPLETE = 'complete';\n\n    protected $_api = null;\n\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Sales\\Model\\Order\n     */\n    protected $_order;\n    /**\n     * @var \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory\n     */\n    protected $_orderCollectionFactory;\n    /**\n     * @var Product\n     */\n    protected $_apiProduct;\n    /**\n     * @var \\Magento\\Catalog\\Model\\ResourceModel\\Product\n     */\n    protected $_product;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Customer\n     */\n    protected $_apiCustomer;\n    /**\n     * @var \\Magento\\Directory\\Model\\CountryFactory\n     */\n    protected $_countryFactory;\n    /**\n     * @var \\Magento\\Catalog\\Model\\ProductFactory\n     */\n    protected $_productFactory;\n    /**\n     * @var \\Magento\\SalesRule\\Model\\Coupon\n     */\n    protected $couponRepository;\n    /**\n     * @var RuleRepository\n     */\n    protected $ruleRepository;\n    /**\n     * @var \\Magento\\Framework\\Url\n     */\n    protected $_urlHelper;\n    protected $_chimpSyncEcommerce;\n    protected $_firstDate;\n    protected $_counter;\n    protected $_batchId;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Sales\\Model\\OrderRepository $order\n     * @param \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollectionFactory\n     * @param \\Magento\\Catalog\\Model\\ResourceModel\\Product $product\n     * @param Product $apiProduct\n     * @param Customer $apiCustomer\n     * @param \\Magento\\Catalog\\Model\\ProductFactory $productFactory\n     * @param \\Magento\\Directory\\Model\\CountryFactory $countryFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimpSyncEcommerce\n     * @param \\Magento\\SalesRule\\Model\\Coupon $couponRepository\n     * @param RuleRepository $ruleRepository\n     * @param \\Magento\\Framework\\Url $urlHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Sales\\Model\\OrderRepository $order,\n        \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollectionFactory,\n        \\Magento\\Catalog\\Model\\ResourceModel\\Product $product,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Product $apiProduct,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Customer $apiCustomer,\n        \\Magento\\Catalog\\Model\\ProductFactory $productFactory,\n        \\Magento\\Directory\\Model\\CountryFactory $countryFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimpSyncEcommerce,\n        \\Magento\\SalesRule\\Model\\Coupon $couponRepository,\n        \\Magento\\SalesRule\\Model\\RuleRepository $ruleRepository,\n        \\Magento\\Framework\\Url $urlHelper\n    ) {\n\n        $this->_helper          = $helper;\n        $this->syncHelper       = $syncHelper;\n        $this->_order           = $order;\n        $this->_orderCollectionFactory = $orderCollectionFactory;\n        $this->_apiProduct      = $apiProduct;\n        $this->_productFactory   = $productFactory;\n        $this->_product         = $product;\n        $this->_apiCustomer     = $apiCustomer;\n        $this->_countryFactory  = $countryFactory;\n        $this->_chimpSyncEcommerce  = $chimpSyncEcommerce;\n        $this->_batchId         = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER. '_' . $this->_helper->getGmtTimeStamp();\n        $this->_counter = 0;\n        $this->_urlHelper    = $urlHelper;\n        $this->couponRepository = $couponRepository;\n        $this->ruleRepository = $ruleRepository;\n    }\n\n    /**\n     * Set the request for orders to be created on MailChimp\n     *\n     * @param $mailchimpStoreId\n     * @param $magentoStoreId\n     * @return array\n     */\n    public function sendOrders($magentoStoreId)\n    {\n        $batchArray = [];\n        $this->_firstDate = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_ECOMMERCE_FIRSTDATE, $magentoStoreId);\n\n        // get all the orders modified\n        $batchArray = array_merge($batchArray, $this->_getModifiedOrders($magentoStoreId));\n        // get new orders\n        $batchArray = array_merge($batchArray, $this->_getNewOrders($magentoStoreId));\n        return $batchArray;\n    }\n    protected function _getCollection()\n    {\n        return $this->_orderCollectionFactory->create();\n    }\n    protected function _getModifiedOrders($magentoStoreId)\n    {\n        $batchArray = [];\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $magentoStoreId\n        );\n        $isSynced = $this->_helper->getMCMinSyncDateFlag($magentoStoreId);\n        $modifiedOrders = $this->_getCollection();\n        // select orders for the current Magento store id\n        $modifiedOrders->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);\n        $modifiedOrders->addFieldToSelect(['store_id','created_at']);\n        //join with mailchimp_ecommerce_sync_data table to filter by sync data.\n        $modifiedOrders->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER.\n            \"' and m4m.mailchimp_store_id = '\".$mailchimpStoreId.\"'\",\n            ['m4m.*']\n        );\n        // be sure that the order are already in mailchimp and not deleted\n        $modifiedOrders->getSelect()->where(\n            \"m4m.mailchimp_sync_modified = 1 AND m4m.mailchimp_store_id = '\".$mailchimpStoreId.\"'\"\n        );\n        // limit the collection\n        $modifiedOrders->getSelect()->limit(self::BATCH_LIMIT);\n        /**\n         * @var $order \\Magento\\Sales\\Model\\Order\n         */\n        foreach ($modifiedOrders as $item) {\n            try {\n                $error = '';\n                $orderId = $item->getEntityId();\n                $order = $this->_order->get($orderId);\n                //create missing products first\n                try {\n                    $productData = $this->_apiProduct->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId);\n                } catch (\\Exception $e) {\n                    $error = $e->getMessage();\n                    $this->_helper->log($error);\n                    $this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);\n                    continue;\n                }\n                if (count($productData)) {\n                    foreach ($productData as $p) {\n                        $batchArray[$this->_counter] = $p;\n                        $this->_counter++;\n                    }\n                }\n\n                $payLoadReturn = $this->generatePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, true, $isSynced);\n                $orderJson = $payLoadReturn['jsonOrder'];\n                $payLoadError = $payLoadReturn['error'];\n                if ($orderJson) {\n                    $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::ORD_MOD);\n                    $batchArray[$this->_counter]['method'] = \"PATCH\";\n                    $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' .\n                        $order->getIncrementId();\n                    $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId;\n                    $batchArray[$this->_counter]['body'] = $orderJson;\n                    //update order delta\n                    $this->_updateOrder($mailchimpStoreId, $orderId);\n                    $this->_counter++;\n                } else {\n                    $error = __($payLoadError);\n                    $this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);\n                    continue;\n                }\n            } catch (Exception $e) {\n                $this->_helper->log($e->getMessage());\n                $error = $e->getMessage();\n                $this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);\n            }\n        }\n        return $batchArray;\n    }\n\n    protected function _getNewOrders($magentoStoreId)\n    {\n        $batchArray = [];\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $magentoStoreId\n        );\n        $isSynced = $this->_helper->getMCMinSyncDateFlag($magentoStoreId);\n        $newOrders = $this->_getCollection();\n        // select carts for the current Magento store id\n        $newOrders->addFieldToFilter('store_id', ['eq' => $magentoStoreId]);\n        $newOrders->addFieldToSelect(['store_id','created_at']);\n        // filter by first date if exists.\n        if ($this->_firstDate) {\n            $newOrders->addFieldToFilter('created_at', ['gt' => $this->_firstDate]);\n        }\n        $newOrders->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER.\n            \"' and m4m.mailchimp_store_id = '\".$mailchimpStoreId.\"'\",\n            ['m4m.*']\n        );\n        // be sure that the quote are not in mailchimp\n        $newOrders->getSelect()->where(\"m4m.mailchimp_sync_delta IS NULL\");\n        // limit the collection\n        $newOrders->getSelect()->limit(self::BATCH_LIMIT);\n\n        /**\n         * @var $order \\Magento\\Sales\\Model\\Order\n         */\n        foreach ($newOrders as $item) {\n            try {\n                $error = '';\n                $orderId = $item->getEntityId();\n                $order = $this->_order->get($orderId);\n                //create missing products first\n                try {\n                    $productData = $this->_apiProduct->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId);\n                } catch (\\Exception $e) {\n                    $error = $e->getMessage();\n                    $this->_helper->log($error);\n                    $this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);\n                    continue;\n                }\n                if (count($productData)) {\n                    foreach ($productData as $p) {\n                        $batchArray[$this->_counter] = $p;\n                        $this->_counter++;\n                    }\n                }\n                $payLoadReturn = $this->generatePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, false, $isSynced);\n                $orderJson = $payLoadReturn['jsonOrder'];\n                $payLoadError = $payLoadReturn['error'];\n                if ($orderJson) {\n                    $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::ORD_NEW);\n                    $batchArray[$this->_counter]['method'] = \"POST\";\n                    $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders';\n                    $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId;\n                    $batchArray[$this->_counter]['body'] = $orderJson;\n                    //update order delta\n                    $this->_updateOrder($mailchimpStoreId, $orderId);\n                    $this->_counter++;\n                } else {\n                    $error = __($payLoadError);\n                    $this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);\n                    continue;\n                }\n            } catch (Exception $e) {\n                $this->_helper->log(\"Can't load the order $orderId\");\n                $this->_helper->log($e->getMessage());\n                $error = $e->getMessage();\n                $this->_updateOrder($mailchimpStoreId, $orderId, $this->_helper->getGmtDate(), $error, 0);\n            }\n        }\n        return $batchArray;\n    }\n\n    /**\n     * Set all the data for each order to be sent\n     *\n     * @param $order\n     * @param $mailchimpStoreId\n     * @param $magentoStoreId\n     * @param $isModifiedOrder\n     * @return array\n     */\n    protected function generatePOSTPayload(\n        \\Magento\\Sales\\Model\\Order $order,\n        $mailchimpStoreId,\n        $magentoStoreId,\n        $isModifiedOrder,\n        $isSynced\n    ) {\n        if (!$order->getCustomerEmail()) {\n            return ['error' => 'Customer email is empty', 'jsonOrder' => null];\n        }\n        $data = [];\n        $data['id'] = $order->getIncrementId();\n        if ($order->getMailchimpCampaignId()) {\n            $data['campaign_id'] = $order->getMailchimpCampaignId();\n        } elseif ($isSynced) {\n            if (!$isModifiedOrder && $campaignId = $this->getCampaign($magentoStoreId, $order->getCustomerEmail())) {\n                $data['campaign_id'] = $campaignId;\n                $order->setMailchimpCampaignId($campaignId);\n                $order->setMailchimpFlag(1);\n            }\n        }\n\n        if ($order->getMailchimpLandingPage()) {\n            $data['landing_site'] = $order->getMailchimpLandingPage();\n        }\n        $data['currency_code'] = $order->getOrderCurrencyCode();\n        $dataPromo = $this->_getPromoData($order);\n        if ($dataPromo !== null) {\n            $data['promos'] = $dataPromo;\n        }\n        $statusArray = $this->_getMailChimpStatus($order);\n        if (isset($statusArray['financial_status'])) {\n            $data['financial_status'] = $statusArray['financial_status'];\n        }\n\n        if (isset($statusArray['fulfillment_status'])) {\n            $data['fulfillment_status'] = $statusArray['fulfillment_status'];\n            $trackNumber = $title = '';\n            $shipments = $order->getShipmentsCollection();\n            /**\n             * @var $ship \\Magento\\Sales\\Model\\Order\\Shipment\n             */\n            foreach ($shipments as $ship) {\n                $tracks = $ship->getAllTracks();\n                foreach ($tracks as $track) {\n                    $title = $track->getTitle();\n                    $trackNumber = $track->getTrackNumber();\n                }\n            }\n            $data['tracking_number'] = $trackNumber;\n            $data['tracking_carrier'] = $title;\n            $data['tracking_url'] = '';\n        }\n\n        $data['processed_at_foreign'] = $order->getCreatedAt();\n        $data['updated_at_foreign'] = $order->getUpdatedAt();\n        if ($order->getState() == \\Magento\\Sales\\Model\\Order::STATE_CANCELED) {\n            $orderCancelDate = null;\n            $commentCollection = $order->getStatusHistoryCollection();\n            /**\n             * @var $comment \\Magento\\Sales\\Model\\Order\\Status\\History\n             */\n            foreach ($commentCollection as $comment) {\n                if ($comment->getStatus() === \\Magento\\Sales\\Model\\Order::STATE_CANCELED) {\n                    $orderCancelDate = $comment->getCreatedAt();\n                }\n            }\n\n            if ($orderCancelDate) {\n                $data['cancelled_at_foreign'] = $orderCancelDate;\n            }\n            $data['order_total'] = 0;\n            $data['tax_total'] = 0;\n            $data['discount_total'] = 0;\n            $data['shipping_total'] = 0;\n        } else {\n            $data['order_total'] = $order->getGrandTotal();\n            $data['tax_total'] = $order->getTaxAmount();\n            $data['discount_total'] = $order->getDiscountAmount() ? abs($order->getDiscountAmount()) : 0;\n            $data['shipping_total'] = $order->getShippingAmount();\n        }\n\n        $data['lines'] = [];\n\n        //order lines\n        try {\n            $items = $order->getAllVisibleItems();\n            $itemCount = 0;\n        } catch (\\Exception $e) {\n            $this->_helper->log(\"Can't load all the visible items\");\n            throw $e;\n        }\n        /**\n         * @var $item \\Magento\\Sales\\Model\\Order\\Item\n         */\n        foreach ($items as $item) {\n            $variant = null;\n            try {\n                $productSyncData = $this->syncHelper->getChimpSyncEcommerce(\n                    $mailchimpStoreId,\n                    $item->getProductId(),\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT\n                );\n            } catch (\\Exception $e){\n                $this->_helper->log($e->getMessage());\n                continue;\n            }\n            if ($productSyncData->getRelatedId()!=$item->getProductId()||($productSyncData->getRelatedId()==$item->getProductId()&&$productSyncData->getMailchimpSyncDeleted()==1)) {\n                continue;\n            }\n            if ($item->getProductType() == \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE) {\n                $options = $item->getProductOptions();\n                if (!isset($options['simple_sku'])) {\n                    $this->_helper->log('The product ['.$item->getId().'] has no simple_sku');\n                    continue;\n                }\n                $sku = $options['simple_sku'];\n                $variant = $this->_productFactory->create()->getIdBySku($sku);\n                if (!$variant) {\n                    continue;\n                }\n            } elseif ($item->getProductType() == \\Magento\\Bundle\\Model\\Product\\Type::TYPE_CODE) {\n                $itemCount++;\n                $data[\"lines\"][] = [\n                    \"id\" => (string)$itemCount,\n                    \"product_id\" => $item->getProductId(),\n                    \"product_variant_id\" => $item-> getProductId().'-min',\n                    \"quantity\" => (int)$item->getQtyOrdered(),\n                    \"price\" => 0,\n                    \"discount\" => 0\n                ];\n                $bundleProducts = $order->getAllItems();\n                foreach ($bundleProducts as $bundleProduct) {\n                    if ($bundleProduct->getParentItemId() == $item->getItemId()) {\n                        $itemCount++;\n                        $data[\"lines\"][] = [\n                            \"id\" => (string)$itemCount,\n                            \"product_id\" => $bundleProduct-> getProductId(),\n                            \"product_variant_id\" => $bundleProduct-> getProductId(),\n                            \"quantity\" => (int)$bundleProduct->getQtyOrdered(),\n                            \"price\" => $bundleProduct->getPrice(),\n                            \"discount\" => $bundleProduct->getDiscountAmount() ? abs($bundleProduct->getDiscountAmount()) : 0\n                        ];\n                    }\n                }\n                continue;\n            } else {\n                $variant = $item->getProductId();\n            }\n            if ($productSyncData->getRelatedId() == $item->getProductId() &&\n                $productSyncData->getMailchimpSyncError() == '' && $variant) {\n                $itemCount++;\n                $data[\"lines\"][] = [\n                    \"id\" => (string)$itemCount,\n                    \"product_id\" => $item->getProductId(),\n                    \"product_variant_id\" => $variant,\n                    \"quantity\" => (int)$item->getQtyOrdered(),\n                    \"price\" => $item->getPrice(),\n                    \"discount\" => $item->getDiscountAmount() ? abs($item->getDiscountAmount()) : 0\n                ];\n            }\n        }\n        if (!$itemCount) {\n            unset($data['lines']);\n            return ['error' => 'Order is empty', 'jsonOrder' => null];\n        }\n\n        //customer data\n        $data['customer'] = [\n            'id' => hash('md5', strtolower($order->getCustomerEmail())),\n            'email_address' => $order->getCustomerEmail(),\n            'opt_in_status' => $this->_apiCustomer->getOptin($magentoStoreId)\n        ];\n\n        $data['order_url'] = $this->_urlHelper->getUrl(\n            'sales/order/view/',\n            [\n                'order_id' => $order->getId(),\n                '_nosid' => true,\n                '_secure' => true\n            ]\n        );\n        if ($order->getCustomerFirstname()) {\n            $data[\"customer\"][\"first_name\"] = $order->getCustomerFirstname();\n        }\n\n        if ($order->getCustomerLastname()) {\n            $data[\"customer\"][\"last_name\"] = $order->getCustomerLastname();\n        }\n        $billingAddress = $order->getBillingAddress();\n        if ($billingAddress) {\n            if ($order->getCustomerIsGuest()) {\n                if ($billingAddress->getFirstname()) {\n                    $data[\"customer\"][\"first_name\"] = $billingAddress->getFirstname();\n                }\n                if ($billingAddress->getLastname()) {\n                    $data[\"customer\"][\"last_name\"] = $billingAddress->getLastname();\n                }\n            }\n\n            $street = $billingAddress->getStreet();\n            $address = [];\n\n            if ($street[0]) {\n                $address[\"address1\"] = $street[0];\n                $data['billing_address'][\"address1\"] = $street[0];\n            }\n\n            if (array_key_exists(1, $street)) {\n                $address[\"address2\"] = $street[1];\n                $data['billing_address'][\"address2\"] = $street[1];\n            }\n            if (array_key_exists(2, $street)) {\n                if (array_key_exists('address2', $address)) {\n                    $address[\"address2\"] = $address['address2'] . \", \" . $street[2];\n                    $data['billing_address'][\"address2\"] = $data['billing_address'][\"address2\"] . \", \" . $street[2];\n                } else {\n                    $address[\"address2\"] = $street[2];\n                    $data['billing_address'][\"address2\"] = $street[2];\n                }\n            }\n\n            if ($billingAddress->getCity()) {\n                $address[\"city\"] = $billingAddress->getCity();\n                $data['billing_address'][\"city\"] = $billingAddress->getCity();\n            }\n\n            if ($billingAddress->getRegion()) {\n                $address[\"province\"] = $billingAddress->getRegion();\n                $data['billing_address'][\"province\"] = $billingAddress->getRegion();\n            }\n\n            if ($billingAddress->getRegionCode()) {\n                $address[\"province_code\"] = $billingAddress->getRegionCode();\n                $data['billing_address'][\"province_code\"] = $billingAddress->getRegionCode();\n            }\n\n            if ($billingAddress->getPostcode()) {\n                $address[\"postal_code\"] = $billingAddress->getPostcode();\n                $data['billing_address'][\"postal_code\"] = $billingAddress->getPostcode();\n            }\n\n            if ($billingAddress->getCountryId()) {\n                /**\n                 * @var $country \\Magento\\Directory\\Model\\Country\n                 */\n                $country = $this->_countryFactory->create()->loadByCode($billingAddress->getCountryId());\n                $address[\"country\"] = $data['billing_address']['country'] = $country->getName('en_US');\n                $address[\"country_code\"] = $data['billing_address']['country_code'] = $billingAddress->getCountryId();\n            }\n            if (count($address)) {\n                $data[\"customer\"][\"address\"] = $address;\n            }\n\n            if ($billingAddress->getName()) {\n                $data['billing_address']['name'] = $billingAddress->getName();\n            }\n\n            //company\n            if ($billingAddress->getCompany()) {\n                $data[\"customer\"][\"company\"] = $billingAddress->getCompany();\n                $data[\"billing_address\"][\"company\"] = $billingAddress->getCompany();\n            }\n        } else {\n            $this->_helper->log(\"Order [\".$order->getId().\"] as no billing address\");\n            return ['error' => \"Order [\".$order->getId().\"] as no billing address\", 'jsonOrder' => null];\n        }\n        $shippingAddress = $order->getShippingAddress();\n        if ($shippingAddress) {\n            $street = $shippingAddress->getStreet();\n            if ($shippingAddress->getName()) {\n                $data['shipping_address']['name'] = $shippingAddress->getName();\n            }\n            if ($street[0]) {\n                $data['shipping_address'][\"address1\"] = $street[0];\n            }\n\n            if (array_key_exists(1, $street)) {\n                $data['shipping_address'][\"address2\"] = $street[1];\n            }\n            if (array_key_exists(2, $street)) {\n                if (array_key_exists('address2',$data['shipping_address'])) {\n                    $data['shipping_address'][\"address2\"] = $data['shipping_address'][\"address2\"] . \", \" . $street[2];\n                } else {\n                    $data['shipping_address'][\"address2\"] = $street[2];\n                }\n            }\n            if ($shippingAddress->getCity()) {\n                $data['shipping_address']['city'] = $shippingAddress->getCity();\n            }\n\n            if ($shippingAddress->getRegion()) {\n                $data['shipping_address']['province'] = $shippingAddress->getRegion();\n            }\n\n            if ($shippingAddress->getRegionCode()) {\n                $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode();\n            }\n\n            if ($shippingAddress->getPostcode()) {\n                $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode();\n            }\n\n            if ($shippingAddress->getCountryId()) {\n                /**\n                 * @var $country \\Magento\\Directory\\Model\\Country\n                 */\n                $country = $this->_countryFactory->create()->loadByCode($shippingAddress->getCountryId());\n                $data['shipping_address'][\"country\"] = $country->getName('en_US');\n                $data['shipping_address'][\"country_code\"] = $shippingAddress->getCountryId();\n            }\n            if ($shippingAddress->getCompany()) {\n                $data[\"shipping_address\"][\"company\"] = $shippingAddress->getCompany();\n            }\n        }\n        //customer orders data\n        $orderCollection = $this->_orderCollectionFactory->create();\n        $orderCollection->addFieldToFilter('state', [\n            ['neq' => \\Magento\\Sales\\Model\\Order::STATE_CANCELED],\n            ['neq' => \\Magento\\Sales\\Model\\Order::STATE_CLOSED]])\n            ->addAttributeToFilter('customer_email', ['eq' => $order->getCustomerEmail()]);\n\n        $orderCollection\n            ->getSelect()\n            ->reset(\\Zend_Db_Select::COLUMNS)\n            ->columns(['grand_total', 'total_refunded', 'total_canceled']);\n\n        $totalOrders = 0;\n        $totalAmountSpent = 0;\n        /**\n         * @var $customerOrder \\Magento\\Sales\\Model\\Order\n         */\n        foreach ($orderCollection as $customerOrder) {\n            $totalOrders++;\n            $totalAmountSpent += $customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded()\n                - $customerOrder->getTotalCanceled();\n        }\n\n        $data[\"customer\"][\"orders_count\"] = $totalOrders;\n        $data[\"customer\"][\"total_spent\"] = $totalAmountSpent;\n        $jsonData = \"\";\n\n        //enconde to JSON\n        $jsonData = json_encode($data);\n        if ($jsonData===false) {\n            $jsonError = json_last_error();\n            $jsonErrorMsg = json_last_error_msg();\n            $this->_helper->log('');\n            $this->_helper->log(\"$jsonErrorMsg on order [\".$order->getEntityId().\"]\");\n        }\n        return ['error' =>  null, 'jsonOrder' => $jsonData];\n    }\n\n    protected function _getMailChimpStatus(\\Magento\\Sales\\Model\\Order $order)\n    {\n        $mailChimpFinancialStatus = null;\n        $mailChimpFulfillmentStatus = null;\n        $totalItemsOrdered = $order->getData('total_qty_ordered');\n        $shippedItemAmount = 0;\n        $invoicedItemAmount = 0;\n        $refundedItemAmount = 0;\n        $mailChimpStatus = [];\n        /**\n         * @var $item \\Magento\\Sales\\Model\\Order\\Item\n         */\n        foreach ($order->getAllVisibleItems() as $item) {\n            $shippedItemAmount += $item->getQtyShipped();\n            $invoicedItemAmount += $item->getQtyInvoiced();\n            $refundedItemAmount += $item->getQtyRefunded();\n        }\n\n        if ($shippedItemAmount > 0) {\n            if ($totalItemsOrdered > $shippedItemAmount) {\n                $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED;\n            } else {\n                $mailChimpFulfillmentStatus = self::SHIPPED;\n            }\n        }\n\n        if ($refundedItemAmount > 0) {\n            if ($totalItemsOrdered > $refundedItemAmount) {\n                $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED;\n            } else {\n                $mailChimpFinancialStatus = self::REFUNDED;\n            }\n        }\n\n        if ($invoicedItemAmount > 0) {\n            if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) {\n                if ($totalItemsOrdered > $invoicedItemAmount) {\n                    $mailChimpFinancialStatus = self::PARTIALLY_PAID;\n                } else {\n                    $mailChimpFinancialStatus = self::PAID;\n                }\n            }\n        }\n\n        if (!$mailChimpFinancialStatus && $order->getState() == \\Magento\\Sales\\Model\\Order::STATE_CANCELED) {\n            $mailChimpFinancialStatus = self::CANCELED;\n        }\n\n        if (!$mailChimpFinancialStatus) {\n            $mailChimpFinancialStatus = self::PENDING;\n        }\n\n        if ($mailChimpFinancialStatus) {\n            $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus;\n        }\n\n        if ($mailChimpFulfillmentStatus) {\n            $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus;\n        }\n\n        return $mailChimpStatus;\n    }\n\n    protected function _getPromoData(\\Magento\\Sales\\Model\\Order $order)\n    {\n        $promo = null;\n        try {\n            $couponCode = $order->getCouponCode();\n            if ($couponCode !== null) {\n                $code = $this->couponRepository->loadByCode($couponCode);\n                if ($code->getCouponId() !== null) {\n                    $rule = $this->ruleRepository->getById($code->getRuleId());\n                    if ($rule->getRuleId() !== null) {\n                        $amountDiscounted = $order->getBaseDiscountAmount() ? $order->getBaseDiscountAmount() : 0;\n                        $type = $rule->getSimpleAction();\n                        if ($type == 'by_percent') {\n                            $type = 'percentage';\n                        } else {\n                            $type = 'fixed';\n                        }\n\n                        $promo = [[\n                            'code' => $couponCode,\n                            'amount_discounted' => abs($amountDiscounted),\n                            'type' => $type\n                        ]];\n                    }\n                }\n            }\n        } catch(\\Exception $e) {\n            $this->_helper->log($e->getMessage());\n        }\n        return $promo;\n    }\n    protected function getCampaign($store, $email)\n    {\n        $campaign_id = null;\n        $api = $this->_helper->getApi($store);\n        $actions = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_CAMPAIGN_ACTION, $store);\n        try {\n            $activity = $api->lists->members->memberActivity->get($this->_helper->getDefaultList($store), hash('md5', $email), null, null, $actions);\n            if ($activity) {\n                foreach ($activity['activity'] as $act) {\n                    if (key_exists('action', $act) && key_exists('campaign_id', $act) && $act['campaign_id']) {\n                        $campaign_id = $act['campaign_id'];\n                        break;\n                    }\n                }\n            }\n        } catch (\\Mailchimp_Error $e) {\n            $this->_helper->log(\"No activity for $email\");\n        }\n        return $campaign_id;\n    }\n    protected function _updateOrder($storeId, $entityId, $sync_delta = null, $sync_error = null, $sync_modified = null)\n    {\n        if (!empty($sync_error)) {\n            $sent = \\Ebizmarts\\MailChimp\\Helper\\Data::NOTSYNCED;\n        } else {\n            $sent = \\Ebizmarts\\MailChimp\\Helper\\Data::WAITINGSYNC;\n        }\n        $this->syncHelper->saveEcommerceData(\n            $storeId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER,\n            $sync_delta,\n            $sync_error,\n            $sync_modified,\n            null,\n            null,\n            $sent\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Api/Product.php",
    "content": "<?php\n/**\n\nmc-magento2 Magento Component\n@category Ebizmarts\n@Package mc-magento2\n@author Ebizmarts Team info@ebizmarts.com\n@copyright Ebizmarts (http://ebizmarts.com)\n@license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)\n@Date: 10/10/16 5:22 PM\n@file: Product.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\nuse Magento\\Framework\\Exception\\NoSuchEntityException;\nuse Magento\\Bundle\\Model\\Product\\Type as ProductTypeBundle;\n\nclass Product\n{\n    const DOWNLOADABLE = 'downloadable';\n    const GROUPED = 'grouped';\n    const PRODUCTIMAGE = 'product_small_image';\n    const MAX = 100;\n\n    protected $_parentImage = null;\n    protected $_childtUrl   = null;\n    protected $productPrice = null;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Catalog\\Model\\ProductRepository\n     */\n    protected $_productRepository;\n    /**\n     * @var \\Magento\\Catalog\\Model\\ResourceModel\\Product\\CollectionFactory\n     */\n    protected $_productCollection;\n    /**\n     * @var \\Magento\\Catalog\\Helper\\Image\n     */\n    protected $_imageHelper;\n    /**\n     * @var \\Magento\\CatalogInventory\\Api\\StockRegistryInterface\n     */\n    protected $_stockRegistry;\n    /**\n     * @var \\Magento\\Catalog\\Model\\CategoryRepository\n     */\n    protected $_categoryRepository;\n    /**\n     * @var string\n     */\n    protected $_batchId;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory\n     */\n    protected $_chimpSyncEcommerce;\n    /**\n     * @var \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable\n     */\n    protected $_configurable;\n    /**\n     * @var \\Magento\\Catalog\\Helper\\Data\n     */\n    protected $taxHelper;\n    /**\n     * @var \\Magento\\Catalog\\Model\\Product\\Option\n     */\n    protected $_option;\n    /**\n     * @var \\Magento\\Catalog\\Model\\ResourceModel\\Category\\CollectionFactory\n     */\n    protected $_categoryCollection;\n    protected $includingTaxes;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory\n     */\n    private $_chimpSyncEcommerceCollection;\n    /**\n     * @var ProductTypeBundle\n     */\n    private $_productTypeBundle;\n\n    /**\n     * @param \\Magento\\Catalog\\Model\\ResourceModel\\Product\\CollectionFactory $productCollection\n     * @param \\Magento\\Catalog\\Model\\ProductRepository $productRepository\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Catalog\\Helper\\Image $imageHelper\n     * @param \\Magento\\CatalogInventory\\Api\\StockRegistryInterface $stockRegistry\n     * @param \\Magento\\Catalog\\Model\\CategoryRepository $categoryRepository\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory $chimpSyncEcommerce\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $chimpSyncEcommerceCollection\n     * @param \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable $configurable\n     * @param \\Magento\\Catalog\\Model\\ResourceModel\\Category\\CollectionFactory $categoryCollection\n     * @param \\Magento\\Catalog\\Helper\\Data $taxHelper\n     * @param \\Magento\\Catalog\\Model\\Product\\Option $option\n     * @param ProductTypeBundle $productTypeBundle\n     */\n    public function __construct(\n        \\Magento\\Catalog\\Model\\ResourceModel\\Product\\CollectionFactory $productCollection,\n        \\Magento\\Catalog\\Model\\ProductRepository $productRepository,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Catalog\\Helper\\Image $imageHelper,\n        \\Magento\\CatalogInventory\\Api\\StockRegistryInterface $stockRegistry,\n        \\Magento\\Catalog\\Model\\CategoryRepository $categoryRepository,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory $chimpSyncEcommerce,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $chimpSyncEcommerceCollection,\n        \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable $configurable,\n        \\Magento\\Catalog\\Model\\ResourceModel\\Category\\CollectionFactory $categoryCollection,\n        \\Magento\\Catalog\\Helper\\Data $taxHelper,\n        \\Magento\\Catalog\\Model\\Product\\Option $option,\n        ProductTypeBundle $productTypeBundle\n    ) {\n\n        $this->_productRepository   = $productRepository;\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->_productCollection   = $productCollection;\n        $this->_imageHelper         = $imageHelper;\n        $this->_stockRegistry       = $stockRegistry;\n        $this->_categoryRepository  = $categoryRepository;\n        $this->_chimpSyncEcommerce  = $chimpSyncEcommerce;\n        $this->_chimpSyncEcommerceCollection = $chimpSyncEcommerceCollection;\n        $this->_configurable        = $configurable;\n        $this->_option              = $option;\n        $this->_categoryCollection  = $categoryCollection;\n        $this->taxHelper            = $taxHelper;\n        $this->_productTypeBundle = $productTypeBundle;\n        $this->_batchId             = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT. '_' .\n            $this->_helper->getGmtTimeStamp();\n    }\n    public function _sendProducts($magentoStoreId)\n    {\n        $batchArray = [];\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $magentoStoreId\n        );\n        $this->includingTaxes = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_INCLUDING_TAXES,\n            $magentoStoreId\n        );\n        $syncSalable = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_SYNC_SALABLE, $magentoStoreId);\n        $this->_markSpecialPrices($magentoStoreId, $mailchimpStoreId);\n        $batchArray = array_merge($batchArray,$this->processDeletedProducts($magentoStoreId, $mailchimpStoreId));\n        $collection = $this->_getCollection();\n        $collection->addFieldToFilter(\"type_id\", [\"neq\"=>self::GROUPED]);\n        $collection->addStoreFilter($magentoStoreId);\n        $collection->getSelect()->reset(\\Zend_Db_Select::COLUMNS)->columns(['entity_id']);\n        $collection->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = e.entity_id and m4m.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT.\n            \"' and m4m.mailchimp_store_id = '\".$mailchimpStoreId.\"'\",\n            ['m4m.*']\n        );\n        $collection->getSelect()->where(\"m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1\");\n        $collection->getSelect()->limit(self::MAX);\n\n        foreach ($collection as $item) {\n            /**\n             * @var $product \\Magento\\Catalog\\Model\\Product\n             */\n            $product = $this->_productRepository->getById($item->getId(), false, $magentoStoreId);\n            if ($item->getMailchimpSyncModified() && $item->getMailchimpSyncDelta()) {\n                if ($product->isSalable() || $syncSalable) {\n                    if (!$item->getMailchimpSyncDeleted()) {\n                        $batchArray = array_merge($this->_buildOldProductRequest(\n                            $product,\n                            $this->_batchId,\n                            $mailchimpStoreId,\n                            $magentoStoreId\n                        ), $batchArray);\n                        $this->_updateProduct($mailchimpStoreId, $product->getId());\n                    } else {\n                        $data = array_merge($this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId), $batchArray);\n                        $batchArray[] = $data;\n                        $this->syncHelper->markEcommorceAsNotDeleted($product->getId(), \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT);\n                        continue;\n                    }\n                } else {\n                    $productId = $product->getId();\n                    $batchArray[] = $this->deleteProduct($mailchimpStoreId, $productId,\"Product not salable\");\n                }\n                continue;\n            } else {\n                if ($product->isSalable() || $syncSalable) {\n                    $data = $this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId);\n                } else {\n                    $this->_updateProduct(\n                        $mailchimpStoreId,\n                        $product->getId(),\n                        $this->_helper->getGmtDate(),\n                        \"This product is not salable.\",\n                        0,\n                        true,\n                        true\n                    );\n                    continue;\n                }\n            }\n            if (!empty($data)) {\n                $batchArray[] = $data;\n                //update product delta\n                $this->_updateProduct($mailchimpStoreId, $product->getId());\n            } else {\n                $this->_updateProduct(\n                    $mailchimpStoreId,\n                    $product->getId(),\n                    $this->_helper->getGmtDate(),\n                    \"This product type is not supported on MailChimp.\",\n                    0\n                );\n            }\n        }\n        return $batchArray;\n    }\n    protected function _markSpecialPrices($magentoStoreId, $mailchimpStoreId)\n    {\n        /**\n         * get the products with current special price that are not synced and mark it as modified\n         */\n        $collection = $this->_getCollection();\n        $collection->addStoreFilter($magentoStoreId);\n        $collection->addAttributeToFilter(\n            'special_price',\n            ['gt'=>0],\n            'left'\n        )->addAttributeToFilter(\n            'special_from_date',\n            ['or' => [ 0 => ['date' => true,\n                'to' => date('Y-m-d', time()).' 23:59:59'],\n                1 => ['is' => new \\Zend_Db_Expr(\n                    'null'\n                )],]],\n            'left'\n        )->addAttributeToFilter(\n            'special_to_date',\n            ['or' => [ 0 => ['date' => true,\n                'from' => date('Y-m-d', time()).' 00:00:00'],\n                1 => ['is' => new \\Zend_Db_Expr(\n                    'null'\n                )],]],\n            'left'\n        );\n        foreach ($collection as $item) {\n            $productId = $this->_productRepository->get($item->getSku(),false, $magentoStoreId)->getId();\n            $mailchimpSync = $this->syncHelper->getChimpSyncEcommerce($mailchimpStoreId, $productId, 'PRO');\n            if ($mailchimpSync->getMailchimpSyncDelta() < $item->getSpecialFromDate()) {\n                $this->_updateProduct($mailchimpStoreId, $productId, null, null, 1);\n            }\n        }\n        /**\n         * get the products that was synced when it have special price and have no more special price\n         */\n        $collection2 = $this->_getCollection();\n        $collection2->addStoreFilter($magentoStoreId);\n        $collection2->addAttributeToFilter(\n            'special_price',\n            ['gt'=>0],\n            'left'\n        )->addAttributeToFilter(\n            'special_to_date',\n            ['or' => [ 0 => ['date' => true,\n                'to' => date('Y-m-d', time()).' 00:00:00'],\n            ]],\n            'left'\n        )->addAttributeToFilter(\n            'special_to_date',\n            ['or' => [ 0 => ['date' => true,\n                'from' => date('Y-m-d', strtotime('-1 day')).' 00:00:00'],\n            ]],\n            'left'\n        );\n        foreach ($collection2 as $item) {\n            $productId = $this->_productRepository->get($item->getSku(),false, $magentoStoreId)->getId();\n            $mailchimpSync = $this->syncHelper->getChimpSyncEcommerce($mailchimpStoreId, $productId, 'PRO');\n            if ($mailchimpSync->getMailchimpSyncDelta() < $item->getSpecialToDate()) {\n                $this->_updateProduct($mailchimpStoreId, $productId, null, null, 1);\n            }\n        }\n    }\n    protected function processDeletedProducts($magentoStoreId, $mailchimpStoreId)\n    {\n        $deletedData = [];\n        $collection = $this->_getMailchimpCollection();\n        $collection->getSelect()->where(\n            \"main_table.mailchimp_sync_deleted = 1 \".\n            \" and main_table.type = '\".\\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT.\"'\".\n            \" and main_table.mailchimp_store_id = '\".$mailchimpStoreId.\"'\".\n            \" and main_table.mailchimp_sent = \".\\Ebizmarts\\Mailchimp\\Helper\\Data::NEEDTORESYNC\n        );\n        $collection->getSelect()->limit(self::MAX);\n        foreach ($collection as $item) {\n            try {\n                $product = $this->_productRepository->getById($item->getRelatedId(), false, $magentoStoreId);\n            } catch (NoSuchEntityException $e) {\n                $productId = $item->getRelatedId();\n                $deletedData[] = $this->deleteProduct($mailchimpStoreId, $productId, \"Deleted product]\");\n            }\n        }\n        return $deletedData;\n    }\n    protected function deleteProduct($mailchimpStoreId, $productId, $error)\n    {\n        $data = [];\n        $data['method'] = \"DELETE\";\n        $data['path'] = \"/ecommerce/stores/$mailchimpStoreId/products/$productId\";\n        $data['operation_id'] = $this->_batchId . '_' . $productId;\n        $data['body'] = \"\";\n        $this->_updateProduct(\n            $mailchimpStoreId,\n            $productId,\n            $this->_helper->getGmtDate(),\n            $error,\n            0,\n            true\n        );\n        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::PRO_DELETED);\n        return $data;\n    }\n    /**\n     * @return \\Magento\\Catalog\\Model\\ResourceModel\\Product\\Collection\n     */\n    protected function _getCollection()\n    {\n        return $this->_productCollection->create();\n    }\n    protected function _getMailchimpCollection()\n    {\n        return $this->_chimpSyncEcommerceCollection->create();\n    }\n    protected function _buildNewProductRequest(\n        \\Magento\\Catalog\\Model\\Product $product,\n        $mailchimpStoreId,\n        $magentoStoreId\n    ) {\n\n        $variantProducts = [];\n        switch ($product->getTypeId()) {\n            case \\Magento\\Catalog\\Model\\Product\\Type::TYPE_SIMPLE:\n                $variantProducts[] = $product;\n                break;\n            case \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE:\n                $childProducts = $product->getTypeInstance()->getChildrenIds($product->getId());\n                $variantProducts[] = $product;\n                if (count($childProducts[0])) {\n                    foreach ($childProducts[0] as $childId) {\n                        $variantProducts[] = $this->_productRepository->getById($childId, false, $magentoStoreId);\n                    }\n                }\n                break;\n            case \\Magento\\Catalog\\Model\\Product\\Type::TYPE_VIRTUAL:\n            case self::DOWNLOADABLE:\n            case ProductTypeBundle::TYPE_CODE:\n                $variantProducts[] = $product;\n                break;\n            default:\n                return [];\n        }\n        $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts);\n        $body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT);\n        if ($body === false) {\n            $jsonError = json_last_error();\n            $jsonErrorMsg = json_last_error_msg();\n            $this->_helper->log(\"\");\n            $this->_helper->log(\"$jsonErrorMsg for product [\".$product->getId().\"]\");\n            return [];\n\n        } else {\n            $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::PRO_NEW);\n            $data = [];\n            $data['method'] = \"POST\";\n            $data['path'] = \"/ecommerce/stores/\" . $mailchimpStoreId . \"/products\";\n            $data['operation_id'] = $this->_batchId . '_' . $product->getId();\n            $data['body'] = $body;\n            $this->productPrice = null;\n        }\n        return $data;\n    }\n    protected function _buildOldProductRequest(\n        \\Magento\\Catalog\\Model\\Product $product,\n        $batchId,\n        $mailchimpStoreId,\n        $magentoStoreId\n    ) {\n        $operations = [];\n        $variantProducts = [];\n        if ($product->getTypeId() == \\Magento\\Catalog\\Model\\Product\\Type::TYPE_SIMPLE ||\n            $product->getTypeId() == \\Magento\\Catalog\\Model\\Product\\Type::TYPE_VIRTUAL ||\n            $product->getTypeId() == self::DOWNLOADABLE) {\n            $data = $this-> _buildProductData($product, $magentoStoreId);\n            $variantProducts [] = $product;\n            // $parentIds = $product->getTypeInstance()->getParentIdsByChild($product->getId());\n            $parentIds = $this->_configurable->getParentIdsByChild($product->getId());\n\n            //add or update variant\n            foreach ($parentIds as $parentId) {\n                $productSync = $this->_chimpSyncEcommerce->create()->getByStoreIdType(\n                    $mailchimpStoreId,\n                    $parentId,\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT\n                );\n                if ($productSync->getMailchimpSyncDelta()) {\n                    $variendata = [];\n                    $variendata[\"id\"] = $data[\"id\"];\n                    $variendata[\"title\"] = $data[\"title\"];\n                    $variendata[\"url\"] = $data[\"url\"];\n                    $variendata[\"sku\"] = $data[\"sku\"];\n                    $variendata[\"price\"] = $data[\"price\"];\n                    $variendata[\"inventory_quantity\"] = $data[\"inventory_quantity\"];\n                    $variendata[\"image_url\"] = $data[\"image_url\"];\n                    $variendata[\"backorders\"] = $data[\"backorders\"];\n                    $variendata[\"visibility\"] = $data[\"visibility\"];\n                    $productdata = [];\n                    $productdata['method'] = \"PUT\";\n                    $productdata['path'] = \"/ecommerce/stores/\" . $mailchimpStoreId . \"/products/\" .\n                        $parentId . '/variants/' . $data['id'];\n                    $productdata['operation_id'] = $batchId . '_' . $parentId;\n                    $body = json_encode($variendata);\n                    if ($body===false) {\n                        $jsonErrorMsg = json_last_error_msg();\n                        $this->_helper->log(\"\");\n                        $this->_helper->log(\"$jsonErrorMsg for product [\".$product->getId().\"]\");\n                        continue;\n                    }\n                    $productdata['body'] = $body;\n                    $operations[] = $productdata;\n                }\n            }\n            $bundleParentIds = $this->_productTypeBundle->getParentIdsByChild($product->getId());\n            foreach ($bundleParentIds as $bundleParentId) {\n                $bundleProduct = $this->_productRepository->getById($bundleParentId, false, $magentoStoreId);\n                $data = $this-> _buildProductData($bundleProduct, $magentoStoreId,false);\n                $body = json_encode($data);\n                if ($body===false) {\n                    $jsonErrorMsg = json_last_error_msg();\n                    $this->_helper->log(\"\");\n                    $this->_helper->log(\"$jsonErrorMsg for product [\".$bundleProduct->getId().\"]\");\n                    continue;\n                }\n                $productdata = [];\n                $productdata['method'] = \"PATCH\";\n                $productdata['path'] = \"/ecommerce/stores/\" . $mailchimpStoreId . \"/products/\" . $bundleParentId;\n                $productdata['operation_id'] = $batchId . '_' . $bundleParentId;\n                $productdata['body'] = $body;\n                $operations[] = $productdata;\n                $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::PRO_MOD);\n            }\n        } elseif ($product->getTypeId() == \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE) {\n            $childProducts = $product->getTypeInstance()->getChildrenIds($product->getId());\n            $variantProducts[] = $product;\n            if (count($childProducts[0])) {\n                foreach ($childProducts[0] as $childId) {\n                    $variantProducts[] = $this->_productRepository->getById($childId, false, $magentoStoreId);\n                }\n            }\n        } else {\n            return [];\n        }\n\n        $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts);\n        $body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT);\n        if ($body===false) {\n            $jsonErrorMsg = json_last_error_msg();\n            $this->_helper->log(\"\");\n            $this->_helper->log(\"$jsonErrorMsg for product [\".$product->getId().\"]\");\n            return [];\n        }\n        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::PRO_MOD);\n        $data = [];\n        $data['method'] = \"PATCH\";\n        $data['path'] = \"/ecommerce/stores/\" . $mailchimpStoreId . \"/products/\".$product->getId();\n        $data['operation_id'] = $this->_batchId . '_' . $product->getId();\n        $data['body'] = $body;\n        $operations[] = $data;\n        $this->productPrice = null;\n        return $operations;\n    }\n    protected function _buildProductData(\n        \\Magento\\Catalog\\Model\\Product $product,\n        $magentoStoreId,\n        $isVarient = true,\n        $variants = []\n    ) {\n\n        $data = [];\n        $parent = null;\n\n        //data applied for both root and varient products\n        $data[\"id\"] = $product->getId();\n        $data[\"title\"] = $product->getName();\n        $data[\"url\"] = $product->getProductUrl();\n        $data[\"image_url\"] = '';\n        if ($product->getImage() && $product->getImage()!='no_selection') {\n            $filePath = 'catalog/product/'.ltrim($product->getImage(), '/');\n            $data[\"image_url\"] = $this->_helper->getBaserUrl($magentoStoreId, \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA).$filePath;\n        } elseif ($this->_parentImage) {\n            $data['image_url'] = $this->_parentImage;\n        } else {\n            $parent = $this->_getParent($product->getId(), $magentoStoreId);\n            if ($parent && $parent->getImage() && $parent->getImage()!='no_selection') {\n                $filePath = 'catalog/product/'.ltrim($parent->getImage(), '/');\n                $data[\"image_url\"] = $this->_helper->getBaserUrl($magentoStoreId, \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA).$filePath;\n            }\n        }\n        $data[\"published_at_foreign\"] = \"\";\n        if ($isVarient) {\n            //this is for a varient product\n            $data[\"sku\"] = $product->getSku() ? $product->getSku() : '';\n            if ($this->productPrice) {\n                $data['price'] = $this->productPrice;\n            } else {\n                $data['price'] = $this->_getProductPrice($product);\n            }\n\n            //stock\n            $stock = $this->_stockRegistry->getStockItem($product->getId(), $magentoStoreId);\n            $data[\"inventory_quantity\"] = (int)$stock->getQty();\n            $data[\"backorders\"] = (string)$stock->getBackorders();\n            if ($product->getVisibility() == \\Magento\\Catalog\\Model\\Product\\Visibility::VISIBILITY_NOT_VISIBLE) {\n                $tailUrl = '';\n                $data[\"visibility\"] = 'false';\n                if (!$parent) {\n                    $parent = $this->_getParent($product->getId(), $magentoStoreId);\n                }\n                if ($parent) {\n                    $options = $parent->getTypeInstance()->getConfigurableAttributesAsArray($parent);\n                    foreach ($options as $option) {\n                        if (strlen($tailUrl)) {\n                            $tailUrl .= '&';\n                        } else {\n                            $tailUrl .= '?';\n                        }\n                        $tailUrl .= $option['attribute_code'] . \"=\" . $product->getData($option['attribute_code']);\n                    }\n                    $this->_childtUrl = $data['url'] = $parent->getProductUrl() . $tailUrl;\n                    if (empty($data['image_url'])) {\n                        $filePath = 'catalog/product'.$parent->getImage();\n                        $data[\"image_url\"] = $this->_helper->getBaserUrl(\n                            $magentoStoreId,\n                            \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA\n                        ).$filePath;\n                    }\n                }\n            } else {\n                $data[\"visibility\"] = 'true';\n            }\n        } else {\n            //this is for a root product\n            if ($product->getData('description')) {\n                $data[\"description\"] = $product->getData('description');\n            }\n\n            $categoryName = $this->getProductCategories($product, $magentoStoreId);\n            if ($categoryName) {\n                $data['type'] = $data['vendor'] = $categoryName;\n            }\n\n            //missing data\n            $data[\"handle\"] = \"\";\n            if (!empty($data['image_url'])) {\n                $this->_parentImage = $data['image_url'];\n            }\n            if ($product->getTypeId() == ProductTypeBundle::TYPE_CODE) {\n                list($min, $max) = $this->_bundleVariants($product, $magentoStoreId);\n                $data[\"variants\"][] = $this->_variantForBundle($product, $magentoStoreId, $min, $product->getSku() . '-min', $product->getId() . '-min');\n                $data[\"variants\"][] = $this->_variantForBundle($product, $magentoStoreId, $max, $product->getSku() . '-max', $product->getId() . '-max');\n            } else {\n                //variants\n                $data[\"variants\"] = [];\n                // put the min price of the simples as the price of the parent\n                foreach ($variants as $variant) {\n                    if ($variant && $variant->getId() != $product->getId()) {\n                        $variantPrice = $this->_getProductPrice($variant);\n                        if ($this->productPrice) {\n                            if ($variantPrice < $this->productPrice) {\n                                $this->productPrice = $variantPrice;\n                            }\n                        } else {\n                            $this->productPrice = $variantPrice;\n                        }\n                    }\n                }\n                /**\n                 * @var $variant \\Magento\\Catalog\\Model\\Product\n                 */\n                foreach ($variants as $variant) {\n                    if ($variant) {\n                        if ($variant->getId() != $product->getId()) {\n                            $this->productPrice = null;\n                        }\n                        $data[\"variants\"][] = $this->_buildProductData($variant, $magentoStoreId);\n                    }\n                }\n                if ($this->_childtUrl) {\n                    if ($product->getTypeId() == \\Magento\\Catalog\\Model\\Product\\Type::TYPE_SIMPLE ||\n                        $product->getTypeId() == \\Magento\\Catalog\\Model\\Product\\Type::TYPE_VIRTUAL ||\n                        $product->getTypeId() == \"downloadable\") {\n                        $data[\"url\"] = $this->_childtUrl;\n                    }\n                    $this->_childtUrl = null;\n                }\n                $this->_parentImage = null;\n            }\n        }\n        return $data;\n    }\n\n    protected function _getParent($productId, $magentoStoreId)\n    {\n        $parentIds =$this->_configurable->getParentIdsByChild($productId);\n        $parent = null;\n        foreach ($parentIds as $id) {\n            $parent = $this->_productRepository->getById($id, false, $magentoStoreId);\n            if ($parent->getTypeId() == \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE) {\n                break;\n            } else {\n                $parent = null;\n            }\n        }\n        return $parent;\n    }\n\n    /**\n     * @param \\Magento\\Catalog\\Model\\Product $product\n     * @param $storeId\n     */\n    protected function getProductCategories(\\Magento\\Catalog\\Model\\Product $product, $storeId)\n    {\n        $categoryIds = $product->getCategoryIds();\n        $categoryNames = [];\n        $categoryName = null;\n        if (is_array($categoryIds) && count($categoryIds)) {\n            $collection = $this->_categoryCollection->create();\n            $collection->addAttributeToSelect(['name'])\n                ->setStoreId($storeId)\n                ->addAttributeToFilter('is_active', ['eq'=>'1'])\n                ->addAttributeToFilter('entity_id', ['in'=>$categoryIds])\n                ->addAttributeToSort('level', 'asc');\n            foreach ($collection as $category) {\n                $categoryNames[] = $category->getName();\n            }\n            $categoryName = (count($categoryNames)) ? implode(\" - \", $categoryNames) : 'None';\n        }\n        return $categoryName;\n    }\n    /**\n     * @param \\Magento\\Sales\\Model\\Order $order\n     * @param $mailchimpStoreId\n     * @return array\n     * @throws \\Magento\\Framework\\Exception\\NoSuchEntityException\n     */\n    public function sendModifiedProduct(\\Magento\\Sales\\Model\\Order $order, $mailchimpStoreId, $magentoStoreId)\n    {\n        $data = [];\n        $batchId = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT . '_' . $this->_helper->getGmtTimeStamp();\n        $items = $order->getAllVisibleItems();\n\n        foreach ($items as $item) {\n            //@todo get from the store not the default\n            try {\n                $product = $this->_productRepository->getById($item->getProductId(), false, $magentoStoreId);\n                $productSyncData = $this->_chimpSyncEcommerce->create()->getByStoreIdType(\n                    $mailchimpStoreId,\n                    $product->getId(),\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT\n                );\n                if ($product->getId() != $item->getProductId() || (\n                        $product->getTypeId() != \\Magento\\Catalog\\Model\\Product\\Type::TYPE_SIMPLE &&\n                        $product->getTypeId() != \\Magento\\Catalog\\Model\\Product\\Type::TYPE_VIRTUAL &&\n                        $product->getTypeId() != \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE &&\n                        $product->getTypeId() != self::DOWNLOADABLE &&\n                        $product->getTypeId() != ProductTypeBundle::TYPE_CODE)) {\n                    $this->_helper->log('The product with id [' . $product->getId() .\n                        '] is not supported [' . $product->getTypeId() . ']');\n                    continue;\n                }\n                if ($productSyncData->getMailchimpSyncModified()) {\n                    $data = array_merge(\n                        $data,\n                        $this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId)\n                    );\n                    $this->_updateProduct($mailchimpStoreId, $product->getId());\n                } elseif (!$productSyncData->getMailchimpSyncDelta()) {\n                    $data[] = $this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId);\n                    $this->_updateProduct($mailchimpStoreId, $product->getId());\n                }\n            } catch(\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n                $this->_helper->log(\"Skip product [\".$item->getProductId().\"]\");\n            }\n        }\n        return $data;\n    }\n\n    public function sendQuoteModifiedProduct(\\Magento\\Quote\\Model\\Quote $quote, $mailchimpStoreId, $magentoStoreId)\n    {\n        $data = [];\n        $batchId = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT . '_' . $this->_helper->getGmtTimeStamp();\n        $items = $quote->getAllVisibleItems();\n        /**\n         * @var $item \\Magento\\Quote\\Model\\Quote\\Item\n         */\n        foreach ($items as $item) {\n            //@todo get from the store not the default\n            $product = $this->_productRepository->getById($item->getProductId(), false, $magentoStoreId);\n            $productSyncData = $this->_chimpSyncEcommerce->create()->getByStoreIdType(\n                $mailchimpStoreId,\n                $product->getId(),\n                \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT\n            );\n            if ($product->getId()!=$item->getProductId() || (\n                    $product->getTypeId() != \\Magento\\Catalog\\Model\\Product\\Type::TYPE_SIMPLE &&\n                    $product->getTypeId() != \\Magento\\Catalog\\Model\\Product\\Type::TYPE_VIRTUAL &&\n                    $product->getTypeId() != \\Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable::TYPE_CODE &&\n                    $product->getTypeId() != self::DOWNLOADABLE &&\n                    $product->getTypeId() != ProductTypeBundle::TYPE_CODE)) {\n                $this->_helper->log(\n                    'The product with id ['.$product->getId().'] is not supported ['.$product->getTypeId().']'\n                );\n                continue;\n            }\n\n            if ($productSyncData->getMailchimpSyncModified()) {\n                $data = array_merge(\n                    $data,\n                    $this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId)\n                );\n                $this->_updateProduct($mailchimpStoreId, $product->getId());\n            } elseif (!$productSyncData->getMailchimpSyncDelta()) {\n                $data[] = $this->_buildNewProductRequest($product, $mailchimpStoreId, $magentoStoreId);\n                $this->_updateProduct($mailchimpStoreId, $product->getId());\n            }\n        }\n        return $data;\n    }\n    protected function _getProductPrice(\\Magento\\Catalog\\Model\\Product $product)\n    {\n        if ($this->includingTaxes) {\n            $price = $this->taxHelper->getTaxPrice($product, $product->getFinalPrice(), true);\n        } else {\n            $price = $this->taxHelper->getTaxPrice($product, $product->getFinalPrice(), false);\n        }\n        return $price;\n    }\n    /**\n     * @param $storeId\n     * @param $entityId\n     * @param $sync_delta\n     * @param $sync_error\n     * @param $sync_modified\n     */\n    protected function _updateProduct(\n        $storeId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null,\n        $deleted = null,\n        $forcedNoWaiting = false\n    ) {\n        if ($forcedNoWaiting) {\n            $sent = \\Ebizmarts\\MailChimp\\Helper\\Data::SYNCED;\n        } else {\n            $sent = \\Ebizmarts\\MailChimp\\Helper\\Data::WAITINGSYNC;\n        }\n        $this->syncHelper->saveEcommerceData(\n            $storeId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT,\n            $sync_delta,\n            $sync_error,\n            $sync_modified,\n            $deleted,\n            null,\n            $sent\n        );\n    }\n    protected function _bundleVariants($product, $magentoStoreId)\n    {\n        $productsArray = [];\n        $simpleProducts = $product->getTypeInstance(true)\n            ->getSelectionsCollection(\n                $product->getTypeInstance(true)->getOptionsIds($product),\n                $product\n            );\n        foreach ($simpleProducts as $item) {\n            $selectionArray = [];\n            $selectionArray['selection_product_name'] = $item->getName();\n            $selectionArray['selection_product_quantity'] = $item->getSelectionQty();\n            $selectionArray['selection_product_price'] = $item->getPrice();\n            $selectionArray['selection_product_id'] = $item->getProductId();\n            $productsArray[$item->getOptionId()]['item'][$item->getSelectionId()] = $selectionArray;\n        }\n        foreach ($productsArray as $key => $productItem) {\n            $min = $max = 0;\n            foreach ($productItem['item'] as $item) {\n                if ($min == 0) {\n                    $min = $item['selection_product_price']*$item['selection_product_quantity'];\n                }\n                if ($item['selection_product_price']*$item['selection_product_quantity'] < $min) {\n                    $min = $item['selection_product_price']*$item['selection_product_quantity'];\n                }\n                if ($item['selection_product_price']*$item['selection_product_quantity'] > $max) {\n                    $max = $item['selection_product_price']*$item['selection_product_quantity'];\n                }\n            }\n            $productsArray[$key]['min'] = $min;\n            $productsArray[$key]['max'] = $max;\n        }\n        $min = $max = 0;\n        foreach ($productsArray as $key => $productItem) {\n            $min += $productItem['min'];\n            $max += $productItem['max'];\n        }\n        return [$min, $max];\n    }\n    protected function _variantForBundle($product, $magentoStoreId, $price, $sku, $id)\n    {\n        $data = [];\n        $parent = null;\n\n        //data applied for both root and varient products\n        $data[\"id\"] = $id;\n        $data[\"title\"] = $product->getName();\n        $data[\"url\"] = $product->getProductUrl();\n        $data[\"image_url\"] = '';\n        if ($product->getImage() && $product->getImage()!='no_selection') {\n            $filePath = 'catalog/product/'.ltrim($product->getImage(), '/');\n            $data[\"image_url\"] = $this->_helper->getBaserUrl(\n                    $magentoStoreId,\n                    \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA\n                ).$filePath;\n        } elseif ($this->_parentImage) {\n            $data['image_url'] = $this->_parentImage;\n        } else {\n            $parent = $this->_getParent($product->getId(), $magentoStoreId);\n            if ($parent && $parent->getImage() && $parent->getImage()!='no_selection') {\n                $filePath = 'catalog/product/'.ltrim($parent->getImage(), '/');\n                $data[\"image_url\"] = $this->_helper->getBaserUrl(\n                        $magentoStoreId,\n                        \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA\n                    ).$filePath;\n            }\n        }\n        $data[\"published_at_foreign\"] = \"\";\n        $data[\"sku\"] = $sku;\n        if ($this->productPrice) {\n            $data['price'] = $this->productPrice;\n        } else {\n            $data['price'] = $price;\n        }\n\n        //stock\n        $stock = $this->_stockRegistry->getStockItem($product->getId(), $magentoStoreId);\n        $data[\"inventory_quantity\"] = (int)$stock->getQty();\n        $data[\"backorders\"] = (string)$stock->getBackorders();\n        if ($product->getVisibility() == \\Magento\\Catalog\\Model\\Product\\Visibility::VISIBILITY_NOT_VISIBLE) {\n            $tailUrl = '';\n            $data[\"visibility\"] = 'false';\n            if (!$parent) {\n                $parent = $this->_getParent($product->getId(), $magentoStoreId);\n            }\n            if ($parent) {\n                $options = $parent->getTypeInstance()->getConfigurableAttributesAsArray($parent);\n                foreach ($options as $option) {\n                    if (strlen($tailUrl)) {\n                        $tailUrl .= '&';\n                    } else {\n                        $tailUrl .= '?';\n                    }\n                    $tailUrl .= $option['attribute_code'] . \"=\" . $product->getData($option['attribute_code']);\n                }\n                $this->_childtUrl = $data['url'] = $parent->getProductUrl() . $tailUrl;\n                if (empty($data['image_url'])) {\n                    $filePath = 'catalog/product'.$parent->getImage();\n                    $data[\"image_url\"] = $this->_helper->getBaserUrl(\n                            $magentoStoreId,\n                            \\Magento\\Framework\\UrlInterface::URL_TYPE_MEDIA\n                        ).$filePath;\n                }\n            }\n        } else {\n            $data[\"visibility\"] = 'true';\n        }\n        return $data;\n    }\n}\n"
  },
  {
    "path": "Model/Api/PromoCodes.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/6/17 1:15 PM\n * @file: Coupon.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Magento\\TestFramework\\Inspection\\Exception;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass PromoCodes\n{\n    const MAX = 100;\n    protected $_batchId;\n    protected $_token;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\SalesRule\\Model\\ResourceModel\\Coupon\\CollectionFactory\n     */\n    protected $_couponCollection;\n    /**\n     * @var \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\CollectionFactory\n     */\n    protected $_ruleCollection;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory\n     */\n    private $_chimpSyncEcommerce;\n    /**\n     * @var PromoRules\n     */\n    private $_promoRules;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory\n     */\n    private $_syncCollection;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\SalesRule\\Model\\ResourceModel\\Coupon\\CollectionFactory $couponCollection\n     * @param \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\CollectionFactory $ruleCollection\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory $chimpSyncEcommerce\n     * @param PromoRules $promoRules\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $syncCollection\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\SalesRule\\Model\\ResourceModel\\Coupon\\CollectionFactory $couponCollection,\n        \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\CollectionFactory $ruleCollection,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerceFactory $chimpSyncEcommerce,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\PromoRules $promoRules,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $syncCollection\n    ) {\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->_couponCollection    = $couponCollection;\n        $this->_ruleCollection      = $ruleCollection;\n        $this->_chimpSyncEcommerce  = $chimpSyncEcommerce;\n        $this->_batchId             = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE. '_' .\n            $this->_helper->getGmtTimeStamp();\n        $this->_promoRules          = $promoRules;\n        $this->_syncCollection      = $syncCollection;\n    }\n    public function sendCoupons($magentoStoreId)\n    {\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $magentoStoreId\n        );\n        $batchArray = [];\n        $batchArray = array_merge($batchArray, $this->_sendDeletedCoupons($mailchimpStoreId, $magentoStoreId));\n//        $batchArray = array_merge($batchArray, $this->_sendModifiedCoupons($mailchimpStoreId, $magentoStoreId));\n        $batchArray = array_merge($batchArray, $this->_sendNewCoupons($mailchimpStoreId, $magentoStoreId));\n\n        return $batchArray;\n    }\n    protected function _sendDeletedCoupons($mailchimpStoreId, $magentoStoreId)\n    {\n        $batchArray = [];\n        $websiteId = $this->_helper->getWebsiteId($magentoStoreId);\n        $collection = $this->_syncCollection->create();\n        $collection->addFieldToFilter('mailchimp_store_id', ['eq'=>$mailchimpStoreId])\n            ->addFieldToFilter('type', ['eq'=>\\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE])\n            ->addFieldToFilter('mailchimp_sync_deleted', ['eq'=>1]);\n        $collection->getSelect()->limit(self::MAX);\n        $counter = 0;\n        /**\n         * @var $syncCoupon \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n         */\n        foreach ($collection as $coupon) {\n            $couponId = $coupon->getRelatedId();\n            $ruleId = $coupon->getDeletedRelatedId();\n            $batchArray[$counter]['method'] = 'DELETE';\n            $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $couponId;\n            $batchArray[$counter]['path'] =\n                \"/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId/promo-codes/$couponId\";\n            $counter++;\n            $syncCoupon =$this->syncHelper->getChimpSyncEcommerce(\n                $mailchimpStoreId,\n                $couponId,\n                \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE\n            );\n            $syncCoupon->getResource()->delete($syncCoupon);\n        }\n        return $batchArray;\n    }\n    protected function _sendNewCoupons($mailchimpStoreId, $magentoStoreId)\n    {\n        $batchArray = [];\n        $websiteId = $this->_helper->getWebsiteId($magentoStoreId);\n        /**\n         * @var $ruleCollection \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\Collection\n         */\n        $ruleCollection = $this->_ruleCollection->create();\n        $ruleCollection->addWebsiteFilter($websiteId);\n        $rulesId = [];\n        foreach ($ruleCollection as $rule) {\n            $rulesId[] = $rule->getRuleId();\n        }\n        if (count($rulesId)) {\n            $inRoules = implode(',', $rulesId);\n            $collection = $this->_couponCollection->create();\n            $collection->getSelect()->joinLeft(\n                ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n                \"m4m.related_id = main_table.coupon_id and m4m.type = '\" .\n                \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE .\n                \"' and m4m.mailchimp_store_id = '\" . $mailchimpStoreId . \"'\",\n                ['m4m.*']\n            );\n            $collection->getSelect()->joinLeft(\n                ['rules' => $this->_helper->getTableName('salesrule')],\n                'main_table.rule_id = rules.rule_id'\n            );\n            $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)\");\n            $collection->getSelect()->limit(self::MAX);\n            $counter = 0;\n            /**\n             * @var $item \\Magento\\SalesRule\\Model\\Coupon\n             */\n            foreach ($collection as $item) {\n                $this->_token = null;\n                $ruleId = $item->getRuleId();\n                $couponId = $item->getCouponId();\n                try {\n                    $promoRule = $this->syncHelper->getChimpSyncEcommerce(\n                        $mailchimpStoreId,\n                        $ruleId,\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE\n                    );\n                    if (!$promoRule->getMailchimpSyncDelta() ||\n                        $promoRule->getMailchimpSyncDelta() < $this->_helper->getMCMinSyncDateFlag($magentoStoreId)) {\n                        // must send the promorule before the promocode\n                        $newPromoRule = $this->_promoRules->getNewPromoRule(\n                            $ruleId,\n                            $mailchimpStoreId,\n                            $magentoStoreId\n                        );\n                        if (!empty($newPromoRule)) {\n                            $batchArray[$counter] = $newPromoRule;\n                            $counter++;\n                        } else {\n                            $error = __('Parent rule with id ' . $ruleId . 'has not been correctly sent.');\n                            $this->_updateSyncData(\n                                $mailchimpStoreId,\n                                $ruleId,\n                                $this->_helper->getGmtDate(),\n                                $error,\n                                0\n                            );\n                            continue;\n                        }\n                    }\n                    if ($promoRule->getMailchimpSyncError()) {\n                        // the promorule associated has an error\n                        $error = __('Parent rule with id ' . $ruleId . 'has not been correctly sent.');\n                        $this->_updateSyncData(\n                            $mailchimpStoreId,\n                            $couponId,\n                            $this->_helper->getGmtDate(),\n                            $error,\n                            0\n                        );\n                        continue;\n                    }\n                    $promoCodeJson = json_encode($this->generateCodeData($item, $magentoStoreId));\n                    if ($promoCodeJson !== false) {\n                        if (!empty($promoCodeJson)) {\n                            $batchArray[$counter]['method'] = 'POST';\n                            $batchArray[$counter]['path'] =\n                                \"/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId/promo-codes/\";\n                            $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $couponId;\n                            $batchArray[$counter]['body'] = $promoCodeJson;\n                        } else {\n                            $error = __('Something went wrong when retrieving the information for promo rule');\n                            $this->_updateSyncData(\n                                $mailchimpStoreId,\n                                $couponId,\n                                $this->_helper->getGmtDate(),\n                                $error,\n                                0\n                            );\n                            continue;\n                        }\n                        $counter++;\n                        $this->_updateSyncData($mailchimpStoreId, $couponId);\n                    } else {\n                        $error = json_last_error_msg();\n                        $this->_updateSyncData(\n                            $mailchimpStoreId,\n                            $couponId,\n                            $this->_helper->getGmtDate(),\n                            $error,\n                            0\n                        );\n                    }\n                } catch (Exception $e) {\n                    $this->_helper->log($e->getMessage());\n                }\n            }\n        }\n        return $batchArray;\n    }\n    protected function generateCodeData($item, $magentoStoreId)\n    {\n        $data = [];\n        $data['id'] = $item->getCouponId();\n        $data['code'] = $item->getCode();\n        $data['redemption_url'] = $this->_getRedemptionUrl($item->getCode(), $magentoStoreId);\n        $data['usage_count'] = (int)$item->getTimesUsed();\n\n        return $data;\n    }\n    protected function _getRedemptionUrl($code, $magentoStoreId)\n    {\n        $token = hash('md5', rand(0, 9999999));\n        $url = $this->_helper->getRedemptionUrl($magentoStoreId, $code, $token);\n        $this->_token = $token;\n        return $url;\n    }\n    protected function _updateSyncData(\n        $storeId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null,\n        $sync_deleted = null\n    ) {\n        $this->syncHelper->saveEcommerceData(\n            $storeId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE,\n            $sync_delta,\n            $sync_error,\n            $sync_modified,\n            $sync_deleted,\n            $this->_token\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Api/PromoRules.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/17/17 2:38 PM\n * @file: PromoRules.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Magento\\Cms\\Test\\Unit\\Controller\\Adminhtml\\Page\\MassEnableTest;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass PromoRules\n{\n    const TYPE_FIXED = 'fixed';\n    const TYPE_PERCENTAGE = 'percentage';\n    const TARGET_PER_ITEM = 'per_item';\n    const TARGET_TOTAL = 'total';\n    const TARGET_SHIPPING = 'shipping';\n    const FREESHIPPING_NO = 0;\n    const FREESHIPPING_FOR_MATHINGI_TEMS_ONLY = 1;\n    const FREESHIPPING_FOR_SHIPMENT_WITH_MATCHING_ITEMS = 3;\n    const MAX = 100;\n\n    private $_batchId;\n    /**\n     * @var \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\CollectionFactory\n     */\n    private $_collection;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\SalesRule\\Model\\RuleRepository\n     */\n    private $_ruleRepo;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory\n     */\n    protected $_syncCollection;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\CollectionFactory $collection\n     * @param \\Magento\\SalesRule\\Model\\RuleRepository $ruleRepo\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $syncCollection\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\CollectionFactory $collection,\n        \\Magento\\SalesRule\\Model\\RuleRepository $ruleRepo,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $syncCollection\n    ) {\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->_collection          = $collection;\n        $this->_ruleRepo             = $ruleRepo;\n        $this->_batchId             = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE. '_' .\n            $this->_helper->getGmtTimeStamp();\n        $this->_syncCollection      = $syncCollection;\n    }\n    public function sendRules($magentoStoreId)\n    {\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $magentoStoreId\n        );\n        $batchArray = [];\n\n        $batchArray = array_merge($batchArray, $this->_getDeletedPromoRules($mailchimpStoreId, $magentoStoreId));\n        $batchArray = array_merge($batchArray, $this->_getModifiedPromoRules($mailchimpStoreId, $magentoStoreId));\n        return $batchArray;\n    }\n    protected function _getDeletedPromoRules($mailchimpStoreId, $magentoStoreId)\n    {\n        $batchArray = [];\n        $collection = $this->_syncCollection->create();\n        $collection->addFieldToFilter('mailchimp_store_id', ['eq'=>$mailchimpStoreId])\n            ->addFieldToFilter('type', ['eq'=>\\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE])\n            ->addFieldToFilter('mailchimp_sync_deleted', ['eq'=>1]);\n        $collection->getSelect()->limit(self::MAX);\n        $count = 0;\n        $api = $this->_helper->getApi($magentoStoreId);\n        /**\n         * @var $rule \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n         */\n        foreach ($collection as $rule) {\n            $ruleId = $rule->getData('related_id');\n            try {\n                $mailchimpRule = $api->ecommerce->promoCodes->getAll($mailchimpStoreId, $ruleId);\n                foreach ($mailchimpRule['promo_codes'] as $promoCode) {\n                    $this->syncHelper->ecommerceDeleteAllByIdType(\n                        $promoCode['id'],\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE,\n                        $mailchimpStoreId\n                    );\n                }\n                $batchArray[$count]['method'] = 'DELETE';\n                $batchArray[$count]['path'] = \"/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId\";\n                $batchArray[$count]['operation_id'] = $this->_batchId . '_' . $ruleId;\n                $count++;\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n            }\n            $this->syncHelper->ecommerceDeleteAllByIdType(\n                $ruleId,\n                \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE,\n                $mailchimpStoreId\n            );\n        }\n        return $batchArray;\n    }\n    protected function _getModifiedPromoRules($mailchimpStoreId, $magentoStoreId)\n    {\n        $batchArray = [];\n        $websiteId = $this->_helper->getWebsiteId($magentoStoreId);\n        /**\n         * @var $collection \\Magento\\SalesRule\\Model\\ResourceModel\\Rule\\Collection\n         */\n        $collection = $this->_collection->create();\n        $collection->addWebsiteFilter($websiteId);\n        $collection->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.rule_id and m4m.type = '\".\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE.\n            \"' and m4m.mailchimp_store_id = '\".$mailchimpStoreId.\"'\",\n            ['m4m.*']\n        );\n        $collection->getSelect()->where(\"m4m.mailchimp_sync_modified = 1\");\n        $collection->getSelect()->limit(self::MAX);\n        $count = 0;\n        /**\n         * @var $rule \\Magento\\SalesRule\\Model\\Rule\n         */\n        $api = $this->_helper->getApi($magentoStoreId);\n        foreach ($collection as $rule) {\n            $ruleId = $rule->getRuleId();\n            try {\n                $mailchimpRule = $api->ecommerce->promoCodes->getAll($mailchimpStoreId, $ruleId);\n                foreach ($mailchimpRule['promo_codes'] as $promoCode) {\n                    $this->syncHelper->ecommerceDeleteAllByIdType(\n                        $promoCode['id'],\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE,\n                        $mailchimpStoreId\n                    );\n                }\n            } catch (\\Mailchimp_Error $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n            }\n            $this->syncHelper->ecommerceDeleteAllByIdType(\n                $rule->getRuleId(),\n                \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE,\n                $mailchimpStoreId\n            );\n            $batchArray[$count]['method'] = 'DELETE';\n            $batchArray[$count]['path'] = \"/ecommerce/stores/$mailchimpStoreId/promo-rules/$ruleId\";\n            $batchArray[$count]['operation_id'] = $this->_batchId. '_' . $rule->getRuleId();\n            $count++;\n        }\n        return $batchArray;\n    }\n    public function getNewPromoRule($ruleId, $mailchimpStoreId, $magentoStoreId)\n    {\n        $data = [];\n        /**\n         * @var $rule \\Magento\\SalesRule\\Model\\Rule\n         */\n        try {\n            $rule = $this->_ruleRepo->getById($ruleId);\n            $promoRules = $this->_generateRuleData($rule);\n            if (!empty($promoRules)) {\n                $promoRulesJson = json_encode($promoRules);\n                if ($promoRulesJson !== false) {\n                    if (!empty($promoRulesJson)) {\n                        $data['method'] = 'POST';\n                        $data['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/promo-rules';\n                        $data['operation_id'] = $this->_batchId . '_' . $ruleId;\n                        $data['body'] = $promoRulesJson;\n                        $this->_updateSyncData($mailchimpStoreId, $ruleId);\n                    } else {\n                        $error = __('Something went wrong when retrieving the information.');\n                        $this->_updateSyncData(\n                            $mailchimpStoreId,\n                            $ruleId,\n                            $this->_helper->getGmtDate(),\n                            $error,\n                            0\n                        );\n                    }\n                } else {\n                    $error = json_last_error_msg();\n                    $this->_updateSyncData(\n                        $mailchimpStoreId,\n                        $ruleId,\n                        $this->_helper->getGmtDate(),\n                        $error,\n                        0\n                    );\n                }\n            } else {\n                $error = __('Something went wrong when retrieving the information.');\n                $this->_updateSyncData(\n                    $mailchimpStoreId,\n                    $ruleId,\n                    $this->_helper->getGmtDate(),\n                    $error,\n                    0\n                );\n            }\n        } catch (\\Exception $e) {\n            $this->_helper->log($e->getMessage());\n        }\n        return $data;\n    }\n\n    private function _generateRuleData($rule)\n    {\n        $data = [];\n        $data['id'] = $rule->getRuleId();\n        $data['title'] = $rule->getName();\n        $data['description'] = $rule->getDescription() ? $rule->getDescription() : $rule->getName();\n        $fromDate = $rule->getFromDate();\n        if ($fromDate) {\n            $data['starts_at'] = $fromDate;\n        }\n        $toDate = $rule->getToDate();\n        if ($toDate) {\n            $data['ends_at'] = $toDate;\n        }\n        $promoAction = $rule->getSimpleAction();\n        $shipping = $rule->getSimpleFreeShipping();\n        $data['type'] = $this->_getMailChimpType($promoAction, $shipping);\n        $data['target'] = $this->_getMailChimpTarget($promoAction, $shipping);\n        switch ($data['type']) {\n            case self::TYPE_PERCENTAGE:\n                $data['amount'] = $rule->getDiscountAmount()/100;\n                break;\n            case self::TYPE_FIXED:\n                if ($data['target']!=self::TARGET_SHIPPING) {\n                    $data['amount'] = $rule->getDiscountAmount();\n                } else {\n                    $data['amount'] = 0;\n                }\n                break;\n        }\n        $data['enabled'] = (bool)$rule->getIsActive();\n        if (!$data['target'] || !$data['type']) {\n            return [];\n        }\n\n        return $data;\n    }\n\n    /**\n     * @param $action\n     * @return null|string\n     */\n    private function _getMailChimpType($action, $shipping)\n    {\n        $mailChimpType = null;\n        if ($shipping==self::FREESHIPPING_NO) {\n            switch ($action) {\n                case \\Magento\\SalesRule\\Model\\Rule::BY_PERCENT_ACTION:\n                    $mailChimpType = self::TYPE_PERCENTAGE;\n                    break;\n                case \\Magento\\SalesRule\\Model\\Rule::BY_FIXED_ACTION:\n                case \\Magento\\SalesRule\\Model\\Rule::CART_FIXED_ACTION:\n                    $mailChimpType = self::TYPE_FIXED;\n                    break;\n            }\n        } else {\n            $mailChimpType = self::TYPE_FIXED;\n        }\n        return $mailChimpType;\n    }\n\n    /**\n     * @param $action\n     * @return null|string\n     */\n    private function _getMailChimpTarget($action, $shipping)\n    {\n        $mailChimpTarget = null;\n        if ($shipping==self::FREESHIPPING_NO) {\n            switch ($action) {\n                case \\Magento\\SalesRule\\Model\\Rule::CART_FIXED_ACTION:\n                case \\Magento\\SalesRule\\Model\\Rule::BY_PERCENT_ACTION:\n                    $mailChimpTarget = self::TARGET_TOTAL;\n                    break;\n                case \\Magento\\SalesRule\\Model\\Rule::BY_FIXED_ACTION:\n                    $mailChimpTarget = self::TARGET_PER_ITEM;\n                    break;\n            }\n        } else {\n            $mailChimpTarget = self::TARGET_SHIPPING;\n        }\n        return $mailChimpTarget;\n    }\n\n    /**\n     * @param $storeId\n     * @param $entityId\n     * @param $sync_delta\n     * @param string $sync_error\n     * @param int $sync_modified\n     */\n    protected function _updateSyncData($storeId, $entityId, $sync_delta = null, $sync_error = '', $sync_modified = 0)\n    {\n        $this->syncHelper->saveEcommerceData(\n            $storeId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE,\n            $sync_delta,\n            $sync_error,\n            $sync_modified\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Api/Result.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/21/16 4:09 PM\n * @file: Result.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\nuse Ebizmarts\\Mailchimp\\Helper\\Data as Helper;\n\nclass Result\n{\n    const MAILCHIMP_TEMP_DIR = 'Mailchimp';\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches\\CollectionFactory\n     */\n    private $_batchCollection;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Framework\\Archive\n     */\n    private $_archive;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory\n     */\n    private $_chimpErrors;\n    /**\n     * @var \\Magento\\Framework\\Filesystem\\Driver\\File\n     */\n    private $_driver;\n    /**\n     * @var \\Magento\\Framework\\HTTP\\Client\\CurlFactory\n     */\n    private $_curlFactory;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches\\CollectionFactory $batchCollection\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $chimpErrors\n     * @param \\Magento\\Framework\\Archive $archive\n     * @param \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n     * @param \\Magento\\Framework\\HTTP\\Client\\CurlFactory $curlFactory\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches\\CollectionFactory $batchCollection,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $chimpErrors,\n        \\Magento\\Framework\\Archive $archive,\n        \\Magento\\Framework\\Filesystem\\Driver\\File $driver,\n        \\Magento\\Framework\\HTTP\\Client\\CurlFactory $curlFactory\n    ) {\n\n        $this->_batchCollection     = $batchCollection;\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->_archive             = $archive;\n        $this->_chimpErrors         = $chimpErrors;\n        $this->_driver              = $driver;\n        $this->_curlFactory         = $curlFactory;\n    }\n    public function processResponses($storeId, $isMailChimpStoreId = false, $mailchimpStoreId)\n    {\n        $collection = $this->_batchCollection->create();\n        $collection\n            ->addFieldToFilter('store_id', ['eq' => $storeId])\n            ->addFieldToFilter('status', ['eq' => 'pending'])\n            ->addFieldToFilter('mailchimp_store_id', ['eq' => $mailchimpStoreId]);\n        /**\n         * @var $item \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches\n         */\n        $item = null;\n        foreach ($collection as $item) {\n            try {\n                $files = $this->getBatchResponse($item->getBatchId(), $storeId);\n                if (is_array($files) && count($files)) {\n                    $this->processEachResponseFile($files, $item->getBatchId(), $mailchimpStoreId, $storeId);\n                    $item->setStatus(\\Ebizmarts\\MailChimp\\Helper\\Data::BATCH_COMPLETED);\n                    $item->setModifiedDate($this->_helper->getGmtDate());\n                    $item->getResource()->save($item);\n                } elseif ($files === false) {\n                    $item->setStatus(\\Ebizmarts\\MailChimp\\Helper\\Data::BATCH_ERROR);\n                    $item->getResource()->save($item);\n                    $this->syncHelper->deleteAllByBatchId($item->getBatchId());\n                    continue;\n                }\n                $baseDir = $this->_helper->getBaseDir();\n                if ($this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $item->getBatchId())) {\n                    $dirFiles = $this->_driver->readDirectory(\n                        $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                        self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR .\n                        $item->getBatchId().DIRECTORY_SEPARATOR\n                    );\n                    foreach ($dirFiles as $dirFile) {\n                        $this->_driver->deleteFile(\n                            $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                            self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR .\n                            $item->getBatchId().DIRECTORY_SEPARATOR.$dirFile\n                        );\n                    }\n                    $this->_driver->deleteDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                        self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $item->getBatchId());\n                }\n            } catch (\\Exception $e) {\n                $this->_helper->log(\"Error with a response: \" . $e->getMessage());\n            }\n        }\n    }\n    public function getBatchResponse($batchId, $storeId = null)\n    {\n        $files = [];\n        try {\n            $baseDir = $this->_helper->getBaseDir();\n            $api = $this->_helper->getApi($storeId);\n            // check the status of the job\n            $response = $api->batchOperation->status($batchId);\n\n            if (isset($response['status']) && $response['status'] == 'finished') {\n                // Create temporary directory, if that does not exist\n                if (!$this->_driver->isDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . self::MAILCHIMP_TEMP_DIR)) {\n                    $this->_driver->createDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . self::MAILCHIMP_TEMP_DIR);\n                }\n                // get the tar.gz file with the results\n                // for AWS S3 use urldecode, for google drive use without urldecode\n                // $fileUrl = urldecode($response['response_body_url']);\n                $fileUrl = $response['response_body_url'];\n                $fileName = $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId;\n                $fd = $this->_driver->fileOpen($fileName . '.tar.gz', 'w');\n                $ch = $this->_curlFactory->create();\n                $ch->setOption(CURLOPT_URL, $fileUrl);\n                $ch->setOption(CURLOPT_FILE, $fd);\n                $ch->setOption(CURLOPT_FOLLOWLOCATION, true);\n                $r =$ch->get($fileUrl);\n                $this->_driver->fileClose($fd);\n                $this->_driver->createDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId);\n                $archive = $this->_archive;\n                $archive->unpack(\n                    $fileName . '.tar.gz',\n                    $baseDir . DIRECTORY_SEPARATOR . 'var' .\n                    DIRECTORY_SEPARATOR . self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId\n                );\n                $archive->unpack(\n                    $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId . '/' . $batchId . '.tar',\n                    $baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId\n                );\n                $dirFiles = $this->_driver->readDirectory($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId);\n                foreach ($dirFiles as $dirFile) {\n                    $name = pathinfo($dirFile);\n                    if ($name['extension'] == 'json') {\n                        $files[] = $dirFile;\n                    }\n                }\n                $this->_driver->deleteFile($baseDir . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR .\n                    self::MAILCHIMP_TEMP_DIR . DIRECTORY_SEPARATOR . $batchId . '/' . $batchId . '.tar');\n                $this->_driver->deleteFile($fileName . '.tar.gz');\n            }\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log($e->getFriendlyMessage());\n            return false;\n        } catch (\\Exception $e) {\n            $this->_helper->log($e->getMessage());\n        }\n        return $files;\n    }\n    protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, $storeId)\n    {\n        $listId = $this->_helper->getDefaultList($storeId);\n        foreach ($files as $file) {\n            $items = json_decode($this->_driver->fileGetContents($file));\n            if ($items!==false) {\n                foreach ($items as $item) {\n                    $line = explode('_', $item->operation_id);\n                    $type = $line[0];\n                    $id = $line[2];\n                    if ($item->status_code != 200) {\n                        //parse error\n                        $response = json_decode($item->response);\n                        if (preg_match('/already exists/', $response->detail)) {\n                            $this->_updateSyncData(\n                                $mailchimpStoreId,\n                                $listId,\n                                $type,\n                                $id,\n                                null,\n                                \\Ebizmarts\\MailChimp\\Helper\\Data::SYNCED\n                            );\n                            continue;\n                        }\n                        $mailchimpErrors = $this->_chimpErrors->create();\n                        $errorDetails = \"\";\n                        if (!empty($response->errors)) {\n                            foreach ($response->errors as $error) {\n                                if (isset($error->field) && isset($error->message)) {\n                                    $errorDetails .= $errorDetails != \"\" ? \" / \" : \"\";\n                                    $errorDetails .= $error->field . \" : \" . $error->message;\n                                }\n                            }\n                        }\n                        if ($errorDetails == \"\") {\n                            $errorDetails = $response->detail;\n                        }\n\n                        $error = $response->title . \" : \" . $response->detail;\n                        if ($type == Helper::IS_PRODUCT and $item->status_code == 404) {\n                            $this->syncHelper->deleteByTypeAndId($type, $id, $mailchimpStoreId);\n                        } else {\n                            $this->_updateSyncData(\n                                $mailchimpStoreId,\n                                $listId,\n                                $type,\n                                $id,\n                                $error,\n                                \\Ebizmarts\\MailChimp\\Helper\\Data::SYNCERROR\n                            );\n                        }\n                        if (property_exists($response, 'type')){\n                            $mailchimpErrors->setType($response->type);\n                        } else {\n                            $mailchimpErrors->setType('Unknown');\n                        }\n                        if (property_exists($response, 'title')){\n                            $mailchimpErrors->setTitle($response->title);\n                        } else {\n                            $mailchimpErrors->setTitle('Unknown');\n                        }\n                        $mailchimpErrors->setStatus($item->status_code);\n                        $mailchimpErrors->setErrors($errorDetails);\n                        $mailchimpErrors->setRegtype($type);\n                        $mailchimpErrors->setOriginalId($id);\n                        $mailchimpErrors->setBatchId($batchId);\n                        $mailchimpErrors->setMailchimpStoreId($mailchimpStoreId);\n                        $mailchimpErrors->setOriginalId($id);\n                        $mailchimpErrors->setBatchId($batchId);\n                        $mailchimpErrors->setStoreId($storeId);\n                        $mailchimpErrors->getResource()->save($mailchimpErrors);\n                    } else {\n                        $this->_updateSyncData(\n                            $mailchimpStoreId,\n                            $listId,\n                            $type,\n                            $id,\n                            null,\n                            \\Ebizmarts\\MailChimp\\Helper\\Data::SYNCED\n                        );\n                    }\n                }\n            } else {\n                switch (json_last_error()) {\n                    case JSON_ERROR_DEPTH:\n                        $this->_helper->log(' - Maximum stack depth exceeded');\n                        break;\n                    case JSON_ERROR_CTRL_CHAR:\n                        $this->_helper->log(' - Unexpected control character found');\n                        break;\n                    case JSON_ERROR_SYNTAX:\n                        $this->_helper->log(' - Syntax error, malformed JSON');\n                        break;\n                    case JSON_ERROR_NONE:\n                        $this->_helper->log(' - No errors');\n                        break;\n                }\n            }\n            $this->_driver->deleteFile($file);\n        }\n    }\n    private function _updateSyncData($mailchimpStoreId, $listId, $type, $id, $error, $status)\n    {\n        /**\n         * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimpSync\n         */\n        if ($type == \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER) {\n            $mailchimpStore = $listId;\n        } else {\n            $mailchimpStore = $mailchimpStoreId;\n        }\n        $this->syncHelper->saveEcommerceData(\n            $mailchimpStore,\n            $id,\n            $type,\n            null,\n            $error,\n            null,\n            null,\n            null,\n            $status,\n            true\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Api/Subscriber.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/15/17 11:02 AM\n * @file: Subscriber.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Api;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Subscriber\n{\n    const BATCH_LIMIT = 100;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\CollectionFactory\n     */\n    protected $_subscriberCollection;\n    /**\n     * @var \\Magento\\Framework\\Message\\ManagerInterface\n     */\n    protected $_message;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $_subscriberFactory;\n    protected $_interest=null;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\CollectionFactory $subscriberCollection\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Magento\\Framework\\Message\\ManagerInterface $message\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Newsletter\\Model\\ResourceModel\\Subscriber\\CollectionFactory $subscriberCollection,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Magento\\Framework\\Message\\ManagerInterface $message\n    ) {\n        $this->_helper                  = $helper;\n        $this->syncHelper               = $syncHelper;\n        $this->_subscriberCollection    = $subscriberCollection;\n        $this->_message                 = $message;\n        $this->_subscriberFactory       = $subscriberFactory;\n    }\n\n    public function sendSubscribers($storeId, $listId)\n    {\n        //get subscribers\n//        $listId = $this->_helper->getGeneralList($storeId);\n        $this->_interest = $this->_helper->getInterest($storeId);\n        $collection = $this->_subscriberCollection->create();\n        $collection->addFieldToFilter('subscriber_status', ['eq' => 1])\n            ->addFieldToFilter('store_id', ['eq' => $storeId]);\n        $collection->getSelect()->joinLeft(\n            ['m4m' => $this->_helper->getTableName('mailchimp_sync_ecommerce')],\n            \"m4m.related_id = main_table.subscriber_id and m4m.type = '\".\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER.\n            \"' and m4m.mailchimp_store_id = '\".$listId.\"'\",\n            ['m4m.*']\n        );\n        $collection->getSelect()->where(\"m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1\");\n        $collection->getSelect()->limit(self::BATCH_LIMIT);\n        $subscriberArray = [];\n        $date = $this->_helper->getDateMicrotime();\n        $batchId = \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER . '_' . $date;\n        $counter = 0;\n        /**\n         * @var $subscriber \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        foreach ($collection as $subscriber) {\n            $data = $this->_buildSubscriberData($subscriber);\n            $md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));\n            $subscriberJson = \"\";\n            //enconde to JSON\n            $subscriberJson = json_encode($data);\n            if ($subscriberJson!==false) {\n                if (!empty($subscriberJson)) {\n                    if ($subscriber->getMailchimpSyncModified() == 1) {\n                        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::SUB_MOD);\n                    } else {\n                        $this->_helper->modifyCounter(\\Ebizmarts\\MailChimp\\Helper\\Data::SUB_NEW);\n                    }\n                    $subscriberArray[$counter]['method'] = \"PUT\";\n                    $subscriberArray[$counter]['path'] = \"/lists/\" . $listId . \"/members/\" . $md5HashEmail;\n                    $subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId();\n                    $subscriberArray[$counter]['body'] = $subscriberJson;\n                    //update subscribers delta\n                    $this->_updateSubscriber($listId, $subscriber->getId());\n                }\n                $counter++;\n            } else {\n                $errorMessage = json_last_error_msg();\n                $this->_updateSubscriber(\n                    $listId,\n                    $subscriber->getId(),\n                    $this->_helper->getGmtDate(),\n                    $errorMessage,\n                    0\n                );\n            }\n        }\n        return $subscriberArray;\n    }\n\n    protected function _buildSubscriberData(\\Magento\\Newsletter\\Model\\Subscriber $subscriber)\n    {\n        $storeId = $subscriber->getStoreId();\n        $data = [];\n        $data[\"email_address\"] = $subscriber->getSubscriberEmail();\n        $mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriber);\n        if ($mergeVars) {\n            $data[\"merge_fields\"] = $mergeVars;\n        }\n        $data[\"status_if_new\"] = $data[\"status\"] = $this->_getMCStatus($subscriber->getStatus(), $storeId);\n        $interest = $this->_getInterest($subscriber);\n        if (count($interest)) {\n            $data['interests'] = $interest;\n        }\n\n        return $data;\n    }\n    protected function _getInterest(\\Magento\\Newsletter\\Model\\Subscriber $subscriber)\n    {\n        $rc = [];\n        $interest = $this->_helper->getSubscriberInterest(\n            $subscriber->getSubscriberId(),\n            $subscriber->getStoreId(),\n            $this->_interest\n        );\n        foreach ($interest as $i) {\n            if (array_key_exists('category', $i)) {\n                foreach ($i['category'] as $key => $value) {\n                    $rc[$value['id']] = $value['checked'];\n                }\n            }\n        }\n        return $rc;\n    }\n    /**\n     * Get status to send confirmation if Need to Confirm enabled on Magento\n     *\n     * @param $status\n     * @param $storeId\n     * @return string\n     */\n    protected function _getMCStatus($status, $storeId)\n    {\n        $confirmationFlagPath = \\Magento\\Newsletter\\Model\\Subscriber::XML_PATH_CONFIRMATION_FLAG;\n        if ($status == \\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNSUBSCRIBED) {\n            $status = 'unsubscribed';\n        } elseif ($this->_helper->getConfigValue($confirmationFlagPath, $storeId) &&\n            ($status == \\Magento\\Newsletter\\Model\\Subscriber::STATUS_NOT_ACTIVE ||\n                $status == \\Magento\\Newsletter\\Model\\Subscriber::STATUS_UNCONFIRMED)\n        ) {\n            $status = 'pending';\n        } elseif ($status == \\Magento\\Newsletter\\Model\\Subscriber::STATUS_SUBSCRIBED) {\n            $status = 'subscribed';\n        }\n        return $status;\n    }\n    public function deleteSubscriber(\\Magento\\Newsletter\\Model\\Subscriber $subscriber)\n    {\n        $storeId = $subscriber->getStoreId();\n        $listId = $this->_helper->getGeneralList($storeId);\n        $api = $this->_helper->getApi($storeId);\n        try {\n            $md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));\n            $api->lists->members->update($listId, $md5HashEmail, null, 'cleaned');\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log($e->getFriendlyMessage(), $storeId);\n            $this->_message->addErrorMessage($e->getMessage());\n        } catch (\\Exception $e) {\n            $this->_helper->log($e->getMessage(), $storeId);\n        }\n    }\n    public function update(\\Magento\\Newsletter\\Model\\Subscriber $subscriber)\n    {\n        $storeId = $subscriber->getStoreId();\n        $listId = $this->_helper->getGeneralList($storeId);\n        $this->_updateSubscriber(\n            $listId,\n            $subscriber->getId(),\n            $this->_helper->getGmtDate(),\n            '',\n            1\n        );\n    }\n    protected function _updateSubscriber(\n        $listId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null\n    ) {\n        $this->syncHelper->saveEcommerceData(\n            $listId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER,\n            $sync_delta,\n            $sync_error,\n            $sync_modified\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Config/Backend/ApiKey.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 9/30/16 12:09 PM\n * @file: Monkeylist.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Backend;\n\nuse Magento\\Framework\\App\\Config\\ScopeConfigInterface;\n\nclass ApiKey extends \\Magento\\Framework\\App\\Config\\Value\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\n     */\n    protected $resourceConfig;\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\DateTime\\DateTime\n     */\n    private $_date;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    private $_storeManager;\n\n    /**\n     * ApiKey constructor.\n     * @param \\Magento\\Framework\\Model\\Context $context\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param ScopeConfigInterface $config\n     * @param \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $resourceConfig\n     * @param \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource|null $resource\n     * @param \\Magento\\Framework\\Data\\Collection\\AbstractDb|null $resourceCollection\n     * @param \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\Model\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $resourceConfig,\n        \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource $resource = null,\n        \\Magento\\Framework\\Data\\Collection\\AbstractDb $resourceCollection = null,\n        \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        array $data = []\n    ) {\n        $this->_helper          = $helper;\n        $this->resourceConfig   = $resourceConfig;\n        $this->_date            = $date;\n        $this->_storeManager    = $storeManager;\n        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);\n    }\n\n    public function beforeSave()\n    {\n        $active = null;\n        $generalData = $this->getData();\n        $data = $this->getData('groups');\n        $found = 0;\n        if (isset($data['ecommerce']['fields']['active']['value'])) {\n            $active = $data['ecommerce']['fields']['active']['value'];\n        } elseif ($data['ecommerce']['fields']['active']['inherit']) {\n            $active = $data['ecommerce']['fields']['active']['inherit'];\n        }\n        if ($active && $this->isValueChanged()) {\n            $mailchimpStore = $this->_helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $this->getScopeId(),\n                $this->getScope()\n            );\n            $this->resourceConfig->deleteConfig(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                $this->getScope(),\n                $this->getScopeId()\n            );\n            foreach ($this->_storeManager->getStores() as $storeId => $val) {\n                if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE, $storeId) ==\n                    $mailchimpStore) {\n                    $found++;\n                }\n            }\n            if ($found==1) {\n                $this->_helper->cancelAllPendingBatches($mailchimpStore);\n            }\n        }\n        return parent::beforeSave();\n    }\n}\n"
  },
  {
    "path": "Model/Config/Backend/MonkeyList.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/22/17 3:08 PM\n * @file: MonkeyList.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Backend;\n\nclass MonkeyList extends \\Magento\\Framework\\App\\Config\\Value\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\n     */\n    protected $resourceConfig;\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\DateTime\\DateTime\n     */\n    private $_date;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    private $_storeManager;\n\n    /**\n     * ApiKey constructor.\n     * @param \\Magento\\Framework\\Model\\Context $context\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param ScopeConfigInterface $config\n     * @param \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $resourceConfig\n     * @param \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource|null $resource\n     * @param \\Magento\\Framework\\Data\\Collection\\AbstractDb|null $resourceCollection\n     * @param \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\Model\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $resourceConfig,\n        \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource $resource = null,\n        \\Magento\\Framework\\Data\\Collection\\AbstractDb $resourceCollection = null,\n        \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        array $data = []\n    ) {\n        $this->_helper          = $helper;\n        $this->resourceConfig   = $resourceConfig;\n        $this->_date            = $date;\n        $this->_storeManager    = $storeManager;\n        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);\n    }\n}\n"
  },
  {
    "path": "Model/Config/Backend/MonkeyStore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/29/17 4:29 PM\n * @file: MonkeyStore.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Backend;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass MonkeyStore extends \\Magento\\Framework\\App\\Config\\Value\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\n     */\n    protected $resourceConfig;\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\DateTime\\DateTime\n     */\n    private $_date;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    private $_storeManager;\n\n    private $oldListId = null;\n    const MAX_LISTS = 200;\n\n    /**\n     * @param \\Magento\\Framework\\Model\\Context $context\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config\n     * @param \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config $resourceConfig\n     * @param \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource|null $resource\n     * @param \\Magento\\Framework\\Data\\Collection\\AbstractDb|null $resourceCollection\n     * @param \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\Model\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList,\n        \\Magento\\Config\\Model\\ResourceModel\\Config $resourceConfig,\n        \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource $resource = null,\n        \\Magento\\Framework\\Data\\Collection\\AbstractDb $resourceCollection = null,\n        \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        array $data = []\n    ) {\n        $this->_helper          = $helper;\n        $this->syncHelper       = $syncHelper;\n        $this->resourceConfig   = $resourceConfig;\n        $this->_date            = $date;\n        $this->_storeManager    = $storeManager;\n        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);\n    }\n\n    public function beforeSave()\n    {\n        $data = $this->getData('groups');\n        $found = 0;\n        $newListId = null;\n        if (isset($data['ecommerce']['fields']['active']['value'])) {\n            $active = $data['ecommerce']['fields']['active']['value'];\n        } elseif ($data['ecommerce']['fields']['active']['inherit']) {\n            $active = $data['ecommerce']['fields']['active']['inherit'];\n        } else {\n            $active = 0;\n        }\n        if ($active && $this->isValueChanged()) {\n            $mailchimpStore     = $this->getOldValue();\n            // charge the $newListId\n            if (isset($data['general']['fields']['apikey']['value'])) {\n                $apiKey = $data['general']['fields']['apikey']['value'];\n            } else {\n                $apiKey = $this->_helper->getApiKey($this->getScopeId(), $this->getScope());\n            }\n            if (isset($data['general']['fields']['monkeylist']['value'])) {\n                $newListId = $data['general']['fields']['monkeylist']['value'];\n            } else {\n                $newListId = $this->getStore($apiKey, $this->getValue());\n                $this->_helper->saveConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST,\n                    $newListId,\n                    $this->getScopeId(),\n                    $this->getScope()\n                );\n            }\n            $this->oldListId = $this->_helper->getConfigValue(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST,\n                $this->getScopeId(),\n                $this->getScope()\n            );\n\n            $createWebhook = true;\n            $this->_helper->deleteConfig(\n                \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_JS_URL,\n                $this->getScopeId(),\n                $this->getScope()\n            );\n            foreach ($this->_storeManager->getStores() as $storeId => $val) {\n                $mstoreId = $this->_helper->getConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                    $storeId\n                );\n                if ($mstoreId == $mailchimpStore) {\n                    $this->_helper->deleteConfig(\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_JS_URL,\n                        $storeId,\n                        'stores'\n                    );\n                    $found++;\n                }\n                $listId = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST, $storeId);\n                if ($listId == $newListId) {\n                    $createWebhook = false;\n                }\n            }\n            if ($found==1) {\n                $this->_helper->cancelAllPendingBatches($mailchimpStore);\n                $this->syncHelper->resetErrors($mailchimpStore, $this->getScopeId(), true);\n            }\n            $this->_helper->restoreAllCanceledBatches($this->getValue());\n            if ($createWebhook) {\n                $this->_helper->createWebHook($apiKey, $newListId);\n            }\n        }\n        return parent::beforeSave();\n    }\n    private function getStore($apiKey, $store)\n    {\n        try {\n            $api = $this->_helper->getApiByApiKey($apiKey);\n            $store = $api->ecommerce->stores->get($store);\n            return $store['list_id'];\n        } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n            $this->_helper->log($e->getFriendlyMessage());\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "Model/Config/Backend/VarsMap.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/30/17 10:27 AM\n * @file: VarsMap.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Backend;\n\nclass VarsMap extends \\Magento\\Framework\\App\\Config\\Value\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\VarsMap\n     */\n    private $_varsHelper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n\n    /**\n     * VarsMap constructor.\n     * @param \\Magento\\Framework\\Model\\Context $context\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config\n     * @param \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList\n     * @param \\Ebizmarts\\MailChimp\\Helper\\VarsMap $varsMap\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource|null $resource\n     * @param \\Magento\\Framework\\Data\\Collection\\AbstractDb|null $resourceCollection\n     * @param array $data\n     */\n    public function __construct(\n        \\Magento\\Framework\\Model\\Context $context,\n        \\Magento\\Framework\\Registry $registry,\n        \\Magento\\Framework\\App\\Config\\ScopeConfigInterface $config,\n        \\Magento\\Framework\\App\\Cache\\TypeListInterface $cacheTypeList,\n        \\Ebizmarts\\MailChimp\\Helper\\VarsMap $varsMap,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\Model\\ResourceModel\\AbstractResource $resource = null,\n        \\Magento\\Framework\\Data\\Collection\\AbstractDb $resourceCollection = null,\n        array $data = []\n    ) {\n    \n        $this->_varsHelper = $varsMap;\n        $this->_helper      = $helper;\n        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);\n    }\n    protected function _afterLoad()\n    {\n        $value = $this->getValue();\n        $value = $this->_varsHelper->makeArrayFieldValue($value);\n        $this->setValue($value);\n    }\n\n    /**\n     * Prepare data before save\n     *\n     * @return void\n     */\n    public function beforeSave()\n    {\n        $value = $this->getValue();\n        if (is_array($value)) {\n            $value = $this->_varsHelper->makeStorableArrayFieldValue($value);\n        }\n        $this->setValue($value);\n    }\n}\n"
  },
  {
    "path": "Model/Config/ModuleVersion.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config;\n\nuse Magento\\Framework\\Component\\ComponentRegistrar;\nuse Magento\\Framework\\Component\\ComponentRegistrarInterface;\nuse Magento\\Framework\\Exception\\FileSystemException;\nuse Magento\\Framework\\Filesystem\\Directory\\ReadFactory;\n\nclass ModuleVersion\n{\n    const COMPOSER_FILE_NAME = 'composer.json';\n    /**\n     * @var ComponentRegistrarInterface\n     */\n    private $componentRegistrar;\n    /**\n     * @var ReadFactory\n     */\n    private $readFactory;\n\n    /**\n     * ModuleVersion constructor.\n     * @param ComponentRegistrarInterface $componentRegistrar\n     * @param ReadFactory $readFactory\n     */\n    public function __construct(ComponentRegistrarInterface $componentRegistrar, ReadFactory $readFactory)\n    {\n        $this->componentRegistrar = $componentRegistrar;\n        $this->readFactory = $readFactory;\n    }\n    public function getModuleVersion($moduleName) : string\n    {\n        $emptyVersionNumber = '';\n        $composerJsonData = null;\n        try {\n            $path = $this->componentRegistrar->getPath(ComponentRegistrar::MODULE, $moduleName);\n            $directoryRead = $this->readFactory->create($path);\n            $composerJsonData = $directoryRead->readFile(self::COMPOSER_FILE_NAME);\n        } catch (\\LogicException $pathException) {\n            return $emptyVersionNumber;\n        } catch (FileSystemException $fsException) {\n            return $emptyVersionNumber;\n        } catch (\\Exception $exception) {\n            return $emptyVersionNumber;\n        }\n        try {\n            $jsonData = json_decode($composerJsonData);\n            if ($jsonData === null) {\n                return $emptyVersionNumber;\n            }\n            return $jsonData->version ?? $emptyVersionNumber;\n        } catch (\\Exception $exception) {\n            return $emptyVersionNumber;\n        }\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/ApiKey.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/30/17 1:36 PM\n * @file: ApiKey.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass ApiKey implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    protected $options = null;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    protected $storeManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var \\Magento\\Framework\\Encryption\\Encryptor\n     */\n    protected $encryptor;\n\n    /**\n     * ApiKey constructor.\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Framework\\App\\RequestInterface $request\n     * @param \\Magento\\Framework\\Encryption\\Encryptor $encryptor\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function __construct(\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\App\\RequestInterface $request,\n        \\Magento\\Framework\\Encryption\\Encryptor $encryptor\n    ) {\n        $this->storeManager = $storeManager;\n        $this->helper = $helper;\n        $this->encryptor    = $encryptor;\n        $storeId = (int) $request->getParam(\"store\", 0);\n        if ($request->getParam('website', 0)) {\n            $scope = 'website';\n            $storeId = $request->getParam('website', 0);\n        } elseif ($request->getParam('store', 0)) {\n            $scope = 'stores';\n            $storeId = $request->getParam('store', 0);\n        } else {\n            $scope = 'default';\n        }\n    }\n    public function toOptionArray()\n    {\n        $rc = [];\n        if (is_array($this->options) && count($this->options)) {\n            $rc[] = ['value' => -1, 'label' => 'Select one ApiKey'];\n            foreach ($this->options as $apiKey) {\n                $rc[] = ['value'=> $this->encryptor->encrypt(trim($apiKey)), 'label' => $this->mask(trim($apiKey))];\n            }\n        }\n        return $rc;\n    }\n    public function getAllApiKeys()\n    {\n        $this->options = $this->helper->getAllApiKeys();\n    }\n    private function mask($str)\n    {\n        if (strlen($str) < 4) {\n            return __('Invalid API Key');\n        } else {\n            return substr($str, 0, 6) . str_repeat('*', strlen($str) - 4) . substr($str, -4);\n        }\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/CampaignAction.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass CampaignAction implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    private $actions = [\n        ['value' => 'sent', 'label' => 'Sent'],\n        ['value' => 'open', 'label' => 'Open'],\n        ['value' => 'click', 'label' => 'Click']\n    ];\n    public function toOptionArray()\n    {\n        return $this->actions;\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/CleanPeriod.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\nuse \\Magento\\Framework\\Data\\OptionSourceInterface;\n\nclass CleanPeriod implements OptionSourceInterface\n{\n    public function toOptionArray() {\n        return [1 => 'One day', 3=> 'Three days', 7=> 'One week'];\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/Cmspage.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 9/30/16 2:46 PM\n * @file: Cmspage.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass Cmspage\n{\n    /**\n     * @var \\Magento\\Cms\\Model\\Page\n     */\n    private $_page;\n    /**\n     * @param \\Magento\\Cms\\Model\\Page $page\n     */\n    public function __construct(\n        \\Magento\\Cms\\Model\\Page $page\n    ) {\n        $this->_page = $page;\n    }\n    public function toOptionArray()\n    {\n        $pages = $this->_page->getCollection()->addOrder('title', 'asc');\n        return ['checkout/cart' => 'Shopping Cart (default page)'] + $pages->toOptionIdArray();\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/Details.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\nuse Ebizmarts\\MailChimp\\Helper\\Http as MailChimpHttp;\nuse Magento\\Directory\\Helper\\Data as DirectoryHelper;\n\nclass Details implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    /**\n     * @var null\n     */\n    private $_options = null;\n    /**\n     * @var MailChimpHelper\n     */\n    private $_helper  = null;\n    /**\n     * @var \\Magento\\Framework\\Message\\ManagerInterface\n     */\n    private $_message;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    private $storeManager;\n    /**\n     * @var MailChimpHttp\n     */\n    private $httpClient;\n    private $_error = '';\n\n    /**\n     * @param MailChimpHelper $helper\n     * @param \\Magento\\Framework\\Message\\ManagerInterface $message\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param \\Magento\\Framework\\App\\RequestInterface $request\n     * @param MailChimpHttp $httpClient\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     * @throws \\Magento\\Framework\\Exception\\NoSuchEntityException\n     */\n    public function __construct(\n        MailChimpHelper $helper,\n        \\Magento\\Framework\\Message\\ManagerInterface $message,\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        \\Magento\\Framework\\App\\RequestInterface $request,\n        MailChimpHttp $httpClient,\n        DirectoryHelper $directoryHelper\n    ) {\n        $this->_message = $message;\n        $this->_helper  = $helper;\n        $this->storeManager = $storeManager;\n        $this->httpClient = $httpClient;\n        $this->httpClient->setUrl($helper->getConfigValue(MailChimpHelper::XML_REGISTER_URL).'/register');\n        $storeId = (int) $request->getParam(\"store\", 0);\n        if ($request->getParam('website', 0)) {\n            $scope = 'website';\n            $storeId = $request->getParam('website', 0);\n        } elseif ($request->getParam('store', 0)) {\n            $scope = 'stores';\n            $storeId = $request->getParam('store', 0);\n        } else {\n            $scope = 'default';\n        }\n\n        if ($this->_helper->getApiKey($storeId, $scope)) {\n            $api = $this->_helper->getApi($storeId, $scope);\n            try {\n                $this->_options = $api->root->info();\n                $optionsList = $api->lists->getLists(\n                    $this->_helper->getConfigValue(\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST,\n                        $storeId,\n                        $scope\n                    )\n                );\n                if ($optionsList &&\n                    array_key_exists('stats', $optionsList) &&\n                    array_key_exists('member_count', $optionsList['stats'])) {\n                    $this->_options['list_subscribers'] = $optionsList['stats']['member_count'];\n                }\n                $mailchimpStoreId = $this->_helper->getConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                    $storeId,\n                    $scope\n                );\n                if ($mailchimpStoreId && $mailchimpStoreId!=-1 &&\n                    $this->_helper->getConfigValue(\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ECOMMERCE_ACTIVE,\n                        $storeId,\n                        $scope\n                    )\n                ) {\n                    $token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $storeId, $scope);\n                    if (!$token) {\n                        $registerData['store_url'] = stripslashes($this->storeManager->getStore($storeId)->getBaseUrl());\n                        $registerData['account_name'] = $this->_options['account_name'];\n                        $registerData['email'] = $this->_options['email'];\n                        $registerData['first_name'] = $this->_options['first_name'];\n                        $registerData['last_name'] = $this->_options['last_name'];\n                        $registerData['pricing_plan_type'] = $this->_options['pricing_plan_type'];\n                        $registerData['username'] = $this->_options['username'];\n                        $registerData['account_id'] = $this->_options['account_id'];\n                        $registerData['city'] = $this->_helper->getConfigValue(\\Magento\\Store\\Model\\Information::XML_PATH_STORE_INFO_CITY,$storeId, $scope);\n                        $registerData['country'] = $directoryHelper->getDefaultCountry($storeId);\n                        $registerData['total_subscribers'] = $this->_options['total_subscribers'];\n                        $registerDataJson = json_encode($registerData);\n                        $ret = $this->httpClient->post($registerDataJson);\n                        $ret = json_decode($ret,true);\n                        if ( !$ret['error']) {\n                            $error = false;\n                            $token = $ret['token'];\n                            $this->_helper->saveConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $token,  $storeId, $scope);\n                        }\n                    }\n                    $storeInfo = $api->ecommerce->stores->get($mailchimpStoreId);\n                    $this->_options['is_syncing'] = $storeInfo['is_syncing'];\n                    $this->_options['date_sync'] = $this->getDateSync($mailchimpStoreId);\n                    $this->_options['store_exists'] = true;\n                    $totalCustomers = $api->ecommerce->customers->getAll($mailchimpStoreId, 'total_items');\n                    $this->_options['total_customers'] = $totalCustomers['total_items'];\n                    $totalProducts = $api->ecommerce->products->getAll($mailchimpStoreId, 'total_items');\n                    $this->_options['total_products'] = $totalProducts['total_items'];\n                    $totalOrders = $api->ecommerce->orders->getAll($mailchimpStoreId, 'total_items');\n                    $this->_options['total_orders'] = $totalOrders['total_items'];\n                    $totalCarts = $api->ecommerce->carts->getAll($mailchimpStoreId, 'total_items');\n                    $this->_options['total_carts'] = $totalCarts['total_items'];\n                } else {\n                    $this->_options['store_exists'] = false;\n                }\n                $token = $this->_helper->getConfigValue(MailChimpHelper::XML_STATISTICS_TOKEN, $storeId, $scope);\n                $this->_options['token'] = $token;\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n                $this->_error = $e->getMessage();\n                $this->_options['store_exists'] = false;\n            }\n        } else {\n            $this->_options = '--- Enter your API Key ---';\n        }\n    }\n\n    /**\n     * @return array\n     */\n    public function toOptionArray()\n    {\n        $ret = '';\n        if ($this->_error != '') {\n            $ret = [['label' => 'Important', 'value' => __(\"Store not found\")]];\n        } elseif(is_array($this->_options)) {\n            if (isset($this->_options['account_name'])) {\n                $ret = [\n                    ['label' => __('Username'), 'value' => $this->_options['account_name']],\n                    ['label' => 'Total Member Subscribers', 'value' => $this->_options['total_subscribers']]];\n                if (array_key_exists('list_subscribers', $this->_options)) {\n                    $ret = array_merge(\n                        $ret,\n                        [['label' => 'Total List Subscribers', 'value' => $this->_options['list_subscribers']]]\n                    );\n                }\n                $ret = array_merge($ret, [['label'=> __('Registration ID'), 'value' => $this->_options['token']]]);\n                if (isset($this->_options['store_exists']) && $this->_options['store_exists']) {\n                    $ret = array_merge($ret, [\n                        ['label' => 'Ecommerce Data uploaded to MailChimp', 'value' => ''],\n                        ['label' => '  Total Customers', 'value' => $this->_options['total_customers']],\n                        ['label' => '  Total Products', 'value' => $this->_options['total_products']],\n                        ['label' => '  Total Orders', 'value' => $this->_options['total_orders']],\n                        ['label' => '  Total Carts', 'value' => $this->_options['total_carts']]\n                    ]);\n                    if ($this->_options['is_syncing']) {\n                        $ret = array_merge($ret, [\n                            ['label'=> __('This account is currently syncing'), 'value'=>'']\n                        ]);\n                    } else {\n                        $ret = array_merge($ret, [\n                            ['label'=> __('Account Synced since'), 'value'=>$this->_options['date_sync']]\n                        ]);\n                    }\n                } else {\n                    $ret = array_merge($ret, [\n                        ['label'=>'Ecommerce disabled, only subscribers will be synchronized (your orders, products,etc will be not synchronized).','value'=>'']\n                    ]);\n                }\n            }\n        } elseif (!$this->_options) {\n            $ret = [\n                ['label' => 'Error', 'value' => __('--- Invalid API Key ---')]\n            ];\n        } else {\n            $ret = [['label' => 'Important', 'value' => __($this->_options)]];\n        }\n        return $ret;\n    }\n    private function getDateSync($mailchimpStoreId)\n    {\n        return $this->_helper->getMCMinSyncDateFlagByMailchimpStore(\n            $mailchimpStoreId,\n            0,\n            \"default\"\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/Interest.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/13/17 12:07 PM\n * @file: Interest.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass Interest implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    private $options = null;\n\n    /**\n     * Interest constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Framework\\App\\RequestInterface $request\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\App\\RequestInterface $request\n    ) {\n\n        $storeId = (int) $request->getParam(\"store\", 0);\n        if ($request->getParam('website', 0)) {\n            $scope = 'website';\n            $storeId = $request->getParam('website', 0);\n        } elseif ($request->getParam('store', 0)) {\n            $scope = 'stores';\n            $storeId = $request->getParam('store', 0);\n        } else {\n            $scope = 'default';\n        }\n        if ($helper->getApiKey($storeId, $scope)) {\n            try {\n                $this->options = $helper->getApi($storeId, $scope)->lists->interestCategory->getAll(\n                    $helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST, $storeId, $scope),\n                    null,\n                    null,\n                    200\n                );\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $helper->log($e->getFriendlyMessage());\n            }\n        }\n    }\n\n    public function toOptionArray()\n    {\n        if (is_array($this->options) && is_array($this->options['categories']) && count($this->options['categories'])) {\n            $rc = [];\n            foreach ($this->options['categories'] as $interest) {\n                $rc[] = ['value'=> $interest['id'], 'label' => $interest['title']];\n            }\n        } else {\n            $rc[] = ['value' => [], 'label' => __('---No Data---')];\n        }\n        return $rc;\n    }\n    public function toArray()\n    {\n        $rc = [];\n        $rc[$this->options['id']] = $this->options['name'];\n        return $rc;\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/MonkeyList.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/28/17 10:57 AM\n * @file: MonkeyStore.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass MonkeyList implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    private $options = null;\n\n    /**\n     * MonkeyList constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Framework\\App\\RequestInterface $request\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\App\\RequestInterface $request\n    ) {\n        $storeId = (int) $request->getParam(\"store\", 0);\n        if ($request->getParam('website', 0)) {\n            $scope = 'website';\n            $storeId = $request->getParam('website', 0);\n        } elseif ($request->getParam('store', 0)) {\n            $scope = 'stores';\n            $storeId = $request->getParam('store', 0);\n        } else {\n            $scope = 'default';\n        }\n\n        if ($helper->getApiKey($storeId, $scope)) {\n            try {\n                $this->options = $helper->getApi($storeId, $scope)->lists->getLists(\n                    $helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST, $storeId, $scope)\n                );\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $helper->log($e->getFriendlyMessage());\n            }\n        }\n    }\n    public function toOptionArray()\n    {\n        if (is_array($this->options)) {\n            $rc = [];\n            if (isset($this->options['id'])) {\n                $rc[] = ['value' => $this->options['id'], 'label' => $this->options['name']];\n            }\n        } else {\n            $rc[] = ['value' => 0, 'label' => __('---No Data---')];\n        }\n        return $rc;\n    }\n    public function toArray()\n    {\n        $rc = [];\n        $rc[$this->options['id']] = $this->options['name'];\n        return $rc;\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/MonkeyStore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/28/17 10:57 AM\n * @file: MonkeyStore.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass MonkeyStore implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    private $options = null;\n\n    /**\n     * MonkeyStore constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Framework\\App\\RequestInterface $request\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\App\\RequestInterface $request\n    ) {\n        $storeId = (int) $request->getParam(\"store\", 0);\n        if ($request->getParam('website', 0)) {\n            $scope = 'website';\n            $storeId = $request->getParam('website', 0);\n        } elseif ($request->getParam('store', 0)) {\n            $scope = 'stores';\n            $storeId = $request->getParam('store', 0);\n        } else {\n            $scope = 'default';\n        }\n        if ($helper->getApiKey($storeId, $scope)) {\n            try {\n                $this->options = $helper->getApi($storeId, $scope)->ecommerce->stores->get(\n                    null,\n                    null,\n                    null,\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::MAXSTORES\n                );\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $helper->log($e->getFriendlyMessage());\n            }\n        }\n    }\n    public function toOptionArray()\n    {\n        if (is_array($this->options)) {\n            $rc = [];\n            $rc[] = ['value' => -1, 'label' => 'Select one Mailchimp Store'];\n            foreach ($this->options['stores'] as $store) {\n                if ($store['platform'] == \\Ebizmarts\\MailChimp\\Helper\\Data::PLATFORM) {\n                    if ($store['list_id']=='') {\n                        continue;\n                    }\n                    if (isset($store['connected_site'])) {\n                        $label = $store['name'];\n                    } else {\n                        $label = $store['name'].' (Warning: not connected)';\n                    }\n\n                    $rc[] = ['value'=> $store['id'], 'label' => $label];\n                }\n            }\n        } else {\n            $rc[] = ['value' => 0, 'label' => __('---No Data---')];\n        }\n        return $rc;\n    }\n    public function toArray()\n    {\n        $rc = [];\n        foreach ($this->options['stores'] as $store) {\n            $rc[$store['id']] = $store['name'];\n        }\n        return $rc;\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/Months.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 15/09/22 12:07 PM\n * @file: Months.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass Months implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    public function toOptionArray()\n    {\n        return [\"0\" => __(\"No\"), \"1\"=> \"1\", \"2\" =>\"2\", \"3\" => \"3\", \"4\" => \"4\"];\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/Timeout.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass Timeout implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    public function toOptionArray()\n    {\n        return [10 => 10, 20=> 20, 30=>30];\n    }\n}\n"
  },
  {
    "path": "Model/Config/Source/WebhookDelete.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/31/17 11:26 AM\n * @file: WebhookDelete.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Config\\Source;\n\nclass WebhookDelete implements \\Magento\\Framework\\Option\\ArrayInterface\n{\n    public function toOptionArray()\n    {\n        return [\n            ['value' => 0, 'label'=>__('Unsubscribe')],\n            ['value' => 1, 'label'=>__('Delete subscriber')]\n        ];\n    }\n}\n"
  },
  {
    "path": "Model/HTTP/Client/Curl.php",
    "content": "<?php\n\ndeclare(strict_types=1);\n\nnamespace Ebizmarts\\MailChimp\\Model\\HTTP\\Client;\n\n/**\n * Class to work with HTTP protocol using curl library\n *\n * @author      Magento Core Team <core@magentocommerce.com>\n * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)\n * @api\n */\nclass Curl implements \\Magento\\Framework\\HTTP\\ClientInterface\n{\n    /**\n     * Max supported protocol by curl CURL_SSLVERSION_TLSv1_2\n     * @var int\n     */\n    private $sslVersion;\n\n    /**\n     * Hostname\n     * @var string\n     */\n    protected $_host = 'localhost';\n\n    /**\n     * @var int\n     */\n    protected $_port = 80;\n\n    /**\n     * Stream resource\n     * @var object\n     */\n    protected $_sock = null;\n\n    /**\n     * Request headers\n     * @var array\n     */\n    protected $_headers = [];\n\n    /**\n     * Fields for POST method - hash\n     * @var array\n     */\n    protected $_postFields = [];\n\n    /**\n     * Request cookies\n     * @var array\n     */\n    protected $_cookies = [];\n\n    /**\n     * @var array\n     */\n    protected $_responseHeaders = [];\n\n    /**\n     * @var string\n     */\n    protected $_responseBody = '';\n\n    /**\n     * @var int\n     */\n    protected $_responseStatus = 0;\n\n    /**\n     * Request timeout\n     * @var int type\n     */\n    protected $_timeout = 300;\n\n    /**\n     * TODO\n     * @var int\n     */\n    protected $_redirectCount = 0;\n\n    /**\n     * Curl\n     * @var resource\n     */\n    protected $_ch;\n\n    /**\n     * User overrides options hash\n     * Are applied before curl_exec\n     *\n     * @var array\n     */\n    protected $_curlUserOptions = [];\n\n    /**\n     * Header count, used while parsing headers\n     * in CURL callback function\n     * @var int\n     */\n    protected $_headerCount = 0;\n\n    /**\n     * Set request timeout\n     *\n     * @param int $value value in seconds\n     * @return void\n     */\n    public function setTimeout($value)\n    {\n        $this->_timeout = (int)$value;\n    }\n\n    /**\n     * @param int|null $sslVersion\n     */\n    public function __construct($sslVersion = null)\n    {\n        $this->sslVersion = $sslVersion;\n    }\n\n    /**\n     * Set headers from hash\n     *\n     * @param array $headers\n     * @return void\n     */\n    public function setHeaders($headers)\n    {\n        $this->_headers = $headers;\n    }\n\n    /**\n     * Add header\n     *\n     * @param string $name name, ex. \"Location\"\n     * @param string $value value ex. \"http://google.com\"\n     * @return void\n     */\n    public function addHeader($name, $value)\n    {\n        $this->_headers[$name] = $value;\n    }\n\n    /**\n     * Remove specified header\n     *\n     * @param string $name\n     * @return void\n     */\n    public function removeHeader($name)\n    {\n        unset($this->_headers[$name]);\n    }\n\n    /**\n     * Authorization: Basic header\n     *\n     * Login credentials support\n     *\n     * @param string $login username\n     * @param string $pass password\n     * @return void\n     */\n    public function setCredentials($login, $pass)\n    {\n        $val = base64_encode(\"{$login}:{$pass}\");\n        $this->addHeader(\"Authorization\", \"Basic {$val}\");\n    }\n\n    /**\n     * Add cookie\n     *\n     * @param string $name\n     * @param string $value\n     * @return void\n     */\n    public function addCookie($name, $value)\n    {\n        $this->_cookies[$name] = $value;\n    }\n\n    /**\n     * Remove cookie\n     *\n     * @param string $name\n     * @return void\n     */\n    public function removeCookie($name)\n    {\n        unset($this->_cookies[$name]);\n    }\n\n    /**\n     * Set cookies array\n     *\n     * @param array $cookies\n     * @return void\n     */\n    public function setCookies($cookies)\n    {\n        $this->_cookies = $cookies;\n    }\n\n    /**\n     * Clear cookies\n     *\n     * @return void\n     */\n    public function removeCookies()\n    {\n        $this->setCookies([]);\n    }\n\n    /**\n     * Make GET request\n     *\n     * @param string $uri uri relative to host, ex. \"/index.php\"\n     * @return void\n     */\n    public function get($uri)\n    {\n        $this->makeRequest(\"GET\", $uri);\n    }\n\n    /**\n     * Make POST request\n     *\n     * String type was added to parameter $param in order to support sending JSON or XML requests.\n     * This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373\n     *\n     * @param string $uri\n     * @param array|string $params\n     * @return void\n     *\n     * @see \\Magento\\Framework\\HTTP\\Client#post($uri, $params)\n     */\n    public function post($uri, $params)\n    {\n        $this->makeRequest(\"POST\", $uri, $params);\n    }\n    public function patch($uri, $params)\n    {\n        $this->makeRequest(\"PATCH\", $uri, $params);\n    }\n    public function put($uri, $params)\n    {\n        $this->makeRequest(\"PUT\", $uri, $params);\n    }\n    /**\n     * Get response headers\n     *\n     * @return array\n     */\n    public function getHeaders()\n    {\n        return $this->_responseHeaders;\n    }\n\n    /**\n     * Get response body\n     *\n     * @return string\n     */\n    public function getBody()\n    {\n        return $this->_responseBody;\n    }\n\n    /**\n     * Get cookies response hash\n     *\n     * @return array\n     */\n    public function getCookies()\n    {\n        if (empty($this->_responseHeaders['Set-Cookie'])) {\n            return [];\n        }\n        $out = [];\n        foreach ($this->_responseHeaders['Set-Cookie'] as $row) {\n            $values = explode(\"; \", $row ?? '');\n            $c = count($values);\n            if (!$c) {\n                continue;\n            }\n            list($key, $val) = explode(\"=\", $values[0]);\n            if ($val === null) {\n                continue;\n            }\n            $out[trim($key)] = trim($val);\n        }\n        return $out;\n    }\n\n    /**\n     * Get cookies array with details\n     * (domain, expire time etc)\n     *\n     * @return array\n     */\n    public function getCookiesFull()\n    {\n        if (empty($this->_responseHeaders['Set-Cookie'])) {\n            return [];\n        }\n        $out = [];\n        foreach ($this->_responseHeaders['Set-Cookie'] as $row) {\n            $values = explode(\"; \", $row ?? '');\n            $c = count($values);\n            if (!$c) {\n                continue;\n            }\n            list($key, $val) = explode(\"=\", $values[0]);\n            if ($val === null) {\n                continue;\n            }\n            $out[trim($key)] = ['value' => trim($val)];\n            array_shift($values);\n            $c--;\n            if (!$c) {\n                continue;\n            }\n            for ($i = 0; $i < $c; $i++) {\n                list($subkey, $val) = explode(\"=\", $values[$i]);\n                $out[trim($key)][trim($subkey)] = $val !== null ? trim($val) : '';\n            }\n        }\n        return $out;\n    }\n\n    /**\n     * Get response status code\n     *\n     * @see lib\\Magento\\Framework\\HTTP\\Client#getStatus()\n     *\n     * @return int\n     */\n    public function getStatus()\n    {\n        return $this->_responseStatus;\n    }\n\n    /**\n     * Make request\n     *\n     * String type was added to parameter $param in order to support sending JSON or XML requests.\n     * This feature was added base on Community Pull Request https://github.com/magento/magento2/pull/8373\n     *\n     * @param string $method\n     * @param string $uri\n     * @param array|string $params - use $params as a string in case of JSON or XML POST request.\n     *\n     * @return void\n     * @SuppressWarnings(PHPMD.CyclomaticComplexity)\n     * @SuppressWarnings(PHPMD.NPathComplexity)\n     */\n    protected function makeRequest($method, $uri, $params = [])\n    {\n        $this->_ch = curl_init();\n        $this->curlOption(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS);\n        $this->curlOption(CURLOPT_URL, $uri);\n        if ($method == 'POST') {\n            $this->curlOption(CURLOPT_POST, 1);\n            $this->curlOption(CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params);\n        } elseif ($method == \"GET\") {\n            $this->curlOption(CURLOPT_HTTPGET, 1);\n        } else {\n            $this->curlOption(CURLOPT_CUSTOMREQUEST, $method);\n            $this->curlOption(CURLOPT_POSTFIELDS, is_array($params) ? http_build_query($params) : $params);\n        }\n\n        if (count($this->_headers)) {\n            $heads = [];\n            foreach ($this->_headers as $k => $v) {\n                $heads[] = $k . ': ' . $v;\n            }\n            $this->curlOption(CURLOPT_HTTPHEADER, $heads);\n        }\n\n        if (count($this->_cookies)) {\n            $cookies = [];\n            foreach ($this->_cookies as $k => $v) {\n                $cookies[] = \"{$k}={$v}\";\n            }\n            $this->curlOption(CURLOPT_COOKIE, implode(\";\", $cookies));\n        }\n\n        if ($this->_timeout) {\n            $this->curlOption(CURLOPT_TIMEOUT, $this->_timeout);\n        }\n\n        if ($this->_port != 80) {\n            $this->curlOption(CURLOPT_PORT, $this->_port);\n        }\n\n        $this->curlOption(CURLOPT_RETURNTRANSFER, 1);\n        $this->curlOption(CURLOPT_HEADERFUNCTION, [$this, 'parseHeaders']);\n        if ($this->sslVersion !== null) {\n            $this->curlOption(CURLOPT_SSLVERSION, $this->sslVersion);\n        }\n\n        if (count($this->_curlUserOptions)) {\n            foreach ($this->_curlUserOptions as $k => $v) {\n                $this->curlOption($k, $v);\n            }\n        }\n\n        $this->_headerCount = 0;\n        $this->_responseHeaders = [];\n        $this->_responseBody = curl_exec($this->_ch);\n        $err = curl_errno($this->_ch);\n        if ($err) {\n            $this->doError(curl_error($this->_ch));\n        }\n        curl_close($this->_ch);\n    }\n\n    /**\n     * Throw error exception\n     *\n     * @param string $string\n     * @return void\n     * @throws \\Exception\n     */\n    public function doError($string)\n    {\n        //  phpcs:ignore Magento2.Exceptions.DirectThrow\n        curl_close($this->_ch);\n        throw new \\Exception($string);\n    }\n\n    /**\n     * Parse headers - CURL callback function\n     *\n     * @param resource $ch curl handle, not needed\n     * @param string $data\n     * @return int\n     * @throws \\Exception\n     * @SuppressWarnings(PHPMD.UnusedFormalParameter)\n     */\n    protected function parseHeaders($ch, $data)\n    {\n        $data = $data !== null ? $data : '';\n        if ($this->_headerCount == 0) {\n            $line = explode(\" \", trim($data), 3);\n            if (count($line) < 2) {\n                $this->doError(\"Invalid response line returned from server: \" . $data);\n            }\n            $this->_responseStatus = (int)$line[1];\n        } else {\n            $name = $value = '';\n            $out = explode(\": \", trim($data), 2);\n            if (count($out) == 2) {\n                $name = $out[0];\n                $value = $out[1];\n            }\n\n            if (strlen($name)) {\n                if ('set-cookie' === strtolower($name)) {\n                    $this->_responseHeaders['Set-Cookie'][] = $value;\n                } else {\n                    $this->_responseHeaders[$name] = $value;\n                }\n            }\n        }\n        $this->_headerCount++;\n\n        return strlen($data);\n    }\n\n    /**\n     * Set curl option directly\n     *\n     * @param string $name\n     * @param mixed $value\n     * @return void\n     */\n    protected function curlOption($name, $value)\n    {\n        curl_setopt($this->_ch, $name, $value);\n    }\n\n    /**\n     * Set curl options array directly\n     *\n     * @param array $arr\n     * @return void\n     */\n    protected function curlOptions($arr)\n    {\n        curl_setopt_array($this->_ch, $arr);\n    }\n\n    /**\n     * Set CURL options overrides array\n     *\n     * @param array $arr\n     * @return void\n     */\n    public function setOptions($arr)\n    {\n        $this->_curlUserOptions = $arr;\n    }\n\n    /**\n     * Set curl option\n     *\n     * @param string $name\n     * @param mixed $value\n     * @return void\n     */\n    public function setOption($name, $value)\n    {\n        $this->_curlUserOptions[$name] = $value;\n    }\n}\n"
  },
  {
    "path": "Model/Logger/Handler.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Logger;\n\nuse Monolog;\n\nclass Handler extends \\Magento\\Framework\\Logger\\Handler\\Base\n{\n    /**\n     * File name\n     * @var string\n     */\n    protected $fileName = '/var/log/MailChimp.log';\n\n    /**\n     * Logging level\n     * @var int\n     */\n    protected $loggerType = Logger::INFO;\n}\n"
  },
  {
    "path": "Model/Logger/Logger.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Logger;\n\nclass Logger extends \\Monolog\\Logger\n{\n\n    public function mailchimpLog($message, $file)\n    {\n        if ($file) {\n            $fileName = BP. DIRECTORY_SEPARATOR .'var'. DIRECTORY_SEPARATOR.'log'.\n                DIRECTORY_SEPARATOR.$file.'_Request.log';\n            $this->pushHandler(new \\Monolog\\Handler\\StreamHandler($fileName));\n        }\n\n        try {\n            if ($message===null) {\n                $message = \"NULL\";\n            }\n            if (is_array($message)) {\n                $message = json_encode($message, JSON_PRETTY_PRINT);\n            }\n            if (is_object($message)) {\n                $message = json_encode($message, JSON_PRETTY_PRINT);\n            }\n            if (!empty(json_last_error())) {\n                $message = (string)json_last_error();\n            }\n            $message = (string)$message;\n        } catch (\\Exception $e) {\n            $message = \"INVALID MESSAGE\";\n        }\n        $message .= \"\\r\\n\";\n        $this->info($message);\n        if ($file) {\n            $this->popHandler();\n        }\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpErrors.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/21/16 4:55 PM\n * @file: MailChimpErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpErrors extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpErrors::class);\n    }\n    public function getByStoreIdType($storeId, $id, $type)\n    {\n        $this->getResource()->getByStoreIdType($this, $storeId, $id, $type);\n        return $this;\n    }\n    public function deleteByStorePeriod($storeId, $interval, $limit)\n    {\n        return $this->getResource()->deleteByStorePeriod($this, $storeId, $interval, $limit);\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpInterestGroup.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/20/17 3:43 PM\n * @file: MailChimpInterestGroup.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpInterestGroup extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup::class);\n    }\n    public function getBySubscriberIdStoreId($subscriberId, $storeId)\n    {\n        $this->getResource()->getBySubscriberIdStoreId($this, $subscriberId, $storeId);\n        return $this;\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpStores.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/21/16 4:55 PM\n * @file: MailChimpErrors.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpStores extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores::class);\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpSyncBatches.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/17/16 4:07 PM\n * @file: MailChimpSyncBatches.php\n */\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpSyncBatches extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches::class);\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpSyncEcommerce.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/21/16 4:55 PM\n * @file: MailChimpSyncEcommerce.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpSyncEcommerce extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        parent::_construct();\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce::class);\n    }\n\n    public function getByStoreIdType($storeId, $id, $type)\n    {\n        $this->getResource()->getByStoreIdType($this, $storeId, $id, $type);\n        return $this;\n    }\n    public function markAllAsDeleted($id, $type, $relatedDeletedId)\n    {\n        $this->getResource()->markAllAsDeleted($this, $id, $type, $relatedDeletedId);\n        return $this;\n    }\n    public function markEcommorceAsNotDeleted($id, $type)\n    {\n        $this->getResource()->markEcommorceAsNotDeleted($this, $id, $type);\n        return $this;\n    }\n    public function markAllAsModified($id, $type)\n    {\n        $this->getResource()->markAllAsModified($this, $id, $type);\n        return $this;\n    }\n    public function deleteAllByIdType($id, $type, $mailchimpStoreId)\n    {\n        $this->getResource()->deleteAllByIdType($this, $id, $type, $mailchimpStoreId);\n        return $this;\n    }\n    public function deleteAllByBatchid($batchId)\n    {\n        $this->getResource()->deleteAllByBatchid($this, $batchId);\n    }\n    public function deleteByTypeAndId($type, $id, $mailchimpStoreId)\n    {\n        $this->getResource()->deleteByTypeAndId($this, $type, $id, $mailchimpStoreId);\n    }\n    public function markAllAsModifiedByIds($mailchimpStoreId, $ids, $type)\n    {\n        $this->getResource()->markAllAsModifiedByIds($this, $mailchimpStoreId, $ids, $type);\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpSyncEcommerceFactory.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/28/17 7:24 PM\n * @file: MailChimpSyncEcommerceFactory.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpSyncEcommerceFactory\n{\n\n    protected $_objectManager;\n    protected $_instanceName;\n\n    /**\n     * MailChimpSyncEcommerceFactory constructor.\n     * @param \\Magento\\Framework\\ObjectManagerInterface $objectManager\n     * @param string $instanceName\n     */\n    public function __construct(\n        \\Magento\\Framework\\ObjectManagerInterface $objectManager,\n        $instanceName = \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce::class\n    ) {\n    \n        $this->_objectManager   = $objectManager;\n        $this->_instanceName    = $instanceName;\n    }\n\n    /**\n     * @param array $data\n     * @return \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n     */\n    public function create(array $data = [])\n    {\n        return $this->_objectManager->create($this->_instanceName, $data);\n    }\n}\n"
  },
  {
    "path": "Model/MailChimpWebhookRequest.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/26/17 11:32 AM\n * @file: MailChimpWebhookRequest.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailChimpWebhookRequest extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest::class);\n    }\n}\n"
  },
  {
    "path": "Model/MailchimpNotification.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model;\n\nclass MailchimpNotification extends \\Magento\\Framework\\Model\\AbstractModel\n{\n    protected function _construct()\n    {\n        $this->_init(\\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailchimpNotification::class);\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/AccountManagement.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/24/17 5:33 PM\n * @file: AccountManagement.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nclass AccountManagement\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Checkout\\Model\\Session\n     */\n    protected $_session;\n    /**\n     * @var \\Magento\\Quote\\Model\\QuoteFactory\n     */\n    protected $_quote;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $_storeManager;\n\n    /**\n     * AccountManagement constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Checkout\\Model\\Session $checkoutSession\n     * @param \\Magento\\Quote\\Model\\QuoteFactory $quote\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Checkout\\Model\\Session $checkoutSession,\n        \\Magento\\Quote\\Model\\QuoteFactory $quote,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n    ) {\n    \n        $this->_helper  = $helper;\n        $this->_quote   = $quote;\n        $this->_session = $checkoutSession;\n        $this->_storeManager = $storeManager;\n    }\n\n    /**\n     * @param \\Magento\\Customer\\Model\\AccountManagement $accountManagement\n     * @param \\Closure $proceed\n     * @param $customerEmail\n     * @param null $websiteId\n     */\n    public function aroundIsEmailAvailable(\n        \\Magento\\Customer\\Model\\AccountManagement $accountManagement,\n        \\Closure $proceed,\n        $customerEmail,\n        $websiteId = null\n    ) {\n    \n        $ret = $proceed($customerEmail, $websiteId);\n        if ($this->_session && $this->_helper->isEmailSavingEnabled($this->_storeManager->getStore()->getId())) {\n            $quoteId = $this->_session->getQuoteId();\n            if ($quoteId) {\n                $quote = $this->_quote->create();\n                $quote->getResource()->load($quote, $quoteId);\n                $quote->setCustomerEmail($customerEmail);\n                $quote->setUpdatedAt(date('Y-m-d H:i:s'));\n                $quote->getResource()->save($quote);\n            }\n        }\n        return$ret;\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/Coupon.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/23/17 1:32 PM\n * @file: Coupon.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Coupon\n{\n    /**\n     * @var SyncHelper\n     */\n    protected $syncHelper;\n\n    /**\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        SyncHelper $syncHelper\n    ) {\n        $this->syncHelper  = $syncHelper;\n    }\n    public function afterAfterDelete(\\Magento\\SalesRule\\Model\\Coupon $coupon)\n    {\n        $this->syncHelper->markEcommerceAsDeleted(\n            $coupon->getCouponId(),\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_CODE,\n            $coupon->getRuleId()\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/Creditmemo.php",
    "content": "<?php\n/**\n * Ebizmarts_mc-magento22 Magento component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_mc-magento22\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n *\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nuse Magento\\Sales\\Api\\Data\\CreditmemoInterface;\nuse Magento\\Sales\\Api\\CreditmemoRepositoryInterface as SalesCreditmemoRepositoryInterface;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Creditmemo\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n        $this->_helper  = $helper;\n        $this->syncHelper = $syncHelper;\n    }\n    public function afterSave(\n        SalesCreditmemoRepositoryInterface $subject,\n        CreditmemoInterface $creditmemo\n    ) {\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $creditmemo->getStoreId()\n        );\n        $this->syncHelper->saveEcommerceData(\n            $mailchimpStoreId,\n            $creditmemo->getOrderId(),\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER,\n            null,\n            null,\n            1,\n            null,\n            null,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::NEEDTORESYNC\n        );\n\n        return $creditmemo;\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/Invoice.php",
    "content": "<?php\n/**\n * Ebizmarts_mc-magento22 Magento component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_mc-magento2\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n *\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nuse Magento\\Sales\\Api\\Data\\InvoiceInterface;\nuse Magento\\Sales\\Model\\Order\\Invoice as SalesInvoice;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Invoice\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n        $this->_helper  = $helper;\n        $this->syncHelper = $syncHelper;\n    }\n    public function afterSave(\n        SalesInvoice $subject,\n        InvoiceInterface $invoice\n    ) {\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $invoice->getStoreId()\n        );\n        $this->syncHelper->saveEcommerceData(\n            $mailchimpStoreId,\n            $invoice->getOrderId(),\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER,\n            null,\n            null,\n            1,\n            null,\n            null,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::NEEDTORESYNC\n        );\n        return $invoice;\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/Newsletter/Save.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/27/17 8:14 PM\n * @file: Save.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin\\Newsletter;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Save\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Customer\\Model\\Session\n     */\n    protected $customerSession;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $subscriberFactory;\n    /**\n     * @var \\Magento\\Framework\\App\\Request\\Http\n     */\n    protected $request;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory\n     */\n    protected $interestGroupFactory;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Customer\\Model\\Session $customerSession\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n     * @param \\Magento\\Framework\\App\\Request\\Http $request\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Customer\\Model\\Session $customerSession,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory,\n        \\Magento\\Framework\\App\\Request\\Http $request\n    ) {\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->customerSession      = $customerSession;\n        $this->subscriberFactory    = $subscriberFactory;\n        $this->request              = $request;\n        $this->interestGroupFactory = $interestGroupFactory;\n    }\n    public function afterExecute()\n    {\n        $params = $this->request->getParams();\n\n        $subscriber = $this->subscriberFactory->create();\n        $interestGroup = $this->interestGroupFactory->create();\n        /**\n         * @var $customer \\Magento\\Customer\\Model\\Customer\n         */\n        $customer = $this->customerSession->getCustomer();\n\n        $email = $customer->getEmail();\n\n        try {\n            $subscriber->loadByCustomerId($this->customerSession->getCustomerId());\n            if ($subscriber->getEmail()==$email) {\n                $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                $interestGroup->setGroupdata($this->helper->serialize($params));\n                $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                $interestGroup->setStoreId($subscriber->getStoreId());\n                $interestGroup->setUpdatedAt($this->helper->getGmtDate());\n                $interestGroup->getResource()->save($interestGroup);\n                $listId = $this->helper->getGeneralList($subscriber->getStoreId());\n                $this->_updateSubscriber($listId, $subscriber->getId(), $this->helper->getGmtDate(), null, 1);\n            } else {\n                $this->subscriberFactory->create()->subscribe($email);\n                $subscriber->loadByEmail($email);\n                $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                $interestGroup->setGroupdata($this->helper->serialize($params));\n                $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                $interestGroup->setStoreId($subscriber->getStoreId());\n                $interestGroup->setUpdatedAt($this->helper->getGmtDate());\n                $interestGroup->getResource()->save($interestGroup);\n            }\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n            $this->helper->log($params);\n        }\n    }\n    protected function _updateSubscriber(\n        $listId,\n        $entityId,\n        $sync_delta = null,\n        $sync_error = null,\n        $sync_modified = null\n    ) {\n        $this->syncHelper->saveEcommerceData(\n            $listId,\n            $entityId,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER,\n            $sync_delta,\n            $sync_error,\n            $sync_modified\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/Quote.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/25/17 7:40 PM\n * @file: Quote.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Quote\n{\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\CookieManagerInterface\n     */\n    protected $_cookieManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n\n    /**\n     * @param \\Magento\\Framework\\Stdlib\\CookieManagerInterface $cookieManager\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Magento\\Framework\\Stdlib\\CookieManagerInterface $cookieManager,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n\n        $this->_cookieManager = $cookieManager;\n        $this->_helper  = $helper;\n        $this->syncHelper = $syncHelper;\n    }\n\n    public function beforeBeforeSave(\\Magento\\Quote\\Model\\Quote $quote)\n    {\n        $mailchimp_campaign_id = $this->_cookieManager->getCookie('mailchimp_campaign_id');\n        if ($mailchimp_campaign_id) {\n            $quote->setData('mailchimp_campaign_id', $mailchimp_campaign_id);\n        }\n        $mailchimp_landing_page = $this->_cookieManager->getCookie('mailchimp_landing_page');\n        if ($mailchimp_landing_page) {\n            $quote->setData('mailchimp_landing_page', $mailchimp_landing_page);\n        }\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $quote->getStoreId()\n        );\n        $this->syncHelper->saveEcommerceData(\n            $mailchimpStoreId,\n            $quote->getId(),\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_QUOTE,\n            null,\n            0,\n            1,\n            0,\n            null\n        );\n    }\n}\n"
  },
  {
    "path": "Model/Plugin/Ship.php",
    "content": "<?php\n/**\n * Ebizmarts_mc-magento22 Magento component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_mc-magento22\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n *\n */\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nuse Magento\\Sales\\Api\\Data\\ShipmentInterface;\nuse Magento\\Sales\\Model\\Order\\Shipment as SalesShipment;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Ship\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    private $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n        $this->_helper  = $helper;\n        $this->syncHelper = $syncHelper;\n    }\n    public function afterSave(\n        SalesShipment $subject,\n        ShipmentInterface $shipment\n    ) {\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $shipment->getStoreId()\n        );\n        $this->syncHelper->saveEcommerceData(\n            $mailchimpStoreId,\n            $shipment->getOrderId(),\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER,\n            null,\n            null,\n            1,\n            null,\n            null,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::NEEDTORESYNC\n        );\n        return $shipment;\n    }\n}\n\n"
  },
  {
    "path": "Model/Plugin/Subscriber.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\Plugin;\n\nclass Subscriber\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Customer\\Model\\Customer\n     */\n    protected $_customer;\n    /**\n     * @var \\Magento\\Customer\\Model\\Session\n     */\n    protected $_customerSession;\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManagerInterface\n     */\n    protected $_storeManager;\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\CustomerRepository $customer\n     * @param \\Magento\\Customer\\Model\\Session $customerSession\n     */\n    protected $_api = null;\n\n    /**\n     * Subscriber constructor.\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Magento\\Customer\\Model\\ResourceModel\\CustomerRepository $customer\n     * @param \\Magento\\Customer\\Model\\Session $customerSession\n     * @param \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Customer\\Model\\ResourceModel\\CustomerRepository $customer,\n        \\Magento\\Customer\\Model\\Session $customerSession,\n        \\Magento\\Store\\Model\\StoreManagerInterface $storeManager\n    ) {\n\n        $this->_helper          = $helper;\n        $this->_customer        = $customer;\n        $this->_customerSession = $customerSession;\n        $this->_storeManager    = $storeManager;\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @param $customerId\n     * @return array\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function beforeUnsubscribeCustomerById(\n        \\Magento\\Newsletter\\Model\\Subscriber $subscriber,\n        $customerId\n    ) {\n        $storeId = $this->getStoreIdFromSubscriber($subscriber);\n        if ($this->_helper->isMailChimpEnabled($storeId)) {\n            if (!$this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAGENTO_MAIL, $storeId)) {\n                $subscriber->setImportMode(true);\n            }\n            $subscriber->loadByCustomerId($customerId);\n            if ($subscriber->isSubscribed()) {\n                $api = $this->_helper->getApi($storeId);\n                try {\n                    $md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));\n                    $api->lists->members->update(\n                        $this->_helper->getDefaultList($storeId),\n                        $md5HashEmail,\n                        null,\n                        'unsubscribed'\n                    );\n                } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                    $this->_helper->log($e->getFriendlyMessage());\n                }\n            }\n        }\n        return [$customerId];\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @param $customerId\n     * @return array\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     * @throws \\Magento\\Framework\\Exception\\NoSuchEntityException\n     */\n    public function beforeSubscribeCustomerById(\n        \\Magento\\Newsletter\\Model\\Subscriber $subscriber,\n        $customerId\n    ) {\n\n        $storeId = $this->getStoreIdFromSubscriber($subscriber);\n        if ($this->_helper->isMailChimpEnabled($storeId)) {\n            $subscriber->loadByCustomerId($customerId);\n            if (!$subscriber->isSubscribed()) {\n                if (!$this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAGENTO_MAIL, $storeId)) {\n                    $subscriber->setImportMode(true);\n                }\n                if ($this->_helper->isMailChimpEnabled($storeId)) {\n                    $customer = $this->_customer->getById($customerId);\n                    $email = $customer->getEmail();\n                    $mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriber, $email);\n                    $api = $this->_helper->getApi($storeId);\n                    if ($this->_helper->isDoubleOptInEnabled($storeId)) {\n                        $status = 'pending';\n                    } else {\n                        $status = 'subscribed';\n                    }\n                    try {\n                        $emailHash = hash('md5', strtolower($customer->getEmail()));\n                        $api->lists->members->addOrUpdate(\n                            $this->_helper->getDefaultList($storeId),\n                            $emailHash,\n                            null,\n                            $status,\n                            $mergeVars,\n                            null,\n                            null,\n                            null,\n                            null,\n                            $email,\n                            $status\n                        );\n                    } catch (\\Mailchimp_Error $e) {\n                        $this->_helper->log($e->getFriendlyMessage());\n                    }\n                }\n            }\n        }\n        return [$customerId];\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @param $email\n     * @return array\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     * @throws \\Magento\\Framework\\Exception\\NoSuchEntityException\n     */\n    public function beforeSubscribe(\n        \\Magento\\Newsletter\\Model\\Subscriber $subscriber,\n        $email\n    ) {\n\n        $storeId = $this->getStoreIdFromSubscriber($subscriber);\n        if ($this->_helper->isMailChimpEnabled($storeId)) {\n            if (!$this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAGENTO_MAIL, $storeId)) {\n                $subscriber->setImportMode(true);\n            }\n            $storeId = $this->_storeManager->getStore()->getId();\n\n            if ($this->_helper->isMailChimpEnabled($storeId)) {\n                $api = $this->_helper->getApi($storeId);\n                if ($this->_helper->isDoubleOptInEnabled($storeId)) {\n                    $status = 'pending';\n                } else {\n                    $status = 'subscribed';\n                }\n                $mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriber, $email);\n                try {\n                    $md5HashEmail = hash('md5', strtolower($email));\n                    $return = $api->lists->members->addOrUpdate(\n                        $this->_helper->getDefaultList($storeId),\n                        $md5HashEmail,\n                        null,\n                        $status,\n                        $mergeVars,\n                        null,\n                        null,\n                        null,\n                        null,\n                        $email,\n                        $status\n                    );\n                } catch (\\Mailchimp_Error $e) {\n                    $this->_helper->log($e->getFriendlyMessage());\n                }\n            }\n        }\n        return [$email];\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @return null\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function beforeUnsubscribe(\n        \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n    ) {\n        $storeId = $this->getStoreIdFromSubscriber($subscriber);\n        if ($this->_helper->isMailChimpEnabled($storeId)) {\n            if (!$this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAGENTO_MAIL, $storeId)) {\n                $subscriber->setImportMode(true);\n            }            $api = $this->_helper->getApi($storeId);\n            try {\n                $md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));\n                $api->lists->members->update(\n                    $this->_helper->getDefaultList($storeId),\n                    $md5HashEmail,\n                    null,\n                    'unsubscribed'\n                );\n            } catch (\\Mailchimp_Error $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n            }\n        }\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @return null\n     * @throws \\Magento\\Framework\\Exception\\LocalizedException\n     */\n    public function afterDelete(\n        \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n    ) {\n\n        $storeId = $this->getStoreIdFromSubscriber($subscriber);\n        if ($this->_helper->isMailChimpEnabled($storeId)) {\n            $api = $this->_helper->getApi($storeId);\n            if ($subscriber->isSubscribed()) {\n                try {\n                    $md5HashEmail = hash('md5', strtolower($subscriber->getSubscriberEmail()));\n                    if ($subscriber->getCustomerId()) {\n                        $api->lists->members->update(\n                            $this->_helper->getDefaultList($storeId),\n                            $md5HashEmail,\n                            null,\n                            'unsubscribed'\n                        );\n                    } else {\n                        $api->lists->members->delete($this->_helper->getDefaultList($storeId), $md5HashEmail);\n                    }\n                } catch (\\Mailchimp_Error $e) {\n                    $this->_helper->log($e->getFriendlyMessage());\n                }\n            }\n        }\n        return null;\n    }\n\n    /**\n     * @param \\Magento\\Newsletter\\Model\\Subscriber $subscriber\n     * @return int\n     */\n    protected function getStoreIdFromSubscriber(\\Magento\\Newsletter\\Model\\Subscriber $subscriber)\n    {\n        return $subscriber->getStoreId();\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/Carts/Collection.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\Carts;\n\nuse Magento\\Framework\\Data\\Collection\\Db\\FetchStrategyInterface as FetchStrategy;\nuse Magento\\Framework\\Data\\Collection\\EntityFactoryInterface as EntityFactory;\nuse Magento\\Framework\\Event\\ManagerInterface as EventManager;\nuse Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult;\nuse Psr\\Log\\LoggerInterface as Logger;\n\nclass Collection extends SearchResult\n{\n    public function __construct(\n        EntityFactory $entityFactory,\n        Logger $logger,\n        FetchStrategy $fetchStrategy,\n        EventManager $eventManager,\n        $mainTable = 'mailchimp_sync_ecommerce',\n        $resourceModel = \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce::class\n    ) {\n        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $mainTable, $resourceModel);\n    }\n    protected function _initSelect()\n    {\n        parent::_initSelect();\n        $this->getSelect()\n            ->where(\n                \"type = 'QUO'\"\n            );\n        $this->getSelect()->join(['alias' => $this->getTable('quote')], 'main_table.related_id = alias.entity_id',\n            ['customer_id', 'customer_email','customer_firstname','customer_lastname','items_count','items_qty','created_at','updated_at','grand_total']);\n        return $this;\n\n    }\n\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpErrors.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/17/16 1:57 PM\n * @file: MailChimpError.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass MailChimpErrors extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_errors', 'id');\n    }\n    public function getByStoreIdType(\\Ebizmarts\\MailChimp\\Model\\MailChimpErrors $errors, $storeId, $id, $type)\n    {\n        $connection = $this->getConnection();\n        $bind = ['store_id' => $storeId, 'regtype' => $type, 'original_id' => $id];\n        $select = $connection->select()->from(\n            $this->getTable('mailchimp_errors')\n        )->where(\n            'store_id = :store_id AND regtype = :regtype AND original_id = :original_id'\n        );\n        $data = $connection->fetchRow($select, $bind);\n        if ($data) {\n            $errors->setData($data);\n        }\n        return $errors;\n    }\n    public function deleteByStorePeriod(\\Ebizmarts\\MailChimp\\Model\\MailChimpErrors $errors, $storeId, $interval, $limit)\n    {\n        $connection = $this->getConnection();\n        $table = $this->getTable('mailchimp_errors');\n        $ret = $connection->query(\"DELETE FROM $table WHERE date_add(added_at, interval $interval month) < now() AND store_id = $storeId LIMIT $limit\");\n        return $ret;\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpInterestGroup/Collection.php",
    "content": "<?php\n/**\n * Created by PhpStorm.\n * User: gonzalo\n * Date: 10/31/18\n * Time: 5:58 PM\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup;\n\nclass Collection extends \\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection\n{\n    protected function _construct()\n    {\n        $this->_init(\n            \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroup::class,\n            \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup::class\n        );\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpInterestGroup.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/20/17 3:51 PM\n * @file: MailChimpInterestGroup.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass MailChimpInterestGroup extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_interest_group', 'id');\n    }\n    public function getBySubscriberIdStoreId(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroup $mailChimpInterestGroup,\n        $subscriberId,\n        $storeId\n    ) {\n        $connection = $this->getConnection();\n        $bind = ['subscriber_id'=>$subscriberId, 'store_id' => $storeId];\n        $select = $connection->select()->from(\n            $this->getTable('mailchimp_interest_group')\n        )->where(\n            'subscriber_id = :subscriber_id AND store_id = :store_id'\n        );\n        $data = $connection->fetchRow($select, $bind);\n        if ($data) {\n            $mailChimpInterestGroup->setData($data);\n        }\n        return $mailChimpInterestGroup;\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpStores/Collection.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/27/17 1:22 PM\n * @file: Collection.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores;\n\nclass Collection extends \\Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult\n{\n    protected function _construct()\n    {\n        $this->_init(\n            \\Ebizmarts\\MailChimp\\Model\\MailChimpStores::class,\n            \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores::class\n        );\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpStores/Grid/Collection.php",
    "content": "<?php\n/**\n * Copyright © 2013-2017 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores\\Grid;\n\nuse Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\Document;\nuse Magento\\Framework\\Data\\Collection\\Db\\FetchStrategyInterface as FetchStrategy;\nuse Magento\\Framework\\Data\\Collection\\EntityFactoryInterface as EntityFactory;\nuse Magento\\Framework\\Event\\ManagerInterface as EventManager;\nuse Psr\\Log\\LoggerInterface as Logger;\n\nclass Collection extends \\Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult\n{\n    /**\n     * @inheritdoc\n     */\n    protected $document = Document::class;\n\n    /**\n     * Initialize dependencies.\n     *\n     * @param EntityFactory $entityFactory\n     * @param Logger $logger\n     * @param FetchStrategy $fetchStrategy\n     * @param EventManager $eventManager\n     * @param string $mainTable\n     * @param string $resourceModel\n     */\n    public function __construct(\n        EntityFactory $entityFactory,\n        Logger $logger,\n        FetchStrategy $fetchStrategy,\n        EventManager $eventManager,\n        $mainTable = 'mailchimp_stores',\n        $resourceModel = \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores::class\n    ) {\n        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $mainTable, $resourceModel);\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpStores.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/3/17 11:42 AM\n * @file: MailChimpStores.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass MailChimpStores extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_stores', 'id');\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpSyncBatches/Collection.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/21/16 4:16 PM\n * @file: Collection.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches;\n\nclass Collection extends \\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection\n{\n    protected function _construct()\n    {\n        $this->_init(\n            \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches::class,\n            \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches::class\n        );\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpSyncBatches.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/17/16 2:27 PM\n * @file: MailChimpSyncBatches.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass MailChimpSyncBatches extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_sync_batches', 'id');\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpSyncEcommerce/Collection.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 12/1/16 2:36 PM\n * @file: Collection.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce;\n\nclass Collection extends \\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection\n{\n    protected function _construct()\n    {\n        $this->_init(\n            \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce::class,\n            \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce::class\n        );\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpSyncEcommerce.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 12/1/16 2:33 PM\n * @file: MailChimpSyncEcommerce.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass   MailChimpSyncEcommerce extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_sync_ecommerce', 'id');\n    }\n    public function getByStoreIdType(\\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp, $storeId, $id, $type)\n    {\n        $connection = $this->getConnection();\n        $bind = ['store_id' => $storeId, 'type' => $type, 'related_id' => $id];\n        $select = $connection->select()->from(\n            $this->getTable('mailchimp_sync_ecommerce')\n        )->where(\n            'mailchimp_store_id = :store_id AND type = :type AND related_id = :related_id'\n        );\n        $data = $connection->fetchRow($select, $bind);\n        if ($data) {\n            $chimp->setData($data);\n        }\n        return $chimp;\n    }\n    public function markAllAsDeleted(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp,\n        $id,\n        $type,\n        $relatedDeletedId\n    ) {\n        $connection = $this->getConnection();\n        $connection->update(\n            $this->getTable('mailchimp_sync_ecommerce'),\n            ['mailchimp_sync_deleted'=>1, 'deleted_related_id'=> $relatedDeletedId, 'mailchimp_sent'=> \\Ebizmarts\\Mailchimp\\Helper\\Data::NEEDTORESYNC],\n            ['related_id = ?'=> $id,'type = ?'=>$type]\n        );\n        return $this;\n    }\n    public function markEcommorceAsNotDeleted(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp,\n                                                          $id,\n                                                          $type\n    ) {\n        $connection = $this->getConnection();\n        $connection->update(\n            $this->getTable('mailchimp_sync_ecommerce'),\n            ['mailchimp_sync_deleted'=>0, 'mailchimp_sync_error' => null,'mailchimp_sync_modified'=>0,'mailchimp_sent'=>\\Ebizmarts\\MailChimp\\Helper\\Data::WAITINGSYNC],\n            ['related_id = ?'=> $id,'type = ?'=>$type]\n        );\n        return $this;\n    }\n    public function markAllAsModified(\\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp, $id, $type)\n    {\n        $connection = $this->getConnection();\n        $connection->update(\n            $this->getTable('mailchimp_sync_ecommerce'),\n            ['mailchimp_sync_modified'=>1,'mailchimp_sent'=>\\Ebizmarts\\MailChimp\\Helper\\Data::NEEDTORESYNC,'batch_id'=>null],\n            ['related_id = ?'=> $id, 'type = ?'=>$type]\n        );\n        return $this;\n    }\n    public function deleteAllByIdType(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp,\n        $id,\n        $type,\n        $mailchimpStoreId\n    ) {\n        $connection = $this->getConnection();\n        $connection->delete(\n            $this->getTable('mailchimp_sync_ecommerce'),\n            ['related_id = ?'=> $id, 'type = ?'=>$type, 'mailchimp_store_id = ?' => $mailchimpStoreId]\n        );\n        return $this;\n    }\n    public function deleteAllByBatchId(\\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp, $batchId)\n    {\n        $connection = $this->getConnection();\n        $connection->delete($this->getTable('mailchimp_sync_ecommerce'), ['batch_id = ?' => $batchId]);\n        return $this;\n    }\n    public function deleteByTypeAndId(\\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp, $type, $id, $mailchimpStoreId)\n    {\n        $connection = $this->getConnection();\n        $connection->delete($this->getTable('mailchimp_sync_ecommerce'), ['type = ?' => $type, 'related_id = ?' => $id, 'mailchimp_store_id = ?' => $mailchimpStoreId]);\n        return $this;\n    }\n    public function markAllAsModifiedByIds(\\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $chimp, $mailchimpStore, $ids, $type)\n    {\n        $connection = $this->getConnection();\n        $connection->update(\n            $this->getTable('mailchimp_sync_ecommerce'),\n            ['mailchimp_sync_modified'=>1],\n            ['related_id in (?)'=> $ids, 'type = ?'=>$type, 'mailchimp_store_id = ?'=>$mailchimpStore]\n        );\n        return $this;\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpWebhookRequest/Collection.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/26/17 11:36 AM\n * @file: Collection.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest;\n\nclass Collection extends \\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection\n{\n    protected function _construct()\n    {\n        $this->_init(\n            \\Ebizmarts\\MailChimp\\Model\\MailChimpWebhookRequest::class,\n            \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest::class\n        );\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailChimpWebhookRequest.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/26/17 11:33 AM\n * @file: MailChimpWebhookRequest.php\n */\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\DB\\Select;\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass MailChimpWebhookRequest extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_webhook_request', 'id');\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailchimpNotification/Collection.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailchimpNotification;\n\nclass Collection extends \\Magento\\Framework\\Model\\ResourceModel\\Db\\Collection\\AbstractCollection\n{\n    protected function _construct()\n    {\n        $this->_init(\n            \\Ebizmarts\\MailChimp\\Model\\MailchimpNotification::class,\n            \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailchimpNotification::class\n        );\n    }\n}\n"
  },
  {
    "path": "Model/ResourceModel/MailchimpNotification.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel;\n\nuse Magento\\Framework\\Model\\ResourceModel\\Db\\AbstractDb;\n\nclass MailchimpNotification extends AbstractDb\n{\n    protected function _construct()\n    {\n        $this->_init('mailchimp_notification', 'id');\n    }\n\n}\n"
  },
  {
    "path": "Model/ResourceModel/Schedule/Collection.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Model\\ResourceModel\\Schedule;\n\nuse \\Magento\\Cron\\Model\\ResourceModel\\Schedule as MagentoSchedule;\nuse \\Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult;\nuse Magento\\Framework\\Data\\Collection\\Db\\FetchStrategyInterface as FetchStrategy;\nuse Magento\\Framework\\Data\\Collection\\EntityFactoryInterface as EntityFactory;\nuse Magento\\Framework\\Event\\ManagerInterface as EventManager;\nuse Psr\\Log\\LoggerInterface as Logger;\nclass Collection extends SearchResult\n{\n\n\n    public function __construct(\n        EntityFactory $entityFactory,\n        Logger $logger,\n        FetchStrategy $fetchStrategy,\n        EventManager $eventManager,\n        $mainTable='cron_schedule',\n        $resourceModel=MagentoSchedule::class\n    ) {\n        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $mainTable, $resourceModel);\n\n    }//end __construct()\n\n\n    protected function _initSelect()\n    {\n        parent::_initSelect();\n        $this->getSelect()\n            ->where(\n                \"job_code IN (\n                    'ebizmarts_webhooks',\n                    'ebizmarts_ecommerce',\n                    'ebizmarts_clean_webhooks',\n                    'ebizmarts_clean_batches',\n                    'ebizmarts_clean_errors'\n                )\"\n            );\n        return $this;\n\n    }//end _initSelect()\n\n\n}//end class\n"
  },
  {
    "path": "Observer/Adminhtml/Customer/SaveAfter.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 12/1/17 2:21 PM\n * @file: SaveAfter.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Customer;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass SaveAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $subscriberFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory\n     */\n    protected $interestGroupFactory;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpInterestGroupFactory $interestGroupFactory\n    ) {\n\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->subscriberFactory    = $subscriberFactory;\n        $this->interestGroupFactory = $interestGroupFactory;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        $customer = $observer->getCustomer();\n        $request  = $observer->getEvent()->getRequest();\n        $allParams = $request->getParams();\n        $subscriber = $this->subscriberFactory->create();\n        if (isset($allParams['customer']['interestgroup'])) {\n            $params = ['group' => $allParams['customer']['interestgroup']];\n            foreach ($params['group'] as $index => $ig) {\n                if (is_array($ig)) {\n                    foreach ($ig as $i => $v) {\n                        if ($v == 1) {\n                            $params['group'][$index][$i] = $i;\n                        }\n                    }\n                }\n            }\n            $interestGroup = $this->interestGroupFactory->create();\n            try {\n                $subscriber->loadByEmail($customer->getEmail());\n                if ($subscriber->getEmail() == $customer->getEmail()) {\n                    $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                    $interestGroup->setGroupdata($this->helper->serialize($params));\n                    $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                    $interestGroup->setStoreId($subscriber->getStoreId());\n                    $interestGroup->setUpdatedAt($this->helper->getGmtDate());\n                    $interestGroup->getResource()->save($interestGroup);\n                    $this->syncHelper->markRegisterAsModified(\n                        $subscriber->getId(),\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER\n                    );\n                } else {\n                    $this->subscriberFactory->create()->subscribe($customer->getEmail());\n                    $subscriber->loadByEmail($customer->getEmail());\n                    $interestGroup->getBySubscriberIdStoreId($subscriber->getSubscriberId(), $subscriber->getStoreId());\n                    $interestGroup->setGroupdata($this->helper->serialize($params));\n                    $interestGroup->setSubscriberId($subscriber->getSubscriberId());\n                    $interestGroup->setStoreId($subscriber->getStoreId());\n                    $interestGroup->setUpdatedAt($this->helper->getGmtDate());\n                    $interestGroup->getResource()->save($interestGroup);\n                }\n            } catch (\\Exception $e) {\n                $this->helper->log($e->getMessage());\n                $this->helper->log($params);\n            }\n        } else {\n            $subscriber->loadByEmail($customer->getEmail());\n            if ($subscriber->getEmail() == $customer->getEmail()) {\n                $this->syncHelper->markRegisterAsModified(\n                    $subscriber->getId(),\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER\n                );\n            }\n        }\n        $this->syncHelper->markRegisterAsModified($customer->getId(), \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER);\n    }\n}\n"
  },
  {
    "path": "Observer/Adminhtml/Product/DeleteAfter.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Product;\n\nuse Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\ConfigurableFactory;\nuse Magento\\Framework\\Event\\Observer;\nuse Magento\\Framework\\Event\\ObserverInterface;\nuse Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\Configurable;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\n\nclass DeleteAfter implements ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var Configurable\n     */\n    protected $configurable;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param Configurable $configurable\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        Configurable $configurable\n\n    ) {\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->configurable         = $configurable;\n    }\n    function execute(Observer $observer)\n    {\n        $product = $observer->getProduct();\n        $mailchimpStore = $this->helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $product->getStoreId()\n        );\n        $this->_updateProduct($product->getId());\n    }\n    protected function _updateProduct($entityId)\n    {\n        $this->syncHelper->markEcommerceAsDeleted($entityId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT);\n    }\n\n}\n"
  },
  {
    "path": "Observer/Adminhtml/Product/ImportAfter.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Product;\n\nuse Magento\\Framework\\Event\\Observer;\nuse Magento\\Catalog\\Model\\ResourceModel\\Product\\CollectionFactory;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass ImportAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var CollectionFactory\n     */\n    protected $productCollectionFactory;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param CollectionFactory $productCollectionFactory\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        CollectionFactory $productCollectionFactory\n    )\n    {\n        $this->helper = $helper;\n        $this->syncHelper = $syncHelper;\n        $this->productCollectionFactory = $productCollectionFactory;\n    }\n    public function execute(Observer $observer)\n    {\n        try {\n            $bunch = $observer->getBunch();\n            $counter = 0;\n            $skus = [];\n            foreach ($bunch as $product) {\n                if ($counter % 100 == 0 && count($skus)) {\n                    $this->updateSkus($skus);\n                    $skus =[];\n                }\n                $sku = $product['sku'];\n                if (key_exists('_store', $product)&&!empty($product['_store'])) {\n                    $storeId = $product['_store'];\n                } else {\n                    $storeId = 0;\n                }\n                $skus[$storeId][]=$sku;\n                $counter++;\n            }\n            if (count($skus)) {\n                $this->updateSkus($skus);\n            }\n        } catch (\\Exception $e) {\n            $this->helper->log($e->getMessage());\n        }\n    }\n    protected function updateSkus($skus)\n    {\n        foreach ($skus as $storeId => $storeskus) {\n            /**\n             * @var $collection \\Magento\\Catalog\\Model\\ResourceModel\\Product\\Collection\n             */\n            $collection = $this->productCollectionFactory->create();\n            $collection->addStoreFilter($storeId);\n            $collection->addFieldToFilter('sku', ['in'=>$storeskus]);\n            $collection->addFieldToSelect('id');\n            $productIds = [];\n            foreach ($collection as $item) {\n                $productIds[] = $item->getId();\n            }\n            $this->markAsModified($storeId, $productIds);\n        }\n\n    }\n    protected function markAsModified($storeId,$productsIds)\n    {\n        $mailchimpStoreId = $this->helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $storeId\n        );\n        $this->syncHelper->markAllAsModifiedByIds($mailchimpStoreId, $productsIds, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT);\n\n    }\n}\n"
  },
  {
    "path": "Observer/Adminhtml/Product/SaveAfter.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 1/18/18 12:30 PM\n * @file: SaveAfter.php\n */\nnamespace Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Product;\n\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass SaveAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\Configurable\n     */\n    protected $configurable;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\Configurable $configurable\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\ConfigurableProduct\\Model\\ResourceModel\\Product\\Type\\Configurable $configurable\n    ) {\n        $this->helper               = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->configurable         = $configurable;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        /**\n         * @var \\Magento\\Catalog\\Model\\Product $product\n         */\n        $product = $observer->getProduct();\n        $mailchimpStore = $this->helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $product->getStoreId()\n        );\n        if ($product->getTypeId() == \\Magento\\Catalog\\Model\\Product\\Type::TYPE_SIMPLE) {\n            $parents = $this->configurable->getParentIdsByChild($product->getId());\n            if (is_array($parents)) {\n                foreach ($parents as $parentid) {\n                    $this->_updateProduct($parentid);\n                }\n            } elseif ($parents) {\n                $this->_updateProduct($parents);\n            }\n        }\n        $this->_updateProduct($product->getId());\n    }\n    protected function _updateProduct($entityId)\n    {\n        $this->syncHelper->markRegisterAsModified($entityId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT);\n    }\n}\n"
  },
  {
    "path": "Observer/ConfigObserver.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/23/17 12:22 PM\n * @file: ConfigObserver.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Observer;\n\nuse Magento\\Framework\\Event\\ObserverInterface;\nuse Magento\\Framework\\Event\\Observer as EventObserver;\n\nclass ConfigObserver implements ObserverInterface\n{\n    /**\n     * @var \\Magento\\Store\\Model\\StoreManager\n     */\n    protected $_storeManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Framework\\Registry\n     */\n    protected $_registry;\n\n    /**\n     * ConfigObserver constructor.\n     * @param \\Magento\\Store\\Model\\StoreManager $storeManager\n     * @param \\Magento\\Framework\\Registry $registry\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        \\Magento\\Store\\Model\\StoreManager $storeManager,\n        \\Magento\\Framework\\Registry $registry,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n    \n        $this->_helper          = $helper;\n        $this->_storeManager    = $storeManager;\n        $this->_registry        = $registry;\n    }\n\n    public function execute(EventObserver $observer)\n    {\n        $oldListId  = $this->_registry->registry('oldListId');\n        $apiKey     = $this->_registry->registry('apiKey');\n        $mustDelete = true;\n\n        foreach ($this->_storeManager->getStores() as $storeId => $val) {\n            $listId = $this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_LIST, $storeId);\n            if ($listId == $oldListId) {\n                $mustDelete = false;\n            }\n        }\n        if ($mustDelete) {\n            $this->_helper->deleteWebHook($apiKey, $oldListId);\n        }\n\n        $this->_registry->unregister('oldListId');\n        $this->_registry->unregister('apiKey');\n    }\n}\n"
  },
  {
    "path": "Observer/Customer/SaveBefore.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/8/17 5:07 PM\n * @file: SafeAfter.php\n */\nnamespace Ebizmarts\\MailChimp\\Observer\\Customer;\n\nuse Magento\\Framework\\Event\\Observer;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass SaveBefore implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $subscriberFactory;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n    ) {\n\n        $this->_helper              = $helper;\n        $this->syncHelper           = $syncHelper;\n        $this->subscriberFactory    = $subscriberFactory;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        /**\n         * @var $customer \\Magento\\Customer\\Model\\Customer\n         */\n        $customer = $observer->getCustomer();\n        $storeId  = $customer->getStoreId();\n        if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ACTIVE)) {\n            if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ECOMMERCE_ACTIVE)) {\n                $mailchimpStoreId = $this->_helper->getConfigValue(\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                    $storeId\n                );\n                $this->syncHelper->saveEcommerceData(\n                    $mailchimpStoreId,\n                    $customer->getId(),\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER,\n                    null,\n                    null,\n                    1\n                );\n            }\n            $subscriber = $this->subscriberFactory->create();\n            $subscriber->loadByEmail($customer->getEmail());\n            if ($subscriber->getEmail() == $customer->getEmail()) {\n                $this->syncHelper->markRegisterAsModified(\n                    $subscriber->getId(),\n                    \\Ebizmarts\\MailChimp\\Helper\\Data::IS_SUBSCRIBER\n                );\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Observer/Sales/Order/SaveAfter.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 2/15/17 3:38 PM\n * @file: SaveAfter.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Observer\\Sales\\Order;\n\nuse Magento\\Framework\\Event\\Observer;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass SaveAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper\n    ) {\n\n        $this->_helper      = $helper;\n        $this->syncHelper   = $syncHelper;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        $order = $observer->getEvent()->getOrder();\n        $mailchimpStoreId = $this->_helper->getConfigValue(\n            \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n            $order->getStoreId()\n        );\n        $this->syncHelper->saveEcommerceData(\n            $mailchimpStoreId,\n            $order->getId(),\n            \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER,\n            null,\n            null,\n            1,\n            null,\n            null,\n            \\Ebizmarts\\MailChimp\\Helper\\Data::NEEDTORESYNC\n        );\n    }\n}\n"
  },
  {
    "path": "Observer/Sales/Order/SubmitAfter.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/26/17 12:36 PM\n * @file: SubmitAfter.php\n */\nnamespace Ebizmarts\\MailChimp\\Observer\\Sales\\Order;\n\nuse Magento\\Framework\\Event\\Observer;\n\nclass SubmitAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\CookieManagerInterface\n     */\n    protected $_cookieManager;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Framework\\Stdlib\\Cookie\\CookieMetadataFactory\n     */\n    protected $_cookieMetadataFactory;\n    /**\n     * @var \\Magento\\Framework\\Session\\SessionManagerInterface\n     */\n    protected $_sessionManager;\n\n    /**\n     * SubmitAfter constructor.\n     * @param \\Magento\\Framework\\Stdlib\\CookieManagerInterface $cookieManager\n     * @param \\Magento\\Framework\\Stdlib\\Cookie\\CookieMetadataFactory $metadataFactory\n     * @param \\Magento\\Framework\\Session\\SessionManagerInterface $sessionManager\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        \\Magento\\Framework\\Stdlib\\CookieManagerInterface $cookieManager,\n        \\Magento\\Framework\\Stdlib\\Cookie\\CookieMetadataFactory $metadataFactory,\n        \\Magento\\Framework\\Session\\SessionManagerInterface $sessionManager,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n    \n        $this->_cookieManager   = $cookieManager;\n        $this->_helper          = $helper;\n        $this->_cookieMetadataFactory   = $metadataFactory;\n        $this->_sessionManager          = $sessionManager;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        try {\n            $this->_cookieManager->deleteCookie(\n                'mailchimp_campaign_id',\n                $this->_cookieMetadataFactory\n                    ->createCookieMetadata()\n                    ->setPath($this->_sessionManager->getCookiePath())\n                    ->setDomain($this->_sessionManager->getCookieDomain())\n            );\n            $this->_cookieManager->deleteCookie(\n                'mailchimp_landing_page',\n                $this->_cookieMetadataFactory\n                    ->createCookieMetadata()\n                    ->setPath($this->_sessionManager->getCookiePath())\n                    ->setDomain($this->_sessionManager->getCookieDomain())\n            );\n        } catch (\\Exception $e) {\n            $this->_helper->log($e->getMessage());\n        }\n\n        return $this;\n    }\n}\n"
  },
  {
    "path": "Observer/Sales/Order/SubmitBefore.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/14/17 11:26 PM\n * @file: SaveBefore.php\n */\nnamespace Ebizmarts\\MailChimp\\Observer\\Sales\\Order;\n\nuse Magento\\Framework\\Event\\Observer;\n\nclass SubmitBefore implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    private $attributes = [\n        'mailchimp_abandonedcart_flag',\n        'mailchimp_campaign_id',\n        'mailchimp_landing_page'\n    ];\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        /* @var \\Magento\\Sales\\Model\\Order $order */\n        $order = $observer->getEvent()->getData('order');\n        /* @var \\Magento\\Quote\\Model\\Quote $quote */\n        $quote = $observer->getEvent()->getData('quote');\n        $flag = 0;\n\n        foreach ($this->attributes as $attribute) {\n            if ($quote->hasData($attribute)) {\n                $order->setData($attribute, $quote->getData($attribute));\n                if ($quote->getData($attribute)) {\n                    $flag = 1;\n                }\n            }\n        }\n        $order->setData('mailchimp_flag', $flag);\n        return $this;\n    }\n}\n"
  },
  {
    "path": "Observer/SalesRule/Rule/DeleteAfter.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/19/17 5:26 PM\n * @file: DeleteAfter.php\n */\nnamespace Ebizmarts\\MailChimp\\Observer\\SalesRule\\Rule;\n\nuse Magento\\Framework\\Event\\Observer;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass DeleteAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n     */\n    protected $_ecommerce;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $ecommerce\n     * @param SyncHelper $syncHelper\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $ecommerce,\n        SyncHelper $syncHelper\n    ) {\n        $this->_ecommerce   = $ecommerce;\n        $this->syncHelper   = $syncHelper;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        $rule = $observer->getEvent()->getRule();\n        $ruleId = $rule->getRuleId();\n        $this->syncHelper->markEcommerceAsDeleted($ruleId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE);\n    }\n}\n"
  },
  {
    "path": "Observer/SalesRule/Rule/SaveAfter.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/19/17 4:14 PM\n * @file: Rule.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Observer\\SalesRule\\Rule;\n\nuse Magento\\Framework\\Event\\Observer;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass SaveAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n     */\n    protected $_ecommerce;\n    /**\n     * @var SyncHelper\n     */\n    protected $syncHelper;\n    protected $_date;\n\n    /**\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $ecommerce\n     * @param SyncHelper $syncHelper\n     * @param \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $ecommerce,\n        SyncHelper $syncHelper,\n        \\Magento\\Framework\\Stdlib\\DateTime\\DateTime $date\n    ) {\n\n        $this->_ecommerce   = $ecommerce;\n        $this->syncHelper   = $syncHelper;\n        $this->_date        = $date;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        /**\n         * @var $rule \\Magento\\SalesRule\\Model\\Rule\n         */\n        $rule = $observer->getEvent()->getRule();\n        $ruleId = $rule->getRuleId();\n        $this->syncHelper->markRegisterAsModified($ruleId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PROMO_RULE);\n    }\n}\n"
  },
  {
    "path": "Observer/Subscriber/SaveAfter.php",
    "content": "<?php\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 11/9/17 5:20 PM\n * @file: SaveBefore.php\n */\nnamespace Ebizmarts\\MailChimp\\Observer\\Subscriber;\n\nuse Magento\\Framework\\Event\\Observer;\n\nclass SaveAfter implements \\Magento\\Framework\\Event\\ObserverInterface\n{\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce\n     */\n    protected $_ecommerce;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\Api\\Subscriber\n     */\n    protected $_subscriberApi;\n    /**\n     * @var \\Magento\\Newsletter\\Model\\SubscriberFactory\n     */\n    protected $_subscriberFactory;\n\n    /**\n     * SaveBefore constructor.\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $ecommerce\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param \\Ebizmarts\\MailChimp\\Model\\Api\\Subscriber $subscriberApi\n     * @param \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncEcommerce $ecommerce,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\Api\\Subscriber $subscriberApi,\n        \\Magento\\Newsletter\\Model\\SubscriberFactory $subscriberFactory\n    ) {\n\n        $this->_ecommerce           = $ecommerce;\n        $this->_helper              = $helper;\n        $this->_subscriberApi       = $subscriberApi;\n        $this->_subscriberFactory   = $subscriberFactory;\n    }\n\n    public function execute(\\Magento\\Framework\\Event\\Observer $observer)\n    {\n        /**\n         * @var $subscriber \\Magento\\Newsletter\\Model\\Subscriber\n         */\n        $factory = $this->_subscriberFactory->create();\n        $subscriber = $observer->getSubscriber();\n        $subscriberOld = $factory->loadByCustomerId($subscriber->getCustomerId());\n\n        if ($this->_helper->isMailChimpEnabled($subscriberOld->getStoreId()) && $subscriber->getEmail() != $subscriberOld->getEmail()) {\n            $api = $this->_helper->getApi($subscriberOld->getStoreId());\n            $mergeVars = $this->_helper->getMergeVarsBySubscriber($subscriberOld, $subscriberOld->getEmail());\n            $status = 'unsubscribed';\n\n            try {\n                $md5HashEmail = hash('md5', strtolower($subscriberOld->getEmail()));\n                $return = $api->lists->members->addOrUpdate(\n                    $this->_helper->getDefaultList($subscriberOld->getStoreId()),\n                    $md5HashEmail,\n                    null,\n                    $status,\n                    $mergeVars,\n                    null,\n                    null,\n                    null,\n                    null,\n                    $subscriberOld->getEmail(),\n                    $status\n                );\n\n            } catch (\\Mailchimp_Error | \\Mailchimp_HttpError $e) {\n                $this->_helper->log($e->getFriendlyMessage());\n            }\n\n        }\n\n        $this->_subscriberApi->update($subscriber);\n    }\n}\n"
  },
  {
    "path": "README.md",
    "content": "\n<h3>Labels applied by the team</h3>\n\n| Label        | Description           |\n| ------------- |-------------|\n| ![bug](https://s3.amazonaws.com/ebizmartsgithubimages/bug.png) | Bug report contains sufficient information to reproduce. Will be solved for associated Milestone.|\n| ![enhancement](https://s3.amazonaws.com/ebizmartsgithubimages/enhancement.png) | Improvement accepted. Will be added for associated Milestone.|\n| ![done](https://s3.amazonaws.com/ebizmartsgithubimages/done.png) | Issue has been solved and will be applied in the associated Milestone. |\n| ![duplicate](https://s3.amazonaws.com/ebizmartsgithubimages/duplicate.png) | Issue has been already reported and will be closed with no further action. |\n| ![wrong issue format](https://s3.amazonaws.com/ebizmartsgithubimages/wrongissueformat.png) | 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. |\n| ![feature request](https://s3.amazonaws.com/ebizmartsgithubimages/featurerequest.png) | Feature request to be considered by the team. After approval will be labeled as enhancement. |\n| ![could not replicate](https://s3.amazonaws.com/ebizmartsgithubimages/couldnotreplicate.png) | The team was not able to replicate issue. It will be closed until missing information is given. |\n| ![contact support](https://s3.amazonaws.com/ebizmartsgithubimages/contactsupport.png) | Contact our support team at mailchimp@ebizmarts-desk.zendesk.com. Issue will be closed with no further action. |\n| ![low priority](https://s3.amazonaws.com/ebizmartsgithubimages/lowpriority.png) | Issue is considered as low priority by the team. |\n| ![priority](https://s3.amazonaws.com/ebizmartsgithubimages/priority.png) | Issue is considered as high priority by the team. |\n| ![conflict](https://s3.amazonaws.com/ebizmartsgithubimages/conflict.png) | Issue reports a conflict with other third party extension. |\n| ![need feedback](https://s3.amazonaws.com/ebizmartsgithubimages/needfeedback.png) | Feedback is required to continue working on the issue. If there is no answer after a week it will be closed. |\n| ![blocked](https://s3.amazonaws.com/ebizmartsgithubimages/blocked.png) | Issue can not be solved due to external causes. |\n| ![read documentation](https://s3.amazonaws.com/ebizmartsgithubimages/readdocumentation.png) | Issue will be closed. Available documentation: [MailChimp For Magento doc](https://kb.mailchimp.com/integrations/e-commerce/connect-or-disconnect-mailchimp-for-magento-2)|\n\n\n\n\n# Issue reporting guidelines\n\nTo 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.\n\nBefore creating an issue, please do the following:\n\n* 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.\n* Check the existing [issues](https://github.com/mailchimp/mc-magento2/issues) to make sure you are not duplicating somebody’s work.\n* 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.\n\nIf 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.\n\n## Title\n\nTitle 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.\n\nGood example would be:\n\n> Unable to place order with Virtual product and PayPal.\n\nUnclear example:\n\n> Can't checkout.\n\n## Issue Description\n\n### Preconditions\n\nDescribing 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.\n\nExample:\n\n    1. Magento CE 2.0.1 without sample data is installed.\n    2. mc-magento 1.0.6.\n    3. Test category is set up.\n    4. Virtual Product is created and assigned to the Test Category.\n    ...\n\n### Steps to reproduce\n\nThis 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.\n\nPrecisely 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.\n\nExample:\n\n    1. Navigate to storefront as a guest.\n    2. Open Test Category.\n    3. Click \"Add to Cart\" on the Virtual Product.\n    4. Open mini shopping cart and click \"Proceed to Checkout\".\n    ...\n\n### Actual and Expected result\n\nTo 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.\n\nExample:\n\n    Expected result:\n    Order is placed successfully, customer is redirected to the success page.\n    Actual result:\n    \"Place order\" button is not visible, order cannot be placed.\n\n### Additional information\n\nAdditional 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.\n\n## Pull requests\n\nBefore 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.\n"
  },
  {
    "path": "Setup/InstallData.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/7/16 1:30 PM\n * @file: InstallSchema.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Setup;\n\nuse Magento\\Eav\\Setup\\EavSetupFactory;\n\nuse Magento\\Framework\\Setup\\InstallDataInterface;\nuse Magento\\Framework\\Setup\\ModuleContextInterface;\nuse Magento\\Framework\\Setup\\ModuleDataSetupInterface;\n\nclass InstallData implements InstallDataInterface\n{\n\n    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)\n    {\n        return;\n    }\n}\n"
  },
  {
    "path": "Setup/InstallSchema.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/7/16 3:36 PM\n * @file: InstallSchema.php\n */\nnamespace Ebizmarts\\MailChimp\\Setup;\n\nuse Magento\\Framework\\Setup\\InstallSchemaInterface;\nuse Magento\\Framework\\Setup\\ModuleContextInterface;\nuse Magento\\Framework\\Setup\\SchemaSetupInterface;\nuse Symfony\\Component\\Config\\Definition\\Exception\\Exception;\nuse Magento\\Framework\\App\\ResourceConnection;\nuse Magento\\Framework\\App\\DeploymentConfig;\n\nclass InstallSchema implements InstallSchemaInterface\n{\n    /**\n     * @var ResourceConnection\n     */\n    protected $_resource;\n    /**\n     * @var DeploymentConfig\n     */\n    protected $_deploymentConfig;\n    /**\n     * @var \\Magento\\Framework\\Filesystem\\Driver\\File\n     */\n    protected $_driver;\n\n    /**\n     * InstallSchema constructor.\n     * @param ResourceConnection $resource\n     * @param DeploymentConfig $deploymentConfig\n     * @param \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n     */\n    public function __construct(\n        ResourceConnection $resource,\n        DeploymentConfig $deploymentConfig,\n        \\Magento\\Framework\\Filesystem\\Driver\\File $driver\n    ) {\n        $this->_resource            = $resource;\n        $this->_deploymentConfig    = $deploymentConfig;\n        $this->_driver              = $driver;\n    }\n\n    /**\n     * {@inheritdoc}\n     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)\n     */\n    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)\n    {\n        $connection = $this->_resource->getConnectionByName('default');\n        $table = $connection\n            ->newTable($setup->getTable('mailchimp_sync_batches'))\n            ->addColumn(\n                'id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                null,\n                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                'Batch Id'\n            )\n            ->addColumn(\n                'store_id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                50,\n                ['unsigned' => true, 'nullable' => false],\n                'Store Id'\n            )\n            ->addColumn(\n                'mailchimp_store_id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                50,\n                ['unsigned' => true, 'nullable' => false],\n                'Store Id'\n            )\n            ->addColumn(\n                'batch_id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                24,\n                [],\n                'Batch Id'\n            )\n            ->addColumn(\n                'status',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                10,\n                [],\n                'Status'\n            )\n            ->addColumn(\n                'carts_new_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of new carts'\n            )\n            ->addColumn(\n                'customers_new_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of new customers'\n            )\n            ->addColumn(\n                'orders_new_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of new orders'\n            )\n            ->addColumn(\n                'products_new_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of new products'\n            )\n            ->addColumn(\n                'subscribers_new_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of new carts'\n            )\n            ->addColumn(\n                'carts_modified_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of modified carts'\n            )\n            ->addColumn(\n                'customers_modified_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of modified customers'\n            )\n            ->addColumn(\n                'orders_modified_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of modified orders'\n            )\n            ->addColumn(\n                'products_modified_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of modified products'\n            )\n            ->addColumn(\n                'subscribers_modified_count',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                null,\n                [],\n                'Number of modified carts'\n            );\n\n        $connection->createTable($table);\n\n        $table = $connection\n            ->newTable($setup->getTable('mailchimp_errors'))\n            ->addColumn(\n                'id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                null,\n                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                'Batch Id'\n            )\n            ->addColumn(\n                'mailchimp_store_id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                50,\n                ['unsigned' => true, 'nullable' => false],\n                'Store Id'\n            )\n            ->addColumn(\n                'type',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                256,\n                [],\n                'type'\n            )\n            ->addColumn(\n                'title',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                128,\n                [],\n                'title'\n            )\n            ->addColumn(\n                'status',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                null,\n                [],\n                'status'\n            )\n            ->addColumn(\n                'errors',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                256,\n                [],\n                'errors'\n            )\n            ->addColumn(\n                'regtype',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                3,\n                [],\n                'regtype'\n            );\n\n        $connection->createTable($table);\n\n        $table = $connection\n            ->newTable($setup->getTable('mailchimp_sync_ecommerce'))\n            ->addColumn(\n                'id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                null,\n                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                'Id'\n            )\n            ->addColumn(\n                'mailchimp_store_id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                50,\n                ['unsigned' => true, 'nullable' => false],\n                'Store Id'\n            )\n            ->addColumn(\n                'type',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                24,\n                [],\n                'Type of register'\n            )\n            ->addColumn(\n                'related_id',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                null,\n                [],\n                'Id of the related entity'\n            )\n            ->addColumn(\n                'mailchimp_sync_modified',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                null,\n                [],\n                'If the entity was modified'\n            )\n            ->addColumn(\n                'mailchimp_sync_delta',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_DATETIME,\n                null,\n                [],\n                'Sync Delta'\n            )->addColumn(\n                'mailchimp_sync_error',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                128,\n                [],\n                'Error on synchronization'\n            )->addColumn(\n                'mailchimp_sync_deleted',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                null,\n                [],\n                'If the object was deleted in mailchimp'\n            )->addColumn(\n                'mailchimp_token',\n                \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                32,\n                [],\n                'Quote token'\n            );\n\n        $connection->createTable($table);\n\n        if ($this->_deploymentConfig->get(\n            \\Magento\\Framework\\Config\\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/sales'\n        )\n        ) {\n            $connection = $this->_resource->getConnectionByName('sales');\n        }\n\n        $connection->addColumn(\n            $setup->getTable('sales_order'),\n            'mailchimp_abandonedcart_flag',\n            [\n                'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                'default' => 0,\n                'comment' => 'Retrieved from Mailchimp'\n            ]\n        );\n        if ($this->_deploymentConfig->get(\n            \\Magento\\Framework\\Config\\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/checkout'\n        )\n        ) {\n            $connection = $this->_resource->getConnectionByName('checkout');\n        }\n        $connection->addColumn(\n            $setup->getTable('quote'),\n            'mailchimp_abandonedcart_flag',\n            [\n                'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                'default' => 0,\n                'comment' => 'Retrieved from Mailchimp'\n            ]\n        );\n\n        $path = BP . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'Mailchimp';\n        if (!$this->_driver->isDirectory($path)) {\n            $this->_driver->createDirectory($path);\n        }\n    }\n}\n"
  },
  {
    "path": "Setup/Uninstall.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Setup;\n\nuse Magento\\Framework\\Setup\\ModuleContextInterface;\nuse Magento\\Framework\\Setup\\SchemaSetupInterface;\nuse Magento\\Framework\\Setup\\UninstallInterface;\n\nclass Uninstall implements UninstallInterface\n{\n    public function uninstall(SchemaSetupInterface $setup, ModuleContextInterface $context)\n    {\n        $tables = [\n            'mailchimp_sync_batches',\n            'mailchimp_errors',\n            'mailchimp_sync_ecommerce',\n            'mailchimp_stores',\n            'mailchimp_webhook_request',\n            'mailchimp_interest_group'\n        ];\n        $tablesFields = [\n            'sales_order' => [\n                'mailchimp_abandonedcart_flag',\n                'mailchimp_campaign_id',\n                'mailchimp_landing_page',\n                'mailchimp_flag'\n            ],\n            'quote' => [\n                'mailchimp_abandonedcart_flag',\n                'mailchimp_campaign_id',\n                'mailchimp_landing_page'\n            ],\n            'sales_order_grid' => [\n                'mailchimp_flag'\n            ]\n        ];\n        $installer = $setup;\n        $installer->startSetup();\n        $connection = $installer->getConnection();\n        foreach ($tables as $table) {\n            $connection->dropTable($setup->getTable($table));\n        }\n        foreach($tablesFields as $table => $columnArray) {\n            foreach($columnArray as $column) {\n                $connection->dropColumn( $setup->getTable($table), $column);\n            }\n        }\n\n        $installer->endSetup();\n    }\n}"
  },
  {
    "path": "Setup/UpgradeData.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/31/16 3:28 PM\n * @file: UpgradeData.php\n */\nnamespace Ebizmarts\\MailChimp\\Setup;\n\nuse Magento\\Framework\\Setup\\ModuleContextInterface;\nuse Magento\\Framework\\Setup\\ModuleDataSetupInterface;\nuse Magento\\Framework\\Setup\\UpgradeDataInterface;\nuse Magento\\Framework\\App\\ResourceConnection;\nuse Magento\\Framework\\App\\DeploymentConfig;\nuse Magento\\Sales\\Model\\OrderFactory;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory as SyncCollectionFactory;\n\nclass UpgradeData implements UpgradeDataInterface\n{\n    /**\n     * @var ResourceConnection\n     */\n    protected $_resource;\n    /**\n     * @var DeploymentConfig\n     */\n    protected $_deploymentConfig;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup\\CollectionFactory\n     */\n    protected $_insterestGroupCollectionFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\CollectionFactory\n     */\n    protected $_webhookCollectionFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Config\\Model\\ResourceModel\\Config\\Data\\CollectionFactory\n     */\n    protected $configFactory;\n    /**\n     * @var SyncCollectionFactory\n     */\n    private $syncCollectionFactory;\n    /**\n     * @var OrderFactory\n     */\n    private $orderFactory;\n    /**\n     * @param ResourceConnection $resource\n     * @param DeploymentConfig $deploymentConfig\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup\\CollectionFactory $interestGroupCollectionFactory\n     * @param \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\CollectionFactory $webhookCollectionFactory\n     * @param \\Magento\\Config\\Model\\ResourceModel\\Config\\Data\\CollectionFactory $configFactory\n     * @param SyncCollectionFactory $syncCollectionFactory\n     * @param OrderFactory $orderFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     */\n    public function __construct(\n        ResourceConnection $resource,\n        DeploymentConfig $deploymentConfig,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup\\CollectionFactory $interestGroupCollectionFactory,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest\\CollectionFactory $webhookCollectionFactory,\n        \\Magento\\Config\\Model\\ResourceModel\\Config\\Data\\CollectionFactory $configFactory,\n        SyncCollectionFactory $syncCollectionFactory,\n        OrderFactory $orderFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n    ) {\n        $this->_resource            = $resource;\n        $this->_deploymentConfig    = $deploymentConfig;\n        $this->_insterestGroupCollectionFactory = $interestGroupCollectionFactory;\n        $this->_webhookCollectionFactory        = $webhookCollectionFactory;\n        $this->configFactory                    = $configFactory;\n        $this->syncCollectionFactory            = $syncCollectionFactory;\n        $this->orderFactory                     = $orderFactory;\n        $this->_helper              = $helper;\n    }\n\n    /**\n     * @param ModuleDataSetupInterface $setup\n     * @param ModuleContextInterface $context\n     */\n    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)\n    {\n        if (version_compare($context->getVersion(), '1.0.24') < 0) {\n            $setup->startSetup();\n            $connection = $this->_resource->getConnectionByName('default');\n            if ($this->_deploymentConfig->get(\n                \\Magento\\Framework\\Config\\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/sales'\n            )\n            ) {\n                    $salesConnection = $this->_resource->getConnectionByName('sales');\n            } else {\n                    $salesConnection = $connection;\n            }\n            $table = $setup->getTable('sales_order');\n            $select = $salesConnection->select()\n                ->from(\n                    false,\n                    ['mailchimp_flag' => new \\Zend_Db_Expr('IF(mailchimp_abandonedcart_flag OR mailchimp_campaign_id OR mailchimp_landing_page, 1, 0)')]\n                )->join(['O'=>$table], 'O.entity_id = G.entity_id', []);\n\n            $query = $salesConnection->updateFromSelect($select, ['G' => $setup->getTable('sales_order_grid')]);\n\n            $salesConnection->query($query);\n            $setup->endSetup();\n        }\n        if (version_compare($context->getVersion(), '1.2.32') < 0) {\n            // delete the old serialized data from core_config_data\n            $setup->startSetup();\n            $connection = $this->_resource->getConnectionByName('default');\n            $table = $setup->getTable('core_config_data');\n            try {\n                $connection->delete($table, ['path = ?'=> \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MERGEVARS]);\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n            }\n\n            // empty table mailchimp_interest_group\n            /**\n             * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpInterestGroup $item\n             */\n            $table = $setup->getTable('mailchimp_interest_group');\n\n            try {\n                $connection->delete($table);\n            } catch (\\Exception $e) {\n                $this->_helper->log($e->getMessage());\n            }\n            // convert table mailchimp_webhook_request\n            /**\n             * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpWebhookRequest $webhookItem\n             */\n            $lastId = 0;\n            $done = false;\n            while (!$done) {\n                $webhookCollection = $this->_webhookCollectionFactory->create();\n                $webhookCollection->addFieldToFilter('processed', ['neq' => 1]);\n                $webhookCollection->addFieldToFilter('id', ['gt' => $lastId]);\n                $webhookCollection->getSelect()->limit(500);\n                if (!$webhookCollection->getSize()) {\n                    $done = true;\n                } else {\n                    foreach ($webhookCollection as $webhookItem) {\n                        try {\n                            $webhookItem->setProcessed(\\Ebizmarts\\MailChimp\\Cron\\Webhook::DATA_NOT_CONVERTED);\n                            $webhookItem->getResource()->save($webhookItem);\n                        } catch (\\Exception $e) {\n                            $this->_helper->log($e->getMessage());\n                            $webhookItem->setProcesed(\\Ebizmarts\\MailChimp\\Cron\\Webhook::DATA_WITH_ERROR);\n                            $webhookItem->getResource()->save($webhookItem);\n                        }\n                        $lastId = $webhookItem->getId();\n                    }\n                }\n            }\n        }\n        if (version_compare($context->getVersion(), '102.3.35') < 0) {\n            $configCollection = $this->configFactory->create();\n            $configCollection->addFieldToFilter('path', ['eq' => \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_APIKEY]);\n            /**\n             * @var $config \\Magento\\Config\\Model\\ResourceModel\\Config\n             */\n            foreach ($configCollection as $config) {\n                try {\n                    $config->setValue($this->_helper->encrypt($config->getvalue()));\n                    $config->getResource()->save($config);\n                } catch (\\Exception $e) {\n                    $this->_helper->log($e->getMessage());\n                }\n            }\n            $configCollection = $this->configFactory->create();\n            $configCollection->addFieldToFilter(\n                'path',\n                ['eq' => \\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_APIKEY_LIST]\n            );\n            foreach ($configCollection as $config) {\n                $config->getResource()->delete($config);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "Setup/UpgradeSchema.php",
    "content": "<?php\n\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 10/31/16 5:23 PM\n * @file: UpgradeSchema.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Setup;\n\nuse Magento\\Framework\\Setup\\UpgradeSchemaInterface;\nuse Magento\\Framework\\Setup\\SchemaSetupInterface;\nuse Magento\\Framework\\Setup\\ModuleContextInterface;\nuse Magento\\Framework\\App\\ResourceConnection;\nuse Magento\\Framework\\App\\DeploymentConfig;\n\nclass UpgradeSchema implements UpgradeSchemaInterface\n{\n    /**\n     * @var ResourceConnection\n     */\n    protected $_resource;\n    /**\n     * @var DeploymentConfig\n     */\n    protected $_deploymentConfig;\n    public function __construct(ResourceConnection $resource, DeploymentConfig $deploymentConfig)\n    {\n        $this->_resource = $resource;\n        $this->_deploymentConfig = $deploymentConfig;\n    }\n\n    /**\n     * {@inheritdoc}\n     */\n    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)\n    {\n        $connection = $this->_resource->getConnectionByName('default');\n        if (\n            $this->_deploymentConfig->get(\n            \\Magento\\Framework\\Config\\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/checkout'\n            )\n        ) {\n            $checkoutConnection = $this->_resource->getConnectionByName('checkout');\n        } else {\n            $checkoutConnection = $connection;\n        }\n        if (\n            $this->_deploymentConfig->get(\n            \\Magento\\Framework\\Config\\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/sales'\n            )\n        ) {\n            $salesConnection = $this->_resource->getConnectionByName('sales');\n        } else {\n            $salesConnection = $connection;\n        }\n        if (version_compare($context->getVersion(), '1.0.5') < 0) {\n            $table = $connection\n                ->newTable($setup->getTable('mailchimp_stores'))\n                ->addColumn(\n                    'id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    null,\n                    ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                    'Id'\n                )\n                ->addColumn(\n                    'apikey',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'mailchimp apikey'\n                )\n                ->addColumn(\n                    'storeid',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'mailchimp store id'\n                )\n                ->addColumn(\n                    'list_id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'mailchimp store id'\n                )\n                ->addColumn(\n                    'name',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    128,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store name'\n                )\n                ->addColumn(\n                    'platform',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store platform'\n                )\n                ->addColumn(\n                    'is_sync',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                    null,\n                    [],\n                    'if the store is synced or not'\n                )\n                ->addColumn(\n                    'email_address',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    128,\n                    ['unsigned' => true, 'nullable' => false],\n                    'email associated to store'\n                )\n                ->addColumn(\n                    'currency_code',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    3,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store currency code'\n                )\n                ->addColumn(\n                    'money_format',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    10,\n                    ['unsigned' => true, 'nullable' => false],\n                    'symbol of currency'\n                )\n                ->addColumn(\n                    'primary_locale',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    5,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store locale'\n                )\n                ->addColumn(\n                    'timezone',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    20,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store timezone'\n                )\n                ->addColumn(\n                    'phone',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store phone number'\n                )\n                ->addColumn(\n                    'address_address1',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store address1'\n                )\n                ->addColumn(\n                    'address_address2',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store address2'\n                )\n                ->addColumn(\n                    'address_city',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store city'\n                )\n                ->addColumn(\n                    'address_province',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store province'\n                )\n                ->addColumn(\n                    'address_province_code',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    2,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store province code'\n                )\n                ->addColumn(\n                    'address_postal_code',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store postal code'\n                )\n                ->addColumn(\n                    'address_country',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store country name'\n                )\n                ->addColumn(\n                    'address_country_code',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    2,\n                    ['unsigned' => true, 'nullable' => false],\n                    'store country code'\n                );\n\n            $connection->createTable($table);\n        }\n        if (version_compare($context->getVersion(), '1.0.7') < 0) {\n            $checkoutConnection->addColumn(\n                $setup->getTable('quote'),\n                'mailchimp_campaign_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 16,\n                    'default' => '',\n                    'comment' => 'Campaign'\n                ]\n            );\n\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_campaign_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 16,\n                    'default' => '',\n                    'comment' => 'Campaign'\n                ]\n            );\n            $checkoutConnection->addColumn(\n                $setup->getTable('quote'),\n                'mailchimp_landing_page',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 512,\n                    'default' => '',\n                    'comment' => 'Landing Page'\n                ]\n            );\n\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_landing_page',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 512,\n                    'default' => '',\n                    'comment' => 'Landing Page'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.8') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_errors'),\n                'original_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    'length' => 11,\n                    'default' => null,\n                    'comment' => 'Associated object ID'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_errors'),\n                'batch_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 64,\n                    'default' => null,\n                    'comment' => 'Mailchimp Batch ID'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.10') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_errors'),\n                'store_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    'length' => 11,\n                    'default' => null,\n                    'comment' => 'Magento Store Id'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.11') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_stores'),\n                'domain',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 512,\n                    'default' => null,\n                    'comment' => 'Domain'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.12') < 0) {\n            if ($connection->tableColumnExists($setup->getTable('mailchimp_stores'), 'address_address1')) {\n                $connection->changecolumn(\n                    $setup->getTable('mailchimp_stores'),\n                    'address_address1',\n                    'address_address_one',\n                    [\n                        'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                        'length' => 255,\n                        'default' => null,\n                        'comment' => 'first street address'\n                    ]\n                );\n            }\n            if ($connection->tableColumnExists($setup->getTable('mailchimp_stores'), 'address_address2')) {\n                $connection->changecolumn(\n                    $setup->getTable('mailchimp_stores'),\n                    'address_address2',\n                    'address_address_two',\n                    [\n                        'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                        'length' => 255,\n                        'default' => null,\n                        'comment' => 'second street address'\n                    ]\n                );\n            }\n        }\n        if (version_compare($context->getVersion(), '1.0.13') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_stores'),\n                'mc_account_name',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 512,\n                    'default' => null,\n                    'comment' => 'MC account name'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_stores'),\n                'list_name',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 512,\n                    'default' => null,\n                    'comment' => 'List Name'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.14') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                'batch_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 64,\n                    'default' => null,\n                    'comment' => 'Mailchimp batch Id'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.15') < 0) {\n            $table = $connection\n                ->newTable($setup->getTable('mailchimp_webhook_request'))\n                ->addColumn(\n                    'id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    null,\n                    ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                    'Id'\n                )\n                ->addColumn(\n                    'type',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    50,\n                    ['unsigned' => true, 'nullable' => false],\n                    'request type'\n                )\n                ->addColumn(\n                    'fired_at',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_DATETIME,\n                    null,\n                    [],\n                    'date of the request'\n                )\n                ->addColumn(\n                    'data_request',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    4096,\n                    ['unsigned' => true, 'nullable' => false],\n                    'data of the request'\n                )\n                ->addColumn(\n                    'processed',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                    null,\n                    [],\n                    'Already processed'\n                );\n            $connection->createTable($table);\n        }\n        if (version_compare($context->getVersion(), '1.0.24') < 0) {\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order_grid'),\n                'mailchimp_flag',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                    'default' => 0,\n                    'comment' => 'Retrieved from Mailchimp'\n                ]\n            );\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_flag',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                    'default' => 0,\n                    'comment' => 'Retrieved from Mailchimp'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.25') < 0) {\n            $connection->addIndex(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                $connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'related_id', 'index'),\n                'related_id'\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                'deleted_related_id',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    'length' => 11,\n                    'default' => null,\n                    'comment' => 'Id related to deleted item'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '1.0.26') < 0) {\n            $table = $connection\n                ->newTable($setup->getTable('mailchimp_interest_group'))\n                ->addColumn(\n                    'id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    null,\n                    ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                    'Id'\n                )\n                ->addColumn(\n                    'subscriber_id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    10,\n                    ['unsigned' => true, 'nullable' => false],\n                    'subscriber id'\n                )\n                ->addColumn(\n                    'store_id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    5,\n                    ['unsigned' => true, 'nullable' => false],\n                    'subscriber id'\n                )\n                ->addColumn(\n                    'updated_at',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_DATETIME,\n                    null,\n                    [],\n                    'date of the request'\n                )\n                ->addColumn(\n                    'groupdata',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    4096,\n                    ['unsigned' => true, 'nullable' => false],\n                    'data'\n                );\n            $connection->createTable($table);\n        }\n        if (version_compare($context->getVersion(), '1.3.33') < 0) {\n            $connection->addIndex(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                $connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'type', 'index'),\n                'type'\n            );\n            $connection->addIndex(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                $connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'batch_id', 'index'),\n                'batch_id'\n            );\n            $connection->addIndex(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                $connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'mailchimp_store_id', 'index'),\n                'mailchimp_store_id'\n            );\n            $connection->changecolumn(\n                $setup->getTable('mailchimp_stores'),\n                'timezone',\n                'timezone',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 32,\n                    'nullable' => false,\n                    'comment' => 'store timezone'\n                ]\n            );\n        }\n\n        if (version_compare($context->getVersion(), '102.3.34') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'modified_date',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_DATETIME,\n                    'default' => null,\n                    'comment' => 'modified date'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                'mailchimp_sent',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'length' => 1,\n                    'default' => 0,\n                    'comment' => 'Sent to Mailchimp'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.35') < 0) {\n            $connection->changeColumn(\n                $setup->getTable('mailchimp_stores'),\n                'apikey',\n                'apikey',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'length' => 128\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.43') < 0) {\n            $connection->addIndex(\n                $setup->getTable('mailchimp_errors'),\n                $connection->getIndexName($setup->getTable('mailchimp_errors'), ['store_id','regtype','original_id'], 'index'),\n                ['store_id','regtype','original_id']\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.45') < 0) {\n            $connection->addIndex(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                $connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'mailchimp_sync_delta', 'index'),\n                'mailchimp_sync_delta'\n            );\n            $connection->addIndex(\n                $setup->getTable('mailchimp_sync_ecommerce'),\n                $connection->getIndexName($setup->getTable('mailchimp_sync_ecommerce'), 'mailchimp_sync_modified', 'index'),\n                'mailchimp_sync_modified'\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.50') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_errors'),\n                'added_at',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TIMESTAMP,\n                    'default' => \\Magento\\Framework\\DB\\Ddl\\Table::TIMESTAMP_INIT,\n                    'comment' => 'added at date'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.51') < 0) {\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'carts_modified_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of modified carts'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'customers_modified_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of modified customers'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'orders_modified_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of modified orders'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'products_modified_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of modified products'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'subscribers_modified_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of modified subscribers'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'carts_new_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of new carts'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'customers_new_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of new customers'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'orders_new_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of new orders'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'products_new_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of new products'\n                ]\n            );\n            $connection->addColumn(\n                $setup->getTable('mailchimp_sync_batches'),\n                'subscribers_new_count',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'default' => null,\n                    'comment' => 'counter of new subscribers'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.52') < 0) {\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_sync_error',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'default' => null,\n                    'length' => 128,\n                    'comment' => 'Error on synchronization'\n                ]\n            );\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_sent',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'length' => 1,\n                    'default' => 0,\n                    'comment' => 'Sent to Mailchimp'\n                ]\n            );\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order_grid'),\n                'mailchimp_sync_error',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'default' => null,\n                    'length' => 128,\n                    'comment' => 'Error on synchronization'\n                ]\n            );\n            $salesConnection->addColumn(\n                $setup->getTable('sales_order_grid'),\n                'mailchimp_sent',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'length' => 1,\n                    'default' => 0,\n                    'comment' => 'Sent to Mailchimp'\n                ]\n            );\n            $salesConnection->addColumn(\n                $setup->getTable('catalog_product_entity'),\n                'mailchimp_sync_error',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    'default' => null,\n                    'length' => 128,\n                    'comment' => 'Error on synchronization'\n                ]\n            );\n            $salesConnection->addColumn(\n                $setup->getTable('catalog_product_entity'),\n                'mailchimp_sent',\n                [\n                    'type' => \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_SMALLINT,\n                    'length' => 1,\n                    'default' => 0,\n                    'comment' => 'Sent to Mailchimp'\n                ]\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.54') < 0) {\n            $salesConnection->dropColumn(\n                $setup->getTable('catalog_product_entity'),\n                'mailchimp_sync_error'\n            );\n            $salesConnection->dropColumn(\n                $setup->getTable('catalog_product_entity'),\n                'mailchimp_sent'\n            );\n            $salesConnection->dropColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_sync_error'\n            );\n            $salesConnection->dropColumn(\n                $setup->getTable('sales_order'),\n                'mailchimp_sent'\n            );\n            $salesConnection->dropColumn(\n                $setup->getTable('sales_order_grid'),\n                'mailchimp_sync_error'\n            );\n            $salesConnection->dropColumn(\n                $setup->getTable('sales_order_grid'),\n                'mailchimp_sent'\n            );\n        }\n        if (version_compare($context->getVersion(), '102.3.66') < 0) {\n            $table = $connection\n                ->newTable($setup->getTable('mailchimp_notification'))\n                ->addColumn(\n                    'id',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_INTEGER,\n                    null,\n                    ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],\n                    'Id'\n                )\n                ->addColumn(\n                    'notification_data',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TEXT,\n                    \\Magento\\Framework\\DB\\Ddl\\Table::MAX_TEXT_SIZE,\n                    [],\n                    'Notification Data'\n                )\n                ->addColumn(\n                    'generated_at',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_TIMESTAMP,\n                    null,\n                    ['default' => \\Magento\\Framework\\DB\\Ddl\\Table::TIMESTAMP_INIT],\n                    'Generated At'\n                )\n                ->addColumn(\n                    'synced_at',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_DATETIME,\n                    null,\n                    ['default' => null],\n                    'date of sync'\n                )\n                ->addColumn(\n                    'processed',\n                    \\Magento\\Framework\\DB\\Ddl\\Table::TYPE_BOOLEAN,\n                    null,\n                    ['default' => false],\n                    'Already processed'\n                );\n            $connection->createTable($table);\n\n        }\n    }\n\n}\n"
  },
  {
    "path": "Ui/Component/Batch/Grid/Column/Batches.php",
    "content": "<?php\n\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/3/17 3:10 PM\n * @file: Batch.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column;\n\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse Magento\\Framework\\UrlInterface;\n\nclass Batches extends Column\n{\n    /**\n     * @var UrlInterface\n     */\n    protected $urlBuilder;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches\n     */\n    protected $mailChimpSyncB;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $helper;\n\n    private $stores=[];\n\n    /**\n     * Batch constructor.\n     * @param ContextInterface $context\n     * @param UiComponentFactory $uiComponentFactory\n     * @param UrlInterface $urlBuilder\n     * @param array $components\n     * @param array $data\n     */\n    public function __construct(\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpSyncBatches $mailChimpSyncB,\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        UrlInterface $urlBuilder,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->helper = $helper;\n        $this->mailChimpSyncB = $mailChimpSyncB;\n        $this->urlBuilder = $urlBuilder;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n\n    public function getDataSourceData()\n    {\n        return $this->getContext()->getDataProvider()->getData();\n    }\n\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            foreach ($dataSource['data']['items'] as &$batch) {\n                $batch_status = &$batch['status'];\n                $batch_status = ucfirst($batch_status);\n                $mailchimp_store_id = $batch['mailchimp_store_id'];\n                $magentoStoreId = $batch['store_id'];\n                $store_name = $this->getMCStoreNameById($mailchimp_store_id, $magentoStoreId);\n                $batch['store_name'] = $store_name;\n                $batch['subscribers'] = $batch['subscribers_new_count'] . \" new;\" . $batch[\"subscribers_modified_count\"] . \" modified\";\n                $batch['customers'] = $batch['customers_new_count'] . \" new;\" . $batch[\"customers_modified_count\"] . \" modified\";\n                $batch['orders'] = $batch['orders_new_count'] . \" new;\" . $batch[\"orders_modified_count\"] . \" modified\";\n                $batch['products'] = $batch['products_new_count'] . \" new;\" . $batch[\"products_modified_count\"] . \" modified\";\n                $batch['carts'] = $batch['carts_new_count'] . \" new;\" . $batch[\"carts_modified_count\"] . \" modified\";\n                $batch[$this->getData('name')] = [\n                    'download' => [\n                        'href' => $this->urlBuilder->getUrl(\n                            'mailchimp/batch/getResponse',\n                            ['id' => $batch['id']]\n                        ),\n                        'label' => 'Download'\n                    ]\n                ];\n            }\n        }\n        return $dataSource;\n    }\n\n    private function getMCStoreNameById($mailchimp_store_id, $magentoStoreId)\n    {\n        if (!key_exists($mailchimp_store_id, $this->stores)) {\n            $api = $this->helper->getApi($magentoStoreId);\n            try {\n                $store = $api->ecommerce->stores->get($mailchimp_store_id);\n                $this->stores[$mailchimp_store_id] = $store['name'];\n            } catch (\\Exception $e) {\n                $this->stores[$mailchimp_store_id] = 'Not existing store';\n            }\n        }\n        return $this->stores[$mailchimp_store_id];\n    }\n}\n"
  },
  {
    "path": "Ui/Component/Carts/Grid/Column/Actions.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Carts\\Grid\\Column;\n\nuse Magento\\Framework\\UrlInterface;\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nclass Actions extends Column\n{\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        UrlInterface $urlBuilder,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->urlBuilder = $urlBuilder;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            foreach ($dataSource['data']['items'] as &$item) {\n                $customerId = $item['customer_id'];\n                if ($customerId) {\n                    $item[$this->getData('name')] = [\n                        'viewcustomer' => [\n                            'href' => $this->urlBuilder->getUrl(\n                                'customer/index/edit',\n                                ['id' => $customerId]\n                            ),\n                            'label' => 'View Customer',\n                            'target' => '_blank'\n                        ]\n                    ];\n                }\n            }\n        }\n        return $dataSource;\n    }\n}\n"
  },
  {
    "path": "Ui/Component/Carts/Grid/Column/Customer.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Carts\\Grid\\Column;\n\nuse Magento\\Framework\\Escaper;\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nclass Customer extends Column\n{\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        Escaper $escaper,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->escaper = $escaper;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            foreach ($dataSource['data']['items'] as & $item) {\n                $item[$this->getData('name')] = $item['customer_firstname'] . ' ' . $item['customer_lastname'];\n            }\n        }\n\n        return $dataSource;\n    }\n}\n"
  },
  {
    "path": "Ui/Component/Carts/Grid/Column/Mailchimp.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Carts\\Grid\\Column;\n\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\nuse Magento\\Framework\\Escaper;\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse Magento\\Framework\\View\\Asset\\Repository;\nuse Magento\\Framework\\App\\RequestInterface;\n\nclass Mailchimp extends Column\n{\n    /**\n     * @var Repository\n     */\n    protected $_assetRepository;\n    protected $_requestInterfase;\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        Escaper $escaper,\n        MailChimpHelper $mailChimpHelper,\n        Repository $assetRepository,\n        RequestInterface $requestInterfase,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->escaper = $escaper;\n        $this->_assetRepository = $assetRepository;\n        $this->_requestInterfase = $requestInterfase;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            foreach ($dataSource['data']['items'] as & $item) {\n                $params = ['_secure' => $this->_requestInterfase->isSecure()];\n                $sync = $item['mailchimp_sent'];\n                $alt = '';\n                switch ($sync) {\n                    case MailChimpHelper::NEVERSYNC:\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/no.png',\n                            $params\n                        );\n                        $text = __('No Syncing');\n                        break;\n                    case MailChimpHelper::SYNCED:\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/yes.png',\n                            $params\n                        );\n                        $text = __('Synced');\n                        $menu = true;\n                        break;\n                    case MailChimpHelper::WAITINGSYNC:\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/waiting.png',\n                            $params\n                        );\n                        $text = __('Waiting');\n                        break;\n                    case MailChimpHelper::SYNCERROR:\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/error.png',\n                            $params\n                        );\n                        $text = __('Error');\n                        break;\n                    case MailChimpHelper::NEEDTORESYNC:\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/resync.png',\n                            $params\n                        );\n                        $text = __('Resyncing');\n                        $menu = true;\n                        break;\n                    case MailChimpHelper::NOTSYNCED:\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/never.png',\n                            $params\n                        );\n                        $text = __('With error');\n                        break;\n                    default:\n                        $url ='';\n                        $text = '';\n                }\n                $item[$this->getData('name')] = \"<div style='width: 50%;margin: 0 auto;text-align: center'><img src='\".$url.\"' style='border: none; width: 5rem; text-align: center; max-width: 100%' title='$alt' class='freddie'/>$text</div>\";\n            }\n        }\n        return $dataSource;\n    }\n\n}\n"
  },
  {
    "path": "Ui/Component/Errors/Grid/Column/Batch.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/3/17 3:10 PM\n * @file: Batch.php\n */\n\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Errors\\Grid\\Column;\n\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse Magento\\Framework\\UrlInterface;\n\nclass Batch extends Column\n{\n    /**\n     * @var UrlInterface\n     */\n    protected $urlBuilder;\n\n    /**\n     * Batch constructor.\n     * @param ContextInterface $context\n     * @param UiComponentFactory $uiComponentFactory\n     * @param UrlInterface $urlBuilder\n     * @param array $components\n     * @param array $data\n     */\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        UrlInterface $urlBuilder,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->urlBuilder = $urlBuilder;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            foreach ($dataSource['data']['items'] as &$item) {\n                $edit = false;\n                switch($item['regtype']) {\n                    case \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER:\n                        $label = 'Edit customer';\n                        $url = 'customer/index/edit';\n                        $id = 'id';\n                        $edit = true;\n                        break;\n                    case \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER:\n                        $label = 'Edit order';\n                        $url = 'sales/order/view';\n                        $id = 'order_id';\n                        $edit = true;\n                        break;\n                    case \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT:\n                        $label = 'Edit product';\n                        $url = 'catalog/product/edit';\n                        $id = 'id';\n                        $edit = true;\n                        break;\n                }\n                $item[$this->getData('name')] = [\n                    'download' => [\n                        'href' => $this->urlBuilder->getUrl(\n                            'mailchimp/errors/getresponse',\n                            ['id' => $item['id']]\n                        ),\n                        'label' => 'Download Response'\n                    ]\n                    ];\n                if ($edit) {\n                    $item[$this->getData('name')]['edit'] =\n                    [\n                        'href' => $this->urlBuilder->getUrl(\n                            $url,\n                            [$id => $item['original_id']]\n                        ),\n                        'label' => $label\n                    ];\n                }\n            }\n        }\n\n        return $dataSource;\n    }\n}\n"
  },
  {
    "path": "Ui/Component/Listing/Column/Customers.php",
    "content": "<?php\n\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Listing\\Column;\n\nuse Magento\\Framework\\App\\RequestInterface;\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse \\Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse Magento\\Customer\\Model\\CustomerFactory;\nuse Ebizmarts\\MailChimp\\Helper\\Sync as SyncHelper;\n\nclass Customers extends Column\n{\n    /**\n     * @var RequestInterface\n     */\n    protected $_requestInterface;\n    /**\n     * @var \\Magento\\Framework\\View\\Asset\\Repository\n     */\n    protected $_assetRepository;\n    /**\n     * @var CustomerFactory\n     */\n    protected $_customerFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Helper\\Data\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory\n     */\n    protected $_mailChimpErrorsFactory;\n\n    /**\n     * @param ContextInterface $context\n     * @param UiComponentFactory $uiComponentFactory\n     * @param RequestInterface $requestInterface\n     * @param \\Magento\\Framework\\View\\Asset\\Repository $assetRepository\n     * @param CustomerFactory $customerFactory\n     * @param \\Ebizmarts\\MailChimp\\Helper\\Data $helper\n     * @param SyncHelper $syncHelper\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $mailChimpErrorsFactory\n     * @param array $components\n     * @param array $data\n     */\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        RequestInterface $requestInterface,\n        \\Magento\\Framework\\View\\Asset\\Repository $assetRepository,\n        CustomerFactory $customerFactory,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        SyncHelper $syncHelper,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $mailChimpErrorsFactory,\n        array $components = [],\n        array $data = [])\n    {\n        $this->_requestInterface = $requestInterface;\n        $this->_assetRepository = $assetRepository;\n        $this->_customerFactory = $customerFactory;\n        $this->_helper          = $helper;\n        $this->syncHelper       = $syncHelper;\n        $this->_mailChimpErrorsFactory = $mailChimpErrorsFactory;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            $params = ['_secure' => $this->_requestInterface->isSecure()];\n            foreach ($dataSource['data']['items'] as & $item) {\n                /**\n                 * @var $customer \\Magento\\Customer\\Model\\Customer\n                 */\n                $customer = $this->_customerFactory->create()->load($item['entity_id']);\n                $params = ['_secure' => $this->_requestInterface->isSecure()];\n                $alt = '';\n                $url = '';\n                $text = '';\n                if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ACTIVE, $customer->getStoreId())) {\n                    $mailchimpStoreId = $this->_helper->getConfigValue(\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::XML_MAILCHIMP_STORE,\n                        $customer->getStoreId()\n                    );\n                    $syncData = $this->syncHelper->getChimpSyncEcommerce(\n                        $mailchimpStoreId,\n                        $customer->getId(),\n                        \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER\n                    );\n                    if (!$syncData || $syncData->getMailchimpStoreId() != $mailchimpStoreId ||\n                        $syncData->getRelatedId() != $customer->getId() ||\n                        $syncData->getType() != \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER) {\n                        $url = $this->_assetRepository->getUrlWithParams(\n                            'Ebizmarts_MailChimp::images/no.png',\n                            $params\n                        );\n                        $text = __('Syncing');\n                    } else {\n                        $sync = $syncData->getMailchimpSent();\n                        switch ($sync) {\n                            case \\Ebizmarts\\MailChimp\\Helper\\Data::SYNCED:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/yes.png',\n                                    $params\n                                );\n                                $text = __('Synced');\n                                $alt = $syncData->getMailchimpSyncDelta();\n                                break;\n                            case \\Ebizmarts\\MailChimp\\Helper\\Data::WAITINGSYNC:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/waiting.png',\n                                    $params\n                                );\n                                $text = __('Waiting');\n                                $alt = $syncData->getMailchimpSyncDelta();\n                                break;\n                            case \\Ebizmarts\\MailChimp\\Helper\\Data::SYNCERROR:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/error.png',\n                                    $params\n                                );\n                                $text = __('Error');\n                                $customerError = $this->_getError($customer->getId(), $customer->getStoreId());\n                                if ($customerError) {\n                                    $alt = $customerError->getErrors();\n                                }\n                                break;\n                            case \\Ebizmarts\\MailChimp\\Helper\\Data::NEEDTORESYNC:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/resync.png',\n                                    $params\n                                );\n                                $text = __('Resyncing');\n                                $alt = $syncData->getMailchimpSyncDelta();\n                                break;\n                            case \\Ebizmarts\\MailChimp\\Helper\\Data::NOTSYNCED:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/never.png',\n                                    $params\n                                );\n                                $text = __('With error');\n                                $alt = $syncData->getMailchimpSyncError();\n                                break;\n                            default:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/error.png',\n                                    $params\n                                );\n                                $text = __('Error');\n                        }\n\n                    }\n\n                }\n                $item['mailchimp_sync'] =\n                    \"<div style='width: 100%;margin: 0 auto;text-align: center'><div><img src='\".$url.\"' style='border: none; width: 5rem; text-align: center; max-width: 100%' title='$alt' /></div><div>$text</div></div>\";\n            }\n        }\n        return $dataSource;\n    }\n    private function _getError($customerId, $storeId)\n    {\n        /**\n         * @var $error \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors\n         */\n        $error = $this->_mailChimpErrorsFactory->create();\n        return $error->getByStoreIdType($storeId, $customerId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_CUSTOMER);\n    }\n\n}\n"
  },
  {
    "path": "Ui/Component/Listing/Column/Monkey.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 3/15/17 1:23 AM\n * @file: Monkey.php\n */\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Listing\\Column;\n\nuse \\Magento\\Sales\\Api\\OrderRepositoryInterface;\nuse \\Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse \\Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse \\Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse \\Magento\\Framework\\Api\\SearchCriteriaBuilder;\nuse Magento\\Framework\\UrlInterface;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory as SyncCollectionFactory;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\Collection as SyncCollection;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\n\nclass Monkey extends Column\n{\n    /**\n     * @var OrderRepositoryInterface\n     */\n    protected $_orderRepository;\n    /**\n     * @var SearchCriteriaBuilder\n     */\n    protected $_searchCriteria;\n    /**\n     * @var \\Magento\\Framework\\View\\Asset\\Repository\n     */\n    protected $_assetRepository;\n    /**\n     * @var \\Magento\\Framework\\App\\RequestInterface\n     */\n    protected $_requestInterfase;\n    /**\n     * @var MailChimpHelper\n     */\n    protected $_helper;\n    /**\n     * @var SyncHelper\n     */\n    private $syncHelper;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory\n     */\n    protected $_syncCommerceCF;\n    /**\n     * @var \\Magento\\Sales\\Model\\OrderFactory\n     */\n    protected $_orderFactory;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory\n     */\n    protected $_mailChimpErrorsFactory;\n    /**\n     * @var UrlInterface\n     */\n    protected $urlBuilder;\n    /**\n     * @var \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory\n     */\n    private $orderCollectionFactory;\n    /**\n     * @var SyncCollectionFactory\n     */\n    private $syncCollectionFactory;\n\n    /**\n     * @param ContextInterface $context\n     * @param UiComponentFactory $uiComponentFactory\n     * @param OrderRepositoryInterface $orderRepository\n     * @param \\Magento\\Framework\\View\\Asset\\Repository $assetRepository\n     * @param \\Magento\\Framework\\App\\RequestInterface $requestInterface\n     * @param SearchCriteriaBuilder $criteria\n     * @param MailChimpHelper $helper\n     * @param SyncCollectionFactory $syncCommerceCF\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $mailChimpErrorsFactory\n     * @param \\Magento\\Sales\\Model\\OrderFactory $orderFactory\n     * @param \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollectionFactory\n     * @param UrlInterface $urlBuilder\n     * @param SyncCollectionFactory $syncCollectionFactory\n     * @param array $components\n     * @param array $data\n     */\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        OrderRepositoryInterface $orderRepository,\n        \\Magento\\Framework\\View\\Asset\\Repository $assetRepository,\n        \\Magento\\Framework\\App\\RequestInterface $requestInterface,\n        SearchCriteriaBuilder $criteria,\n        MailChimpHelper $helper,\n        \\Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory $syncCommerceCF,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $mailChimpErrorsFactory,\n        \\Magento\\Sales\\Model\\OrderFactory $orderFactory,\n        \\Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory $orderCollectionFactory,\n        UrlInterface $urlBuilder,\n        SyncCollectionFactory $syncCollectionFactory,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->_orderRepository = $orderRepository;\n        $this->_searchCriteria  = $criteria;\n        $this->_assetRepository = $assetRepository;\n        $this->_requestInterfase= $requestInterface;\n        $this->_helper          = $helper;\n        $this->_syncCommerceCF  = $syncCommerceCF;\n        $this->_orderFactory    = $orderFactory;\n        $this->orderCollectionFactory = $orderCollectionFactory;\n        $this->_mailChimpErrorsFactory  = $mailChimpErrorsFactory;\n        $this->urlBuilder       = $urlBuilder;\n        $this->syncCollectionFactory = $syncCollectionFactory;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            $ordersIds = $this->getOrdersIds($dataSource);\n            $orderMap = $this->getOrderDataByOrderIds($ordersIds);\n            $syncMap = $this->getSyncDataByOrderIds($ordersIds);\n            foreach ($dataSource['data']['items'] as & $item) {\n                $status = $item['mailchimp_flag'];\n                $orderId = $item['entity_id'];\n                if (key_exists($item['entity_id'],$syncMap)) {\n                    $sync = $syncMap[$item['entity_id']]->getMailchimpSent();\n                    $syncError = $syncMap[$item['entity_id']]->getMailchimpSyncError();\n                } else {\n                    $sync = MailChimpHelper::NEVERSYNC;\n                    $syncError = '';\n                }\n\n                $order = $orderMap[$orderId]\n                    ?? $this->_orderFactory->create()->loadByIncrementId($orderId); // Backwards Compatibility\n                $menu = false;\n                $params = ['_secure' => $this->_requestInterfase->isSecure()];\n                $storeId = $order->getStoreId();\n                if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ACTIVE, $storeId)) {\n                    $alt = '';\n                    switch ($sync) {\n                        case MailChimpHelper::NEVERSYNC:\n                            $url = $this->_assetRepository->getUrlWithParams(\n                                'Ebizmarts_MailChimp::images/no.png',\n                                $params\n                            );\n                            $text = __('Syncing');\n                            break;\n                        case MailChimpHelper::SYNCED:\n                            $url = $this->_assetRepository->getUrlWithParams(\n                                'Ebizmarts_MailChimp::images/yes.png',\n                                $params\n                            );\n                            $text = __('Synced');\n                            $menu = true;\n                            break;\n                        case MailChimpHelper::WAITINGSYNC:\n                            $url = $this->_assetRepository->getUrlWithParams(\n                                'Ebizmarts_MailChimp::images/waiting.png',\n                                $params\n                            );\n                            $text = __('Waiting');\n                            break;\n                        case MailChimpHelper::SYNCERROR:\n                            $url = $this->_assetRepository->getUrlWithParams(\n                                'Ebizmarts_MailChimp::images/error.png',\n                                $params\n                            );\n                            $text = __('Error');\n                            $orderError = $this->_getError($orderId, $storeId);\n                            if ($orderError) {\n                                $alt = $orderError->getErrors();\n                            }\n                            break;\n                        case MailChimpHelper::NEEDTORESYNC:\n                            $url = $this->_assetRepository->getUrlWithParams(\n                                'Ebizmarts_MailChimp::images/resync.png',\n                                $params\n                            );\n                            $text = __('Resyncing');\n                            $menu = true;\n                            break;\n                        case MailChimpHelper::NOTSYNCED:\n                            $url = $this->_assetRepository->getUrlWithParams(\n                                'Ebizmarts_MailChimp::images/never.png',\n                                $params\n                            );\n                            $text = __('With error');\n                            $alt = $syncError;\n                            break;\n                        default:\n                            $url ='';\n                            $text = '';\n                    }\n                    $item['mailchimp_sync'] =\n                        \"<div style='width: 50%;margin: 0 auto;text-align: center'><img src='\".$url.\"' style='border: none; width: 5rem; text-align: center; max-width: 100%' title='$alt' class='freddie'/>$text</div>\";\n                    if ($status) {\n                        $item['mailchimp_sync'] =\n                            \"<div style='width: 50%;margin: 0 auto;text-align: center'><img src='\".$url.\"' style='border: none; width: 5rem; text-align: center; max-width: 100%' title='$alt' class='freddie'/>$text</div>\";\n                        if ($menu) {\n                            $item[$this->getData('name')] = [\n                                'campaign' => [\n                                    'href' => $this->urlBuilder->getUrl(\n                                        'mailchimp/orders/campaign',\n                                        ['orderId' => $item['entity_id']]\n                                    ),\n                                    'label' => 'View campaign',\n                                    'target' => '_blank'\n                                ],\n                                'member' => [\n                                    'href' => $this->urlBuilder->getUrl(\n                                        'mailchimp/orders/member',\n                                        ['orderId' => $item['entity_id']]\n                                    ),\n                                    'label' => 'View member',\n                                    'target' => '_blank'\n                                ]\n                            ];\n                        }\n                    } else {\n                        $item['mailchimp_sync'] =\n                            \"<div style='width: 50%;margin: 0 auto;text-align: center'><img src='\".$url.\"' style='border: none; width: 5rem; text-align: center; max-width: 100%' title='$alt'/>$text</div>\";\n                    }\n\n                }\n            }\n        }\n\n        return $dataSource;\n    }\n    private function _getError($orderId, $storeId)\n    {\n        /**\n         * @var $error \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors\n         */\n        $error = $this->_mailChimpErrorsFactory->create();\n        return $error->getByStoreIdType($storeId, $orderId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_ORDER);\n    }\n\n    /**\n     * @param array $orderIds\n     * @return OrderInterface[]\n     */\n    private function getOrderDataByOrderIds(array $orderIds): array\n    {\n        if (empty($orderIds)) {\n            return [];\n        }\n\n        $orderCollection = $this->orderCollectionFactory->create();\n        $orderCollection->getSelect()->columns(['entity_id','store_id']);\n        $orderCollection->addAttributeToFilter(\n            'entity_id',\n            ['in' => $orderIds]\n        );\n\n        $ordersMap = [];\n        /** @var OrderInterface $order */\n        foreach ($orderCollection->getItems() as $order) {\n            $ordersMap[$order->getEntityId()] = $order;\n        }\n\n        return $ordersMap;\n    }\n    private function getOrdersIds(array $dataSource)\n    {\n        if (!isset($dataSource['data']['items'])) {\n            return [];\n        }\n\n        return array_filter(array_unique(array_column($dataSource['data']['items'], 'entity_id')));\n    }\n\n    private function getSyncDataByOrderIds(array $OrderIds)\n    {\n        $syncMap = [];\n        /**\n         * @var SyncCollection $syncCollection\n         */\n        $syncCollection = $this->syncCollectionFactory->create();\n        $syncCollection->addFieldToFilter('related_id', ['in' => $OrderIds]);\n        $syncCollection->addFieldToFilter('type', ['eq' => MailChimpHelper::IS_ORDER]);\n        foreach($syncCollection as $item) {\n            $syncMap[$item->getRelatedId()] = $item;\n        }\n        return $syncMap;\n    }\n}\n"
  },
  {
    "path": "Ui/Component/Listing/Column/Products.php",
    "content": "<?php\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Listing\\Column;\n\nuse Magento\\Catalog\\Model\\ProductFactory;\nuse Magento\\Catalog\\Model\\ResourceModel\\Product\\CollectionFactory as ProductCollectionFactory;\nuse Magento\\ConfigurableProduct\\Model\\Product\\Type\\Configurable as ProductTypeConfigurable;\nuse Magento\\Catalog\\Model\\Product\\Type as ProductType;\nuse Magento\\Downloadable\\Model\\Product\\Type as ProductTypeDownloadable;\nuse Magento\\Framework\\App\\RequestInterface;\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\CollectionFactory as SyncCollectionFactory;\nuse Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncEcommerce\\Collection as SyncCollection;\nuse Ebizmarts\\MailChimp\\Helper\\Data as MailChimpHelper;\n\n\nclass Products extends Column\n{\n    private const SUPPORTED_PRODUCT_TYPES = [\n        ProductType::TYPE_SIMPLE,\n        ProductType::TYPE_VIRTUAL,\n        ProductTypeConfigurable::TYPE_CODE,\n        ProductTypeDownloadable::TYPE_DOWNLOADABLE,\n        ProductType::TYPE_BUNDLE\n    ];\n    /**\n     * @var ProductFactory\n     */\n    protected $_productFactory;\n    /**\n     * @var RequestInterface\n     */\n    protected $_requestInterface;\n    /**\n     * @var MailChimpHelper\n     */\n    protected $_helper;\n    /**\n     * @var \\Magento\\Framework\\View\\Asset\\Repository\n     */\n    protected $_assetRepository;\n    /**\n     * @var \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory\n     */\n    protected $_mailChimpErrorsFactory;\n    /**\n     * @var ProductCollectionFactory\n     */\n    private $productCollectionFactory;\n    /**\n     * @var SyncCollectionFactory\n     */\n    private $syncCollectionFactory;\n\n    /**\n     * @param ContextInterface $context\n     * @param UiComponentFactory $uiComponentFactory\n     * @param ProductFactory $productFactory\n     * @param ProductCollectionFactory $productCollectionFactory\n     * @param RequestInterface $requestInterface\n     * @param MailChimpHelper $helper\n     * @param \\Magento\\Framework\\View\\Asset\\Repository $assetRepository\n     * @param \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $mailChimpErrorsFactory\n     * @param SyncCollectionFactory $syncCollectionFactory\n     * @param array $components\n     * @param array $data\n     */\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        ProductFactory $productFactory,\n        ProductCollectionFactory $productCollectionFactory,\n        RequestInterface $requestInterface,\n        \\Ebizmarts\\MailChimp\\Helper\\Data $helper,\n        \\Magento\\Framework\\View\\Asset\\Repository $assetRepository,\n        \\Ebizmarts\\MailChimp\\Model\\MailChimpErrorsFactory $mailChimpErrorsFactory,\n        SyncCollectionFactory $syncCollectionFactory,\n        array $components = [],\n        array $data = [])\n    {\n        $this->_productFactory = $productFactory;\n        $this->_requestInterface = $requestInterface;\n        $this->_helper = $helper;\n        $this->_assetRepository = $assetRepository;\n        $this->_mailChimpErrorsFactory = $mailChimpErrorsFactory;\n        $this->productCollectionFactory = $productCollectionFactory;\n        $this->syncCollectionFactory = $syncCollectionFactory;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            $productsMap = $this->getProductsByEntityIds(\n                $this->getProductsIds($dataSource)\n            );\n            $syncMap = $this->getSyncDataByEntityIds($this->getProductsIds($dataSource));\n            foreach ($dataSource['data']['items'] as & $item) {\n                /**\n                 * @var $product \\Magento\\Catalog\\Model\\Product\n                 */\n                $product = $productsMap[$item['entity_id']]\n                    ?? $this->_productFactory->create()->load($item['entity_id']); // Backwards Compatibility\n                if (key_exists($item['entity_id'],$syncMap)) {\n                    $sync = $syncMap[$item['entity_id']]->getMailchimpSent();\n                } else {\n                    $sync = MailChimpHelper::NEVERSYNC;\n                }\n                $params = ['_secure' => $this->_requestInterface->isSecure()];\n                $alt = '';\n                $url = '';\n                $text = '';\n                if (in_array($product->getTypeId(), self::SUPPORTED_PRODUCT_TYPES, true)) {\n                    $url = '';\n                    $text = '';\n                    if ($this->_helper->getConfigValue(\\Ebizmarts\\MailChimp\\Helper\\Data::XML_PATH_ACTIVE, $product->getStoreId())) {\n                        switch ($sync) {\n                            case MailChimpHelper::NEVERSYNC:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/no.png',\n                                    $params\n                                );\n                                $text = __('Syncing');\n                                break;\n                            case MailChimpHelper::SYNCED:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/yes.png',\n                                    $params\n                                );\n                                $text = __('Synced');\n                                break;\n                            case MailChimpHelper::WAITINGSYNC:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/waiting.png',\n                                    $params\n                                );\n                                $text = __('Waiting');\n                                break;\n                            case MailChimpHelper::SYNCERROR:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/error.png',\n                                    $params\n                                );\n                                $text = __('Error');\n                                $orderError = $this->_getError($product->getId(), $product->getStoreId());\n                                if ($orderError) {\n                                    $alt = $orderError->getErrors();\n                                }\n                                break;\n                            case MailChimpHelper::NEEDTORESYNC:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/resync.png',\n                                    $params\n                                );\n                                $text = __('Resyncing');\n                                break;\n                            case MailChimpHelper::NOTSYNCED:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/never.png',\n                                    $params\n                                );\n                                $text = __('With error');\n                                break;\n                            default:\n                                $url = $this->_assetRepository->getUrlWithParams(\n                                    'Ebizmarts_MailChimp::images/error.png',\n                                    $params\n                                );\n                                $text = __('Error');\n                        }\n                    }\n                } else {\n                    $url = $this->_assetRepository->getUrlWithParams(\n                        'Ebizmarts_MailChimp::images/never.png',\n                        $params\n                    );\n                    $text = __('Unsupported');\n                    $alt = \"Mailchimp does not support bundled or grouped products.\";\n                }\n                $item['mailchimp_sync'] =\n                    \"<div style='width: 100%;margin: 0 auto;text-align: center'><div><img src='\".$url.\"' style='border: none; width: 5rem; text-align: center; max-width: 100%' title='$alt' /></div><div>$text</div></div>\";\n            }\n        }\n        return $dataSource;\n    }\n    private function _getError($productId, $storeId)\n    {\n        /**\n         * @var $error \\Ebizmarts\\MailChimp\\Model\\MailChimpErrors\n         */\n        $error = $this->_mailChimpErrorsFactory->create();\n        return $error->getByStoreIdType($storeId, $productId, \\Ebizmarts\\MailChimp\\Helper\\Data::IS_PRODUCT);\n    }\n    private function getProductsByEntityIds(array $productIds): array\n    {\n        if (empty($productIds)) {\n            return [];\n        }\n\n        /** @var \\Magento\\Catalog\\Model\\ResourceModel\\Product\\Collection $productsCollection */\n        $productsCollection = $this->productCollectionFactory->create();\n        $productsCollection->addAttributeToFilter('entity_id', ['in' => $productIds]);\n\n        $productsMap = [];\n        foreach ($productsCollection->getItems() as $product) {\n            $productsMap[$product->getId()] = $product;\n        }\n\n        return $productsMap;\n    }\n\n    private function getProductsIds(array $dataSource)\n    {\n        if (!isset($dataSource['data']['items'])) {\n            return [];\n        }\n\n        return array_filter(array_unique(array_column($dataSource['data']['items'], 'entity_id')));\n    }\n    private function getSyncDataByEntityIds(array $productIds)\n    {\n        $syncMap = [];\n        /**\n         * @var SyncCollection $syncCollection\n         */\n        $syncCollection = $this->syncCollectionFactory->create();\n        $syncCollection->addFieldToFilter('related_id', ['in' => $productIds]);\n        $syncCollection->addFieldToFilter('type', ['eq' => MailChimpHelper::IS_PRODUCT]);\n        foreach($syncCollection as $item) {\n            $syncMap[$item->getRelatedId()] = $item;\n        }\n        return $syncMap;\n    }\n}\n"
  },
  {
    "path": "Ui/Component/Stores/Grid/Column/Actions.php",
    "content": "<?php\n/**\n * mc-magento2 Magento Component\n *\n * @category Ebizmarts\n * @package mc-magento2\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 4/5/17 11:19 AM\n * @file: Actions.php\n */\nnamespace Ebizmarts\\MailChimp\\Ui\\Component\\Stores\\Grid\\Column;\n\nuse Magento\\Framework\\View\\Element\\UiComponent\\ContextInterface;\nuse Magento\\Framework\\View\\Element\\UiComponentFactory;\nuse Magento\\Ui\\Component\\Listing\\Columns\\Column;\nuse Magento\\Framework\\UrlInterface;\n\n/**\n * Class ProductActions\n */\nclass Actions extends Column\n{\n    /**\n     * @var UrlInterface\n     */\n    protected $urlBuilder;\n\n    /**\n     * @param ContextInterface $context\n     * @param UiComponentFactory $uiComponentFactory\n     * @param UrlInterface $urlBuilder\n     * @param array $components\n     * @param array $data\n     */\n    public function __construct(\n        ContextInterface $context,\n        UiComponentFactory $uiComponentFactory,\n        UrlInterface $urlBuilder,\n        array $components = [],\n        array $data = []\n    ) {\n        $this->urlBuilder = $urlBuilder;\n        parent::__construct($context, $uiComponentFactory, $components, $data);\n    }\n\n    /**\n     * Prepare Data Source\n     *\n     * @param array $dataSource\n     * @return array\n     */\n    public function prepareDataSource(array $dataSource)\n    {\n        if (isset($dataSource['data']['items'])) {\n            $storeId = $this->context->getFilterParam('store_id');\n\n            foreach ($dataSource['data']['items'] as &$item) {\n                $item[$this->getData('name')]['edit'] = [\n                    'href' => $this->urlBuilder->getUrl(\n                        'mailchimp/stores/edit',\n                        ['id' => $item['id']]\n                    ),\n                    'label' => __('Edit'),\n                    'hidden' => false,\n                ];\n            }\n        }\n\n        return $dataSource;\n    }\n}\n"
  },
  {
    "path": "composer.json",
    "content": "{\n  \"name\": \"mailchimp/mc-magento2\",\n  \"autoload\": {\n    \"psr-4\": {\"Ebizmarts\\\\MailChimp\\\\\":\"\"},\n    \"files\": [\"registration.php\"]\n  },\n  \"description\": \"Connect MailChimp with Magento\",\n  \"type\": \"magento2-module\",\n  \"version\": \"102.3.78\",\n  \"authors\": [\n    {\n      \"name\": \"Ebizmarts Corp\",\n      \"email\": \"mailchimp@ebizmarts-desk.zendesk.com\",\n      \"homepage\": \"http://ebizmarts.com\"\n    }\n  ],\n  \"license\": [\n    \"OSL-3.0\",\n    \"AFL-3.0\"\n  ],\n  \"support\": {\n    \"email\": \"mailchimp@ebizmarts-desk.zendesk.com\",\n    \"wiki\": \"https://connect.mailchimp.com/integrations/magento\",\n    \"forum\": \"http://ebizmarts.com/forums/view/6\"\n  },\n  \"require\" : {\n    \"magento/framework\": \"102.0.*\",\n    \"ebizmarts/mailchimp-lib\": \">=3.0.44\",\n    \"ext-json\": \"*\"\n  }\n}\n"
  },
  {
    "path": "etc/acl.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 5/10/17 3:26 PM\n * @file: acl.xml\n */\n -->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Acl/etc/acl.xsd\">\n    <acl>\n        <resources>\n            <resource id=\"Magento_Backend::admin\">\n                <resource id=\"Magento_Backend::stores\">\n                    <resource id=\"Magento_Backend::stores_settings\">\n                        <resource id=\"Magento_Config::config\">\n                            <resource id=\"Ebizmarts_MailChimp::config_mailchimp\" title=\"MailChimp section\" sortOrder=\"60\" />\n                        </resource>\n                    </resource>\n                </resource>\n                <resource id=\"Ebizmarts_MailChimp::main_menu\" title=\"MailChimp\">\n                    <resource id=\"Ebizmarts_MailChimp::batch_grid\" title=\"MailChimp Batch Grid\" sortOrder=\"90\"/>\n                    <resource id=\"Ebizmarts_MailChimp::error_grid\" title=\"MailChimp Error Grid\" sortOrder=\"100\"/>\n                    <resource id=\"Ebizmarts_MailChimp::cron_grid\" title=\"MailChimp Cron Grid\" sortOrder=\"105\"/>\n                    <resource id=\"Ebizmarts_MailChimp::stores_grid\" title=\"MailChimp Stores Grid\" sortOrder=\"110\">\n                        <resource id=\"Ebizmarts_MailChimp::stores_edit\" title=\"MailChimp Stores Edit\" sortOrder=\"120\"/>\n                    </resource>\n                    <resource id=\"Ebizmarts_MailChimp::mailchimp_access\" title=\"Access data in mailchimp\" sortOrder=\"100\"/>\n                </resource>\n            </resource>\n        </resources>\n    </acl>\n</config>\n"
  },
  {
    "path": "etc/adminhtml/events.xml",
    "content": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Event/etc/events.xsd\">\n    <event name=\"admin_system_config_changed_section_mailchimp\">\n        <observer name=\"mailchimp_admin_system_config_changed_section_mailchimp\" instance=\"Ebizmarts\\MailChimp\\Observer\\ConfigObserver\"/>\n    </event>\n    <event name=\"salesrule_rule_save_after\">\n        <observer name=\"mailchimp_admin_salesrule_rule_save_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\SalesRule\\Rule\\SaveAfter\"/>\n    </event>\n    <event name=\"salesrule_rule_delete_after\">\n        <observer name=\"mailchimp_admin_salesrule_rule_delete_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\SalesRule\\Rule\\DeleteAfter\"/>\n    </event>\n    <event name=\"adminhtml_customer_save_after\">\n        <observer name=\"mailchimp_admin_customer_save_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Customer\\SaveAfter\" />\n    </event>\n    <event name=\"catalog_product_delete_after\">\n        <observer name=\"mailchimp_admin_product_delete_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Product\\DeleteAfter\" />\n    </event>\n</config>\n"
  },
  {
    "path": "etc/adminhtml/menu.xml",
    "content": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Backend:etc/menu.xsd\">\n    <menu>\n        <add id=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             title=\"Mailchimp\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"110\"\n             dependsOnModule=\"Ebizmarts_MailChimp\"\n             resource=\"Ebizmarts_MailChimp::main_menu\"\n        />\n        <add id=\"Ebizmarts_MailChimp::config_menu\"\n             title=\"Configuration\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"10\"\n             resource=\"Ebizmarts_MailChimp::config_mailchimp\"\n             parent=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             action=\"adminhtml/system_config/edit/section/mailchimp\"\n        />\n        <add id=\"Ebizmarts_MailChimp::store_menu\"\n             title=\"Mailchimp Stores\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"20\"\n             resource=\"Ebizmarts_MailChimp::stores_grid\"\n             parent=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             action=\"mailchimp/stores\"\n        />\n        <add id=\"Ebizmarts_MailChimp::error_menu\"\n             title=\"Errors\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"30\"\n             resource=\"Ebizmarts_MailChimp::error_grid\"\n             parent=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             action=\"mailchimp/errors\"\n        />\n        <add id=\"Ebizmarts_MailChimp::batch_menu\"\n             title=\"Batches\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"40\"\n             resource=\"Ebizmarts_MailChimp::batch_grid\"\n             parent=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             action=\"mailchimp/batch\"\n        />\n        <add id=\"Ebizmarts_MailChimp::cron_menu\"\n             title=\"Cron\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"50\"\n             resource=\"Ebizmarts_MailChimp::cron_grid\"\n             parent=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             action=\"mailchimp/cron\"\n        />\n        <add id=\"Ebizmarts_MailChimp::carts_menu\"\n             title=\"Abandoned Carts\"\n             module=\"Ebizmarts_MailChimp\"\n             sortOrder=\"60\"\n             resource=\"Ebizmarts_MailChimp::carts_grid\"\n             parent=\"Ebizmarts_MailChimp::mailchimp_menu\"\n             action=\"mailchimp/carts\"\n        />\n    </menu>\n</config>\n"
  },
  {
    "path": "etc/adminhtml/routes.xml",
    "content": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:App/etc/routes.xsd\">\n    <router id=\"admin\">\n        <route id=\"mailchimp\" frontName=\"mailchimp\">\n            <module name=\"Ebizmarts_MailChimp\" before=\"Magento_Backend\" />\n        </route>\n    </router>\n</config>"
  },
  {
    "path": "etc/adminhtml/system.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Config:etc/system_file.xsd\">\n    <system>\n        <tab id=\"mailchimp\" translate=\"label\" sortOrder=\"450\">\n            <label>Mailchimp</label>\n        </tab>\n        <section id=\"mailchimp\" translate=\"label\" type=\"text\" sortOrder=\"100\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n            <class>separator-top</class>\n            <label>Mailchimp</label>\n            <tab>mailchimp</tab>\n            <resource>Ebizmarts_MailChimp::config_mailchimp</resource>\n            <group id=\"hint\" translate=\"label\" type=\"text\" sortOrder=\"0\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Fieldset\\Hint</frontend_model>\n            </group>\n            <group id=\"general\" translate=\"label\" type=\"text\" sortOrder=\"10\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                <label>Mailchimp General Configuration</label>\n                <field id=\"active\" translate=\"label comment\" type=\"select\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Enabled</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <comment><![CDATA[By enabling this extension, you agree to <a href=\"https://mailchimp.com/legal/additional-terms/\" target=\"_blank\">Mailchimp's additional terms</a>.]]></comment>\n                </field>\n                <field id=\"oauth_wizard\" translate=\"label\" sortOrder=\"12\" showInDefault=\"1\" showInStore=\"1\" showInWebsite=\"1\">\n                    <attribute type=\"button_label\">Get API credentials</attribute>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\OauthWizard</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"apikey\" translate=\"label\" type=\"obscure\" sortOrder=\"20\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>API Key</label>\n                    <backend_model>Magento\\Config\\Model\\Config\\Backend\\Encrypted</backend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"monkeystore\" translate=\"label comment\" type=\"select\" sortOrder=\"30\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Mailchimp Store</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\MonkeyStore</source_model>\n                    <backend_model>Ebizmarts\\MailChimp\\Model\\Config\\Backend\\MonkeyStore</backend_model>\n                    <comment>You must create a MailChimp Store for this API key to connect to this account</comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"monkeylist\" translate=\"label\" type=\"select\" sortOrder=\"30\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Mailchimp List</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\MonkeyList</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"account_details\" translate=\"label\" type=\"textarea\" sortOrder=\"40\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Account Details</label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Account</frontend_model>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\Details</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"popup_form\" translate=\"label comment\" type=\"select\" sortOrder=\"42\" showInStore=\"1\" showInWebsite=\"1\" showInDefault=\"1\">\n                    <label>Change the footer link</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <comment>Enabling this, the \"Subscribe\" button at the bottom open a popup with the Mailchimp subscription form</comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"popup_url\" translate=\"label\" type=\"text\" sortOrder=\"43\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Popup Url</label>\n                    <comment>Paste the form URL from your MailChimp audience</comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                        <field id=\"*/*/popup_form\">1</field>\n                    </depends>\n                </field>\n                <field id=\"magentoemail\" translate=\"label\" type=\"select\" sortOrder=\"45\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Magento always manage emails</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"webhook_active\" translate=\"label comment\" type=\"select\" sortOrder=\"50\" showInDefault=\"1\">\n                    <label>Enable Two Way Sync</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <comment><![CDATA[If this is set to \"No\", the synchronization will be from Magento's newsletter to Mailchimp only]]></comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"webhook_create\" translate=\"button_label label\" type=\"button\" sortOrder=\"55\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Create Webhook</button_label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\CreateWebhook</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                        <field id=\"*/*/webhook_active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"webhook_delete\" translate=\"label\" type=\"select\" sortOrder=\"60\" showInDefault=\"1\">\n                    <label>Webhooks Delete action</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\WebhookDelete</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"log\" translate=\"label\" type=\"select\" sortOrder=\"70\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Enable log</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"enable_support\" translate=\"label comment\" type=\"select\" sortOrder=\"75\" showInDefault=\"1\" showInWebsite=\"0\" showInStore=\"0\">\n                    <label>Enable Support</label>\n                    <comment>\n                        <![CDATA[By enabling this, you accept <a id='mailchimp_support' style=\"cursor: pointer\">this</a>]]>\n                    </comment>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"clean_support_period\" translate=\"label comment\" type=\"select\" sortOrder=\"77\" showInDefault=\"1\" showInWebsite=\"0\" showInStore=\"0\">\n                    <label>Clean support period</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\CleanPeriod</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"map_fields\" translate=\"label comment tooltip\" sortOrder=\"80\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Customer Fields Mapping</label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Form\\Field\\CustomerMap</frontend_model>\n                    <backend_model>Ebizmarts\\MailChimp\\Model\\Config\\Backend\\VarsMap</backend_model>\n                    <comment>\n                        <![CDATA[Add the magento to mailchimp mapping]]>\n                    </comment>\n                    <tooltip>Map the magento customer field to mailchimp merge_fields</tooltip>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"resync_subscribers\" translate=\"button_label label\" type=\"button\" sortOrder=\"85\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Resync Subscribers</button_label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\ResyncSubscriber</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"fix_mailchimpjs\" translate=\"button_label label\" type=\"button\" sortOrder=\"88\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Fix Mailchimp JS in frontend</button_label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\FixMailchimpJS</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"interest\" translate=\"label comment\" type=\"multiselect\" sortOrder=\"90\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Available Groups</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\Interest</source_model>\n                    <can_be_empty>1</can_be_empty>\n                    <comment><![CDATA[If you <a href=\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\" target=\"_blank\">set up groups in Mailchimp</a>, include them in your checkout page so customers can choose the type of email marketing they want to receive.]]></comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"interest_in_success\" translate=\"label comment\" type=\"select\" sortOrder=\"100\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Show groups after checkout?</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <comment><![CDATA[Don't use in magento 2.1 see at <a href=\"https://github.com/magento/magento2/issues/4999\" target=\"_blank\">here</a>]]></comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"interest_success_html_before\" translate=\"label\" type=\"textarea\" sortOrder=\"110\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Group Description</label>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                        <field id=\"*/*/interest_in_success\">1</field>\n                    </depends>\n                </field>\n                <field id=\"interest_success_html_after\" translate=\"label\" type=\"textarea\" sortOrder=\"120\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Success message</label>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                        <field id=\"*/*/interest_in_success\">1</field>\n                    </depends>\n                </field>\n                <field id=\"timeout\" translate=\"label\" type=\"select\" sortOrder=\"130\" showInDefault=\"1\" showInStore=\"1\" showInWebsite=\"0\">\n                    <label>Connection timeout</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\Timeout</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n            </group>\n            <group id=\"ecommerce\" translate=\"label\" type=\"text\" sortOrder=\"110\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                <label>Ecommerce Configuration</label>\n                <field id=\"active\" translate=\"label\" type=\"select\" sortOrder=\"110\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Enabled</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                </field>\n                <field id=\"all_customers\" translate=\"label comment\" type=\"select\" sortOrder=\"115\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Sync all customers</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <comment><![CDATA[Sync all customers or only customer with orders\"]]></comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"customer_optin\" translate=\"label\" type=\"select\" sortOrder=\"120\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Subscribe all customers to the newsletter</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"firstdate\" translate=\"label\" type=\"date\" showInDefault=\"1\" sortOrder=\"130\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>First Date</label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Date</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"syncsalable\" translate=\"label\" type=\"select\" sortOrder=\"135\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Sync not salable products</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"send_promo\" translate=\"label\" type=\"select\" sortOrder=\"140\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Send Promo Rules and Promo Codes</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"including_taxes\" translate=\"label comment\" type=\"select\" sortOrder=\"150\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Prices including taxes</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <comment><![CDATA[You must configure Price Display Settings in Sales/Tax to \"including taxes\"]]></comment>\n\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"campaign_action\" translate=\"label\" type=\"multiselect\" sortOrder=\"155\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Campaign Attribution Action</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\CampaignAction</source_model>\n                    <can_be_empty>1</can_be_empty>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                    <comment>Order attribution based on customer actions</comment>\n                </field>\n                <field id=\"reset_errors_retry\" translate=\"button_label label comment\" type=\"button\" sortOrder=\"160\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Reset Errors and retry</button_label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\ResetErrors</frontend_model>\n                    <comment>Truncate the errors table and retry all the registers with error</comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"reset_errors_noretry\" translate=\"button_label label comment\" type=\"button\" sortOrder=\"170\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Reset Errors and no retry</button_label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\ResetErrorsNoRetry</frontend_model>\n                    <comment>Truncate the errors table and retry all the registers with error</comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"clean_errors_months\" translate=\"label comment\" type=\"select\" sortOrder=\"175\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Months to clear the error table</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\Months</source_model>\n                    <comment><![CDATA[How many month before clean the error from the error table automatically and not retry]]></comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"delete_store\" translate=\"button_label comment\" type=\"button\" sortOrder=\"180\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Delete Store</button_label>\n                    <comment>Proceed with caution, this delete the mailchimp store for all the connected magento stores</comment>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\DeleteStore</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"resync_products\" translate=\"button_label label\" type=\"button\" sortOrder=\"190\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <button_label>Resync all products</button_label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\ResyncProducts</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n            </group>\n            <group id=\"abandonedcart\" translate=\"label\" type=\"text\" sortOrder=\"130\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                <label>Abandoned Cart Configuration</label>\n                <field id=\"active\" translate=\"label\" type=\"select\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Enabled</label>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                </field>\n                <field id=\"firstdate\" translate=\"label\" type=\"date\" sortOrder=\"30\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>First Date</label>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\Date</frontend_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"page\" translate=\"label\" type=\"select\" sortOrder=\"40\" showInDefault=\"1\" showInStore=\"0\" showInWebsite=\"0\">\n                    <label>Redirect Page</label>\n                    <source_model>Ebizmarts\\MailChimp\\Model\\Config\\Source\\Cmspage</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"save_email_in_quote\" translate=\"label comment\" sortOrder=\"50\" type=\"select\" showInDefault=\"1\" showInWebsite=\"1\" showInStore=\"1\">\n                    <label>Save Email to the Quote before place Order</label>\n                    <comment>Select No to prevent saving customer Email to the quote before Order was placed</comment>\n                    <source_model>Magento\\Config\\Model\\Config\\Source\\Yesno</source_model>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n                <field id=\"create_abandonedcart_automation\" translate=\"label comment\" sortOrder=\"60\" showInDefault=\"1\" showInStore=\"1\" showInWebsite=\"1\">\n                    <attribute type=\"button_label\">Create Abandoned Cart Automation</attribute>\n                    <frontend_model>Ebizmarts\\MailChimp\\Block\\Adminhtml\\System\\Config\\CreateAbandonedCart</frontend_model>\n                    <comment>Must be logged in to MailChimp's website previously to see the automation wizard, re-open if not</comment>\n                    <depends>\n                        <field id=\"*/*/active\">1</field>\n                    </depends>\n                </field>\n            </group>\n        </section>\n    </system>\n</config>\n"
  },
  {
    "path": "etc/config.xml",
    "content": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Store:etc/config.xsd\">\n    <default>\n        <mailchimp>\n            <general>\n                <clean_support_period>7</clean_support_period>\n            </general>\n            <ecommerce>\n                <campaign_action>sent,open,click</campaign_action>\n                <all_customers>Yes</all_customers>\n            </ecommerce>\n            <statistics>\n                <token>f71334c7039eb7f6574676bd5f43b6bc</token>\n                <notification_url>https://logs-mc4mage.ebizmarts.com/batches</notification_url>\n                <register_url>https://users-mc4mage.ebizmarts.com</register_url>\n            </statistics>\n        </mailchimp>\n    </default>\n</config>\n"
  },
  {
    "path": "etc/cron_groups.xml",
    "content": "<?xml version=\"1.0\"?>\n\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Cron:etc/cron_groups.xsd\">\n    <group id=\"mailchimp\">\n        <schedule_generate_every>1</schedule_generate_every>\n        <schedule_ahead_for>4</schedule_ahead_for>\n        <schedule_lifetime>2</schedule_lifetime>\n        <history_cleanup_every>10</history_cleanup_every>\n        <history_success_lifetime>60</history_success_lifetime>\n        <history_failure_lifetime>600</history_failure_lifetime>\n        <use_separate_process>1</use_separate_process>\n    </group>\n</config>"
  },
  {
    "path": "etc/crontab.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * MailChimp Magento Component\n *\n * @category Ebizmarts\n * @package MailChimp\n * @author Ebizmarts Team <info@ebizmarts.com>\n * @copyright Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n * @date: 9/30/16 3:26 PM\n * @file: Cron.xml\n */\n -->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Cron:etc/crontab.xsd\">\n    <group id=\"mailchimp\">\n       <job name=\"ebizmarts_ecommerce\" instance=\"Ebizmarts\\MailChimp\\Cron\\Ecommerce\" method=\"execute\">\n            <schedule>*/5 * * * *</schedule>\n        </job>\n        <job name=\"ebizmarts_webhooks\" instance=\"Ebizmarts\\MailChimp\\Cron\\Webhook\" method=\"execute\">\n            <schedule>*/5 * * * *</schedule>\n        </job>\n        <job name=\"ebizmarts_clean_webhooks\" instance=\"Ebizmarts\\MailChimp\\Cron\\WebhookClean\" method=\"execute\">\n            <schedule>0 * * * *</schedule>\n        </job>\n        <job name=\"ebizmarts_clean_batches\" instance=\"Ebizmarts\\MailChimp\\Cron\\BatchesClean\" method=\"execute\">\n            <schedule>0 * * * *</schedule>\n        </job>\n        <job name=\"ebizmarts_clean_errors\" instance=\"Ebizmarts\\MailChimp\\Cron\\ErrorsClean\" method=\"execute\">\n            <schedule>0 * * * *</schedule>\n        </job>\n        <job name=\"ebizmarts_generate_statistics\" instance=\"Ebizmarts\\MailChimp\\Cron\\GenerateStatistics\" method=\"execute\">\n            <schedule>0 */12 * * *</schedule>\n        </job>\n        <job name=\"ebizmarts_sync_statistics\" instance=\"Ebizmarts\\MailChimp\\Cron\\SyncStatistics\" method=\"execute\">\n            <schedule>0 */1 * * *</schedule>\n        </job>\n    </group>\n</config>\n"
  },
  {
    "path": "etc/di.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:ObjectManager/etc/config.xsd\">\n    <type name=\"Ebizmarts\\MailChimp\\Block\\Mailchimpjs\">\n        <arguments>\n            <argument name=\"helper\" xsi:type=\"object\">Ebizmarts\\MailChimp\\Helper\\Data\\Proxy</argument>\n        </arguments>\n    </type>\n    <type name=\"Magento\\Quote\\Model\\Quote\">\n        <plugin name=\"mailchimp-save-quote\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Quote\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Magento\\Newsletter\\Controller\\Manage\\Save\">\n        <plugin name=\"mailchimp-account-interest-group\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Newsletter\\Save\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Ebizmarts\\MailChimp\\Model\\Logger\\Handler\">\n        <arguments>\n            <argument name=\"filesystem\" xsi:type=\"object\">Magento\\Framework\\Filesystem\\Driver\\File</argument>\n        </arguments>\n    </type>\n    <type name=\"Ebizmarts\\MailChimp\\Model\\Logger\\Logger\">\n        <arguments>\n            <argument name=\"name\" xsi:type=\"string\">MailChimpLogger</argument>\n            <argument name=\"handlers\"  xsi:type=\"array\">\n                <item name=\"system\" xsi:type=\"object\">Ebizmarts\\MailChimp\\Model\\Logger\\Handler</item>\n            </argument>\n        </arguments>\n    </type>\n    <virtualType name=\"Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpErrors\\Collection\" type=\"Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult\">\n        <arguments>\n            <argument name=\"mainTable\" xsi:type=\"string\">mailchimp_errors</argument>\n            <argument name=\"resourceModel\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpErrors</argument>\n        </arguments>\n    </virtualType>\n    <virtualType name=\"Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatchesGrid\\Collection\" type=\"Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult\">\n        <arguments>\n            <argument name=\"mainTable\" xsi:type=\"string\">mailchimp_sync_batches</argument>\n            <argument name=\"resourceModel\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatches</argument>\n        </arguments>\n    </virtualType>\n    <type name=\"Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\CollectionFactory\">\n        <arguments>\n            <argument name=\"collections\" xsi:type=\"array\">\n                <item name=\"mailchimp_errors_grid_data_source\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpErrors\\Collection</item>\n                <item name=\"mailchimp_stores_grid_data_source\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores\\Grid\\Collection</item>\n                <item name=\"mailchimp_batch_grid_data_source\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpSyncBatchesGrid\\Collection</item>\n                <item name=\"mailchimp_cron_grid_data_source\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\Schedule\\Collection</item>\n                <item name=\"mailchimp_carts_grid_data_source\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\Carts\\Collection</item>\n            </argument>\n        </arguments>\n    </type>\n    <virtualType name=\"Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores\\Collection\" type=\"Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\SearchResult\">\n        <arguments>\n            <argument name=\"mainTable\" xsi:type=\"string\">mailchimp_stores</argument>\n            <argument name=\"resourceModel\" xsi:type=\"string\">Ebizmarts\\MailChimp\\Model\\ResourceModel\\MailChimpStores</argument>\n        </arguments>\n    </virtualType>\n    <type name=\"Magento\\Newsletter\\Model\\Subscriber\">\n        <plugin name=\"mailchimp-subscriber\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Subscriber\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Magento\\Customer\\Model\\AccountManagement\">\n        <plugin name=\"abandoned-checkout-save-quote\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\AccountManagement\" sortOrder=\"10\"/>\n    </type>\n    <virtualType name=\"Magento\\Sales\\Model\\ResourceModel\\Order\\Grid\" type=\"Magento\\Sales\\Model\\ResourceModel\\Grid\">\n        <arguments>\n            <argument name=\"columns\" xsi:type=\"array\">\n                <item name=\"mailchimp_flag\" xsi:type=\"string\">sales_order.mailchimp_flag</item>\n            </argument>\n        </arguments>\n    </virtualType>\n    <type name=\"Magento\\SalesRule\\Model\\Coupon\">\n        <plugin name=\"mailchimp-coupon\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Coupon\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Magento\\Sales\\Model\\Order\\Shipment\">\n        <plugin name=\"mailchimp_save_shipment\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Ship\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Magento\\Sales\\Model\\Order\\Invoice\">\n        <plugin name=\"mailchimp_save_invoice\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Invoice\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Magento\\Sales\\Model\\Order\\CreditmemoRepository\">\n        <plugin name=\"mailchimp_save_creditmemo\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Creditmemo\" sortOrder=\"10\"/>\n    </type>\n    <preference for=\"Magento\\Newsletter\\Block\\Subscribe\" type=\"Ebizmarts\\MailChimp\\Block\\Subscribe\"/>\n</config>\n"
  },
  {
    "path": "etc/events.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Event/etc/events.xsd\">\n    <event name=\"sales_order_save_after\">\n        <observer name=\"mailchimp_sales_order_save_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Sales\\Order\\SaveAfter\"/>\n    </event>\n    <event name=\"sales_model_service_quote_submit_before\">\n        <observer name=\"mailchimp_sales_model_service_quote_submit_before\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Sales\\Order\\SubmitBefore\" />\n    </event>\n    <event name=\"sales_model_service_quote_submit_success\">\n        <observer name=\"mailchimp_sales_model_service_quote_submit_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Sales\\Order\\SubmitAfter\" />\n    </event>\n    <event name=\"customer_save_before\">\n        <observer name=\"mailchimp_customer_save_before\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Customer\\SaveBefore\" />\n    </event>\n    <event name=\"catalog_product_save_after\">\n        <observer name=\"mailchimp_product_save_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Product\\SaveAfter\" />\n    </event>\n    <event name=\"newsletter_subscriber_save_after\">\n        <observer name=\"mailchimp_newsletter_subscriber_save_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Subscriber\\SaveAfter\" />\n    </event>\n    <event name=\"catalog_product_import_bunch_save_after\">\n        <observer name=\"mailchimp_product_import\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Adminhtml\\Product\\ImportAfter\"/>\n    </event>\n</config>\n"
  },
  {
    "path": "etc/fieldset.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n        xsi:noNamespaceSchemaLocation=\"urn:magento:framework:DataObject/etc/fieldset.xsd\">\n    <scope id=\"global\">\n        <fieldset id=\"sales_convert_quote\">\n            <field name=\"mailchimp_abandonedcart_flag\">\n                <aspect name=\"to_order\" />\n            </field>\n            <field name=\"mailchimp_campaign_id\">\n                <aspect name=\"to_order\" />\n            </field>\n            <field name=\"mailchimp_landing_page\">\n                <aspect name=\"to_order\" />\n            </field>\n        </fieldset>\n    </scope>\n</config>"
  },
  {
    "path": "etc/frontend/di.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:ObjectManager/etc/config.xsd\">\n    <type name=\"Magento\\Quote\\Model\\Quote\">\n        <plugin name=\"mailchimp-save-quote\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Quote\" sortOrder=\"10\"/>\n    </type>\n    <type name=\"Magento\\Newsletter\\Controller\\Manage\\Save\">\n        <plugin name=\"mailchimp-account-interest-group\" type=\"Ebizmarts\\MailChimp\\Model\\Plugin\\Newsletter\\Save\" sortOrder=\"10\"/>\n    </type>\n</config>"
  },
  {
    "path": "etc/frontend/events.xml",
    "content": "<?xml version=\"1.0\"?>\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Event/etc/events.xsd\">\n    <event name=\"sales_model_service_quote_submit_success\">\n        <observer name=\"mailchimp_sales_model_service_quote_submit_after\" instance=\"\\Ebizmarts\\MailChimp\\Observer\\Sales\\Order\\SubmitAfter\" />\n    </event>\n</config>\n"
  },
  {
    "path": "etc/frontend/routes.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n/**\n * routes\n *\n * @copyright Copyright © 2017 Ebizmarts Corp.. All rights reserved.\n * @author    info@ebizmarts.com\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:App/etc/routes.xsd\">\n    <router id=\"standard\">\n        <route id=\"mailchimp\" frontName=\"mailchimp\">\n            <module name=\"Ebizmarts_MailChimp\"/>\n        </route>\n    </router>\n</config>\n"
  },
  {
    "path": "etc/module.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<config xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Module/etc/module.xsd\">\n    <module name=\"Ebizmarts_MailChimp\" setup_version=\"102.3.78\">\n        <sequence>\n            <module name=\"Magento_Newsletter\"/>\n            <module name=\"Magento_Sales\"/>\n        </sequence>\n    </module>\n</config>\n"
  },
  {
    "path": "i18n/es_ES.csv",
    "content": "MailChimp,MailChimp\nSave,Guardar\nSave and Continue Edit,Guardar y continuar Editar\nDelete,Borrar\nEdit Store '%1',Editar Tienda '%1'\nAdd Store,Añadir Tienda\nAddress,Dirección\nStreet,Calle\nCity,Ciudad\nPostal Code,Código Postal\nSelect one,Seleccionar una\nCountry,País\nStore Address Info,Información de la Dirección de la Tienda\nGeneral,General\nApikey,Apikey\nSelect first an ApiKey,Seleccione primero una ApiKey\nList,Lista\nName,Nombre\nDomain,Dominio\nEmail,Correo Electrónico\nCurrency,Moneda\nLocale,Configuración regional\nTimeZone,Zona horaria\nPhone,Teléfono\nStore Info,Información de la Tienda\nMailchimp Store Information,Información de la Tienda MailChimp\nbutton_label,button_label\nMailchimp,Mailchimp\nMagento,Magento\nAdd,Añadir\nShipping Zip Code,Código Postal de Envío\nShipping Country,País de Envío\nShipping City,Ciudad de Envío\nShipping State,Estado de Envío\nShipping Telephone,Teléfono de Envío\nShipping Company,Empresa de Envío\nShipping Street,Calle de envío\nBilling Zip Code,Código Postal de Facturación\nBilling Country,País de Facturación\nBilling City,Ciudad de Facturación\nBilling State,Estado de Facturación\nBilling Telephone,Teléfono de Facturación\nBilling Company,Empresa de Facturación\nBilling Street, Calle de facturación\nMailchimp Batches,Lotes de Mailchimp\nMailchimp Cron,Mailchimp Cron\nUser name:,Nombre de usuario:\nTotal Account Subscribers:,Total de suscriptores de la cuenta:\nTotal List Subscribers:,Total de suscriptores de la lista:\nEcommerce Data uploaded to MailChimp:,Datos de comercio electrónico cargados a MailChimp:\nTotal customers:,Total de clientes:\nTotal products:,Total de productos:\nTotal orders:,Total de pedidos:\nTotal Carts:,Total de carritos:\n\"Ecommerce disabled, save configuration to enable\",\"Comercio electrónico deshabilitado, guardar configuración para habilitar\"\n\"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)\"\n--- Invalid API Key ---,--- Clave API no válida ---\nMailchimp Errors,Errores de Mailchimp\nYou deleted the store.,Eliminó la tienda.\n'Store could not be deleted.' .,'No se pudo eliminar la tienda.' .\nThis store no longer exists.,Esta tienda ya no existe.\nMailchimp Store,Tienda Mailchimp\nMailchimp Stores,Tiendas Mailchimp\n'Store could not be saved.' .,'No se pudo guardar la tienda.' .\nYou can't access this cart,No puede acceder a este carrito\nLogin to complete your order,Inicie sesión para completar su pedido\nThanks for sharing your interest with us,Gracias por compartir su interés con nosotros\nJson error,Error de JSON\nError retrieving interest groups for store ,Error al recuperar grupos de interés para la tienda\nOrder [' . . '] is empty,El pedido [' . . '] está vacío\nParent rule with id ' . . 'has not been correctly sent.,La regla principal con id ' . . ' no se ha enviado correctamente.\nSomething went wrong when retrieving the information for promo rule,Algo salió mal al recuperar la información para la regla de promoción\nSomething went wrong when retrieving the information.,Algo salió mal al recuperar la información.\nInvalid API Key,Clave API no válida\nUsername,Nombre de usuario\nThis account is currently syncing,Esta cuenta se está sincronizando actualmente\nAccount Synced since,Cuenta sincronizada desde\n---No Data---,---Sin datos---\nNo,No\nUnsubscribe,Cancelar suscripción\nDelete subscriber,Eliminar suscriptor\nSyncing,Sincronizando\nSynced,Sincronizado\nWaiting,En espera\nError,Error\nResyncing,Resincronizando\nWith error,Con error\nUnsupported,No compatible\nEdit,Editar\nMailChimp Information,Información de MailChimp\nNo Interest groups found,No se encontraron grupos de interés\nMailchimp v,Mailchimp v\n by,por\nNeed help? See our ,¿Necesita ayuda? Consulte nuestra\nWiki,Wiki\n Got feedback? ,¿Tiene comentarios?\nEmail us,Envíenos un correo electrónico\nYou can find more extension in our ,Puede encontrar más extensiones en nuestra\nStore,Tienda\nSubscribe to more detailed newsletters,Suscríbase a boletines informativos más detallados\nNewsletter,Boletín informativo\nSign Up for Our Newsletter:,Suscríbase a nuestro boletín informativo:\nEnter your email address,Ingrese su dirección de correo electrónico\nEnter your phone,Ingrese su teléfono\nSubscribe,Suscribirse\nMailchimp General Configuration,Configuración general de Mailchimp\nEnabled,Habilitado\nAPI Key,Clave API\nYou 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\nMailchimp List,Lista de Mailchimp\nAccount Details,Detalles de la cuenta\nChange the footer link,Cambiar el enlace de pie de página\n\"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\"\nPopup Url,URL emergente\nPaste the form URL from your MailChimp audience,Pegue la URL del formulario de su audiencia de MailChimp\nMagento always manage emails,Magento siempre administra correos electrónicos\nEnable Two Way Sync,Habilitar sincronización bidireccional\n\"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\"\nCreate Webhook,Crear webhook\nWebhooks Delete action,Acción de eliminación de webhooks\nEnable Log,Habilitar registro\nCustomer Fields Mapping,Mapeo de campos de clientes\nAdd the magento to mailchimp mapping,Agregar el mapeo de magento a mailchimp\nMap the magento customer field to mailchimp merge_fields,Mapear el campo de cliente de magento a los campos de combinación de mailchimp\nResync Subscribers,Resincronizar suscriptores\nFix Mailchimp JS in frontend,Reparar Mailchimp JS en el frontend\nAvailable Groups,Grupos disponibles\n\"If you <a href=\"\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\"\" target=\"\"_blank\"\">set up groups in Mailchimp</a>, include them in your checkout page so customers can choose the type of email marketing they want to receive.\",\"Si <a href=\"\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\"\" target=\"\"_blank\"\">configura grupos en Mailchimp</a>, 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.\"\nShow groups after checkout?,¿Mostrar grupos después del pago?\n\"Don't use in magento 2.1 see at <a href=\"\"https://github.com/magento/magento2/issues/4999\"\" target=\"\"_blank\"\">here</a>\",\"No lo use en Magento 2.1, consulte <a href=\"\"https://github.com/magento/magento2/issues/4999\"\" target=\"\"_blank\"\">aquí</a>\"\nGroup Description,Descripción del grupo\nSuccess message,Mensaje de éxito\nConnection timeout,Tiempo de espera de conexión\nEcommerce Configuration,Configuración de comercio electrónico\nSubscribe all customers to the newsletter,Suscribir a todos los clientes al boletín informativo\nFirst Date,Primera fecha\nSend Promo Rules and Promo Codes,Enviar reglas de promoción y códigos de promoción\nPrices including taxes,Precios con impuestos incluidos\n\"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\"\"\"\nCampaign Attribution Action,Acción de atribución de campaña\nOrder attribution based on customer actions,Atribución de pedidos basada en acciones del cliente\nReset Errors and retry,Restablecer errores y volver a intentar\nTruncate the errors table and retry all the registers with error,Truncar la tabla de errores y volver a intentar todos los registros con error\nReset Errors and no retry,Restablecer errores y no volver a intentar\nTruncate 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\nMonths to clear the error table,Meses para borrar la tabla de errores\nHow 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?\nDelete Store,Eliminar tienda\n\"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\"\nResync all products,Resincronizar todos los productos\nAbandoned Cart Configuration,Configuración de carrito abandonado\nRedirect Page,Redireccionamiento Página\nSave Email to the Quote before place Order,Guardar correo electrónico en la cotización antes de realizar el pedido\nSelect 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\n\"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á\nAll Store Views,Todas las vistas de la tienda\nStore View,Vista de la tienda\nID,ID\nStatus,Estado\nLast modified,Última modificación\n#Customers,#Clientes\n#Orders,#Pedidos\n#Products,#Productos\n#Carts,#Carritos\n#Subscribers,#Suscriptores\nBatch JSON,JSON por lotes\nJob Code,Código de trabajo\nMessages,Mensajes\nCreated at,Creado en\nScheduled at,Programado en\nExecuted at,Ejecutado en\nFinished at,Terminado en\nType,Tipo\nTitle,Título\nDate,Fecha\nAction,Acción\nCreate New Mailchimp Store,Crear nueva tienda de Mailchimp\nMC Account name,Nombre de la cuenta de MC\nStore name,Nombre de la tienda\nList name,Nombre de la lista\nMailchimp Sync,Sincronización de Mailchimp\nSync all customers or only customer with orders, Sincronza todos los clientes o solo los que tienen ordenes\n"
  },
  {
    "path": "i18n/fr_FR.csv",
    "content": "MailChimp,MailChimp\nSave,Enregistrer\nSave and Continue Edit,Enregistrer et continuer la modification\nDelete,Supprimer\nEdit Store '%1',Modifier la boutique '%1'\nAdd Store,Ajouter une boutique\nAddress,Adresse\nStreet,Rue\nCity,Ville\nPostal Code,Code postal\nSelect one,Sélectionnez-en une\nCountry,Pays\nStore Address Info,Informations sur l'adresse de la boutique\nGeneral,Général\nApikey,Apikey\nSelect first an ApiKey,Sélectionnez d'abord une ApiKey\nList,Liste\nName,Nom\nDomain,Domaine\nEmail,E-mail\nCurrency,Devise\nLocale,Localité\nTimeZone,Fuseau horaire\nPhone,Téléphone\nStore Info,Informations sur la boutique\nMailchimp Store Information,Informations sur la boutique Mailchimp\nbutton_label,button_label\nMailchimp,Mailchimp\nMagento,Magento\nAdd,Ajouter\nShipping Zip Code,Code postal d'expédition\nShipping Country,Pays d'expédition\nShipping City,Ville d'expédition\nShipping State,État d'expédition\nShipping Telephone,Téléphone d'expédition\nShipping Company,Société de livraison\nShipping Street,Rue de la navigation\nBilling Zip Code,Code postal de facturation\nBilling Country,Pays de facturation\nBilling City,Ville de facturation\nBilling State,État de facturation\nBilling Telephone,Téléphone de facturation\nBilling Company,Société de facturation\nBilling Street,Rue de la facturation\nMailchimp Batches,Lots Mailchimp\nMailchimp Cron,Mailchimp Cron\nUser name:,Nom d'utilisateur :\nTotal Account Subscribers:,Nombre total d'abonnés au compte :\nTotal List Subscribers:,Nombre total d'abonnés à la liste :\nEcommerce Data uploaded to MailChimp:,Données de commerce électronique téléchargées sur MailChimp :\nTotal customers:,Nombre total de clients :\nTotal products:,Nombre total de produits :\nTotal orders:,Nombre total de commandes :\nTotal Carts:,Nombre total de paniers :\n\"Ecommerce disabled, save configuration to enable\",\"Commerce électronique désactivé, enregistrer la configuration pour activer\"\n\"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)\"\n--- Invalid API Key ---,--- Clé API non valide ---\nMailchimp Errors,Erreurs Mailchimp\nYou deleted the store.,Vous avez supprimé la boutique.\n'Store could not be deleted.' .,'La boutique n'a pas pu être supprimée.' .\nThis store no longer exists.,Cette boutique n'existe plus.\nMailchimp Store,Boutique Mailchimp\nMailchimp Stores,Boutiques Mailchimp\n'Store could not be saved.' .,'La boutique n'a pas pu être enregistrée.' .\nYou can't access this cart,Vous ne pouvez pas accéder à ce panier\nLogin to complete your order,Connectez-vous pour terminer votre commande\nThanks for sharing your interest with us,Merci d'avoir partagé votre intérêt avec nous\nJson error,Erreur Json\nError retrieving interest groups for store ,Erreur lors de la récupération des groupes d'intérêt pour la boutique\nOrder [' . . '] is empty,La commande [' . . '] est vide\nParent rule with id ' . . 'has not been correctly sent.,La règle parente avec l'ID ' . . ' n'a pas été correctement envoyée.\nSomething 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\nSomething went wrong when retrieving the information.,Une erreur s'est produite lors de la récupération des informations.\nInvalid API Key,Clé API non valide\nUsername,Nom d'utilisateur\nThis account is currently syncing,Ce compte est en cours de synchronisation\nAccount Synced since,Compte synchronisé depuis\n---No Data---,---Aucune donnée---\nNo,Non\nUnsubscribe,Se désabonner\nDelete subscriber,Supprimer l'abonné\nSyncing,Synchronisation\nSynced,Synchronisé\nWaiting,En attente\nError,Erreur\nResyncing,Resynchronisation\nWith error,Avec erreur\nUnsupported,Non pris en charge\nEdit,Modifier\nMailChimp Information,Informations MailChimp\nNo Interest groups found,Aucun groupe d'intérêt trouvé\nMailchimp v,Mailchimp v\n by,par\nNeed help? See our ,Besoin d'aide ? Consultez notre\nWiki,Wiki\n Got feedback? ,Vous avez des commentaires ?\nEmail us,Envoyez-nous un e-mail\nYou can find more extension in our ,Vous pouvez trouver plus d'extensions dans notre\nStore,Boutique\nSubscribe to more detailed newsletters,Abonnez-vous à des newsletters plus détaillées\nNewsletter,Newsletter\nSign Up for Our Newsletter:,Inscrivez-vous à notre newsletter :\nEnter your email address,Entrez votre adresse e-mail\nEnter your phone,Entrez votre téléphone\nSubscribe,S'abonner\nMailchimp General Configuration,Configuration générale de Mailchimp\nEnabled,Activé\nAPI Key,Clé API\nYou 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\nMailchimp List,Liste Mailchimp\nAccount Details,Détails du compte\nChange the footer link,Modifier le lien de pied de page\n\"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\"\nPopup Url,URL de la fenêtre contextuelle\nPaste the form URL from your MailChimp audience,Collez l'URL du formulaire à partir de votre audience MailChimp\nMagento always manage emails,Magento gère toujours les e-mails\nEnable Two Way Sync,Activer la synchronisation bidirectionnelle\n\"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\"\nCreate Webhook,Créer un Webhook\nWebhooks Delete action,Action de suppression des Webhooks\nEnable Log,Activer le journal\nCustomer Fields Mapping,Mappage des champs client\nAdd the magento to mailchimp mapping,Ajoutez le mappage magento vers mailchimp\nMap the magento customer field to mailchimp merge_fields,Mappez le champ client magento vers les champs de fusion mailchimp\nResync Subscribers,Resynchroniser Abonnés\nFix Mailchimp JS in frontend,Correction du JS Mailchimp dans le frontend\nAvailable Groups,Groupes disponibles\n\"If you <a href=\"\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\"\" target=\"\"_blank\"\">set up groups in Mailchimp</a>, include them in your checkout page so customers can choose the type of email marketing they want to receive.\",\"Si vous <a href=\"\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\"\" target=\"\"_blank\"\">configurez des groupes dans Mailchimp</a>, incluez-les dans votre page de paiement afin que les clients puissent choisir le type de marketing par e-mail qu'ils souhaitent recevoir.\"\nShow groups after checkout?,Afficher les groupes après le paiement ?\n\"Don't use in magento 2.1 see at <a href=\"\"https://github.com/magento/magento2/issues/4999\"\" target=\"\"_blank\"\">here</a>\",\"Ne pas utiliser dans magento 2.1, voir <a href=\"\"https://github.com/magento/magento2/issues/4999\"\" target=\"\"_blank\"\">ici</a>\"\nGroup Description,Description du groupe\nSuccess message,Message de réussite\nConnection timeout,Délai de connexion expiré\nEcommerce Configuration,Configuration du commerce électronique\nSubscribe all customers to the newsletter,Abonnez tous les clients à la newsletter\nFirst Date,Premier rendez-vous\nSend Promo Rules and Promo Codes,Envoyer les règles de promotion et les codes promotionnels\nPrices including taxes,Prix TTC\n\"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\"\"\"\nCampaign Attribution Action,Action d'attribution de campagne\nOrder attribution based on customer actions,Attribution de commande en fonction des actions du client\nReset Errors and retry,Réinitialiser les erreurs et réessayer\nTruncate the errors table and retry all the registers with error,Tronquer la table des erreurs et réessayer tous les registres avec erreur\nReset Errors and no retry,Réinitialiser les erreurs et ne pas réessayer\nTruncate 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\nMonths to clear the error table,Mois pour effacer la table des erreurs\nHow 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\nDelete Store,Supprimer la boutique\n\"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\"\nResync all products,Resynchroniser tout produits\nAbandoned Cart Configuration,Configuration du panier abandonné\nRedirect Page,Page de redirection\nSave Email to the Quote before place Order,Enregistrer l'e-mail dans le devis avant de passer la commande\nSelect 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\n\"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\"\nAll Store Views,Toutes les vues de la boutique\nStore View,Vue de la boutique\nID,ID\nStatus,Statut\nLast modified,Dernière modification\n#Customers,#Clients\n#Orders,#Commandes\n#Products,#Produits\n#Carts,#Paniers\n#Subscribers,#Abonnés\nBatch JSON,Lot JSON\nJob Code,Code de tâche\nMessages,Messages\nCreated at,Créé à\nScheduled at,Planifié à\nExecuted at,Exécuté à\nFinished at,Terminé à\nType,Type\nTitle,Titre\nDate,Date\nAction,Action\nCreate New Mailchimp Store,Créer une nouvelle boutique Mailchimp\nMC Account name,Nom du compte MC\nStore name,Nom de la boutique\nList name,Nom de la liste\nMailchimp Sync,Synchronisation Mailchimp\nSync all customers or only customer with orders,Synchroniser tous les clients ou uniquement les clients avec les commandes\n"
  },
  {
    "path": "i18n/it_IT.csv",
    "content": "MailChimp,MailChimp\nSave,Salva\nSave and Continue Edit,Salva e continua Modifica\nDelete,Elimina\nEdit Store '%1',Modifica negozio '%1'\nAdd Store,Aggiungi negozio\nAddress,Indirizzo\nStreet,Via\nCity,Citt\nPostal Code,Codice postale\nSelect one,Selezionane uno\nCountry,Paese\nStore Address Info,Informazioni indirizzo negozio\nGeneral,Generale\nApikey,ApiKey\nSelect first an ApiKey,Seleziona prima un'ApiKey\nList,Elenco\nName,Nome\nDomain,Dominio\nEmail,E-mail\nCurrency,Valuta\nLocale,Locale\nTimeZone,Fuso orario\nPhone,Telefono\nStore Info,Informazioni negozio\nMailchimp Store Information,Informazioni negozio Mailchimp\nbutton_label,button_label\nMailchimp,Mailchimp\nMagento,Magento\nAdd,Aggiungi\nShipping Zip Code,CAP spedizione\nShipping Country,Paese spedizione\nShipping City,Città di spedizione\nShipping State,Stato spedizione\nShipping Telephone,Telefono spedizione\nShipping Company,Compagnia di spedizione\nShipping Street,Via di spedizione\nBilling Zip Code,CAP fatturazione\nBilling Country,Paese fatturazione\nBilling City,Città  fatturazione\nBilling State,Stato fatturazione\nBilling Telephone,Telefono fatturazione\nBilling Company,Compagnia fatturazione\nBilling Street,Via della fatturazione\nMailchimp Batches,Batch Mailchimp\nMailchimp Cron,Cron Mailchimp\nUser name:,Nome utente:\nTotal Account Subscribers:,Totale iscritti account:\nTotal List Subscribers:,Totale iscritti elenco:\nEcommerce Data uploaded to MailChimp:,Dati e-commerce caricati su MailChimp:\nTotal customers:,Totale clienti:\nTotal products:,Totale prodotti:\nTotal orders:,Totale ordini:\nTotal Carts:,Totale carrelli:\n\"Ecommerce disabled, save configuration to enable\",\"E-commerce disabilitato, salva configurazione per abilitare\"\n\"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)\"\n--- Invalid API Key ---,--- Chiave API non valida ---\nMailchimp Errors,Errori Mailchimp\nYou deleted the store.,Hai eliminato il negozio.\n'Store could not be deleted.' .,'Impossibile eliminare il negozio.' .\nThis store no longer exists.,Questo negozio non esiste più.\nMailchimp Store,Mailchimp Store\nMailchimp Stores,Mailchimp Stores\n'Store could not be saved.' .,'Impossibile salvare il negozio.' .\nYou can't access this cart,Non puoi accedere a questo carrello\nLogin to complete your order,Accedi per completare l'ordine\nThanks for sharing your interest with us,Grazie per aver condiviso il tuo interesse con noi\nJson error,Errore Json\nError retrieving interest groups for store ,Errore nel recupero dei gruppi di interesse per il negozio\nOrder [' . . '] is empty,L'ordine [' . . '] è vuoto\nParent rule with id ' . . 'has not been correctly sent.,La regola padre con ID ' . . 'non � stata inviata correttamente.\nSomething went wrong when retrieving the information for promo rule,Si è verificato un errore durante il recupero delle informazioni per la regola promozionale\nSomething went wrong when retrieving the information.,Si è verificato un problema durante il recupero delle informazioni.\nInvalid API Key,Chiave API non valida\nUsername,Nome utente\nThis account is currently syncing,Questo account è attualmente in fase di sincronizzazione\nAccount Synced since,Account sincronizzato da\n---No Data---,---Nessun dato---\nNo,No\nUnsubscribe,Annulla iscrizione\nDelete subscriber,Elimina abbonato\nSyncing,Sincronizzazione\nSynced,Sincronizzato\nWaiting,In attesa\nError,Errore\nResyncing,Risincronizzazione\nWith error,Con errore\nUnsupported,Non supportato\nEdit,Modifica\nMailChimp Information,Informazioni MailChimp\nNo Interest groups found,Nessun gruppo di interesse trovato\nMailchimp v,Mailchimp v\n by,di\nNeed help? See our ,Hai bisogno di aiuto? Consulta il nostro\nWiki,Wiki\n Got feedback? ,Hai feedback?\nEmail us,Inviaci un'e-mail\nYou can find more extension in our ,Puoi trovare altre estensioni nel nostro\nStore,Negozio\nSubscribe to more detailed newsletters,Subscribe to more detailed newsletters\nNewsletter,Newsletter\nSign Up for Our Newsletter:,Iscriviti alla nostra newsletter:\nEnter your email address,Inserisci il tuo indirizzo e-mail\nEnter your phone,Inserisci il tuo telefono\nSubscribe,Iscriviti\nMailchimp General Configuration,Configurazione generale di Mailchimp\nEnabled,Abilitato\nAPI Key,Chiave API\nYou 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\nMailchimp List,Elenco Mailchimp\nAccount Details,Dettagli account\nChange the footer link,Cambia il collegamento del piè di pagina\n\"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\"\nPopup Url,URL popup\nPaste the form URL from your MailChimp audience,Incolla l'URL del modulo dal tuo pubblico MailChimp\nMagento always manage emails,Magento gestisce sempre le e-mail\nEnable Two Way Sync,Abilita sincronizzazione bidirezionale\n\"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\"\nCreate Webhook,Crea webhook\nWebhooks Delete action,Azione di eliminazione dei webhook\nEnable Log,Abilita registro\nCustomer Fields Mapping,Mappatura campi cliente\nAdd the magento to mailchimp mapping,Aggiungi la mappatura di Magento a Mailchimp\nMap the magento customer field to mailchimp merge_fields,Mappa il campo cliente di Magento ai merge_field di Mailchimp\nResync Subscribers,Risincronizza gli iscritti\nFix Mailchimp JS in frontend,Correggi Mailchimp JS nel frontend\nAvailable Groups,Gruppi disponibili\n\"If you <a href=\"\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\"\" target=\"\"_blank\"\">set up groups in Mailchimp</a>, include them in your checkout page so customers can choose the type of email marketing they want to receive.\",\"Se <a href=\"\"https://kb.mailchimp.com/lists/groups/create-a-new-list-group\"\" target=\"\"_blank\"\">configuri gruppi in Mailchimp</a>, includili nella pagina di pagamento in modo che i clienti possano scegliere il tipo di email marketing che desiderano ricevere.\"\nShow groups after checkout?,Mostra i gruppi dopo il checkout?\n\"Don't use in magento 2.1 see at <a href=\"\"https://github.com/magento/magento2/issues/4999\"\" target=\"\"_blank\"\">here</a>\",\"Non utilizzare in Magento 2.1, vedere <a href=\"\"https://github.com/magento/magento2/issues/4999\"\" target=\"\"_blank\"\">qui</a>\"\nGroup Description,Descrizione gruppo\nSuccess message,Messaggio di successo\nConnection timeout,Timeout di connessione\nEcommerce Configuration,Configurazione e-commerce\nSubscribe all customers to the newsletter,Iscrivi tutti i clienti alla newsletter\nFirst Date,Primo appuntamento\nSend Promo Rules and Promo Codes,Invia regole promozionali e codici promozionali\nPrices including taxes,Prezzi tasse incluse\n\"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\"\"\"\nCampaign Attribution Action,Azione di attribuzione campagna\nOrder attribution based on customer actions,Attribuzione ordine in base alle azioni del cliente\nReset Errors and retry,Reimposta errori e riprova\nTruncate the errors table and retry all the registers with error,Tronca la tabella degli errori e riprova tutti i registri con errore\nReset Errors and no retry,Reimposta errori e non riprovare\nTruncate the errors table and no retry all the registers with error,Tronca la tabella degli errori e non riprovare tutti i registri con errore\nMonths to clear the error table,Mesi per cancellare la tabella degli errori\nHow 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\nDelete Store,Elimina negozio\n\"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\"\nResync all products,Risincronizza tutti i prodotti\nAbandoned Cart Configuration,Configurazione carrello abbandonato\nRedirect Page,Pagina di reindirizzamento\nSave Email to the Quote before place Order,Salva e-mail nel preventivo prima di effettuare l'ordine\nSelect 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\n\"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\"\nAll Store Views,Tutte le visualizzazioni del negozio\nStore View,Visualizzazione del negozio\nID,ID\nStatus,Stato\nLast modified,Ultima modifica\n#Customers,#Clienti\n#Orders,#Ordini\n#Products,#Prodotti\n#Carts,#Carrelli\n#Subscribers,#Iscritti\nBatch JSON,JSON batch\nJob Code,Codice lavoro\nMessages,Messaggi\nCreated at,Creato alle\nScheduled at,Pianificato alle\nExecuted at,Eseguito at\nFinished at,Finito alle\nType,Tipo\nTitle,Titolo\nDate,Data\nAction,Azione\nCreate New Mailchimp Store,Crea nuovo negozio Mailchimp\nMC Account name,Nome account MC\nStore name,Nome negozio\nList name,Nome elenco\nMailchimp Sync,Sincronizzazione Mailchimp\nSync all customers or only customer with orders,Sincronizza tutti i clienti o solo i clienti con gli ordini\n"
  },
  {
    "path": "modman",
    "content": "* app/code/Ebizmarts/MailChimp\n"
  },
  {
    "path": "registration.php",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\n\\Magento\\Framework\\Component\\ComponentRegistrar::register(\n    \\Magento\\Framework\\Component\\ComponentRegistrar::MODULE,\n    'Ebizmarts_MailChimp',\n    __DIR__\n);\n"
  },
  {
    "path": "view/adminhtml/layout/customer_index_edit.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" layout=\"admin-2columns-left\"\n      xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <body>\n        <referenceContainer name=\"content\">\n            <referenceBlock name=\"customer_form\">\n                <block class=\"Ebizmarts\\MailChimp\\Block\\Adminhtml\\Customer\\Edit\\Tabs\\Mailchimp\" name=\"customer_edit_tab_mailchimp\" template=\"tab/view.phtml\" ifconfig=\"mailchimp/general/active\">\n                    <arguments>\n                        <argument name=\"sort_order\" xsi:type=\"number\">50</argument>\n                    </arguments>\n                    <block class=\"Ebizmarts\\MailChimp\\Block\\Adminhtml\\Customer\\Edit\\Tabs\\View\\Customer\" name=\"mailchimp\"  template=\"customer/edit/tabs/mailchimp.phtml\" />\n                </block>\n            </referenceBlock>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/adminhtml/layout/default.xml",
    "content": "<?xml version=\"1.0\"?>\n\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" layout=\"admin-1column\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <head>\n        <css src=\"Ebizmarts_MailChimp::css/styles.css\"/>\n    </head>\n</page>"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_batch_index.xml",
    "content": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <update handle=\"styles\"/>\n    <body>\n        <referenceContainer name=\"content\">\n            <uiComponent name=\"mailchimp_batch_grid\"/>\n        </referenceContainer>\n    </body>\n</page>"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_carts_index.xml",
    "content": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <update handle=\"styles\"/>\n    <body>\n        <referenceContainer name=\"content\">\n            <uiComponent name=\"mailchimp_carts_grid\"/>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_cron_index.xml",
    "content": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <update handle=\"styles\"/>\n    <body>\n        <referenceContainer name=\"content\">\n            <uiComponent name=\"mailchimp_cron_grid\"/>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_errors_index.xml",
    "content": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <update handle=\"styles\"/>\n    <body>\n        <referenceContainer name=\"content\">\n            <uiComponent name=\"mailchimp_errors_grid\"/>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_stores_edit.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" layout=\"admin-2columns-left\"\n      xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <body>\n        <referenceContainer name=\"js\">\n            <block class=\"Magento\\Backend\\Block\\Template\" template=\"Ebizmarts_MailChimp::system/config/js.phtml\"/>\n        </referenceContainer>\n        <referenceContainer name=\"left\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit\\Tabs\"\n                   name=\"ebizmarts_mailchimp_store.edit.tabs\"/>\n        </referenceContainer>\n        <referenceContainer name=\"content\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Adminhtml\\Stores\\Edit\" name=\"ebizmarts_mailchimp_store.edit\"/>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_stores_grid.xml",
    "content": "<?xml version=\"1.0\"?>\n<layout xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/layout_generic.xsd\">\n    <update handle=\"formkey\"/>\n    <update handle=\"mailchimp_stores_grid_block\"/>\n    <container name=\"root\">\n        <block class=\"Magento\\Backend\\Block\\Widget\\Grid\\Container\" name=\"mailchimp.error.grid.container\" template=\"Magento_Backend::widget/grid/container/empty.phtml\"/>\n    </container>\n</layout>"
  },
  {
    "path": "view/adminhtml/layout/mailchimp_stores_index.xml",
    "content": "<?xml version=\"1.0\"?>\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd\">\n    <update handle=\"styles\"/>\n    <body>\n        <referenceBlock name=\"menu\">\n            <action method=\"setActive\">\n                <argument name=\"itemId\" xsi:type=\"string\">Ebizmarts_MailChimp::stores</argument>\n            </action>\n        </referenceBlock>\n        <referenceBlock name=\"page.title\">\n            <action method=\"setTitleClass\">\n                <argument name=\"class\" xsi:type=\"string\">complex</argument>\n            </action>\n        </referenceBlock>\n        <referenceContainer name=\"content\">\n            <uiComponent name=\"mailchimp_stores_grid\"/>\n        </referenceContainer>\n    </body>\n</page>\n\n"
  },
  {
    "path": "view/adminhtml/requirejs-config.js",
    "content": "/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nvar config = {\n    \"map\": {\n        \"*\": {\n            monkeyapikey: 'Ebizmarts_MailChimp/js/apikey',\n            configmonkeyapikey: 'Ebizmarts_MailChimp/js/configapikey',\n            mailchimpconfirmation: 'Ebizmarts_MailChimp/js/mailchimpconfirmation'\n        }\n    }\n};"
  },
  {
    "path": "view/adminhtml/templates/customer/edit/tabs/mailchimp.phtml",
    "content": "<?php\n/**\n * @var $block \\Ebizmarts\\MailChimp\\Block\\Adminhtml\\Customer\\Edit\\Tabs\\View\\Customer\n */\n$interest = $block->getInterest();\n?>\n<div class=\"fieldset-wrapper\">\n    <div class=\"fieldset-wrapper-title\">\n        <span class=\"title\"><?= $block->escapeHtml(__('MailChimp Information')) ?></span>\n    </div>\n    <div class=\"admin__fieldset-wrapper-content\">\n    <fieldset class=\"admin__fieldset\">\n    <?php if (count($interest)): ?>\n    <?php foreach ($interest as $i): ?>\n        <div class=\"admin__field\">\n            <label class=\"admin__field-label\" for=\"<?= $block->escapeHtml($i['interest']['id']) ?>\">\n                <span><?= $block->escapeHtml($i['interest']['title']) ?></span>\n            </label>\n            <div class=\"admin__field-control control\">\n                <div class=\"fields\">\n                    <?php switch ($i['interest']['type']):\n                        case 'checkboxes': ?>\n                            <ul class=\"admin_field_field field\" style=\"list-style: none\">\n                                <?php foreach ($i['category'] as $c): ?>\n                                    <li class=\"field no-label\">\n                                        <input\n                                               name=\"customer[interestgroup][<?= $block->escapeHtml($i['interest']['id']) ?>][<?= $block->escapeHtml($c['id']) ?>]\"\n                                               type=\"checkbox\"\n                                               data-form-part=\"customer_form\"\n                                               value=\"<?= $block->escapeHtml($c['id']) ?>\"\n                                               id=\"<?= $block->escapeHtml('mailchimp_group_'.$c['id']) ?>\"\n                                               title=\"<?= $block->escapeHtml($c['name']) ?>\"\n                                            <?php if ($c['checked']) { echo $block->escapeHtml('checked');} ?>\n                                        />\n                                        <label class=\"field label\"><?= $block->escapeHtml($c['name'])?></label>\n                                    </li>\n                                <?php endforeach; ?>\n                            </ul>\n                            <?php       break;\n                        case 'dropdown': ?>\n                            <div class=\"field no-label\">\n                                <select class=\"admin_field_field field\"\n                                        data-form-part=\"customer_form\"\n                                        name=\"customer[interestgroup][<?= $block->escapeHtml($i['interest']['id']) ?>]\"\n                                        id=\"<?= $block->escapeHtml('mailchimp_group_'.$i['interest']['id']) ?>\"\n                                        title=\"<?= $block->escapeHtml($i['interest']['title']) ?>\">\n                                    <option value=\"\"></option>\n                                    <?php foreach ($i['category'] as $c): ?>\n                                        <option value=\"<?= $block->escapeHtml($c['id'])?>\" <?php if ($c['checked']) { echo $block->escapeHtml('selected'); } ?>><?= $block->escapeHtml($c['name']) ?></option>\n                                    <?php endforeach; ?>\n                                </select>\n\n                            </div>\n                            <?php       break;\n                        case 'radio': ?>\n                            <ul class=\"admin_field_field field\">\n                                <?php foreach ($i['category'] as $c): ?>\n                                    <li class=\"field no-label\" style=\"list-style: none\">\n                                        <input class=\"\"\n                                               name=\"customer[interestgroup][<?= $block->escapeHtml($i['interest']['id']) ?>]\"\n                                               type=\"radio\"\n                                               data-form-part=\"customer_form\"\n                                               value=\"<?= $block->escapeHtml($c['id']) ?>\"\n                                               id=\"<?= $block->escapeHtml('mailchimp_group_'.$c['id']) ?>\"\n                                               title=\"<?= $block->escapeHtml($c['name']) ?>\"\n                                            <?php if ($c['checked']) { echo $block->escapeHtml('checked');} ?>\n                                        />\n                                        <label class=\"field label\"><?= $block->escapeHtml($c['name'])?></label>\n                                    </li>\n                                <?php endforeach; ?>\n                            </ul>\n                            <?php       break; ?>\n                        <?php endswitch; ?>\n                </div>\n            </div>\n        </div>\n    <?php endforeach; ?>\n    <?php else: ?>\n        <div class=\"admin__field\">\n            <?= $block->escapeHtml(__(\"No Interest groups found\")); ?>\n        </div>\n    <?php endif; ?>\n</fieldset>\n    </div>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/create_abandonedcart_automation.phtml",
    "content": "<div class=\"actions actions-get-apikey\">\n    <button onclick=\"javascript:window.open('<?= $block->escapeUrl($block->authorizeRequestUrl()) ?>', 'apiwizard','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, ,left=100, top=100, width=800, height=600'); return false;\" class=\"action-get-apikey\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/createwebhook.phtml",
    "content": "<div class=\"actions actions-create-webhook\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button class=\"action-create-webhook\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/deletestore.phtml",
    "content": "<div id=\"monkey_storeconfirmation\" style=\"display:none;\" data-mage-init='{\"mailchimpconfirmation\":{}}'>\n</div>\n<div class=\"actions actions-delete-store\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button onclick=\"mailchimpdeleteconfirmation('<?= $block->escapeHtml($block->getAjaxCheckUrl()) ?>')\" class=\"action-delete-store\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/fieldset/hint.phtml",
    "content": "<?php\n/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n?>\n<div id=\"configmonkey_apikey\" class=\"admin__page-section-item\" style=\"display:none;\"\n     data-mage-init='{\"configmonkeyapikey\":{\n     \"storeUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/stores/get'));?>\",\n     \"detailsUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/getaccountdetails'));?>\",\n     \"storeGridUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/stores/index'));?>\",\n     \"createWebhookUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/createWebhook'));?>\",\n     \"getInterestUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/getInterest'));?>\",\n     \"resyncSubscribersUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/resyncSubscribers'));?>\",\n     \"resyncProductsUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/resyncProducts'));?>\",\n     \"fixMailchimpjsUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/fixMailchimpJS'));?>\",\n     \"registerUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/register'));?>\",\n     \"scope\": \"<?= $block->escapeHtml($block->getScope());?>\",\n     \"scopeId\": \"<?= $block->escapeUrl($block->getScopeId()); ?>\",\n     \"registerToken\": \"<?= $block->escapeUrl($block->getRegisterToken()); ?>\",\n     \"switchurl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/ecommerce/SyncLog'));?>\"\n    }}'>\n</div>\n<div style=\"background:#EAF0EE;border:1px solid #CCCCCC;margin-bottom:10px;padding:11px 0 0 10px;\">\n    <h4>\n        <img width=\"224px\" style=\"padding-left: 15px;\" height=\"60px\" src=\"https://ebizmarts-website.s3.amazonaws.com/Logo_Ebizmarts.png\"/><br><br>\n        <div style=\"padding-left: 15px;\">\n            <p> <strong style=\"color:#EA7601;\"><?= $block->escapeHtml(__('Mailchimp v')) ?><?= $block->escapeHtml($block->getModuleVersion()) ?><?= $block->escapeHtml(__(' by')) ?></strong> <a target=\"_blank\" href=\"http://ebizmarts.com\"><strong>ebizmarts</strong></a></p>\n            <p><?= $block->escapeHtml(__('Need help? See our ')) ?><a href=\"https://github.com/mailchimp/mc-magento2/wiki\" target=\"_blank\"><?= $block->escapeHtml(__('Wiki')) ?></a><?= $block->escapeHtml(__(' Got feedback? ')) ?><a href=\"mailto:mailchimp@ebizmarts-desk.zendesk.com?Subject=MailChimp For Magento Version <?= $block->escapeHtml($block->getModuleVersion())?>\"><?= $block->escapeHtml(__('Email us')) ?></a></p>\n            <p><?= $block->escapeHtml(__('You can find more extension in our ')) ?><a href=\"http://store.ebizmarts.com\" target=\"_blank\"><?= $block->escapeHtml(__('Store')) ?></a></p>\n            <?php if (!$block->getHasApiKey()): ?>\n                <p><a style=\"padding-top: 5px;padding-bottom:5px;padding-left: 30px;padding-right: 30px;background-color:#D75F07 ;color:white;font-weight: bold\" href=\"https://bit.ly/2KpDH5C\" target=\"_blank\">Support Mailchimp4Magento, Subscribe for a free Mailchimp Account!</a> </p>\n            <?php endif; ?>\n        </div>\n    </h4>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/fixmailchimpjs.phtml",
    "content": "<div class=\"actions actions-fix-mailchimp-js\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button class=\"action-fix-mailchimp-js\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/js.phtml",
    "content": "<div id=\"monkey_apikey\" class=\"admin__page-section-item\" style=\"display:none;\"\n     data-mage-init='{\"monkeyapikey\":{\"apikeyUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/lists/get'));?>\"}}'>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/oauth_wizard.phtml",
    "content": "<div class=\"actions actions-get-apikey\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button onclick=\"javascript:window.open('<?= $block->escapeUrl($block->authorizeRequestUrl()) ?>', 'apiwizard','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, ,left=100, top=100, width=500, height=700'); return false;\" class=\"action-get-apikey\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/reseterrors.phtml",
    "content": "<div id=\"monkey_errorconfirmation\" style=\"display:none;\" data-mage-init='{\"mailchimpconfirmation\":{}}'>\n</div>\n<div class=\"actions actions-reset-errors\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button onclick=\"mailchimpdeleteconfirmation('<?= $block->escapeUrl($block->getAjaxCheckUrl()) ?>')\" class=\"action-reset-errors\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/reseterrorsnoretry.phtml",
    "content": "<div id=\"monkey_errorconfirmation\" style=\"display:none;\" data-mage-init='{\"mailchimpconfirmation\":{}}'>\n</div>\n<div class=\"actions actions-reset-errors\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button onclick=\"mailchimpdeleteconfirmation('<?= $block->escapeUrl($block->getAjaxCheckUrl()) ?>')\" class=\"action-reset-errors\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/resetstore.phtml",
    "content": "<script>\n    //<![CDATA[\n    function resetStore() {\n        jQuery.ajax({\n            url: '<?= $block->escapeUrl($block->getAjaxCheckUrl()) ?>',\n            data: {form_key: window.FORM_KEY},\n            type: 'POST',\n            success: function(data){\n                if(data.valid==0) {\n                    alert('Error: '+data.message);\n                }\n                else if(data.valid==1) {\n                    alert('A new store was created');\n                }\n            }\n        }).done(function(a) {\n            console.log(a);\n        });\n    }\n    //]]>\n</script>\n\n\n<?php //echo  __($block->escapeHtml('Reset errors')); ?>\n\n\n<div class=\"actions actions-reset-store\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button onclick=\"javascript:resetStore(); return false;\" class=\"action-reset-store\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/resyncproducts.phtml",
    "content": "<div class=\"actions actions-resync-products\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button class=\"action-resync-products\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/system/config/resyncsubscriber.phtml",
    "content": "<div class=\"actions actions-resync-customer\">\n    <div id=\"validation_result\" class=\"message-validation hidden\"></div>\n    <button class=\"action-resync-subscribers\" type=\"button\" id=\"<?= $block->getHtmlId() ?>\">\n        <span><?= $block->escapeHtml($block->getButtonLabel()) ?></span>\n    </button>\n</div>\n"
  },
  {
    "path": "view/adminhtml/templates/tab/view.phtml",
    "content": "<?php\n/** @var $block \\Ebizmarts\\MailChimp\\Block\\Adminhtml\\Customer\\Edit\\Tabs\\Mailchimp */\n?>\n<?= $block->getChildHtml(); ?>\n"
  },
  {
    "path": "view/adminhtml/ui_component/customer_listing.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <columns name=\"customer_columns\">\n        <column name=\"mailchimp_sync\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Listing\\Column\\Customers\" sortOrder=\"40\">\n            <settings>\n                <label translate=\"true\">Mailchimp</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n    </columns>\n</listing>\n"
  },
  {
    "path": "view/adminhtml/ui_component/mailchimp_batch_grid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <argument name=\"data\" xsi:type=\"array\">\n        <item name=\"js_config\" xsi:type=\"array\">\n            <item name=\"provider\" xsi:type=\"string\">mailchimp_batch_grid.mailchimp_batch_grid_data_source</item>\n            <item name=\"deps\" xsi:type=\"string\">mailchimp_batch_grid.mailchimp_batch_grid_data_source</item>\n            <!--Declare the data source name which will be defined below-->\n        </item>\n        <item name=\"spinner\" xsi:type=\"string\">mailchimp_batch_columns</item>\n        <item name=\"buttons\" xsi:type=\"array\">\n        </item>\n    </argument>\n    <dataSource name=\"mailchimp_batch_grid_data_source\">\n        <!--The data source-->\n        <argument name=\"dataProvider\" xsi:type=\"configurableObject\">\n            <argument name=\"class\" xsi:type=\"string\">Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider</argument>\n            <argument name=\"name\" xsi:type=\"string\">mailchimp_batch_grid_data_source</argument>\n            <argument name=\"primaryFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"requestFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"component\" xsi:type=\"string\">Magento_Ui/js/grid/provider</item>\n                    <item name=\"update_url\" xsi:type=\"url\" path=\"mui/index/render\"/>\n                    <item name=\"storageConfig\" xsi:type=\"array\">\n                        <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    </item>\n                </item>\n            </argument>\n        </argument>\n    </dataSource>\n\n    <container name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"template\" xsi:type=\"string\">ui/grid/toolbar</item>\n                <item name=\"stickyTmpl\" xsi:type=\"string\">ui/grid/sticky/toolbar</item>\n            </item>\n        </argument>\n    </container>\n\n    <listingToolbar name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"sticky\" xsi:type=\"boolean\">true</item>\n            </item>\n        </argument>\n        <bookmark name=\"bookmarks\"/>\n        <columnsControls name=\"columns_controls\"/>\n        <filters name=\"listing_filters\">\n            <filterSelect name=\"store_id\">\n                <argument name=\"optionsProvider\" xsi:type=\"configurableObject\">\n                    <argument name=\"class\" xsi:type=\"string\">Magento\\Store\\Ui\\Component\\Listing\\Column\\Store\\Options</argument>\n                </argument>\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"provider\" xsi:type=\"string\">${ $.parentName }</item>\n                        <item name=\"dataScope\" xsi:type=\"string\">store_id</item>\n                        <item name=\"caption\" xsi:type=\"string\" translate=\"true\">All Store Views</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">Store View</item>\n                    </item>\n                </argument>\n            </filterSelect>\n        </filters>\n        <paging name=\"listing_paging\"/>\n    </listingToolbar>\n\n    <columns name=\"mailchimp_batch_columns\">\n\n        <column name=\"batch_id\">\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"filter\" xsi:type=\"string\">text</item>\n                        <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">ID</item>\n                    </item>\n                </argument>\n        </column>\n\n        <column name=\"status\">\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"filter\" xsi:type=\"string\">text</item>\n                        <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">Status</item>\n                    </item>\n                </argument>\n        </column>\n\n\n        <column name=\"modified_date\">\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"filter\" xsi:type=\"string\">text</item>\n                        <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">Last modified</item>\n                    </item>\n                </argument>\n        </column>\n\n\n        <column name=\"store_name\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <settings>\n                <label translate=\"true\">Mailchimp Store</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        <column name=\"customers\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <settings>\n                <label translate=\"true\">#Customers</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        \n        <column name=\"orders\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <settings>\n                <label translate=\"true\">#Orders</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        <column name=\"products\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <settings>\n                <label translate=\"true\">#Products</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        <column name=\"carts\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <settings>\n                <label translate=\"true\">#Carts</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        <column name=\"subscribers\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <settings>\n                <label translate=\"true\">#Subscribers</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        <actionsColumn name=\"actions\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Batch\\Grid\\Column\\Batches\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Batch JSON</item>\n                </item>\n            </argument>\n        </actionsColumn>\n\n    </columns>\n\n</listing>\n"
  },
  {
    "path": "view/adminhtml/ui_component/mailchimp_carts_grid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <argument name=\"data\" xsi:type=\"array\">\n        <item name=\"js_config\" xsi:type=\"array\">\n            <item name=\"provider\" xsi:type=\"string\">mailchimp_carts_grid.mailchimp_carts_grid_data_source</item>\n            <item name=\"deps\" xsi:type=\"string\">mailchimp_carts_grid.mailchimp_carts_grid_data_source</item>\n            <!--Declare the data source name which will be defined below-->\n        </item>\n        <item name=\"spinner\" xsi:type=\"string\">mailchimp_carts_columns</item>\n        <item name=\"buttons\" xsi:type=\"array\">\n        </item>\n    </argument>\n    <dataSource name=\"mailchimp_batch_grid_data_source\">\n        <!--The data source-->\n        <argument name=\"dataProvider\" xsi:type=\"configurableObject\">\n            <argument name=\"class\" xsi:type=\"string\">Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider</argument>\n            <argument name=\"name\" xsi:type=\"string\">mailchimp_carts_grid_data_source</argument>\n            <argument name=\"primaryFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"requestFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"component\" xsi:type=\"string\">Magento_Ui/js/grid/provider</item>\n                    <item name=\"update_url\" xsi:type=\"url\" path=\"mui/index/render\"/>\n                    <item name=\"storageConfig\" xsi:type=\"array\">\n                        <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    </item>\n                </item>\n            </argument>\n        </argument>\n    </dataSource>\n\n    <container name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"template\" xsi:type=\"string\">ui/grid/toolbar</item>\n                <item name=\"stickyTmpl\" xsi:type=\"string\">ui/grid/sticky/toolbar</item>\n            </item>\n        </argument>\n    </container>\n\n    <listingToolbar name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"sticky\" xsi:type=\"boolean\">true</item>\n            </item>\n        </argument>\n        <bookmark name=\"bookmarks\"/>\n        <columnsControls name=\"columns_controls\"/>\n        <filters name=\"listing_filters\">\n            <filterSelect name=\"store_id\">\n                <argument name=\"optionsProvider\" xsi:type=\"configurableObject\">\n                    <argument name=\"class\" xsi:type=\"string\">Magento\\Store\\Ui\\Component\\Listing\\Column\\Store\\Options</argument>\n                </argument>\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"provider\" xsi:type=\"string\">${ $.parentName }</item>\n                        <item name=\"dataScope\" xsi:type=\"string\">store_id</item>\n                        <item name=\"caption\" xsi:type=\"string\" translate=\"true\">All Store Views</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">Store View</item>\n                    </item>\n                </argument>\n            </filterSelect>\n        </filters>\n        <paging name=\"listing_paging\"/>\n    </listingToolbar>\n\n    <columns name=\"mailchimp_carts_columns\">\n        <column name=\"customer_email\" >\n            <settings>\n                <filter>text</filter>\n                <label translate=\"true\">Customer Email</label>\n            </settings>\n        </column>\n        <column name=\"customer_name\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Carts\\Grid\\Column\\Customer\">\n            <settings>\n                <filter>text</filter>\n                <label translate=\"true\">Customer Name</label>\n            </settings>\n        </column>\n\n        <column name=\"items_count\" >\n            <settings>\n                <filter>text</filter>\n                <label translate=\"true\">Items</label>\n            </settings>\n        </column>\n        <column name=\"items_qty\" >\n            <settings>\n                <filter>text</filter>\n                <label translate=\"true\">Qty</label>\n            </settings>\n        </column>\n        <column name=\"grand_total\" class=\"Magento\\Sales\\Ui\\Component\\Listing\\Column\\PurchasedPrice\">\n            <settings>\n                <filter>textRange</filter>\n                <label translate=\"true\">Grand Total</label>\n            </settings>\n        </column>\n        <column name=\"created_at\" class=\"Magento\\Ui\\Component\\Listing\\Columns\\Date\" component=\"Magento_Ui/js/grid/columns/date\">\n            <settings>\n                <filter>dateRange</filter>\n                <dataType>date</dataType>\n                <label translate=\"true\">Quote Date</label>\n                <sorting>desc</sorting>\n            </settings>\n        </column>\n        <column name=\"mailchimp_sync_delta\" class=\"Magento\\Ui\\Component\\Listing\\Columns\\Date\" component=\"Magento_Ui/js/grid/columns/date\">\n            <settings>\n                <filter>dateRange</filter>\n                <dataType>date</dataType>\n                <label translate=\"true\">Sync Date</label>\n                <sorting>desc</sorting>\n            </settings>\n        </column>\n        <column name=\"mailchimp_sync\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Carts\\Grid\\Column\\Mailchimp\">\n            <settings>\n                <altField>mailchimp_sync</altField>\n                <hasPreview>0</hasPreview>\n                <label translate=\"true\">Mailchimp</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n\n        <actionsColumn name=\"actions\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Carts\\Grid\\Column\\Actions\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Customer</item>\n                    <item name=\"sortOrder\" xsi:type=\"number\">120</item>\n                </item>\n            </argument>\n        </actionsColumn>\n    </columns>\n</listing>\n"
  },
  {
    "path": "view/adminhtml/ui_component/mailchimp_cron_grid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <!--Declare data source, columns list, button...-->\n    <argument name=\"data\" xsi:type=\"array\">\n        <item name=\"js_config\" xsi:type=\"array\">\n            <item name=\"provider\" xsi:type=\"string\">mailchimp_cron_grid.mailchimp_cron_grid_data_source</item>\n        </item>\n    </argument>\n    <settings>\n        <spinner>mailchimp_cron_columns</spinner>\n        <deps>\n            <dep>mailchimp_cron_grid.mailchimp_cron_grid_data_source</dep>\n        </deps>\n    </settings>\n    <dataSource name=\"mailchimp_cron_grid_data_source\" component=\"Magento_Ui/js/grid/provider\">\n        <!--The data source-->\n        <settings>\n            <updateUrl path=\"mui/index/render\"/>\n            <storageConfig>\n                <param name=\"indexField\" xsi:type=\"string\">schedule_id</param>\n            </storageConfig>\n        </settings>\n        <dataProvider class=\"Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider\" name=\"mailchimp_cron_grid_data_source\">\n            <settings>\n                <requestFieldName>schedule_id</requestFieldName>\n                <primaryFieldName>schedule_id</primaryFieldName>\n            </settings>\n        </dataProvider>\n    </dataSource>\n\n    <listingToolbar name=\"listing_top\">\n        <columnsControls name=\"columns_controls\"/>\n        <exportButton name=\"export_button\"/>\n        <filters name=\"listing_filters\"/>\n        <paging name=\"listing_paging\"/>\n    </listingToolbar>\n\n\n    <columns name=\"mailchimp_cron_columns\">\n        <!--The list of columns-->\n        <selectionsColumn name=\"ids\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">number</item>\n                    <item name=\"indexField\" xsi:type=\"string\">schedule_id</item>\n                </item>\n            </argument>\n        </selectionsColumn>\n        <column name=\"schedule_id\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">desc</item>\n                    <item name=\"sortable\" xsi:type=\"boolean\">true</item>\n                    <item name=\"sortOrder\" xsi:type=\"string\">1</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">ID</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"job_code\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">select</item>\n                    <item name=\"options\" xsi:type=\"array\">\n                        <item name=\"ebizmarts_clean_batches_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">ebizmarts_clean_batches</item>\n                            <item name=\"value\" xsi:type=\"string\">ebizmarts_clean_batches</item>\n                        </item>\n                        <item name=\"ebizmarts_clean_errors_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">ebizmarts_clean_errors</item>\n                            <item name=\"value\" xsi:type=\"string\">ebizmarts_clean_errors</item>\n                        </item>\n                        <item name=\"ebizmarts_clean_webhooks_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">ebizmarts_clean_webhooks</item>\n                            <item name=\"value\" xsi:type=\"string\">ebizmarts_clean_webhooks</item>\n                        </item>\n                        <item name=\"ebizmarts_ecommerce_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">ebizmarts_ecommerce</item>\n                            <item name=\"value\" xsi:type=\"string\">ebizmarts_ecommerce</item>\n                        </item>\n                        <item name=\"ebizmarts_webhooks_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">ebizmarts_webhooks</item>\n                            <item name=\"value\" xsi:type=\"string\">ebizmarts_webhooks</item>\n                        </item>\n                    </item>\n                    <item name=\"dataType\" xsi:type=\"string\">select</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Job Code</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"status\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">select</item>\n                    <item name=\"options\" xsi:type=\"array\">\n                        <item name=\"error_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">error</item>\n                            <item name=\"value\" xsi:type=\"string\">error</item>\n                        </item>\n                        <item name=\"missed_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">missed</item>\n                            <item name=\"value\" xsi:type=\"string\">missed</item>\n                        </item>\n                        <item name=\"pending_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">pending</item>\n                            <item name=\"value\" xsi:type=\"string\">pending</item>\n                        </item>\n                        <item name=\"running_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">running</item>\n                            <item name=\"value\" xsi:type=\"string\">running</item>\n                        </item>\n                        <item name=\"scheduled_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">scheduled</item>\n                            <item name=\"value\" xsi:type=\"string\">scheduled</item>\n                        </item>\n                        <item name=\"success_filter\" xsi:type=\"array\">\n                            <item name=\"label\" xsi:type=\"string\">success</item>\n                            <item name=\"value\" xsi:type=\"string\">success</item>\n                        </item>\n                    </item>\n                    <item name=\"dataType\" xsi:type=\"string\">select</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Status</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"messages\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Messages</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"created_at\">\n            <settings>\n                <filter>dateRange</filter>\n                <dataType>date</dataType>\n                <label translate=\"true\">Created at</label>\n            </settings>\n        </column>\n        <column name=\"scheduled_at\">\n            <settings>\n                <filter>dateRange</filter>\n                <dataType>date</dataType>\n                <label translate=\"true\">Scheduled at</label>\n            </settings>\n        </column>\n        <column name=\"executed_at\">\n            <settings>\n                <filter>dateRange</filter>\n                <dataType>date</dataType>\n                <label translate=\"true\">Executed at</label>\n            </settings>\n        </column>\n        <column name=\"finished_at\">\n            <settings>\n                <filter>dateRange</filter>\n                <dataType>date</dataType>\n                <label translate=\"true\">Finished at</label>\n            </settings>\n        </column>\n    </columns>\n</listing>"
  },
  {
    "path": "view/adminhtml/ui_component/mailchimp_errors_grid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <!--Declare data source, columns list, button...-->\n    <argument name=\"data\" xsi:type=\"array\">\n        <item name=\"js_config\" xsi:type=\"array\">\n            <item name=\"provider\" xsi:type=\"string\">mailchimp_errors_grid.mailchimp_errors_grid_data_source</item>\n            <item name=\"deps\" xsi:type=\"string\">mailchimp_errors_grid.mailchimp_errors_grid_data_source</item>\n            <!--Declare the data source name which will be defined below-->\n        </item>\n        <item name=\"spinner\" xsi:type=\"string\">mailchimp_errors_columns</item>\n        <item name=\"buttons\" xsi:type=\"array\">\n        </item>\n    </argument>\n    <dataSource name=\"mailchimp_errors_grid_data_source\">\n        <!--The data source-->\n        <argument name=\"dataProvider\" xsi:type=\"configurableObject\">\n            <argument name=\"class\" xsi:type=\"string\">Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider</argument>\n            <argument name=\"name\" xsi:type=\"string\">mailchimp_errors_grid_data_source</argument>\n            <argument name=\"primaryFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"requestFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"component\" xsi:type=\"string\">Magento_Ui/js/grid/provider</item>\n                    <item name=\"update_url\" xsi:type=\"url\" path=\"mui/index/render\"/>\n                    <item name=\"storageConfig\" xsi:type=\"array\">\n                        <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    </item>\n                </item>\n            </argument>\n        </argument>\n    </dataSource>\n\n    <container name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"template\" xsi:type=\"string\">ui/grid/toolbar</item>\n                <item name=\"stickyTmpl\" xsi:type=\"string\">ui/grid/sticky/toolbar</item>\n            </item>\n        </argument>\n    </container>\n\n    <listingToolbar name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"sticky\" xsi:type=\"boolean\">true</item>\n            </item>\n        </argument>\n        <bookmark name=\"bookmarks\"/>\n        <columnsControls name=\"columns_controls\"/>\n        <filters name=\"listing_filters\">\n            <filterSelect name=\"store_id\">\n                <argument name=\"optionsProvider\" xsi:type=\"configurableObject\">\n                    <argument name=\"class\" xsi:type=\"string\">Magento\\Store\\Ui\\Component\\Listing\\Column\\Store\\Options</argument>\n                </argument>\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"provider\" xsi:type=\"string\">${ $.parentName }</item>\n                        <item name=\"dataScope\" xsi:type=\"string\">store_id</item>\n                        <item name=\"caption\" xsi:type=\"string\" translate=\"true\">All Store Views</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">Store View</item>\n                    </item>\n                </argument>\n            </filterSelect>\n        </filters>\n        <paging name=\"listing_paging\"/>\n    </listingToolbar>\n\n\n    <columns name=\"mailchimp_errors_columns\">\n        <!--The list of columns-->\n        <selectionsColumn name=\"id\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">ID</item>\n                </item>\n            </argument>\n        </selectionsColumn>\n        <column name=\"regtype\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Type</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"title\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Title</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"status\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Status</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"errors\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Error</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"added_at\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Date</item>\n                </item>\n            </argument>\n        </column>\n        <actionsColumn name=\"actions\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Errors\\Grid\\Column\\Batch\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Action</item>\n                </item>\n            </argument>\n        </actionsColumn>\n\n    </columns>\n</listing>\n\n"
  },
  {
    "path": "view/adminhtml/ui_component/mailchimp_stores_grid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <argument name=\"data\" xsi:type=\"array\">\n        <item name=\"js_config\" xsi:type=\"array\">\n            <item name=\"provider\" xsi:type=\"string\">mailchimp_stores_grid.mailchimp_stores_grid_data_source</item>\n            <item name=\"deps\" xsi:type=\"string\">mailchimp_stores_grid.mailchimp_stores_grid_data_source</item>\n            <!--Declare the data source name which will be defined below-->\n        </item>\n        <item name=\"spinner\" xsi:type=\"string\">mailchimp_stores_columns</item>\n        <item name=\"buttons\" xsi:type=\"array\">\n            <item name=\"add\" xsi:type=\"array\">\n                <item name=\"name\" xsi:type=\"string\">add</item>\n                <item name=\"label\" xsi:type=\"string\" translate=\"true\">Create New Mailchimp Store</item>\n                <item name=\"class\" xsi:type=\"string\">primary</item>\n                <item name=\"url\" xsi:type=\"string\">mailchimp/stores/edit</item>\n            </item>\n        </item>\n    </argument>\n    <dataSource name=\"mailchimp_stores_grid_data_source\">\n        <!--The data source-->\n        <argument name=\"dataProvider\" xsi:type=\"configurableObject\">\n            <argument name=\"class\" xsi:type=\"string\">Magento\\Framework\\View\\Element\\UiComponent\\DataProvider\\DataProvider</argument>\n            <argument name=\"name\" xsi:type=\"string\">mailchimp_stores_grid_data_source</argument>\n            <argument name=\"primaryFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"requestFieldName\" xsi:type=\"string\">id</argument>\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"component\" xsi:type=\"string\">Magento_Ui/js/grid/provider</item>\n                    <item name=\"storageConfig\" xsi:type=\"array\">\n                        <item name=\"indexField\" xsi:type=\"string\">id</item>\n                        <item name=\"cacheRequests\" xsi:type=\"boolean\">false</item>\n                    </item>\n                    <item name=\"update_url\" xsi:type=\"url\" path=\"mui/index/render\"/>\n                </item>\n            </argument>\n        </argument>\n    </dataSource>\n    <!-- ... other block of code -->\n    <container name=\"listing_top\">\n        <argument name=\"data\" xsi:type=\"array\">\n            <item name=\"config\" xsi:type=\"array\">\n                <item name=\"template\" xsi:type=\"string\">ui/grid/toolbar</item>\n                <item name=\"stickyTmpl\" xsi:type=\"string\">ui/grid/sticky/toolbar</item>\n            </item>\n        </argument>\n    </container>\n    <listingToolbar name=\"listing_top\">\n        <bookmark name=\"bookmarks\"/>\n        <columnsControls name=\"columns_controls\"/>\n        <filters name=\"listing_filters\">\n            <filterSelect name=\"store_id\">\n                <argument name=\"optionsProvider\" xsi:type=\"configurableObject\">\n                    <argument name=\"class\" xsi:type=\"string\">Magento\\Store\\Ui\\Component\\Listing\\Column\\Store\\Options</argument>\n                </argument>\n                <argument name=\"data\" xsi:type=\"array\">\n                    <item name=\"config\" xsi:type=\"array\">\n                        <item name=\"provider\" xsi:type=\"string\">${ $.parentName }</item>\n                        <item name=\"dataScope\" xsi:type=\"string\">store_id</item>\n                        <item name=\"caption\" xsi:type=\"string\" translate=\"true\">All Store Views</item>\n                        <item name=\"label\" xsi:type=\"string\" translate=\"true\">Store View</item>\n                    </item>\n                </argument>\n            </filterSelect>\n        </filters>\n        <paging name=\"listing_paging\"/>\n    </listingToolbar>\n    <!-- ... other block of code -->\n    <columns name=\"mailchimp_stores_columns\">\n        <!--The list of columns-->\n        <column name=\"mc_account_name\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">MC Account name</item>\n                    <item name=\"sortOrder\" xsi:type=\"number\">30</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"name\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Store name</item>\n                    <item name=\"sortOrder\" xsi:type=\"number\">40</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"list_name\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">List name</item>\n                    <item name=\"sortOrder\" xsi:type=\"number\">50</item>\n                </item>\n            </argument>\n        </column>\n        <column name=\"email_address\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"filter\" xsi:type=\"string\">text</item>\n                    <item name=\"sorting\" xsi:type=\"string\">asc</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">Email</item>\n                    <item name=\"sortOrder\" xsi:type=\"number\">60</item>\n                </item>\n            </argument>\n        </column>\n        <actionsColumn name=\"actions\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Stores\\Grid\\Column\\Actions\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    <item name=\"sortOrder\" xsi:type=\"number\">70</item>\n                </item>\n            </argument>\n        </actionsColumn>\n    </columns>\n\n</listing>\n\n"
  },
  {
    "path": "view/adminhtml/ui_component/product_listing.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <columns name=\"product_columns\">\n        <column name=\"mailchimp_sync\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Listing\\Column\\Products\">\n            <settings>\n                <altField>mailchimp_sync</altField>\n                <hasPreview>0</hasPreview>\n                <addField>true</addField>\n                <label translate=\"true\">Mailchimp</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n    </columns>\n</listing> "
  },
  {
    "path": "view/adminhtml/ui_component/sales_order_grid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<listing xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc/ui_configuration.xsd\">\n    <columns name=\"sales_order_columns\">\n        <column name=\"mailchimp_sync\">\n            <settings>\n                <label translate=\"true\">Mailchimp Sync</label>\n                <bodyTmpl>ui/grid/cells/html</bodyTmpl>\n                <sortable>false</sortable>\n            </settings>\n        </column>\n        <actionsColumn name=\"mailchimp_links\" class=\"\\Ebizmarts\\MailChimp\\Ui\\Component\\Listing\\Column\\Monkey\">\n            <argument name=\"data\" xsi:type=\"array\">\n                <item name=\"config\" xsi:type=\"array\">\n                    <item name=\"indexField\" xsi:type=\"string\">id</item>\n                    <item name=\"label\" xsi:type=\"string\" translate=\"true\">MailChimp</item>\n                </item>\n            </argument>\n        </actionsColumn>\n    </columns>\n</listing>\n"
  },
  {
    "path": "view/adminhtml/web/css/styles.css",
    "content": "@font-face {\n    font-family: 'mailchimp';\n    src:  url('../fonts/mailchimp.eot?3g8ubh');\n    src:  url('../fonts/mailchimp.eot?3g8ubh#iefix') format('embedded-opentype'),\n    url('../fonts/mailchimp.ttf?3g8ubh') format('truetype'),\n    url('../fonts/mailchimp.woff?3g8ubh') format('woff'),\n    url('../fonts/mailchimp.svg?3g8ubh#mailchimp') format('svg');\n    font-weight: normal;\n    font-style: normal;}\n.admin__menu .item-mailchimp-menu.parent.level-0 > a:before {\n    font-family: 'mailchimp';\n    content: \"\\e991\"\n}\n\n.admin__data-grid-wrap .data-grid .data-grid-draggable .data-row .data-grid-thumbnail-cell .admin__control-thumbnail > img:before {\n    border:none;\n}\n\n.freddie {\n    background-image:url('../images/freddie.png');\n    background-repeat:no-repeat;\n    font-size:0px;\n    display:block;\n    background-size: 20px;\n    background-position: right bottom;\n}\n"
  },
  {
    "path": "view/adminhtml/web/js/apikey.js",
    "content": "/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\ndefine(\n    [\n        'jquery',\n        'Magento_Ui/js/modal/alert'\n    ],\n    function ($,alert) {\n        \"use strict\";\n\n        $.widget('mage.monkeyapikey', {\n            \"options\": {\n                \"apikeyUrl\": \"\"\n            },\n\n            _init: function () {\n                var apiUrl = this.options.apikeyUrl;\n                $('#stores_apikey').change(function () {\n                    // remove all items in list combo\n                    $('#stores_list_id').empty();\n                    // get the selected apikey\n                    var apiKey = $('#stores_apikey').find(':selected').val();\n                    // get the list for this apikey via ajax\n                    //var apiUrl = this.options.apikeyUrl;\n                    $.ajax({\n                        url: apiUrl,\n                        data: {'form_key':  window.FORM_KEY, 'apikey': apiKey, 'encrypt': 1},\n                        type: 'POST',\n                        dataType: 'json',\n                        showLoader: true\n                    }).done(function (data) {\n                        if (data.valid==1) {\n                            $.each(data.lists, function (i, item) {\n                                $('#stores_list_id').append($('<option>', {\n                                    value: item.id,\n                                    text: item.name\n                                }));\n                            });\n                        } else {\n                            alert({content:data.errormsg});\n                        }\n                    });\n                });\n            }\n        });\n        return $.mage.monkeyapikey;\n    }\n);"
  },
  {
    "path": "view/adminhtml/web/js/configapikey.js",
    "content": "/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\ndefine(\n    [\n        'jquery',\n        'Magento_Ui/js/modal/alert',\n        'Magento_Ui/js/modal/confirm'\n    ],\n    function ($, alert, confirmation) {\n        \"use strict\";\n\n        $.widget('mage.configmonkeyapikey', {\n            \"options\": {\n                \"storeUrl\": \"\",\n                \"detailsUrl\": \"\",\n                \"storeGridUrl\": \"\",\n                \"createWebhookUrl\": \"\",\n                \"getInterestUrl\": \"\",\n                \"resyncSubscribersUrl\": \"\",\n                \"resyncProductsUrl\": \"\",\n                \"fixMailchimpjsUrl\": \"\",\n                \"registerUrl\": \"\",\n                \"scope\": \"\",\n                \"scopeId\": \"\",\n                \"registerToken\": \"\",\n                \"switchurl\": \"\"\n            },\n\n            _init: function () {\n                var self = this;\n                if(!this.options.registerToken && $('#mailchimp_general_monkeystore').find(':selected').val() > 0) {\n                    self._showRegistationDetails();\n                }\n                $('#mailchimp_general_apikey').change(function () {\n                    var apiKey = $('#mailchimp_general_apikey').val();\n                    self._loadStores(apiKey);\n                });\n                $('#mailchimp_general_monkeystore').change(function () {\n                    self._loadDetails();\n                    // self._loadInterest();\n                });\n                $('#row_mailchimp_general_monkeystore').find('.note').append(' <a href=\"' + self.options.storeGridUrl + '\">here</a>');\n                if ($('#mailchimp_general_monkeystore option').length > 1) {\n                    $('#row_mailchimp_general_monkeystore .note').hide();\n                }\n                $('#mailchimp_general_webhook_create').click(function () {\n                    var apiKey = $('#mailchimp_general_apikey').val();\n                    var listId = $('#mailchimp_general_monkeylist').find(':selected').val();\n                    self._createWebhook(apiKey, listId);\n                });\n                $('#mailchimp_general_resync_subscribers').click(function () {\n                    var listId = $('#mailchimp_general_monkeylist').find(':selected').val();\n                    self._resyncSubscribers(listId);\n                });\n                $('#mailchimp_ecommerce_resync_products').click(function () {\n                    var mailchimpStoreId = $('#mailchimp_general_monkeystore').find(':selected').val();\n                    self._resyncProducts(mailchimpStoreId);\n                });\n                $('#mailchimp_general_fix_mailchimpjs').click(function () {\n                    self._fixMailchimpJS();\n                });\n                $('#mailchimp_ecommerce_active').change(function () {\n                    var ecommerceEnabled = $('#mailchimp_ecommerce_active').find(':selected').val();\n                    var abandonedCartEnabled = $('#mailchimp_abandonedcart_active').find(':selected').val();\n                    if (ecommerceEnabled == 0 && abandonedCartEnabled == 1) {\n                        self._changeEcommerce();\n                    }\n                });\n                $('#mailchimp_abandonedcart_active').change(function () {\n                    var ecommerceEnabled = $('#mailchimp_ecommerce_active').find(':selected').val();\n                    var abandonedCartEnabled = $('#mailchimp_abandonedcart_active').find(':selected').val();\n                    if (ecommerceEnabled == 0 && abandonedCartEnabled == 1) {\n                        self._changeAbandonedCart();\n                    }\n                });\n                $('#mailchimp_general_enable_support').change(function () {\n                    var supportenabled = $('#mailchimp_general_enable_support').find(':selected').val();\n                    self._switchsupport(supportenabled);\n                });\n                $('#mailchimp_support').click(function () {\n                    self._showSupport();\n                });\n                var ecommerceEnabled = $('#mailchimp_ecommerce_active').find(':selected').val();\n                var abandonedCartEnabled = $('#mailchimp_abandonedcart_active').find(':selected').val();\n                if (ecommerceEnabled == 0 && abandonedCartEnabled == 1) {\n                    self._changeAbandonedCart();\n                }\n                $('#mailchimp_ecommerce_campaign_action').attr('size',3);\n\n            },\n            _changeEcommerce: function () {\n                var self = this;\n                confirmation( {\n                        content: \"If you disable Ecommerce, we will disable Abandoned Cart\",\n                        actions: {\n                            confirm: function () {\n                                var tag = '#mailchimp_abandonedcart_active'\n                                $(tag).empty();\n                                $(tag).append($('<option>', {\n                                    value: \"0\",\n                                    text: 'No',\n                                    selected: \"selected\"\n                                }));\n                                $(tag).append($('<option>', {\n                                    value: \"1\",\n                                    text: 'Yes'\n                                }));\n                                self._hideAbandonedCart();\n                            },\n                            cancel: function () {\n                                var tag = '#mailchimp_ecommerce_active'\n                                $(tag).empty();\n                                $(tag).append($('<option>', {\n                                    value: \"0\",\n                                    text: 'No',\n                                }));\n                                $(tag).append($('<option>', {\n                                    value: \"1\",\n                                    text: 'Yes',\n                                    selected: \"selected\"\n                                }));\n                                self._showEcommerce();\n                            }\n                        }\n                    }\n                );\n            },\n            _changeAbandonedCart: function () {\n                var self = this;\n                confirmation( {\n                        content: \"If you enable Abandoned Cart we need to enable Ecommerce\",\n                        actions: {\n                            confirm: function () {\n                                var tag = '#mailchimp_ecommerce_active'\n                                $(tag).empty();\n                                $(tag).append($('<option>', {\n                                    value: \"0\",\n                                    text: 'No'\n                                }));\n                                $(tag).append($('<option>', {\n                                    value: \"1\",\n                                    text: 'Yes',\n                                    selected: \"selected\"\n                                }));\n                                self._showEcommerce();\n                            },\n                            cancel: function () {\n                                var tag = '#mailchimp_abandonedcart_active'\n                                $(tag).empty();\n                                $(tag).append($('<option>', {\n                                    value: \"0\",\n                                    text: 'No',\n                                    selected: \"selected\"\n                                }));\n                                $(tag).append($('<option>', {\n                                    value: \"1\",\n                                    text: 'Yes'\n                                }));\n                                self._hideAbandonedCart();\n                            }\n                        }\n                    }\n                );\n            },\n            _hideAbandonedCart: function () {\n                $(\"#row_mailchimp_abandonedcart_firstdate\").hide();\n                $(\"#row_mailchimp_abandonedcart_page\").hide();\n                $(\"#row_mailchimp_abandonedcart_save_email_in_quote\").hide();\n                $(\"#row_mailchimp_abandonedcart_create_abandonedcart_automation\").hide();\n            },\n            _showEcommerce: function () {\n                $(\"#row_mailchimp_ecommerce_all_customers\").show();\n                $(\"#mailchimp_ecommerce_all_customers\").show();\n                $(\"#row_mailchimp_ecommerce_customer_optin\").show();\n                $(\"#mailchimp_ecommerce_customer_optin\").show();\n                $(\"#row_mailchimp_ecommerce_firstdate\").show();\n                $(\"#mailchimp_ecommerce_firstdate\").show();\n                $(\"#row_mailchimp_ecommerce_send_promo\").show();\n                $(\"#mailchimp_ecommerce_send_promo\").show();\n                $(\"#row_mailchimp_ecommerce_including_taxes\").show();\n                $(\"#mailchimp_ecommerce_including_taxes\").show();\n                $(\"#row_mailchimp_ecommerce_reset_errors_retry\").show();\n                $(\"#mailchimp_ecommerce_reset_errors_retry\").show();\n                $(\"#row_mailchimp_ecommerce_reset_errors_noretry\").show();\n                $(\"#mailchimp_ecommerce_reset_errors_noretry\").show();\n                $(\"#row_mailchimp_ecommerce_clean_errors_months\").show();\n                $(\"#mailchimp_ecommerce_clean_errors_months\").show();\n                $(\"#row_mailchimp_ecommerce_delete_store\").show();\n                $(\"#mailchimp_ecommerce_delete_store\").show();\n                $(\"#row_mailchimp_ecommerce_resync_products\").show();\n                $(\"#mailchimp_ecommerce_resync_products\").show();\n            },\n            _fixMailchimpJS: function ()\n            {\n                var fixMailchimpjsUrl = this.options.fixMailchimpjsUrl;\n                var scope = this.options.scope;\n                var scopeId = this.options.scopeId;\n\n                $.ajax({\n                    url: fixMailchimpjsUrl,\n                    data: {'form_key': window.FORM_KEY,'scope': scope, 'scopeId': scopeId},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                    if (data.valid == 0) {\n                        alert({content: 'Error: can\\'t fix it'});\n                    } else if (data.valid == 1) {\n                        alert({content: 'Frontend fixed, please refresh your cache'});\n                    }\n                });\n            },\n            _resyncSubscribers: function (listId) {\n                var resyncSubscribersUrl = this.options.resyncSubscribersUrl;\n                $.ajax({\n                    url: resyncSubscribersUrl,\n                    data: {'form_key': window.FORM_KEY, 'listId': listId},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                    if (data.valid == 0) {\n                        alert({content: 'Error: can\\'t resync your subscribers'});\n                    } else if (data.valid == 1) {\n                        alert({content: 'All subscribers marked for resync'});\n                    }\n                });\n            },\n            _resyncProducts: function (mailchimpStoreId) {\n                var resyncProductsUrl = this.options.resyncProductsUrl;\n                $.ajax({\n                    url: resyncProductsUrl,\n                    data: {'form_key': window.FORM_KEY, 'mailchimpStoreId': mailchimpStoreId},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                    if (data.valid == 0) {\n                        alert({content: 'Error: can\\'t resync your products'});\n                    } else if (data.valid == 1) {\n                        alert({content: 'All products marked for resync'});\n                    }\n                });\n            },\n            _createWebhook: function (apiKey, listId) {\n                var createWebhookUrl = this.options.createWebhookUrl;\n                var scope = this.options.scope;\n                var scopeId = this.options.scopeId;\n                $.ajax({\n                    url: createWebhookUrl,\n                    data: {'form_key': window.FORM_KEY, 'apikey': apiKey, 'listId': listId, 'scope': scope, 'scopeId': scopeId},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                    if (data.valid == 0) {\n                        alert({content: 'Error: can\\'t create WebHook. Your WebHook is already created or your web is private'});\n                    } else if (data.valid == 1) {\n                        alert({content: 'WebHook created'});\n                    }\n                });\n            },\n            _loadStores: function (apiKey) {\n                var self = this;\n                var storeUrl = this.options.storeUrl;\n                // remove all items in list combo\n                $('#mailchimp_general_monkeystore').empty();\n                // get the selected apikey\n                $('#mailchimp_general_monkeystore').append($('<option>', {\n                    value: -1,\n                    text: 'Select one Mailchimp Store'\n                }));\n                $('#mailchimp_general_monkeylist').append($('<option>', {\n                    value: -1,\n                    text: 'Select one Mailchimp Store'\n                }));\n                // get the list for this apikey via ajax\n                $.ajax({\n                    url: storeUrl,\n                    data: {'form_key': window.FORM_KEY, 'apikey': apiKey, 'encrypt': 0},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                    if (data.valid == 1) {\n                        var unique = data.stores.length;\n                        $.each(data.stores, function (i, item) {\n                            if (unique == 1) {\n                                $('#mailchimp_general_monkeystore').append($('<option>', {\n                                    value: item.id,\n                                    text: item.name,\n                                    selected: \"selected\"\n                                }));\n                            } else {\n                                $('#mailchimp_general_monkeystore').append($('<option>', {\n                                    value: item.id,\n                                    text: item.name\n                                }));\n                            }\n                        });\n                        if ($('#mailchimp_general_monkeystore option').length > 1) {\n                            $('#row_mailchimp_general_monkeystore').find('.note').hide();\n                        } else {\n                            $('#row_mailchimp_general_monkeystore').find('.note').show();\n                        }\n                        self._loadDetails();\n                    } else {\n                        if (data.errormsg != '') {\n                            alert({content: data.errormsg});\n                        } else {\n                            alert({content: \"API Key Invalid\"});\n                        }\n                    }\n                });\n            },\n            _showSupport: function () {\n                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.\"});\n            },\n            _showRegistationDetails: function () {\n                var registerUrl = this.options.registerUrl;\n                var detailsUrl = this.options.detailsUrl;\n                var accountdata = {};\n                var apiKey = $('#mailchimp_general_apikey').val();\n                var scope = this.options.scope;\n                var scopeId = this.options.scopeId;\n                var selectedStore = $('#mailchimp_general_monkeystore').find(':selected').val();\n                var encrypt = 0;\n                if (apiKey == '******') {\n                    encrypt = 3;\n                }\n\n                $.ajax({\n                    url: detailsUrl,\n                    data: {'form_key': window.FORM_KEY, 'apikey': apiKey, \"store\": selectedStore, 'encrypt': encrypt, \"scope\": scope, \"scopeId\": scopeId},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                        $.each(data, function (i, item) {\n                            if (item.hasOwnProperty('label')) {\n                                $('#mailchimp_general_account_details_ul').append('<li>' + item.label + ' ' + item.value + '</li>');\n                            } else if (item.hasOwnProperty('code')) {\n                                accountdata[item.code] = {'value': item.value, 'html': item.html};\n                            }\n                        });\n                        var outputtext = \"<table style='border-collapse; margin-left: 10px;' >\"\n                        for (const key in accountdata) {\n                            if (accountdata.hasOwnProperty(key)) {\n                                outputtext += '<tr><td style=\"border: 1px solid black;padding-left: 10px;padding-right: 10px;\"><strong>' + accountdata[key]['html'] + '</strong></td><td style=\"border: 1px solid black;padding-left: 10px;padding-right: 10px;\">' + accountdata[key]['value'] + '</td></tr>';\n                            }\n                        }\n                        outputtext += '</table>';\n                        confirmation({\n                                content: \"Confirm your data <br><br>\" + outputtext,\n                                actions: {\n                                    confirm: function () {\n                                        $.ajax({\n                                            url: registerUrl,\n                                            dataType: 'json',\n                                            data: {\n                                                'form_key': window.FORM_KEY,\n                                                'apikey': apiKey,\n                                                \"data\": accountdata,\n                                                'scope': scope,\n                                                'scopeId': scopeId\n                                            },\n                                            type: 'POST',\n                                            showLoader: true\n                                        }).done(function (data) {\n                                            if (data.error == 0) {\n                                                alert({content: 'You confirm, thanks ' + data.token});\n                                            } else {\n                                                alert({content: \"Something went wrong!\"});\n                                            }\n                                        });\n                                    },\n                                    cancel: function () {\n                                        $('#mailchimp_general_monkeystore option[value=\"-1\"]').attr('selected', 'selected');\n                                        $('#mailchimp_general_monkeylist').empty();\n                                    }\n                                }\n                            }\n                        );\n                    }\n                )\n            },\n            _switchsupport: function (supportenabled) {\n                var scope = this.options.scope;\n                var scopeId = this.options.scopeId;\n                var switchurl = this.options.switchurl;\n\n                $.ajax({\n                    url: switchurl,\n                    data: {'form_key': window.FORM_KEY, 'scope': scope, 'scopeId': scopeId,'onoff': supportenabled},\n                    dataType: 'json',\n                    type: 'POST',\n                    showLoader: true\n                }).done(function (data) {\n                    if (data.error == 1) {\n                        alert({content: data.message});\n                        $('#mailchimp_general_enable_support option[value=\"0\"]').prop('selected', 'selected');\n                    }\n                })\n            },\n            _loadDetails: function () {\n                var registerUrl = this.options.registerUrl;\n                var detailsUrl = this.options.detailsUrl;\n                var interestUrl = this.options.getInterestUrl;\n                var apiKey = $('#mailchimp_general_apikey').val();\n                var selectedStore = $('#mailchimp_general_monkeystore').find(':selected').val();\n                var encrypt = 0;\n                var accountdata = {};\n                var scope = this.options.scope;\n                var scopeId = this.options.scopeId;\n\n                if (apiKey == '******') {\n                    encrypt = 3;\n                }\n                $('#mailchimp_general_account_details_ul').empty();\n                $('#mailchimp_general_monkeylist').empty();\n                $.ajax({\n                    url: detailsUrl,\n                    data: {'form_key': window.FORM_KEY, 'apikey': apiKey, \"store\": selectedStore, 'encrypt': encrypt, 'scope': scope, 'scopeId': scopeId},\n                    type: 'GET',\n                    dataType: 'json',\n                    showLoader: true\n                }).done(function (data) {\n                    $.each(data, function (i, item) {\n                        if (item.hasOwnProperty('label')) {\n                            $('#mailchimp_general_account_details_ul').append('<li>' + item.label + ' ' + item.value + '</li>');\n                        } else if (item.hasOwnProperty('code')) {\n                            accountdata[item.code] = {'value': item.value,'html':item.html};\n                        }\n                    });\n                    if (data.list_id) {\n                        $('#mailchimp_general_monkeylist').append($('<option>', {\n                            value: data.list_id,\n                            text: data.list_name,\n                            selected: \"selected\"\n                        }));\n                    }\n                    var selectedList = data.list_id;\n                    $('#mailchimp_general_interest').empty();\n                    $.ajax({\n                        url: interestUrl,\n                        data: {'form_key': window.FORM_KEY, 'apikey': apiKey, \"list\": selectedList, \"encrypt\": encrypt},\n                        type: 'GET',\n                        dataType: 'json',\n                        showLoader: true\n                    }).done(function (data) {\n                        if (data.error == 0) {\n                            if (data.data.length) {\n                                $.each(data.data, function (i, item) {\n                                    $('#mailchimp_general_interest').append($('<option>', {\n                                        value: item.id,\n                                        text: item.title\n                                    }));\n                                });\n                            } else {\n                                $('#mailchimp_general_interest').append($('<optgroup>', {\n                                    label: '---No Data---'\n                                }));\n                            }\n                        }\n                    });\n                    if ($('#mailchimp_general_monkeystore').find(':selected').val() <= 0) {\n                        return;\n                    }\n\n                    var outputtext = \"<table style='border-collapse; margin-left: 10px;' >\"\n                    for (const key in accountdata) {\n                        if (accountdata.hasOwnProperty(key)) {\n                            outputtext += '<tr><td style=\"border: 1px solid black;padding-left: 10px;padding-right: 10px;\"><strong>'+accountdata[key]['html'] + '</strong></td><td style=\"border: 1px solid black;padding-left: 10px;padding-right: 10px;\">' + accountdata[key]['value']+'</td></tr>';\n                        }\n                    }\n                    outputtext += '</table>';\n                    confirmation( {\n                            content: \"Confirm your data <br><br>\"+outputtext,\n                            actions: {\n                                confirm: function () {\n                                    $.ajax({\n                                        url: registerUrl,\n                                        dataType: 'json',\n                                        data: {'form_key': window.FORM_KEY, 'apikey': apiKey, \"data\": accountdata,'scope': scope, 'scopeId': scopeId},\n                                        type: 'POST',\n                                        showLoader: true\n                                    }).done(function (data) {\n                                        if (data.error == 0) {\n                                            alert({content: 'You confirm, thanks '+data.token});\n                                        } else {\n                                            alert({content: \"Something went wrong!\"});\n                                        }\n                                    });\n                                },\n                                cancel: function () {\n                                    $('#mailchimp_general_monkeystore option[value=\"-1\"]').attr('selected', 'selected');\n                                    $('#mailchimp_general_monkeylist').empty();\n                                }\n                            }\n                        }\n                    );\n                });\n            }\n        });\n        return $.mage.configmonkeyapikey;\n    }\n);\n"
  },
  {
    "path": "view/adminhtml/web/js/mailchimpconfirmation.js",
    "content": "/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\ndefine(\n    [\n        'jquery',\n        'Magento_Ui/js/modal/confirm',\n        'Magento_Ui/js/modal/alert'\n    ], function ($ , confirmation, alert) {\n        'use strict';\n\n        window.mailchimpdeleteconfirmation = function (ajaxurl) {\n            var message = 'Are you sure you want to do this?';\n            confirmation( {\n                content: message,\n                actions: {\n                    confirm: function () {\n                        $.ajax({\n                            url: ajaxurl,\n                            data: {form_key: window.FORM_KEY},\n                            type: 'POST',\n                            success: function (retdata) {\n                                if (retdata.valid == 0) {\n                                    alert({\n                                        content: 'Error: ' + data.message\n                                    });\n                                }\n                                else if (retdata.valid == 1) {\n                                    alert({\n                                        content: 'Operation OK'\n                                    });\n                                }\n                            }\n                        }).done(function (a) {\n                            console.log(a);\n                        });\n                    }\n                }\n            });\n            return false;\n        }\n    }\n);\n"
  },
  {
    "path": "view/frontend/layout/checkout_onepage_success.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <body>\n        <referenceContainer name=\"order.success.additional.info\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Checkout\\Success\" ifconfig=\"mailchimp/general/interest_in_success\" name=\"mailchimp.order.success\" template=\"Ebizmarts_MailChimp::checkout/order/success.phtml\"/>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/frontend/layout/default.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n      xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <body>\n        <referenceBlock name=\"head.additional\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Mailchimpjs\" name=\"mailchimp.block.mcjs\" template=\"Ebizmarts_MailChimp::mailchimpjs.phtml\" ifconfig=\"mailchimp/general/active\"/>\n        </referenceBlock>\n        <referenceContainer name=\"content\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Catcher\" name=\"mailchimp.block.catcher\" template=\"Ebizmarts_MailChimp::catcher.phtml\" ifconfig=\"mailchimp/general/active\"/>\n        </referenceContainer>\n        <referenceBlock name=\"form.subscribe\">\n            <action method=\"setTemplate\" ifconfig=\"mailchimp/general/popup_form\">\n                <argument name=\"template\" xsi:type=\"string\">Ebizmarts_MailChimp::footer.phtml</argument>\n            </action>\n        </referenceBlock>\n    </body>\n</page>\n"
  },
  {
    "path": "view/frontend/layout/mailchimp_cart_loadquote.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n/**\n * ebizmarts_mailchimp_loadquote_index.xml\n *\n * @copyright Copyright © 2017 Ebizmarts Corp.. All rights reserved.\n * @author    info@ebizmarts.com\n */\n-->\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" layout=\"1column\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <body>\n        <referenceContainer name=\"content\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Loadquote\" name=\"mailchimp.loadquote\" ifconfig=\"mailchimp/general/active\" cacheable=\"false\"/>\n        </referenceContainer>\n    </body>\n</page>\n"
  },
  {
    "path": "view/frontend/layout/newsletter_manage_index.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n/**\n * Ebizmarts_MailChimp\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n-->\n<page xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:View/Layout/etc/page_configuration.xsd\">\n    <body>\n        <referenceBlock name=\"customer_newsletter\">\n            <block class=\"Ebizmarts\\MailChimp\\Block\\Newsletter\"  name=\"customer.form.newsletter.extra\" template=\"form/newsletter.phtml\" ifconfig=\"mailchimp/general/active\"/>\n        </referenceBlock>\n    </body>\n</page>\n"
  },
  {
    "path": "view/frontend/requirejs-config.js",
    "content": "/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\n\nvar config = {\n    \"map\": {\n        \"*\": {\n            campaigncatcher: 'Ebizmarts_MailChimp/js/campaigncatcher'\n        }\n    }\n};"
  },
  {
    "path": "view/frontend/templates/catcher.phtml",
    "content": "<div id=\"monkey_campaign\" style=\"display:none;\"\n     data-mage-init='{\"campaigncatcher\":{\"checkCampaignUrl\": \"<?= $block->escapeUrl($block->getUrl('mailchimp/campaign/check'));?>\"}}'>\n</div>\n"
  },
  {
    "path": "view/frontend/templates/checkout/order/success.phtml",
    "content": "<?php\n/**\n * @var $block \\Ebizmarts\\MailChimp\\Block\\checkout\\Success\n */\n$interest = $block->getInterest();\n//echo $interest;\n?>\n<p>\n    <?= $block->escapeHtml($block->getMessageBefore()) ?>\n<form class=\"form\" action=\"<?= $block->escapeUrl($block->getFormUrl()) ?>\" method=\"get\" id=\"mailchimp-groups\">\n    <fieldset class=\"fieldset\">\n            <?php foreach ($interest as $i): ?>\n                <div class=\"field\">\n                    <label class=\"label\" for=\"<?= $block->escapeHtml($i['interest']['id']) ?>\">\n                        <span><?= $block->escapeHtml($i['interest']['title']) ?></span>\n                    </label>\n                    <div class=\"control\">\n                        <div class=\"fields\">\n                            <?php switch ($i['interest']['type']):\n                                case 'checkboxes': ?>\n                                    <ul class=\"field\" style=\"list-style: none\">\n                                    <?php foreach ($i['category'] as $c): ?>\n                                        <li class=\"field no-label\">\n                                            <input class=\"\"\n                                                   name=\"group[<?=  $block->escapeHtml($i['interest']['id']) ?>][<?= $block->escapeHtml($c['id']) ?>]\"\n                                                   type=\"checkbox\"\n                                                   value=\"<?= $block->escapeHtml($c['id']) ?>\"\n                                                   id=\"<?= $block->escapeHtml('mailchimp_group_'.$c['id']) ?>\"\n                                                   title=\"<?= $block->escapeHtml($c['name']) ?>\"\n                                                   <?php if ($c['checked']) { echo $block->escapeHtml('checked');} ?>\n                                            />\n                                            <label class=\"field label\"><?= $block->escapeHtml($c['name']) ?></label>\n                                        </li>\n                                    <?php endforeach; ?>\n                                    </ul>\n                                <?php       break;\n                                case 'dropdown': ?>\n                                    <div class=\"field no-label\">\n                                        <select class=\"field\"\n                                                name=\"group[<?= $block->escapeHtml($i['interest']['id']) ?>]\"\n                                                id=\"<?= $block->escapeHtml('mailchimp_group_'.$i['interest']['id']) ?>\"\n                                                title=\"<?= $block->escapeHtml($i['interest']['title']) ?>\">\n                                            <option value=\"\"></option>\n                                            <?php foreach ($i['category'] as $c): ?>\n                                                <option value=\"<?= $block->escapeHtml($c['id'])?>\" <?php if ($c['checked']) { echo $block->escapeHtml('selected'); } ?>><?= $block->escapeHtml($c['name']) ?></option>\n                                            <?php endforeach; ?>\n                                        </select>\n\n                                    </div>\n                                <?php       break;\n                                case 'radio': ?>\n                                    <ul class=\"field\">\n                                        <?php foreach ($i['category'] as $c): ?>\n                                            <li class=\"field no-label\" style=\"list-style: none\">\n                                                <input class=\"\"\n                                                       name=\"group[<?= $block->escapeHtml($i['interest']['id']) ?>]\"\n                                                       type=\"radio\"\n                                                       value=\"<?= $block->escapeHtml($c['id']) ?>\"\n                                                       id=\"<?= $block->escapeHtml('mailchimp_group_'.$c['id']) ?>\"\n                                                       title=\"<?= $block->escapeHtml($c['name']) ?>\"\n                                                    <?php if ($c['checked']) { echo $block->escapeHtml('checked');} ?>\n                                                />\n                                                <label class=\"field label\"><?= $block->escapeHtml($c['name'])?></label>\n                                            </li>\n                                        <?php endforeach; ?>\n                                    </ul>\n                                <?php       break; ?>\n                            <?php endswitch; ?>\n                        </div>\n                    </div>\n                </div>\n            <?php endforeach; ?>\n    </fieldset>\n    <div class=\"actions-toolbar\">\n        <div class=\"primary\">\n            <button type=\"submit\"\n                    class=\"action primary\"\n                    title=\"<?= $block->escapeHtml(__('Subscribe to more detailed newsletters')) ?>\">\n                <span><?= $block->escapeHtml( __('Subscribe to more detailed newsletters')) ?></span>\n            </button>\n        </div>\n    </div>\n</form>\n<?= $block->escapeHtml($block->getMessageAfter()) ?>\n\n</p>\n"
  },
  {
    "path": "view/frontend/templates/footer.phtml",
    "content": "<div class=\"block newsletter\">\n    <div class=\"title\"><strong><?= $block->escapeHtml(__('Newsletter')) ?></strong></div>\n    <div class=\"content\">\n        <button class=\"action subscribe primary\"\n                id=\"mailchimp-subscribe\"\n                title=\"<?= $block->escapeHtmlAttr(__('Subscribe')) ?>\"\n                aria-label=\"Subscribe\">\n            <span><?= $block->escapeHtml(__('Subscribe')) ?></span>\n        </button>\n    </div>\n</div>\n\n<script>\n    require([\n        'jquery',\n        'popupWindow'\n    ], function ($) {\n        'use strict';\n\n        $(\"#mailchimp-subscribe\").popupWindow({\n            \"windowURL\": \"<?= $block->escapeUrl($block->getPopupUrl()); ?>\",\n            \"windowName\": \"Subscribe\",\n            \"width\": 800,\n            \"height\": 800,\n            \"left\": 0,\n            \"top\": 0,\n            \"resizable\": 1,\n            \"scrollbars\": 1\n        });\n    });\n</script>\n"
  },
  {
    "path": "view/frontend/templates/form/newsletter.phtml",
    "content": "<?php\n/**\n * @var $block \\Ebizmarts\\MailChimp\\Block\\Newsletter\n */\n$interest = $block->getInterest();\n?>\n    <fieldset class=\"fieldset\">\n        <?php foreach($interest as $i): ?>\n            <div class=\"field\">\n                <label class=\"label\" for=\"<?= $block->escapeHtml($i['interest']['id']) ?>\">\n                    <span><?= $block->escapeHtml($i['interest']['title']) ?></span>\n                </label>\n                <div class=\"control\">\n                    <div class=\"fields\">\n                        <?php switch ($i['interest']['type']):\n                            case 'checkboxes': ?>\n                                <ul class=\"field\" style=\"list-style: none\">\n                                    <?php foreach ($i['category'] as $c): ?>\n                                        <li class=\"field no-label\">\n                                            <input class=\"\"\n                                                   name=\"group[<?= $block->escapeHtml($i['interest']['id']) ?>][<?= $block->escapeHtml($c['id'])?>]\"\n                                                   type=\"checkbox\"\n                                                   value=\"<?= $block->escapeHtml($c['id']) ?>\"\n                                                   id=\"<?= $block->escapeHtml('mailchimp_group_'.$c['id']) ?>\"\n                                                   title=\"<?= $block->escapeHtml($c['name']) ?>\"\n                                                <?php if ($c['checked']) { echo $block->escapeHtml('checked');} ?>\n                                            />\n                                            <label class=\"field label\"><?= $block->escapeHtml($c['name'])?></label>\n                                        </li>\n                                    <?php endforeach; ?>\n                                </ul>\n                                <?php       break;\n                            case 'dropdown': ?>\n                                <div class=\"field no-label\">\n                                    <select class=\"field\"\n                                            name=\"group[<?= $block->escapeHtml($i['interest']['id']) ?>]\"\n                                            id=\"<?= $block->escapeHtml('mailchimp_group_'.$i['interest']['id']) ?>\"\n                                            title=\"<?= $block->escapeHtml($i['interest']['title']) ?>\">\n                                        <option value=\"\"></option>\n                                        <?php foreach ($i['category'] as $c): ?>\n                                            <option value=\"<?= $block->escapeHtml($c['id']) ?>\" <?php if ($c['checked']) { echo $block->escapeHtml('selected'); } ?>><?= $block->escapeHtml($c['name']) ?></option>\n                                        <?php endforeach; ?>\n                                    </select>\n\n                                </div>\n                                <?php       break;\n                            case 'radio': ?>\n                                <ul class=\"field\">\n                                    <?php foreach ($i['category'] as $c): ?>\n                                        <li class=\"field no-label\" style=\"list-style: none\">\n                                            <input class=\"\"\n                                                   name=\"group[<?= $block->escapeHtml($i['interest']['id']) ?>]\"\n                                                   type=\"radio\"\n                                                   value=\"<?= $block->escapeHtml($c['id']) ?>\"\n                                                   id=\"<?= $block->escapeHtml('mailchimp_group_'.$c['id']) ?>\"\n                                                   title=\"<?= $block->escapeHtml($c['name']) ?>\"\n                                                <?php if ($c['checked']) { echo $block->escapeHtml('checked');} ?>\n                                            />\n                                            <label class=\"field label\"><?= $block->escapeHtml($c['name'])?></label>\n                                        </li>\n                                    <?php endforeach; ?>\n                                </ul>\n                                <?php       break; ?>\n                            <?php endswitch; ?>\n                    </div>\n                </div>\n            </div>\n        <?php endforeach; ?>\n    </fieldset>\n"
  },
  {
    "path": "view/frontend/templates/loadquote.phtml",
    "content": "<?php\n/**\n * loadquote\n *\n * @copyright Copyright © 2017 Ebizmarts Corp.. All rights reserved.\n * @author    info@ebizmarts.com\n */\n?>\n<?php\n/** @var \\Ebizmarts\\MailChimp\\Block\\Loadquote $block  */\n// Add your template code here ...\n\n?>\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "view/frontend/templates/mailchimpjs.phtml",
    "content": "<?php\n    $url = $block->getJsUrl();\n?>\n<script\" src=\"<?= $block->escapeHtml($url);?>\" defer></script>\n"
  },
  {
    "path": "view/frontend/web/js/campaigncatcher.js",
    "content": "/**\n * Ebizmarts_MailChimp Magento JS component\n *\n * @category    Ebizmarts\n * @package     Ebizmarts_MailChimp\n * @author      Ebizmarts Team <info@ebizmarts.com>\n * @copyright   Ebizmarts (http://ebizmarts.com)\n * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)\n */\ndefine(\n    [\n        'jquery',\n        'mage/cookies'\n    ],\n    function ($) {\n        \"use strict\";\n\n        $.widget('mage.campaigncatcher', {\n            \"options\": {\n                \"checkCampaignUrl\": \"\"\n            },\n\n            _init: function () {\n                var self = this;\n                $(document).ready(function () {\n                    var path = location;\n                    var urlparams = null;\n                    var isGet = path.search.search('\\\\?');\n                    var mc_cid = null;\n                    var isMailchimp = false;\n                    var checkCampaignUrl = self.options.checkCampaignUrl;\n                    if(isGet != -1) {\n                        urlparams = self.getUrlVars();\n                        urlparams.forEach(function (item) {\n                            if (item.key=='utm_source') {\n                                var reg = /^mailchimp$/;\n                                if (reg.exec(item.value)) {\n                                    isMailchimp = true;\n                                }\n                            } else {\n                                if (item.key=='mc_cid') {\n                                    mc_cid = item.value;\n                                }\n                            }\n                        });\n                    } else {\n                        urlparams = path.href.split('/');\n                        var utmIndex = $.inArray('utm_source', urlparams);\n                        var mccidIndex = $.inArray('mc_cid', urlparams);\n                        if (utmIndex != -1) {\n                            var value = urlparams[utmIndex + 1];\n                            var reg = /^mailchimp$/;\n                            if (reg.exec(value)) {\n                                isMailchimp = true;\n                            }\n                        } else {\n                            if (mccidIndex != -1) {\n                                mc_cid = urlparams[mccidIndex + 1];\n                            }\n                        }\n                    }\n                    if (mc_cid && !isMailchimp) {\n                        $.ajax({\n                            url: checkCampaignUrl + 'mc_cid/' + mc_cid + '/',\n                            type: 'GET',\n                            dataType: 'json',\n                            cache: true,\n                            showLoader: false\n                        }).done(function (data) {\n                            if (data.valid==0) {\n                                $.mage.cookies.clear('mailchimp_campaign_id');\n                                $.mage.cookies.set('mailchimp_landing_page', location);\n                            } else if (data.valid==1) {\n                                $.mage.cookies.set('mailchimp_campaign_id' , mc_cid);\n                                $.mage.cookies.set('mailchimp_landing_page', location);\n                            }\n                        });\n                    }\n\n                    if (isMailchimp) {\n                        $.mage.cookies.clear('mailchimp_campaign_id');\n                        $.mage.cookies.set('mailchimp_landing_page', location);\n                    }\n                });\n            },\n            getUrlVars: function() {\n                var vars = [];\n                var i = 0;\n                var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {\n                    vars[i] = {'value':value,'key':key};\n                    i++;\n                });\n                return vars;\n            }\n        });\n        return $.mage.campaigncatcher;\n    }\n);\n"
  }
]