diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c7fdbd59..8492bc54e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,17 +1,34 @@ # Changelog -## [1.1.17](https://github.com/mailchimp/mc-magento/releases/tag/1.1.17) - 2019-07-04 +## [1.1.18](https://github.com/mailchimp/mc-magento/releases/tag/1.1.18) - 2019-09-13 **Fixed** -- Currency discrepancy in order confirmation email [\#982](https://github.com/mailchimp/mc-magento/issues/982) -- Fix subscription confirmation email when "Subscribe all customers to the newsletter" is enabled [\#978](https://github.com/mailchimp/mc-magento/issues/978) -- Errors saved in mailchimp_sync_ecommerce_data table may not set the sync_modified value to 0 [\#976](https://github.com/mailchimp/mc-magento/issues/976) -- Fix for infinite sync of modified orders containing only unsupported products [\#970](https://github.com/mailchimp/mc-magento/issues/970) -- Promo codes unexpectedly deleted from Mailchimp [\#967](https://github.com/mailchimp/mc-magento/issues/967) -- Unknown column 'at_special_from_date_default.value' in 'on clause' [\#964](https://github.com/mailchimp/mc-magento/issues/964) -- Remove error message when resend an item with error [\#963](https://github.com/mailchimp/mc-magento/issues/963) -- Customer and subscriber with same email sent to mailchimp with different id [\#952](https://github.com/mailchimp/mc-magento/issues/952) -- getLastRealOrder() doesn't exist [\#946](https://github.com/mailchimp/mc-magento/issues/946) +- Product resend internal problem [\#1066](https://github.com/mailchimp/mc-magento/issues/1066) +- Notice: Undefined index: NOT SENT in app/code/community/Ebizmarts/MailChimp/Helper/Data.php [\#1050](https://github.com/mailchimp/mc-magento/issues/1050) +- Use empty function correctly [\#1039](https://github.com/mailchimp/mc-magento/issues/1039) +- Fix for bug preventing carts from synchronising [\#1029](https://github.com/mailchimp/mc-magento/issues/1029) +- Problems when resending Ecommerce Data [\#1024](https://github.com/mailchimp/mc-magento/issues/1024) +- PHP notice when MC API call fails [\#1021](https://github.com/mailchimp/mc-magento/issues/1021) +- Cannot resend Ecommerce data from particular scope [\#1017](https://github.com/mailchimp/mc-magento/issues/1017) +- Handle json_encode errors correctly [\#1010](https://github.com/mailchimp/mc-magento/issues/1010) **Changed** +- Fix for re-using synch batch models causing batch responses to not be processed [\#1057](https://github.com/mailchimp/mc-magento/issues/1057) +- Apply MEQP1 code standar [\#1055](https://github.com/mailchimp/mc-magento/issues/1055) +- Validate API key field at Mailchimp configuration [\#1052](https://github.com/mailchimp/mc-magento/issues/1052) +- Add Invalid API Key message when adding a new Mailchimp Store [\#1045](https://github.com/mailchimp/mc-magento/issues/1045) +- Remove redundant system config and template file [\#1043](https://github.com/mailchimp/mc-magento/pull/1043) +- Stop flagging Customers as modified after an order is made. [\#1027](https://github.com/mailchimp/mc-magento/issues/1027) +- Improve batch behavior [\#1025](https://github.com/mailchimp/mc-magento/issues/1025) +- Serialize/Unserialize deprecated - MEQP [\#1019](https://github.com/mailchimp/mc-magento/issues/1019) +- Improve performance when resetting errors [\#975](https://github.com/mailchimp/mc-magento/issues/975) +- Maximum # Merge fields in MC [\#957](https://github.com/mailchimp/mc-magento/issues/957) +- How can we clean the table mailchimp_ecommerce_sync_data [\#897](https://github.com/mailchimp/mc-magento/issues/897) +- Certain Merge fields not transferred [\#425](https://github.com/mailchimp/mc-magento/issues/425) + +## [1.1.17](https://github.com/mailchimp/mc-magento/releases/tag/1.1.17) - 2019-07-23 +**Changed** +- Avoid sending Subscriber via cron job when setting "Use Magento Emails" enabled. [\#996](https://github.com/mailchimp/mc-magento/issues/996) +- Rename delete customer account option [\#992](https://github.com/mailchimp/mc-magento/issues/992) +- Coding standards fix [\#989](https://github.com/mailchimp/mc-magento/pull/989) - Change "List" appearances to "Audience" [\#977](https://github.com/mailchimp/mc-magento/issues/977) - Encrypt sensitive data [\#955](https://github.com/mailchimp/mc-magento/issues/955) - Improve logging [\#947](https://github.com/mailchimp/mc-magento/pull/947) @@ -21,6 +38,18 @@ - Add some js in the admin to avoid save before continue [\#649](https://github.com/mailchimp/mc-magento/issues/649) - Get guest information from orders made with the same email address [\#545](https://github.com/mailchimp/mc-magento/issues/545) +**Fixed** +- Error subscribing customer from backend. [\#990](https://github.com/mailchimp/mc-magento/issues/990) +- Currency discrepancy in order confirmation email [\#982](https://github.com/mailchimp/mc-magento/issues/982) +- Fix subscription confirmation email when "Subscribe all customers to the newsletter" is enabled [\#978](https://github.com/mailchimp/mc-magento/issues/978) +- Errors saved in mailchimp_sync_ecommerce_data table may not set the sync_modified value to 0 [\#976](https://github.com/mailchimp/mc-magento/issues/976) +- Fix for infinite sync of modified orders containing only unsupported products [\#970](https://github.com/mailchimp/mc-magento/issues/970) +- Promo codes unexpectedly deleted from Mailchimp [\#967](https://github.com/mailchimp/mc-magento/issues/967) +- Unknown column 'at_special_from_date_default.value' in 'on clause' [\#964](https://github.com/mailchimp/mc-magento/issues/964) +- Remove error message when resend an item with error [\#963](https://github.com/mailchimp/mc-magento/issues/963) +- Customer and subscriber with same email sent to mailchimp with different id [\#952](https://github.com/mailchimp/mc-magento/issues/952) +- getLastRealOrder() doesn't exist [\#946](https://github.com/mailchimp/mc-magento/issues/946) + ## [1.1.16](https://github.com/mailchimp/mc-magento/releases/tag/1.1.16) - 2019-04-30 **Fixed** - Error syncing order with disabled product [\#943](https://github.com/mailchimp/mc-magento/issues/943) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php index e15943121..60f1fef4a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php @@ -23,18 +23,18 @@ class Ebizmarts_MailChimp_Block_Adminhtml_Customer_Edit_Tab_Mailchimp extends Ma /** * @var Ebizmarts_MailChimp_Helper_Data */ - protected $helper; - protected $storeId; + protected $_helper; + protected $_storeId; public function __construct() { parent::__construct(); $this->setTemplate('ebizmarts/mailchimp/customer/tab/mailchimp.phtml'); - $this->helper = $this->makeHelper(); + $this->_helper = $this->makeHelper(); $customerId = (int) $this->getRequest()->getParam('id'); if ($customerId) { $this->_customer = $this->getCustomerModel()->load($customerId); - $this->storeId = $this->getCustomer()->getStoreId(); + $this->_storeId = $this->getCustomer()->getStoreId(); } } @@ -46,7 +46,7 @@ public function getInterest() $subscriberId = $subscriber->getSubscriberId(); $customerId = $customer->getId(); $storeId = $this->getStoreId(); - $interest = $this->helper->getInterestGroups($customerId, $subscriberId, $storeId); + $interest = $this->_helper->getInterestGroups($customerId, $subscriberId, $storeId); return $interest; } @@ -90,10 +90,11 @@ protected function getCustomer() */ protected function getStoreId() { - $storeId = $this->storeId; + $storeId = $this->_storeId; if (!$storeId) { $storeId = $this->_customer->getMailchimpStoreView(); } + return $storeId; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata.php index 74cb60c12..af7b56575 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata.php @@ -1,6 +1,7 @@ __('Data to send'); } - - public function _prepareForm() - { - } } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata/Form.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata/Form.php index c56c6ef91..16b79afd0 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata/Form.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Ecommerce/Resendecommercedata/Form.php @@ -1,11 +1,27 @@ 'edit_form', 'action' => $this->getUrl('*/*/resendEcommerceData'), 'method' => 'post')); - $fieldset = $form->addFieldset('base_fieldset', array('legend' => Mage::helper('mailchimp')->__('Resend Data'))); + $request = $this->getRequest(); + $scope = $request->getParam('scope'); + $scopeId = $request->getParam('scope_id'); + + $form = new Varien_Data_Form( + array( + 'id' => 'edit_form', + 'action' => $this->getUrl('*/*/resendEcommerceData'), + 'method' => 'post' + ) + ); + $fieldset = $form->addFieldset( + 'base_fieldset', + array( + 'legend' => Mage::helper('mailchimp')->__('Resend Data') + ) + ); $fieldset->addField( @@ -68,11 +84,31 @@ protected function _prepareForm() 'label' => "Promo Rules", 'id' => 'promo', 'title' => 'Promo Rules', - 'value' => Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE. ', ' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, + 'value' => Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE. ', ' + . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, 'required' => false, 'checked' => '1', ) ); + $fieldset->addField( + 'scope', + 'hidden', + array( + 'name' => 'scope', + 'id' => 'scope', + 'value' => $scope + ) + ); + $fieldset->addField( + 'scopeId', + 'hidden', + array( + 'name' => 'scope_id', + 'id' => 'scopeId', + 'value' => $scopeId + ) + ); + $form->setUseContainer(true); $this->setForm($form); diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php index f07f67d83..1977553a0 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php @@ -10,39 +10,49 @@ * @date: 6/10/16 2:23 PM * @file: Link.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_Mailchimperrors_Link extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Ebizmarts_MailChimp_Block_Adminhtml_Mailchimperrors_Link + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) { $id = $row->getData('original_id'); switch ($row->getData('regtype')) { - case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: - $url = Mage::helper("adminhtml")->getUrl("adminhtml/customer/edit", array('id'=>$id)); - $displayText = '' . $this->__('Go to Customer view. Id:') . ' ' . $id . ''; - break; - case Ebizmarts_MailChimp_Model_Config::IS_ORDER: - $url = Mage::helper("adminhtml")->getUrl("adminhtml/sales_order/view", array('order_id'=>$id)); - $displayText = '' . $this->__('Go to Order view. Id:') . ' ' . $id . ''; - break; - case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: - $url = Mage::helper("adminhtml")->getUrl("adminhtml/catalog_product/edit", array('id'=>$id)); - $displayText = '' . $this->__('Go to Product view. Id:') . ' ' . $id . ''; - break; - case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: - $displayText = $this->__('Quote view not available. Id:') . ' ' . $id; - break; - case Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER: - $displayText = $this->__('Subscriber view not available. Id:') . ' ' . $id; - break; - case Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE: - $displayText = $this->__('Promo Rule view not available. Id:') . ' ' . $id; - break; - case Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE: - $displayText = $this->__('Promo Code view not available. Id:') . ' ' . $id; - break; - default: - $displayText = $this->__('Something went wrong when retrieving original item.'); - break; + case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: + $url = Mage::helper("adminhtml")->getUrl("adminhtml/customer/edit", array('id'=>$id)); + $displayText = + '' + . $this->__('Go to Customer view. Id:') . ' ' . $id + . ''; + break; + case Ebizmarts_MailChimp_Model_Config::IS_ORDER: + $url = Mage::helper("adminhtml")->getUrl("adminhtml/sales_order/view", array('order_id'=>$id)); + $displayText = + '' + . $this->__('Go to Order view. Id:') . ' ' . $id + . ''; + break; + case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: + $url = Mage::helper("adminhtml")->getUrl("adminhtml/catalog_product/edit", array('id'=>$id)); + $displayText = + '' + . $this->__('Go to Product view. Id:') . ' ' . $id + . ''; + break; + case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: + $displayText = $this->__('Quote view not available. Id:') . ' ' . $id; + break; + case Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER: + $displayText = $this->__('Subscriber view not available. Id:') . ' ' . $id; + break; + case Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE: + $displayText = $this->__('Promo Rule view not available. Id:') . ' ' . $id; + break; + case Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE: + $displayText = $this->__('Promo Code view not available. Id:') . ' ' . $id; + break; + default: + $displayText = $this->__('Something went wrong when retrieving original item.'); + break; } return $displayText; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit.php index 71cfa028b..987dd29e7 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit.php @@ -20,7 +20,8 @@ public function __construct() parent::__construct(); $this->removeButton('reset'); - $this->updateButton('delete', null, array( + $this->updateButton( + 'delete', null, array( 'label' => Mage::helper('adminhtml')->__('Delete Store'), 'class' => 'delete', 'onclick' => 'deleteMCStoreConfirm(\'' @@ -31,7 +32,8 @@ public function __construct() . $this->getDeleteUrl() . '\')', 'sort_order' => 0 - )); + ) + ); $scopeArray = $this->getScopeArrayIfValueExists(); if ($scopeArray !== false) { @@ -39,6 +41,7 @@ public function __construct() } else { $jsCondition = 'false'; } + $mcInUseMessage = $this->getMCInUseMessage($scopeArray); $this->_formScripts[] = "function deleteMCStoreConfirm(message, url) { if ($jsCondition) { @@ -83,10 +86,16 @@ protected function getMCInUseMessage($scope) $helper = $this->makeHelper(); if ($scope !== false) { $scopeName = $helper->getScopeName($scope); - $message = $helper->__("This store is currently in use for this Magento store at %s scope. Do you want to proceed anyways?", $scopeName); + $message = $helper->__( + "This store is currently in use for this Magento store at %s scope. Do you want to proceed anyways?", + $scopeName + ); } else { - $message = $helper->__("This store is currently in use for this Magento store. Do you want to proceed anyways?"); + $message = $helper->__( + "This store is currently in use for this Magento store. Do you want to proceed anyways?" + ); } + return $message; } @@ -101,6 +110,7 @@ protected function getScopeArrayIfValueExists() if ($keyIfExist === null) { $keyIfExist = 'false'; } + return $keyIfExist; } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php index bb1a0df2a..c6facfddf 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php @@ -17,153 +17,207 @@ protected function _prepareForm() { $helper = $this->makeHelper(); - $form = new Varien_Data_Form(array( + $form = new Varien_Data_Form( + array( 'id' => 'edit_form', 'action' => $this->getUrl('*/*/save'), 'method' => 'post', - )); + ) + ); $store = Mage::registry('current_mailchimpstore'); if ($store->getStoreid()) { - $form->addField('storeid', 'hidden', array( + $form->addField( + 'storeid', 'hidden', array( 'name' => 'storeid', - )); - $form->addField('apikey', 'hidden', array( + ) + ); + $form->addField( + 'apikey', 'hidden', array( 'name' => 'apikey' - )); + ) + ); $form->setValues($store->getData()); } - $fieldset = $form->addFieldset('base_fieldset', array( + + $fieldset = $form->addFieldset( + 'base_fieldset', array( 'legend' => $helper->__('Store Information'), 'class' => 'fieldset', - )); + ) + ); + if (!$store->getId()) { $stores = Mage::app()->getStores(); $apikeys = array(); + foreach ($stores as $s) { - $apikey = $helper->getApiKey($s); + $prefix = ''; + $storeId = $s->getStoreId(); + + if(!$helper->ping($storeId)) { + $prefix = '[Invalid]: '; + } + + $apikey = $helper->getApiKey($storeId); + if (!array_key_exists($apikey, $apikeys)) { $encryptedApiKey = $helper->encryptData($apikey); - $apikeys[$encryptedApiKey] = $helper->mask($apikey); + $apikeys[$encryptedApiKey] = $helper->mask($apikey, $prefix); } } - $apikeyField = $fieldset->addField('apikey', 'select', array( + + $apikeyField = $fieldset->addField( + 'apikey', 'select', array( 'label' => $helper->__('Api Key'), 'title' => $helper->__('Api Key'), 'name' => 'apikey', 'required' => true, 'options' => $apikeys, - )); + ) + ); + $getStoresUrl = Mage::helper('adminhtml')->getUrl('adminhtml/mailchimpstores/getstores'); $apikeyField->setAfterElementHtml(""); - $fieldset->addField('listid', 'select', array( + $fieldset->addField( + 'listid', 'select', array( 'name' => 'listid', 'label' => $helper->__('List'), 'title' => $helper->__('List'), 'required' => true, 'options' => array() - )); + ) + ); } - $fieldset->addField('name', 'text', array( + + $fieldset->addField( + 'name', 'text', array( 'name' => 'name', 'label' => $helper->__('Store Name'), 'title' => $helper->__('Store Name'), 'required' => true, - )); - $fieldset->addField('domain', 'text', array( - 'name' => 'domain', - 'label' => $helper->__('Domain'), - 'title' => $helper->__('Domain'), + ) + ); + $fieldset->addField( + 'domain', 'text', array( + 'name' => 'domain', + 'label' => $helper->__('Domain'), + 'title' => $helper->__('Domain'), 'required' => true - )); - $fieldset->addField('email_address', 'text', array( - 'name' => 'email_address', - 'label' => $helper->__('Email'), - 'title' => $helper->__('Email'), - 'required' => true - )); + ) + ); + $fieldset->addField( + 'email_address', 'text', array( + 'name' => 'email_address', + 'label' => $helper->__('Email'), + 'title' => $helper->__('Email'), + 'required' => true + ) + ); $currencies = Mage::getModel('adminhtml/system_config_source_currency')->toOptionArray(false); $currencyArray = array(); foreach ($currencies as $c) { $currencyArray[$c['value']] = $c['label']; } - $fieldset->addField('currency_code', 'select', array( + + $fieldset->addField( + 'currency_code', 'select', array( 'label' => $helper->__('Currency'), 'title' => $helper->__('Currency'), 'name' => 'currency_code', 'required' => true, 'options' => $currencyArray, - )); + ) + ); $locales = Mage::getModel('adminhtml/system_config_source_locale')->toOptionArray(); $localeArray = array(); foreach ($locales as $c) { $localeArray[$c['value']] = $c['label']; } - $fieldset->addField('primary_locale', 'select', array( + + $fieldset->addField( + 'primary_locale', 'select', array( 'label' => $helper->__('Locale'), 'title' => $helper->__('Locale'), 'name' => 'primary_locale', 'required' => true, 'options' => $localeArray, - )); + ) + ); $timeszones = Mage::getModel('adminhtml/system_config_source_locale_timezone')->toOptionArray(); $timezoneArray = array(); foreach ($timeszones as $c) { $timezoneArray[$c['value']] = $c['label']; } - $fieldset->addField('timezone', 'select', array( + + $fieldset->addField( + 'timezone', 'select', array( 'label' => $helper->__('Time Zone'), 'title' => $helper->__('Time Zone'), 'name' => 'timezone', 'required' => true, 'options' => $timezoneArray, - )); + ) + ); - $fieldset->addField('phone', 'text', array( + $fieldset->addField( + 'phone', 'text', array( 'name' => 'phone', 'label' => $helper->__('Phone'), 'title' => $helper->__('Phone'), 'required' => true - )); - $fieldset->addField('address_address_one', 'text', array( + ) + ); + $fieldset->addField( + 'address_address_one', 'text', array( 'name' => 'address_address_one', 'label' => $helper->__('Street'), 'title' => $helper->__('Street'), 'required' => true - )); + ) + ); - $fieldset->addField('address_address_two', 'text', array( + $fieldset->addField( + 'address_address_two', 'text', array( 'name' => 'address_address_two', 'label' => $helper->__('Street'), 'title' => $helper->__('Street'), 'required' => false - )); - $fieldset->addField('address_city', 'text', array( + ) + ); + $fieldset->addField( + 'address_city', 'text', array( 'name' => 'address_city', 'label' => $helper->__('City'), 'title' => $helper->__('City'), 'required' => true - )); - $fieldset->addField('address_postal_code', 'text', array( + ) + ); + $fieldset->addField( + 'address_postal_code', 'text', array( 'name' => 'address_postal_code', 'label' => $helper->__('Postal Code'), 'title' => $helper->__('Postal Code'), 'required' => true - )); + ) + ); $countries = Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(); $countryArray = array(); foreach ($countries as $c) { $countryArray[$c['value']] = $c['label']; } - $fieldset->addField('address_country_code', 'select', array( + + $fieldset->addField( + 'address_country_code', 'select', array( 'label' => $helper->__('Country'), 'title' => $helper->__('Country'), 'name' => 'address_country_code', 'required' => true, 'options' => $countryArray, - )); + ) + ); $form->setValues($store->getData()); diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php index dcdf0227d..0d6648973 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php @@ -19,16 +19,12 @@ public function __construct() $this->_removeButton("back"); $this->_removeButton("reset"); } - // public function getMovtypes() - // { - // $types = Mage::getSingleton('mailchimp/system_config_source_movtype')->getMovtypes(); - // return $types; - // } + + /** + * @return string + */ public function getHeaderText() { return Mage::helper('mailchimp')->__('New Field Type'); } - public function _prepareForm() - { - } } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php index cb19e5b8e..48054ac43 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php @@ -10,8 +10,17 @@ class Ebizmarts_MailChimp_Block_Adminhtml_Mergevars_Add_Form extends Mage_Adminh { protected function _prepareForm() { - $form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getUrl('*/*/saveadd'), 'method' => 'post')); - $fieldset = $form->addFieldset('base_fieldset', array('legend' => Mage::helper('mailchimp')->__('Mergevars Data'))); + $form = new Varien_Data_Form( + array( + 'id' => 'edit_form', + 'action' => $this->getUrl('*/*/saveadd'), + 'method' => 'post' + ) + ); + $fieldset = $form->addFieldset( + 'base_fieldset', + array('legend' => Mage::helper('mailchimp')->__('Mergevars Data')) + ); $fieldset->addField( @@ -45,7 +54,8 @@ protected function _prepareForm() 'label' => Mage::helper('mailchimp')->__('Merge Field Tag'), 'id' => 'mergevar_value', 'title' => Mage::helper('mailchimp')->__('Merge Field Tag'), - 'note' => 'This value will be used when adding the logic in the Observer. Blank spaces are not allowed.', + 'note' => 'This value will be used when adding the logic in the Observer. ' + . 'Blank spaces are not allowed.', 'required' => true ) ); diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Firstname.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Firstname.php index 4f7842dd3..d410cb393 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Firstname.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Firstname.php @@ -5,7 +5,8 @@ * Date: 22/05/15 * Time: 05:23 PM */ -class Ebizmarts_MailChimp_Block_Adminhtml_Newsletter_Subscriber_Renderer_Firstname extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Ebizmarts_MailChimp_Block_Adminhtml_Newsletter_Subscriber_Renderer_Firstname + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Lastname.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Lastname.php index eb7e68fa6..f5ae3c66f 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Lastname.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Newsletter/Subscriber/Renderer/Lastname.php @@ -5,7 +5,8 @@ * Date: 22/05/15 * Time: 05:23 PM */ -class Ebizmarts_MailChimp_Block_Adminhtml_Newsletter_Subscriber_Renderer_Lastname extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Ebizmarts_MailChimp_Block_Adminhtml_Newsletter_Subscriber_Renderer_Lastname + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { public function render(Varien_Object $row) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php index 29bcb83b2..d96d589f1 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php @@ -18,7 +18,9 @@ public function getMessageNotification() $helper = $this->makeHelper(); if ($helper->isImageCacheFlushed() && $helper->isEcomSyncDataEnabledInAnyScope()) { $message = 'Important: '. - 'Image cache has been flushed please resend the products in order to update image URL'; + 'Image cache has been flushed please ' + . '' + . 'resend the products in order to update image URL'; return $message; } } @@ -29,7 +31,9 @@ public function getMessageNotification() public function getMessage() { $helper = $this->makeHelper(); - $message = 'Are you sure you want to delete the local data in order to send all items again?\nAutomations will work normally but the synchronization process for the old data will take longer than resetting the MailChimp store.'; + $message = 'Are you sure you want to delete the local data in order to send all items again?\n' + .'Automations will work normally but the synchronization process for the old data will take ' + . 'longer than resetting the MailChimp store.'; return $helper->__($message); } @@ -40,6 +44,22 @@ public function getAjaxCheckUrl() return $helper->getUrlForNotification(); } + public function getUrlForResendEcommerce() + { + $helper = $this->makeHelper(); + $scopeArray = $helper->getCurrentScope(); + $url = Mage::helper('adminhtml') + ->getUrl( + 'adminhtml/ecommerce/renderresendecom', + array('scope' => $scopeArray['scope'], 'scope_id' => $scopeArray['scope_id'] + ) + ); + + return $url; + } + + + /** * @return Ebizmarts_MailChimp_Helper_Data */ diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php index ce2d5fd7a..a8bcc5a16 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php @@ -10,19 +10,28 @@ * @date: 7/7/16 1:31 PM * @file: Abandoned.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_Grid_Renderer_Mailchimp extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_Grid_Renderer_Mailchimp + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { + /** + * @param Varien_Object $row + * @return string + */ public function render(Varien_Object $row) { $result = ''; try { - $order = Mage::getModel('sales/order')->load($row->getData('entity_id')); + $order = Mage::getModel('sales/order') + ->load($row->getData('entity_id')); if ($order->getMailchimpAbandonedcartFlag() || $order->getMailchimpCampaignId()) { - $result = ''; + $result = ''; } } catch (Exception $e) { + Mage::throwException($e->getMessage()); } return $result; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/MailchimpOrder.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/MailchimpOrder.php index 2fa92b535..9229e7077 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/MailchimpOrder.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/MailchimpOrder.php @@ -11,7 +11,8 @@ * @date: 12/12/17 3:28 PM * @file: Abandoned.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_Grid_Renderer_MailchimpOrder extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract +class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_Grid_Renderer_MailchimpOrder + extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract { const SYNCED = 1; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php index 9cfff0bd9..c4032cffb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php @@ -17,13 +17,16 @@ class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey extends M /** * @var string $campaignName */ - protected $campaignName = null; + protected $_campaignName = null; /** * @var Mage_Sales_Model_Order $order */ - protected $order = null; + protected $_order = null; + /** + * @return bool + */ public function isReferred() { $order = $this->getCurrentOrder(); @@ -49,18 +52,18 @@ public function getCampaignId() */ public function getCampaignName() { - if (!$this->campaignName) { + if (!$this->_campaignName) { $campaignId = $this->getCampaignId(); $order = $this->getCurrentOrder(); $storeId = $order->getStoreId(); $helper = $this->getMailChimpHelper(); if ($helper->isEcomSyncDataEnabled($storeId)) { - $this->campaignName = $helper->getMailChimpCampaignNameById($campaignId, $storeId); + $this->_campaignName = $helper->getMailChimpCampaignNameById($campaignId, $storeId); } } - return $this->campaignName; + return $this->_campaignName; } /** @@ -76,10 +79,11 @@ protected function getMailChimpHelper() */ protected function getCurrentOrder() { - if (!$this->order) { - $this->order = Mage::registry('current_order'); + if (!$this->_order) { + $this->_order = Mage::registry('current_order'); } - return $this->order; + + return $this->_order; } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateMergeFields.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateMergeFields.php index 117544291..6e2e61ef6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateMergeFields.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateMergeFields.php @@ -10,7 +10,8 @@ * @date: 30/8/16 1:02 PM * @file: CreateMergeFields.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_CreateMergeFields extends Mage_Adminhtml_Block_System_Config_Form_Field +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_CreateMergeFields + extends Mage_Adminhtml_Block_System_Config_Form_Field { const CREATE_MERGE_PATH = 'adminhtml/ecommerce/createMergeFields'; @@ -52,10 +53,15 @@ public function getAjaxCheckUrl() public function getMessageForMailchimpErrorLog() { $helper = $this->makeHelper(); - $message = 'There was an error on the merge fields creation. Please check the MailChimp_Errors.log file for more information.'; + $message = + 'There was an error on the merge fields creation. ' + . 'Please check the MailChimp_Errors.log file for more information.'; if (!$helper->isErrorLogEnabled()) { - $message = 'There was an error on the merge fields creation. Please enable the error logs and try again for more information.'; + $message = + 'There was an error on the merge fields creation. ' + . 'Please enable the error logs and try again for more information.'; } + return $helper->__($message); } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateWebhook.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateWebhook.php index be4102174..b27e35aa2 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/CreateWebhook.php @@ -6,7 +6,8 @@ * Time: 4:15 PM */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_CreateWebhook extends Mage_Adminhtml_Block_System_Config_Form_Field +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_CreateWebhook + extends Mage_Adminhtml_Block_System_Config_Form_Field { protected function _construct() { diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mailchimp/Hint.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mailchimp/Hint.php index 56df5e980..136b88fbb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mailchimp/Hint.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mailchimp/Hint.php @@ -9,7 +9,8 @@ * @date: 4/29/16 3:55 PM * @file: Hint.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_Fieldset_Mailchimp_Hint extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_Fieldset_Mailchimp_Hint + extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface { protected $_template = 'ebizmarts/mailchimp/system/config/fieldset/hint.phtml'; @@ -96,7 +97,7 @@ public function isApiKeySet() /** * @return Ebizmarts_MailChimp_Helper_Data */ - private function makeHelper() + protected function makeHelper() { return Mage::helper('mailchimp'); } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mandrill/Hint.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mandrill/Hint.php index 71424353b..f2c2b5694 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mandrill/Hint.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Fieldset/Mandrill/Hint.php @@ -9,7 +9,8 @@ * @date: 4/29/16 3:55 PM * @file: Hint.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_Fieldset_Mandrill_Hint extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_Fieldset_Mandrill_Hint + extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface { protected $_template = 'ebizmarts/mandrill/system/config/fieldset/hint.phtml'; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php index d2dc43631..fbcf75865 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php @@ -10,25 +10,31 @@ * @date: 6/28/16 3:55 PM * @file: Mapfields.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_Form_Field_Mapfields extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_Form_Field_Mapfields + extends Mage_Adminhtml_Block_System_Config_Form_Field_Array_Abstract { protected $_customerAttributes; + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $_helper; + public function __construct() { - $helper = $this->makeHelper(); + $this->_helper = $this->makeHelper(); $this->addColumn( 'mailchimp', array( - 'label' => $helper->__('Mailchimp'), + 'label' => $this->_helper->__('Mailchimp'), 'style' => 'width:120px', ) ); $this->addColumn( 'magento', array( - 'label' => $helper->__('Customer'), + 'label' => $this->_helper->__('Customer'), 'style' => 'width:120px', ) ); @@ -48,9 +54,10 @@ public function __construct() } } - $scopeArray = $helper->getCurrentScope(); - $mapFields = $helper->getCustomMergeFieldsSerialized($scopeArray['scope_id'], $scopeArray['scope']); - $customFieldTypes = unserialize($mapFields); + $scopeArray = $this->_helper->getCurrentScope(); + $mapFields = $this->_helper->getCustomMergeFieldsSerialized($scopeArray['scope_id'], $scopeArray['scope']); + $customFieldTypes = $this->_helper->unserialize($mapFields); + if (is_array($customFieldTypes)) { foreach ($customFieldTypes as $customFieldType) { $label = $customFieldType['label']; @@ -62,10 +69,14 @@ public function __construct() ksort($this->_customerAttributes); } + /** + * @param string $columnName + * @return string + */ protected function _renderCellTemplate($columnName) { if (empty($this->_columns[$columnName])) { - throw new Exception('Wrong column name specified.'); + Mage::throwException('Wrong column name specified.'); } $column = $this->_columns[$columnName]; @@ -79,17 +90,26 @@ protected function _renderCellTemplate($columnName) $rendered .= ''; } else { - return ''; + return + ''; } return $rendered; } + /** + * @return string + */ protected function _getMailChimpValue() { return Mage::getSingleton('core/session')->getMailchimpValue(); } + /** + * @return string + */ protected function _getMailChimpLabel() { return Mage::getSingleton('core/session')->getMailchimpLabel(); diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php index bda183625..e13a45041 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php @@ -9,7 +9,8 @@ * @date: 4/29/16 3:55 PM * @file: OauthWizard.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_OauthWizard extends Mage_Adminhtml_Block_System_Config_Form_Field +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_OauthWizard + extends Mage_Adminhtml_Block_System_Config_Form_Field { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php index ad72e5250..cb3244c17 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php @@ -10,7 +10,8 @@ * @date: 5/27/16 1:16 PM * @file: ResendEcommerceData.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResendEcommerceData extends Mage_Adminhtml_Block_System_Config_Form_Field +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResendEcommerceData + extends Mage_Adminhtml_Block_System_Config_Form_Field { protected function _construct() { @@ -27,7 +28,12 @@ public function getButtonHtml() { $helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); - if ($helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray['scope_id'], $scopeArray['scope'])) { + if ($helper->getIfConfigExistsForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, + $scopeArray['scope_id'], + $scopeArray['scope'] + ) + ) { $label = $helper->__('Resend Ecommerce Data'); $button = $this->getLayout()->createBlock('adminhtml/widget_button') ->setData( diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendSubscribers.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendSubscribers.php index 97ba9bd86..5e7c04bfc 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendSubscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendSubscribers.php @@ -10,7 +10,8 @@ * @date: 5/27/16 1:02 PM * @file: ResendSubscribers.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResendSubscribers extends Mage_Adminhtml_Block_System_Config_Form_Field +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResendSubscribers + extends Mage_Adminhtml_Block_System_Config_Form_Field { protected function _construct() { @@ -27,7 +28,9 @@ public function getButtonHtml() { $helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); - if ($helper->isSubscriptionEnabled($scopeArray['scope_id'], $scopeArray['scope']) || $scopeArray['scope_id'] == 0) { + if ($helper->isSubscriptionEnabled($scopeArray['scope_id'], $scopeArray['scope']) + || $scopeArray['scope_id'] == 0 + ) { $button = $this->getLayout()->createBlock('adminhtml/widget_button') ->setData( array( diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php index 78a4e8873..67a74ed07 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php @@ -10,7 +10,8 @@ * @date: 5/27/16 1:02 PM * @file: ResetErrors.php */ -class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResetErrors extends Mage_Adminhtml_Block_System_Config_Form_Field +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResetErrors + extends Mage_Adminhtml_Block_System_Config_Form_Field { protected function _construct() { @@ -27,7 +28,9 @@ public function getButtonHtml() { $helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); - if ($helper->isSubscriptionEnabled($scopeArray['scope_id'], $scopeArray['scope']) || $scopeArray['scope_id'] == 0) { + if ($helper->isSubscriptionEnabled($scopeArray['scope_id'], $scopeArray['scope']) + || $scopeArray['scope_id'] == 0 + ) { $button = $this->getLayout()->createBlock('adminhtml/widget_button') ->setData( array( @@ -41,6 +44,7 @@ public function getButtonHtml() return $button->toHtml(); } } + public function getAjaxCheckUrl() { $helper = $this->makeHelper(); diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php index e3fc73cde..b7a733e63 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php @@ -3,10 +3,10 @@ /** * Checkout subscribe checkbox block renderer * - * @category Ebizmarts - * @package Ebizmarts_MageMonkey - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MageMonkey + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Block_Checkout_Subscribe extends Mage_Core_Block_Template { @@ -20,14 +20,14 @@ class Ebizmarts_MailChimp_Block_Checkout_Subscribe extends Mage_Core_Block_Templ /** * @var Ebizmarts_MailChimp_Helper_Data */ - protected $helper; - protected $storeId; + protected $_helper; + protected $_storeId; public function __construct() { parent::__construct(); - $this->helper = Mage::helper('mailchimp'); - $this->storeId = Mage::app()->getStore()->getId(); + $this->_helper = Mage::helper('mailchimp'); + $this->_storeId = Mage::app()->getStore()->getId(); } /** @@ -37,8 +37,8 @@ public function __construct() */ protected function _toHtml() { - $helper = $this->helper; - $storeId = $this->storeId; + $helper = $this->_helper; + $storeId = $this->_storeId; $alreadySubscribed = Mage::getModel('newsletter/subscriber') ->loadByEmail($this->getQuote()->getCustomerEmail()) @@ -64,7 +64,7 @@ protected function getQuote() protected function getCurrentCheckoutSubscribeValue() { - return $this->helper->getCheckoutSubscribeValue($this->storeId); + return $this->_helper->getCheckoutSubscribeValue($this->_storeId); } protected function isForceHidden($currentValue = null) @@ -72,6 +72,7 @@ protected function isForceHidden($currentValue = null) if (!$currentValue) { $currentValue = $this->getCurrentCheckoutSubscribeValue(); } + return ($currentValue == Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::FORCE_HIDDEN); } @@ -91,6 +92,7 @@ public function isForceEnabled() if ($this->isForceHidden($currentValue) || $this->isForceVisible($currentValue)) { return true; } + return false; } @@ -100,6 +102,7 @@ public function isChecked() if ($this->isCheckedByDefault($currentValue) || $this->isForceVisible($currentValue)) { return true; } + return false; } @@ -115,8 +118,8 @@ public function addToPostOnLoad() */ public function getGeneralList() { - $storeId = $this->storeId; - $helper = $this->helper; + $storeId = $this->_storeId; + $helper = $this->_helper; $listId = $helper->getGeneralList($storeId); return $listId; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php index 0691b6a6e..2a0d38ccd 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php @@ -3,10 +3,10 @@ /** * Checkout subscribe interest groups block renderer * - * @category Ebizmarts - * @package Ebizmarts_MailChimp - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MailChimp + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Block_Checkout_Success_Groups extends Mage_Core_Block_Template { @@ -14,27 +14,39 @@ class Ebizmarts_MailChimp_Block_Checkout_Success_Groups extends Mage_Core_Block_ /** * @var Ebizmarts_MailChimp_Helper_Data */ - protected $helper; - protected $storeId; + protected $_helper; + protected $_toreId; public function __construct() { parent::__construct(); - $this->helper = Mage::helper('mailchimp'); - $this->storeId = Mage::app()->getStore()->getId(); + $this->_helper = Mage::helper('mailchimp'); + $this->_storeId = Mage::app()->getStore()->getId(); } + /** + * @return string + */ public function getFormUrl() { return $this->getSuccessInterestUrl(); } + /** + * @return string + * @throws Mage_Core_Model_Store_Exception + */ public function getSuccessInterestUrl() { $url = 'mailchimp/group/index'; return Mage::app()->getStore()->getUrl($url); } + /** + * @return array|null + * @throws Mage_Core_Exception + * @throws MailChimp_Error + */ public function getInterest() { $subscriber = $this->getSubscriberModel(); @@ -47,16 +59,24 @@ public function getInterest() return $interest; } + /** + * @return string + * @throws Mage_Core_Exception + */ public function getMessageBefore() { - $storeId = $this->storeId; + $storeId = $this->_storeId; $message = $this->getMailChimpHelper()->getCheckoutSuccessHtmlBefore($storeId); return $message; } + /** + * @return string + * @throws Mage_Core_Exception + */ public function getMessageAfter() { - $storeId = $this->storeId; + $storeId = $this->_storeId; $message = $this->getMailChimpHelper()->getCheckoutSuccessHtmlAfter($storeId); return $message; } @@ -87,6 +107,6 @@ protected function getSessionLastRealOrder() */ protected function getMailChimpHelper() { - return $this->helper; + return $this->_helper; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php b/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php index ac87f3bb7..90632c4c9 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php @@ -3,10 +3,10 @@ /** * Customer account subscribe interest groups block renderer * - * @category Ebizmarts - * @package Ebizmarts_MageMonkey - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MageMonkey + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Block_Customer_Newsletter_Index extends Mage_Customer_Block_Newsletter { @@ -21,16 +21,22 @@ class Ebizmarts_MailChimp_Block_Customer_Newsletter_Index extends Mage_Customer_ /** * @var Ebizmarts_MailChimp_Helper_Data */ - protected $helper; - protected $storeId; + protected $_helper; + protected $_storeId; public function __construct() { $this->setTemplate('ebizmarts/mailchimp/customer/newsletter/index.phtml'); - $this->helper = Mage::helper('mailchimp'); - $this->storeId = Mage::app()->getStore()->getId(); + $this->_helper = Mage::helper('mailchimp'); + $this->_storeId = Mage::app()->getStore()->getId(); } + /** + * @return array|null + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception + * @throws MailChimp_Error + */ public function getInterest() { $subscriber = $this->getSubscriberModel(); @@ -45,6 +51,7 @@ public function getInterest() $customerId = null; $storeId = $subscriber->getStoreId(); } + $interest = $helper->getInterestGroups($customerId, $subscriber->getSubscriberId(), $storeId); return $interest; } @@ -56,7 +63,7 @@ public function getInterest() */ protected function _getEmail() { - return $this->helper('customer')->getCustomer()->getEmail(); + return $this->getCustomerSession()->getCustomer()->getEmail(); } /** @@ -64,7 +71,7 @@ protected function _getEmail() */ protected function getMailChimpHelper() { - return $this->helper; + return $this->_helper; } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php b/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php index bfdf6600f..b31819dd2 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php @@ -3,10 +3,10 @@ /** * Interest group type template selector block * - * @category Ebizmarts - * @package Ebizmarts_MageMonkey - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MageMonkey + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Block_Group_Type extends Mage_Core_Block_Template { @@ -19,6 +19,7 @@ public function __construct(array $args = array()) $type = $interests['interest']['type']; $this->setTemplate("ebizmarts/mailchimp/group/type/$type.phtml"); } + parent::__construct($args); } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php b/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php index 7f511e6a4..4b3fcf842 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php @@ -15,7 +15,11 @@ class Ebizmarts_MailChimp_Block_Popup_Emailcatcher extends Mage_Core_Block_Templ protected function _canCancel() { $storeId = Mage::app()->getStore()->getId(); - return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ENABLE_POPUP, $storeId) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::POPUP_CAN_CANCEL, $storeId); + return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ENABLE_POPUP, $storeId) + && Mage::getStoreConfig( + Ebizmarts_MailChimp_Model_Config::POPUP_CAN_CANCEL, + $storeId + ); } protected function _popupHeading() diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php old mode 100755 new mode 100644 index f8234f0e5..d9f027d1d --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -12,33 +12,40 @@ */ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract { - const DEFAULT_SIZE = '0'; - const SMALL_SIZE = '1'; - const THUMBNAIL_SIZE = '2'; - const ORIGINAL_SIZE = '3'; - - const SUB_MOD = "SubscriberModified"; - const SUB_NEW = "SubscriberNew"; - const PRO_MOD = "ProductModified"; - const PRO_NEW = "ProductNew"; - const CUS_MOD = "CustomerModified"; - const CUS_NEW = "CustomerNew"; - const ORD_MOD = "OrderModified"; - const ORD_NEW = "OrderNew"; - const QUO_MOD = "QuoteModified"; - const QUO_NEW = "QuoteNew"; + const DEFAULT_SIZE = '0'; + const SMALL_SIZE = '1'; + const THUMBNAIL_SIZE = '2'; + const ORIGINAL_SIZE = '3'; + + const SUB_MOD = "SubscriberModified"; + const SUB_NEW = "SubscriberNew"; + const PRO_MOD = "ProductModified"; + const PRO_NEW = "ProductNew"; + const CUS_MOD = "CustomerModified"; + const CUS_NEW = "CustomerNew"; + const ORD_MOD = "OrderModified"; + const ORD_NEW = "OrderNew"; + const QUO_MOD = "QuoteModified"; + const QUO_NEW = "QuoteNew"; const DATA_NOT_SENT_TO_MAILCHIMP = 'NOT SENT'; - const DATA_SENT_TO_MAILCHIMP = 'SENT'; + const DATA_SENT_TO_MAILCHIMP = 'SENT'; const BATCH_STATUS_LOG = 'Mailchimp_Batch_Status.log'; - protected $countersSendBatch = array(); - protected $countersSubscribers = array(); - protected $countersGetResponseBatch = array(); + const BATCH_CANCELED = 'canceled'; + const BATCH_COMPLETED = 'completed'; + const BATCH_PENDING = 'pending'; + const BATCH_ERROR = 'error'; + + + protected $_countersSendBatch = array(); + protected $_countersSubscribers = array(); + protected $_countersGetResponseBatch = array(); /** * All MailChimp available language codes + * * @var array */ public static $MAILCHIMP_LANGUAGES = array( @@ -100,7 +107,7 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract * * @param $path * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -118,8 +125,8 @@ public function getConfigValueForScope($path, $scopeId, $scope = null) /** * Get storeId and/or websiteId if scope selected on back end * - * @param null $storeId - * @param null $websiteId + * @param null $storeId + * @param null $websiteId * @return array */ public function getConfigScopeId($storeId = null, $websiteId = null) @@ -171,6 +178,7 @@ public function getCurrentScope() public function getScopeName($scopeArray) { $storeName = false; + if (isset($scopeArray['scope'])) { switch ($scopeArray['scope']) { case 'stores': @@ -198,7 +206,11 @@ public function getScopeName($scopeArray) */ public function isUsingConfigStoreName($scopeId, $scope) { - $storeName = $this->getConfigValueForScope(Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME, $scopeId, $scope); + $storeName = $this->getConfigValueForScope( + Mage_Core_Model_Store::XML_PATH_STORE_STORE_NAME, + $scopeId, + $scope + ); if ($storeName == '') { $usingConfigName = false; } else { @@ -224,7 +236,11 @@ public function getStoreDomain($scopeId, $scope) $websiteCode = $website->getCode(); $domain = (string)Mage::getConfig()->getNode('web/unsecure/base_url', 'website', $websiteCode); } else { - $domain = $this->getConfigValueForScope(Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_LINK_URL, $scopeId, $scope); + $domain = $this->getConfigValueForScope( + Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_LINK_URL, + $scopeId, + $scope + ); } return $domain; @@ -248,6 +264,7 @@ public function getStoreRelation() if (!array_key_exists($mcStoreId, $storeRelation)) { $storeRelation[$mcStoreId] = array(); } + $storeRelation[$mcStoreId][] = $storeId; } } @@ -260,8 +277,8 @@ public function getStoreRelation() /** * Get all Magento stores associated to the MailChimp store configured for the given scope. * - * @param $scopeId - * @param $scope + * @param $scopeId + * @param $scope * @return array|mixed * @throws Mage_Core_Exception */ @@ -270,13 +287,10 @@ public function getMagentoStoresForMCStoreIdByScope($scopeId, $scope) $ret = array(); $storeRelation = $this->getStoreRelation(); $mailchimpStoreIdForScope = $this->getMCStoreId($scopeId, $scope); + $isThereAnyStore = array_key_exists($mailchimpStoreIdForScope, $storeRelation); - if ($mailchimpStoreIdForScope) { - foreach ($storeRelation as $mailchimpStoreId => $magentoStoreIds) { - if ($mailchimpStoreIdForScope == $mailchimpStoreId) { - $ret = $magentoStoreIds; - } - } + if ($mailchimpStoreIdForScope && $isThereAnyStore) { + $ret = $storeRelation[$mailchimpStoreIdForScope]; } return $ret; @@ -286,13 +300,13 @@ public function getMagentoStoresForMCStoreIdByScope($scopeId, $scope) * Validate if api key exists, could still be incorrect * * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed */ public function validateApiKey($scopeId, $scope = null) { $apiKey = $this->getApiKey($scopeId, $scope); - $isApiKeyValid = !is_null($apiKey) && $apiKey != ""; + $isApiKeyValid = $apiKey !== null && $apiKey != ""; return $isApiKeyValid; } @@ -300,7 +314,7 @@ public function validateApiKey($scopeId, $scope = null) * Return if module is enabled for given scope. * * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed */ public function isMailChimpEnabled($scopeId, $scope = null) @@ -309,7 +323,6 @@ public function isMailChimpEnabled($scopeId, $scope = null) } /** - * * @param $scopeId * @return bool | returns true if useMagentoEmails is enabled */ @@ -322,7 +335,7 @@ public function isUseMagentoEmailsEnabled($scopeId) * Return if module is enabled and list selected for given scope. * * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed */ public function isSubscriptionEnabled($scopeId, $scope = null) @@ -337,8 +350,8 @@ public function isSubscriptionEnabled($scopeId, $scope = null) /** * Return Api Key if exists for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -355,7 +368,7 @@ public function getApiKey($scopeId, $scope = null) /** * Return decrypted data. * - * @param $data + * @param $data * @return mixed */ public function decryptData($data) @@ -366,7 +379,7 @@ public function decryptData($data) /** * Return encrypted data. * - * @param $data + * @param $data * @return mixed */ public function encryptData($data) @@ -376,33 +389,41 @@ public function encryptData($data) /** * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getWebhookDeleteAction($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_UNSUBSCRIBE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_UNSUBSCRIBE, + $scopeId, + $scope + ); } /** * Get local store_id value of the MC store for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getMCStoreId($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, + $scopeId, + $scope + ); } /** * Delete all data related to the configured store in a given scope. * * @param $scopeId - * @param string $scope + * @param string $scope */ public function deletePreviousConfiguredMCStoreLocalData($mailchimpStoreId, $scopeId, $scope = 'stores') { @@ -410,10 +431,18 @@ public function deletePreviousConfiguredMCStoreLocalData($mailchimpStoreId, $sco if ($mailchimpStoreId !== null && $mailchimpStoreId !== '') { foreach ($this->getAllStoresForScope($scopeId, $scope) as $storeId) { - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", 'stores', $storeId); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", + 'stores', + $storeId + ); } - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", $scope, $scopeId); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", + $scope, + $scopeId + ); } $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $scope, $scopeId); @@ -436,7 +465,7 @@ public function deletePreviousConfiguredMCStoreLocalData($mailchimpStoreId, $sco * Delete all data related to the configured store in a given scope. * * @param $scopeId - * @param string $scope + * @param string $scope */ public function deleteAllConfiguredMCStoreLocalData($mailchimpStoreId, $scopeId, $scope = 'stores') { @@ -459,9 +488,21 @@ public function deleteAllMCStoreData($mailchimpStoreId) { //Delete default configurations for this store. $config = $this->getConfig(); - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", 'default', 0); - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", 'default', 0); - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", 'default', 0); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", + 'default', + 0 + ); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", + 'default', + 0 + ); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", + 'default', + 0 + ); //Delete local ecommerce data and errors for this store. $this->removeEcommerceSyncDataByMCStore($mailchimpStoreId); @@ -470,115 +511,152 @@ public function deleteAllMCStoreData($mailchimpStoreId) //Delete particular scopes configuraion flags for this store $scopeArrayIfExist = $this->getScopeByMailChimpStoreId($mailchimpStoreId); if ($scopeArrayIfExist !== false) { - $this->deleteAllConfiguredMCStoreLocalData($mailchimpStoreId, $scopeArrayIfExist['scope_id'], $scopeArrayIfExist['scope']); + $this->deleteAllConfiguredMCStoreLocalData( + $mailchimpStoreId, + $scopeArrayIfExist['scope_id'], + $scopeArrayIfExist['scope'] + ); } } /** * Return if Ecommerce configuration is enabled for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function isEcommerceEnabled($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ACTIVE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ACTIVE, + $scopeId, + $scope + ); } /** * Get general list configured for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getGeneralList($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, + $scopeId, + $scope + ); } /** * Get map fields configured for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getMapFields($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MAP_FIELDS, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MAP_FIELDS, + $scopeId, + $scope + ); } /** * Get custom merge fields configured for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getCustomMergeFieldsSerialized($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, $scopeId, $scope + ); } /** * Get if Abandoned Cart module is enabled. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function isAbandonedCartEnabled($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_ACTIVE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_ACTIVE, + $scopeId, + $scope + ); } /** * Get date configured for carts to be sent for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getAbandonedCartFirstDate($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_FIRSTDATE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_FIRSTDATE, + $scopeId, + $scope + ); } /** * Get date configured for ecommerce data to be sent for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getEcommerceFirstDate($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE, + $scopeId, + $scope + ); } /** * Get local is_syncing value of the MC store. * If data was saved in the old way get it from the scope and update it to the new way. * - * @param $mailchimpStoreId - * @param int $scopeId - * @param string $scope + * @param $mailchimpStoreId + * @param int $scopeId + * @param string $scope * @return mixed|null * @throws Mage_Core_Exception */ public function getMCIsSyncing($mailchimpStoreId, $scopeId = 0, $scope = 'stores') { - $oldSyncingFlag = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, $scopeId, $scope); - $syncingFlag = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", $scopeId, $scope); + $oldSyncingFlag = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, + $scopeId, + $scope + ); + $syncingFlag = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", + $scopeId, $scope + ); //Save old value in new place. if ($syncingFlag === null && $oldSyncingFlag !== null) { @@ -589,7 +667,12 @@ public function getMCIsSyncing($mailchimpStoreId, $scopeId = 0, $scope = 'stores } //Delete old entry if exists particularly in this scope. - if ($oldSyncingFlag !== null && $this->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, $scopeId, $scope)) { + if ($oldSyncingFlag !== null && $this->getIfConfigExistsForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, + $scopeId, + $scope + ) + ) { $config = $this->getConfig(); $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, $scope, $scopeId); $config->cleanCache(); @@ -602,29 +685,50 @@ public function getMCIsSyncing($mailchimpStoreId, $scopeId = 0, $scope = 'stores * Minimum date for which ecommerce data needs to be uploaded. * If data was saved in the old way get it from the scope and update it to the new way. * - * @param $mailchimpStoreId - * @param $scopeId - * @param null $scope + * @param $mailchimpStoreId + * @param $scopeId + * @param null $scope * @return mixed|null * @throws Mage_Core_Exception */ public function getEcommMinSyncDateFlag($mailchimpStoreId, $scopeId, $scope = null) { - $oldEcommMinsyncDateFlag = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, $scopeId, $scope); - $ecommMinsyncDateFlag = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", 0, 'stores'); + $oldEcommMinsyncDateFlag = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, + $scopeId, + $scope + ); + $ecommMinsyncDateFlag = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", + 0, + 'stores' + ); //Save old value in new place. if ($ecommMinsyncDateFlag === null && $this->validateDate($oldEcommMinsyncDateFlag)) { $configValue = array( - array(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", $oldEcommMinsyncDateFlag) + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", + $oldEcommMinsyncDateFlag + ) ); $this->saveMailchimpConfig($configValue, 0, 'default'); } //Delete old entry if exists particularly in this scope. - if ($oldEcommMinsyncDateFlag !== null && $this->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, $scopeId, $scope)) { + if ($oldEcommMinsyncDateFlag !== null + && $this->getIfConfigExistsForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, + $scopeId, + $scope + ) + ) { $config = $this->getConfig(); - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, $scope, $scopeId); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, + $scope, + $scopeId + ); $config->cleanCache(); } @@ -646,47 +750,59 @@ public function getLogsEnabled() /** * Get if two way sync is enabled for given scope. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getTwoWaySyncEnabled($scopeId = 0, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_TWO_WAY_SYNC, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_TWO_WAY_SYNC, + $scopeId, + $scope + ); } /** * Get webhook Id. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getWebhookId($scopeId = 0, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, + $scopeId, + $scope + ); } /** * Get if monkey should be displayed in order grid. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getMonkeyInGrid($scopeId = 0, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ORDER_GRID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_ORDER_GRID, + $scopeId, + $scope + ); } /** * Get if Email Catcher popup is enabled for given scope. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -696,7 +812,7 @@ public function isEmailCatcherEnabled($scopeId = 0, $scope = null) } /** - * @param int $scopeId + * @param int $scopeId * @param null $scope * @return mixed * @throws Mage_Core_Exception @@ -704,7 +820,11 @@ public function isEmailCatcherEnabled($scopeId = 0, $scope = null) public function getDateSyncFinishByStoreId($scopeId = 0, $scope = null) { $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", + 0, + 'default' + ); } /** @@ -714,14 +834,17 @@ public function getDateSyncFinishByStoreId($scopeId = 0, $scope = null) */ public function getDateSyncFinishByMailChimpStoreId($mailchimpStoreId) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", + 0, + 'default' + ); } /** - * Set the values to send all the items again. - * * @param $scopeId * @param $scope + * @param null $filters * @throws Mage_Core_Exception */ public function resendMCEcommerceData($scopeId, $scope, $filters = null) @@ -730,21 +853,24 @@ public function resendMCEcommerceData($scopeId, $scope, $filters = null) if (!$this->getResendEnabled($scopeId, $scope)) { $this->saveLastItemsSent($scopeId, $scope, $filters); } + $this->removeEcommerceSyncData($scopeId, $scope, false, $filters); $this->clearErrorGrid($scopeId, $scope, true, $filters); - if (in_array('PRO', $filters)) { + if ($filters !== null && in_array(Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $filters)) { $this->deleteFlushMagentoCacheFlag(); } } } /** - * Remove items from mailchimp_ecommerce_sync_data table to allow them to be sent. If scopeId is 0 remova from all scopes. + * Remove items from mailchimp_ecommerce_sync_data table to allow them to be sent. + * If scopeId is 0 remova from all scopes. * * @param $scopeId * @param $scope * @param bool $deleteErrorsOnly + * @param null $filters * @throws Mage_Core_Exception */ public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = false, $filters = null) @@ -758,7 +884,7 @@ public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = fa } /** - * @throws Mage_Core_Exception + * @param null $filters */ public function removeAllEcommerceSyncDataErrors($filters = null) { @@ -766,10 +892,10 @@ public function removeAllEcommerceSyncDataErrors($filters = null) $connection = $resource->getConnection('core_write'); $tableName = $resource->getTableName('mailchimp/ecommercesyncdata'); $where = array(); - $where []= "mailchimp_sync_error != ''"; + $where[] = "mailchimp_sync_error != ''"; if ($filters !== null) { - $where [] = $connection->quoteInto('type IN (?)', $filters); + $where[] = $connection->quoteInto('type IN (?)', $filters); } try { @@ -782,7 +908,7 @@ public function removeAllEcommerceSyncDataErrors($filters = null) /** * @param $mailchimpStoreId * @param bool $deleteErrorsOnly - * @throws Mage_Core_Exception + * @param null $filters */ public function removeEcommerceSyncDataByMCStore($mailchimpStoreId, $deleteErrorsOnly = false, $filters = null) { @@ -792,13 +918,16 @@ public function removeEcommerceSyncDataByMCStore($mailchimpStoreId, $deleteError $where = array(); if ($deleteErrorsOnly) { - $where []= $connection->quoteInto("mailchimp_store_id = ? AND mailchimp_sync_error != ''", $mailchimpStoreId); + $where[] = $connection->quoteInto( + "mailchimp_store_id = ? AND mailchimp_sync_error != ''", + $mailchimpStoreId + ); } else { - $where []= $connection->quoteInto("mailchimp_store_id = ?", $mailchimpStoreId); + $where[] = $connection->quoteInto("mailchimp_store_id = ?", $mailchimpStoreId); } if ($filters !== null) { - $where [] = $connection->quoteInto('type IN (?)', $filters); + $where[] = $connection->quoteInto('type IN (?)', $filters); } try { @@ -811,9 +940,9 @@ public function removeEcommerceSyncDataByMCStore($mailchimpStoreId, $deleteError /** * Check if Ecommerce data is configured to be sent. * - * @param $scopeId - * @param null $scope - * @param bool $isStoreCreation + * @param $scopeId + * @param null $scope + * @param bool $isStoreCreation * @return bool * @throws Mage_Core_Exception */ @@ -827,7 +956,7 @@ public function isEcomSyncDataEnabled($scopeId, $scope = null, $isStoreCreation $ecommerceEnabled = $this->isEcommerceEnabled($scopeId, $scope); $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); - $ret = (!is_null($mailchimpStoreId) || $isStoreCreation) + $ret = ($mailchimpStoreId !== null || $isStoreCreation) && $subscriptionEnabled && $ecommerceEnabled; } @@ -869,7 +998,7 @@ public function logError($message) * succesfully or not to Mailchimp * in the file "Mailchimp_Batch_Status.log" * - * @param $message + * @param $message * @throws Mage_Core_Exception */ public function logBatchStatus($message) @@ -884,7 +1013,7 @@ public function logBatchStatus($message) * how many data was successfully and not sent to Mailchimp * in the file "Mailchimp_Batch_Status.log" * - * @param $message + * @param $message * @throws Mage_Core_Exception */ public function logBatchQuantity($message) @@ -898,7 +1027,7 @@ public function logBatchQuantity($message) * Save request made to MailChimp's API in "MailChimp_Requests.log" file. * * @param $message - * @param null $batchId + * @param null $batchId */ public function logRequest($message, $batchId = null) { @@ -909,11 +1038,13 @@ public function logRequest($message, $batchId = null) Mage::log($message, null, 'MailChimp_Failing_Requests.log', true); } elseif ($logRequestEnabled) { $logDir = Mage::getBaseDir('var') . DS . 'log'; + if (!file_exists($logDir)) { mkdir($logDir, 0750); } $logDir .= DS . 'MailChimp_Requests'; + if (!file_exists($logDir)) { mkdir($logDir, 0750); } @@ -933,7 +1064,9 @@ protected function isRequestLogEnabled() { $logEnabled = false; $logConfig = $this->getLogsEnabled(); - if ($logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::REQUEST_LOG || $logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::BOTH) { + if ($logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::REQUEST_LOG + || $logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::BOTH + ) { $logEnabled = true; } @@ -948,7 +1081,9 @@ public function isErrorLogEnabled() { $logEnabled = false; $logConfig = $this->getLogsEnabled(); - if ($logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::ERROR_LOG || $logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::BOTH) { + if ($logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::ERROR_LOG + || $logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::BOTH + ) { $logEnabled = true; } @@ -967,27 +1102,17 @@ public function getWebhooksKey() } /** - * Reset error messages from Products, Subscribers, Customers, Orders, Quotes and set them to be sent again for given scope. + * Reset error messages from Products, Subscribers, Customers, Orders, Quotes + * and set them to be sent again for given scope. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @throws Mage_Core_Exception */ public function resetErrors($scopeId, $scope = 'stores') { - // reset subscribers with errors - $collection = Mage::getResourceModel('newsletter/subscriber_collection') - ->addFieldToFilter('mailchimp_sync_error', array('neq' => '')); - - if ($scopeId != 0) { - $collection = $this->addStoresToFilter($collection, $scopeId, $scope); - } + $this->removeErrorsFromSubscribers($scopeId, $scope); - foreach ($collection as $subscriber) { - $subscriber->setData("mailchimp_sync_delta", '0000-00-00 00:00:00'); - $subscriber->setData("mailchimp_sync_error", ''); - $subscriber->save(); - } // reset ecommerce data with errors $this->removeEcommerceSyncData($scopeId, $scope, true); $this->clearErrorGrid($scopeId, $scope); @@ -1000,6 +1125,7 @@ public function resetErrors($scopeId, $scope = 'stores') * @param $scopeId * @param $scope * @param bool $excludeSubscribers + * @param null $filters * @throws Mage_Core_Exception */ public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false, $filters = null) @@ -1017,6 +1143,7 @@ public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false, $f /** * @param $mailchimpStoreId + * @param null $filters */ public function clearErrorGridByMCStore($mailchimpStoreId, $filters = null) { @@ -1024,10 +1151,10 @@ public function clearErrorGridByMCStore($mailchimpStoreId, $filters = null) $connection = $resource->getConnection('core_write'); $tableName = $resource->getTableName('mailchimp/mailchimperrors'); $where = array(); - $where []= $connection->quoteInto("mailchimp_store_id = ?", $mailchimpStoreId); + $where[] = $connection->quoteInto("mailchimp_store_id = ?", $mailchimpStoreId); if ($filters !== null) { - $where [] = $connection->quoteInto('type IN (?)', $filters); + $where[] = $connection->quoteInto('type IN (?)', $filters); } $connection->delete($tableName, $where); @@ -1035,6 +1162,7 @@ public function clearErrorGridByMCStore($mailchimpStoreId, $filters = null) /** * @param $scopeId + * @param null $filters */ public function clearErrorGridByStoreId($scopeId, $filters = null) { @@ -1044,11 +1172,11 @@ public function clearErrorGridByStoreId($scopeId, $filters = null) $where = array(); if ($scopeId !== 0) { - $where []= $connection->quoteInto("store_id = ?", $scopeId); + $where[] = $connection->quoteInto("store_id = ?", $scopeId); } if ($filters !== null) { - $where [] = $connection->quoteInto('type IN (?)', $filters); + $where[] = $connection->quoteInto('type IN (?)', $filters); } $connection->delete($tableName, $where); @@ -1075,6 +1203,7 @@ public function handleOldErrors() /** * @param $scopeId * @param $scope + * @param null $filters * @throws Mage_Core_Exception */ public function saveLastItemsSent($scopeId, $scope, $filters = null) @@ -1082,27 +1211,43 @@ public function saveLastItemsSent($scopeId, $scope, $filters = null) $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); $isSyncing = $this->getMCIsSyncing($mailchimpStoreId, $scopeId, $scope); - if ($isSyncing != 1) { + if ($isSyncing != 1 && $filters !== null) { $configValues = array(); - if ($this->getCustomerResendLastId($scopeId, $scope) !== null && in_array(Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $filters)) { + if ($this->getCustomerResendLastId($scopeId, $scope) === null + && in_array(Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $filters) + ) { $customerLastId = $this->getLastCustomerSent($scopeId, $scope); $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $customerLastId); } - if ($this->getProductResendLastId($scopeId, $scope) !== null && in_array( Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $filters)) { + + if ($this->getProductResendLastId($scopeId, $scope) === null + && in_array(Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $filters) + ) { $productLastId = $this->getLastProductSent($scopeId, $scope); $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $productLastId); } - if ($this->getOrderResendLastId($scopeId, $scope) !== null && in_array(Ebizmarts_MailChimp_Model_Config::IS_ORDER, $filters)) { + + if ($this->getOrderResendLastId($scopeId, $scope) === null + && in_array(Ebizmarts_MailChimp_Model_Config::IS_ORDER, $filters) + ) { $orderLastId = $this->getLastOrderSent($scopeId, $scope); $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $orderLastId); } - if ($this->getCartResendLastId($scopeId, $scope) !== null && in_array(Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $filters)) { + + if ($this->getCartResendLastId($scopeId, $scope) === null + && in_array(Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $filters) + ) { $cartLastId = $this->getLastCartSent($scopeId, $scope); $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $cartLastId); } - if ($this->getPromoCodeResendLastId($scopeId, $scope) !== null - && in_array(Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE .', ' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, $filters)) { + + if ($this->getPromoCodeResendLastId($scopeId, $scope) === null + && in_array( + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE . ', ' + . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, $filters + ) + ) { $promoCodeLastId = $this->getLastPromoCodeSent($scopeId, $scope); $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PCD_LAST_ID, $promoCodeLastId); } @@ -1120,7 +1265,7 @@ public function saveLastItemsSent($scopeId, $scope, $filters = null) */ protected function getLastCustomerSent($scopeId, $scope) { - $lastCustomerSent = 0; + $lastCustomerSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) @@ -1143,7 +1288,7 @@ protected function getLastCustomerSent($scopeId, $scope) */ protected function getLastProductSent($scopeId, $scope) { - $lastProductSent = 0; + $lastProductSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) @@ -1166,7 +1311,7 @@ protected function getLastProductSent($scopeId, $scope) */ protected function getLastOrderSent($scopeId, $scope) { - $lastOrderSent = 0; + $lastOrderSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) @@ -1189,7 +1334,7 @@ protected function getLastOrderSent($scopeId, $scope) */ protected function getLastCartSent($scopeId, $scope) { - $lastCartSent = 0; + $lastCartSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) @@ -1201,6 +1346,7 @@ protected function getLastCartSent($scopeId, $scope) $cartSyncData = $syncDataCollection->getFirstItem(); $lastCartSent = $cartSyncData->getRelatedId(); } + return $lastCartSent; } @@ -1211,7 +1357,7 @@ protected function getLastCartSent($scopeId, $scope) */ protected function getLastPromoCodeSent($scopeId, $scope) { - $lastPromoCodeSent = 0; + $lastPromoCodeSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); $syncDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection') ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) @@ -1230,103 +1376,141 @@ protected function getLastPromoCodeSent($scopeId, $scope) /** * Create MailChimp merge fields existing in the extension configuration page. * - * @param $scopeId - * @param $scope + * @param $scopeId + * @param $scope * @throws Exception */ public function createMergeFields($scopeId, $scope) { + $success = 0; $listId = $this->getGeneralList($scopeId, $scope); - $maps = unserialize($this->getMapFields($scopeId, $scope)); - $customFieldTypes = unserialize($this->getCustomMergeFieldsSerialized($scopeId, $scope)); - try { - $api = $this->getApi($scopeId, $scope); - $mailchimpFields = array(); + $maps = $this->unserialize($this->getMapFields($scopeId, $scope)); + $customFieldTypes = $this->unserialize($this->getCustomMergeFieldsSerialized($scopeId, $scope)); + + if (count($maps) > 30 ) { + $success = 2; + } else { try { - $mailchimpFields = $api->lists->mergeFields->getAll($listId, null, null, 50); - } catch (MailChimp_Error $e) { - $this->logError($e->getFriendlyMessage()); - } + $api = $this->getApi($scopeId, $scope); + $mailchimpFields = array(); - if (count($mailchimpFields) > 0) { - foreach ($maps as $map) { - $customAtt = $map['magento']; - $chimpTag = $map['mailchimp']; - $alreadyExists = false; - $created = false; - foreach ($mailchimpFields['merge_fields'] as $mailchimpField) { - if ($mailchimpField['tag'] == $chimpTag || strtoupper($chimpTag) == 'EMAIL') { - $alreadyExists = true; - } - } + try { + $mailchimpFields = $api->getLists()->getMergeFields()->getAll( + $listId, + null, + null, + 50 + ); + } catch (MailChimp_Error $e) { + $this->logError($e->getFriendlyMessage()); + } - if (!$alreadyExists) { - foreach ($customFieldTypes as $customFieldType) { - if ($customFieldType['value'] == $customAtt) { - try { - $api->lists->mergeFields->add($listId, $customFieldType['label'], $customFieldType['field_type'], null, $chimpTag); - } catch (MailChimp_Error $e) { - $this->logError($e->getFriendlyMessage()); - } - $created = true; - } - } + if (!empty($mailchimpFields)) { + foreach ($maps as $map) { + $customAtt = $map['magento']; + $chimpTag = $map['mailchimp']; + $alreadyExists = false; - if (!$created) { - $attrSetId = Mage::getResourceModel('eav/entity_attribute_collection') - ->setEntityTypeFilter(1) - ->addSetInfo() - ->getData(); - $label = null; - foreach ($attrSetId as $option) { - if ($option['attribute_id'] == $customAtt && $option['frontend_label']) { - $label = $option['frontend_label']; - } + foreach ($mailchimpFields['merge_fields'] as $mailchimpField) { + if ($mailchimpField['tag'] == $chimpTag || strtoupper($chimpTag) == 'EMAIL') { + $alreadyExists = true; } + } - try { - if ($label) { - //Shipping and Billing Address - if ($customAtt == 13 || $customAtt == 14) { - $api->lists->mergeFields->add($listId, $label, 'address', null, $chimpTag); - //Birthday - } elseif ($customAtt == 11) { - $api->lists->mergeFields->add($listId, $label, 'birthday', null, $chimpTag); - } else { - $api->lists->mergeFields->add($listId, $label, 'text', null, $chimpTag); - } - } - } catch (MailChimp_Error $e) { - $this->logError($e->getFriendlyMessage()); - } + if (!$alreadyExists) { + $this->_createCustomFieldTypes($customFieldTypes, $api, $customAtt, $listId, $chimpTag); } } + + $success = 1; } + } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { + $this->logError($e->getMessage()); } - } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { - $this->logError($e->getMessage()); } + + return $success; } - /** - * get Date with Microtime. - * - * @return string - */ - public function getDateMicrotime() + protected function _createCustomFieldTypes($customFieldTypes, $api, $customAtt, $listId, $chimpTag) + { + $created = false; + foreach ($customFieldTypes as $customFieldType) { + if ($customFieldType['value'] == $customAtt) { + try { + $api->lists->mergeFields->add( + $listId, + $customFieldType['label'], + $customFieldType['field_type'], + null, + $chimpTag + ); + } catch (MailChimp_Error $e) { + $this->logError($e->getFriendlyMessage()); + } + + $created = true; + } + } + + if (!$created) { + $attrSetId = Mage::getResourceModel('eav/entity_attribute_collection') + ->setEntityTypeFilter(1) + ->addSetInfo() + ->getData(); + $label = null; + foreach ($attrSetId as $option) { + if ($option['attribute_id'] == $customAtt && $option['frontend_label']) { + $label = $option['frontend_label']; + } + } + + $this->_addMergeFieldByLabel($api, $label, $customAtt, $listId, $chimpTag); + } + } + + protected function _addMergeFieldByLabel($api, $label, $customAtt, $listId, $chimpTag) { - $microtime = explode(' ', microtime()); - $msec = $microtime[0]; - $msecArray = explode('.', $msec); - $date = date('Y-m-d-H-i-s') . '-' . $msecArray[1]; - return $date; + try { + if ($label) { + //Shipping and Billing Address + if ($customAtt == 13 || $customAtt == 14) { + $api->lists->mergeFields->add( + $listId, + $label, + 'address', + null, + $chimpTag + ); + //Birthday + } elseif ($customAtt == 11) { + $api->lists->mergeFields->add( + $listId, + $label, + 'birthday', + null, + $chimpTag + ); + } else { + $api->lists->mergeFields->add( + $listId, + $label, + 'text', + null, + $chimpTag + ); + } + } + } catch (MailChimp_Error $e) { + $this->logError($e->getFriendlyMessage()); + } } /** * Get Api object for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return Ebizmarts_MailChimp|null * @throws Exception */ @@ -1335,8 +1519,17 @@ public function getApi($scopeId, $scope = null) $apiKey = $this->getApiKey($scopeId, $scope); $api = null; if ($apiKey != null && $apiKey != "") { - $timeOut = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_TIME_OUT, $scopeId, $scope); - $api = new Ebizmarts_MailChimp($apiKey, array('timeout' => $timeOut), 'Mailchimp4Magento' . (string)$this->getConfig()->getNode('modules/Ebizmarts_MailChimp/version')); + $timeOut = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_TIME_OUT, + $scopeId, + $scope + ); + $api = new Ebizmarts_MailChimp( + $apiKey, + array('timeout' => $timeOut), + 'Mailchimp4Magento' + . (string)$this->getConfig()->getNode('modules/Ebizmarts_MailChimp/version') + ); } else { $e = new Ebizmarts_MailChimp_Helper_Data_ApiKeyException('You must provide a MailChimp API key'); $this->logError($e->getTraceAsString()); @@ -1349,7 +1542,7 @@ public function getApi($scopeId, $scope = null) /** * Get Api object by ApiKey. * - * @param $apiKey + * @param $apiKey * @return Ebizmarts_MailChimp|null * @throws Ebizmarts_MailChimp_Helper_Data_ApiKeyException * @throws MailChimp_Error @@ -1358,7 +1551,12 @@ public function getApiByKey($apiKey) { $api = null; if ($apiKey != null && $apiKey != "") { - $api = new Ebizmarts_MailChimp($apiKey, null, 'Mailchimp4Magento' . (string)$this->getConfig()->getNode('modules/Ebizmarts_MailChimp/version')); + $api = new Ebizmarts_MailChimp( + $apiKey, + null, + 'Mailchimp4Magento' + . (string)$this->getConfig()->getNode('modules/Ebizmarts_MailChimp/version') + ); } else { $e = new Ebizmarts_MailChimp_Helper_Data_ApiKeyException('You must provide a MailChimp API key'); throw $e; @@ -1373,15 +1571,15 @@ public function getApiByKey($apiKey) * @param $itemId * @param $itemType * @param $mailchimpStoreId - * @param null $syncDelta - * @param null $syncError - * @param int $syncModified - * @param null $syncDeleted - * @param null $token - * @param null $syncedFlag - * @param bool $saveOnlyIfexists - * @param null $deletedRelatedId - * @param bool $allowBatchRemoval + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param null $syncDeleted + * @param null $token + * @param null $syncedFlag + * @param bool $saveOnlyIfexists + * @param null $deletedRelatedId + * @param bool $allowBatchRemoval */ public function saveEcommerceSyncData( $itemId, @@ -1398,32 +1596,13 @@ public function saveEcommerceSyncData( $allowBatchRemoval = true ) { $ecommerceSyncDataItem = $this->getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId); + if (!$saveOnlyIfexists || $ecommerceSyncDataItem->getMailchimpSyncDelta()) { - if ($syncDelta) { - $ecommerceSyncDataItem->setData("mailchimp_sync_delta", $syncDelta); - } elseif ($allowBatchRemoval) { - $ecommerceSyncDataItem->setData("batch_id", null); - } - if ($syncError) { - $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); - } - //Always set modified value to 0 when saving sync delta or errors. - $ecommerceSyncDataItem->setData("mailchimp_sync_modified", $syncModified); - if ($syncDeleted !== null) { - $ecommerceSyncDataItem->setData("mailchimp_sync_deleted", $syncDeleted); - if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT && $syncError == '') { - $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); - } - } - if ($token) { - $ecommerceSyncDataItem->setData("mailchimp_token", $token); - } - if ($deletedRelatedId) { - $ecommerceSyncDataItem->setData("deleted_related_id", $deletedRelatedId); - } - if ($syncedFlag !== null) { - $ecommerceSyncDataItem->setData("mailchimp_synced_flag", $syncedFlag); - } + $this->setEcommerceSyncDataItemValues( + $itemType, $syncDelta, $syncError, $syncModified, $syncDeleted, + $token, $syncedFlag, $deletedRelatedId, $allowBatchRemoval, $ecommerceSyncDataItem + ); + $ecommerceSyncDataItem->save(); } } @@ -1453,6 +1632,7 @@ public function getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId) ->setData("type", $itemType) ->setData("mailchimp_store_id", $mailchimpStoreId); } + return $ecommerceSyndDataItem; } @@ -1487,7 +1667,7 @@ public function addStoresToFilter($collection, $scopeId, $scope) } } - if (count($filterArray)) { + if (!empty($filterArray)) { $collection->addFieldToFilter('store_id', $filterArray); } @@ -1504,7 +1684,10 @@ public function getMailChimpScopeByStoreId($storeId) { $mailchimpScope = null; $mailChimpStoreId = $this->getMCStoreId($storeId); - $mailchimpScope = $this->getFirstScopeFromConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $mailChimpStoreId); + $mailchimpScope = $this->getFirstScopeFromConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, + $mailChimpStoreId + ); return $mailchimpScope; } @@ -1543,7 +1726,7 @@ public function getDefaultStoreIdForMailChimpScope($magentoStoreId) * @param $configValues * @param $scopeId * @param $scope - * @param bool $cleanCache + * @param bool $cleanCache */ public function saveMailchimpConfig($configValues, $scopeId, $scope, $cleanCache = true) { @@ -1572,8 +1755,8 @@ public function getMailChimpProductImageUrl($parentImageUrl, $productImageUrl) /** * Returns product image url by id, if it does not have one returns null. * - * @param $productId - * @param $magentoStoreId + * @param $productId + * @param $magentoStoreId * @return null|string * @throws Mage_Core_Model_Store_Exception */ @@ -1633,7 +1816,7 @@ public function getImageUrl($productModel, $imageSize) /** * Returns imageSize converted to camel case, and concatenates with functionName * - * @param $imageSize + * @param $imageSize * @return string */ public function getImageFunctionName($imageSize) @@ -1661,7 +1844,7 @@ protected function getImageUrlForSize($imageSize, $productModel) /** * Returns imageSize separated word by word in array * - * @param $imageSize + * @param $imageSize * @return array */ public function setImageSizeVarToArray($imageSize) @@ -1674,7 +1857,7 @@ public function setImageSizeVarToArray($imageSize) /** * Returns imageSize in camel case concatenated * - * @param $imageArray + * @param $imageArray * @return string */ public function setWordToCamelCase($imageArray) @@ -1691,7 +1874,7 @@ public function setWordToCamelCase($imageArray) /** * Returns imageSize in camel case concatenated with functionName * - * @param $functionName + * @param $functionName * @return string */ public function setFunctionName($functionName) @@ -1713,13 +1896,17 @@ protected function _getImageHelper() /** * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getImageSize($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_IMAGE_SIZE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_IMAGE_SIZE, + $scopeId, + $scope + ); } /** @@ -1806,12 +1993,13 @@ public function customMergeFieldAlreadyExists($value, $scopeId, $scope) * Get custom merge fields for given scope as an array. * * @param $scopeId - * @param null $scope + * @param null $scope * @return array|mixed */ public function getCustomMergeFields($scopeId, $scope = null) { - $customMergeFields = unserialize($this->getCustomMergeFieldsSerialized($scopeId, $scope)); + $customMergeFields = $this->unserialize($this->getCustomMergeFieldsSerialized($scopeId, $scope)); + if (!$customMergeFields) { $customMergeFields = array(); } @@ -1842,8 +2030,13 @@ public function getMCJs() $url = null; $storeId = $this->getMageApp()->getStore()->getId(); $mailchimpStoreId = $this->getMCStoreId($storeId); + if ($this->isEcomSyncDataEnabled($storeId)) { - $currentUrl = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", 0, 'default'); + $currentUrl = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", + 0, + 'default' + ); if (!empty($currentUrl)) { $url = $currentUrl; @@ -1860,21 +2053,28 @@ public function getMCJs() /** * Retrieve store data and save the MCJs URL for the current store in config table. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return bool * @throws Mage_Core_Exception */ public function retrieveAndSaveMCJsUrlInConfig($scopeId, $scope = 'stores') { $mcJsUrlSaved = false; + try { $api = $this->getApi($scopeId, $scope); $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); $response = $api->getEcommerce()->getStores()->get($mailchimpStoreId, 'connected_site'); + if (isset($response['connected_site']['site_script']['url'])) { $url = $response['connected_site']['site_script']['url']; - $configValues = array(array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", $url)); + $configValues = array( + array( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", + $url + ) + ); $this->saveMailchimpConfig($configValues, 0, 'default'); $mcJsUrlSaved = true; } @@ -1894,16 +2094,30 @@ public function retrieveAndSaveMCJsUrlInConfig($scopeId, $scope = 'stores') */ public function handleMigrationUpdates() { - $initialTime = time(); - $migrateFrom115 = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, 0, 'default'); - $migrateFrom116 = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, 0, 'default'); - $migrateFrom1164 = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, 0, 'default'); + $dateHelper = $this->getDateHelper(); + + $initialTime = $dateHelper->getTimestamp(); + $migrateFrom115 = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, + 0, + 'default' + ); + $migrateFrom116 = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, + 0, + 'default' + ); + $migrateFrom1164 = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, + 0, + 'default' + ); if ($migrateFrom115) { $this->_migrateFrom115($initialTime); - } elseif ($migrateFrom116 && !$this->timePassed($initialTime)) { + } elseif ($migrateFrom116 && !$dateHelper->timePassed($initialTime)) { $this->_migrateFrom116($initialTime); - } elseif ($migrateFrom1164 && !$this->timePassed($initialTime)) { + } elseif ($migrateFrom1164 && !$dateHelper->timePassed($initialTime)) { $this->_migrateFrom1164($initialTime); } } @@ -1911,11 +2125,12 @@ public function handleMigrationUpdates() /** * Migrate data from version 1.1.5 to the mailchimp_ecommerce_sync_data table. * - * @param $initialTime + * @param $initialTime * @throws Mage_Core_Exception */ protected function _migrateFrom115($initialTime) { + $dateHelper = $this->getDateHelper(); $arrayMigrationConfigData = array('115' => true, '116' => false, '1164' => false); //migrate data from older version to the new schemma if ($this->isEcommerceEnabled(0)) { @@ -1924,50 +2139,20 @@ protected function _migrateFrom115($initialTime) //migrate customers $this->_migrateCustomersFrom115($mailchimpStoreId, $initialTime); - if (!$this->timePassed($initialTime)) { + if (!$dateHelper->timePassed($initialTime)) { //migrate products $this->_migrateProductsFrom115($mailchimpStoreId, $initialTime); - if (!$this->timePassed($initialTime)) { + + if (!$dateHelper->timePassed($initialTime)) { //migrate orders $this->_migrateOrdersFrom115($mailchimpStoreId, $initialTime); - if (!$this->timePassed($initialTime)) { + + if (!$dateHelper->timePassed($initialTime)) { //migrate carts $finished = $this->_migrateCartsFrom115($mailchimpStoreId, $initialTime); - if ($finished) { - $this->handleDeleteMigrationConfigData($arrayMigrationConfigData); - - //Remove attributes no longer used - $setup = Mage::getResourceModel('catalog/setup', 'catalog_setup'); - try { - $setup->removeAttribute('catalog_product', 'mailchimp_sync_delta'); - $setup->removeAttribute('catalog_product', 'mailchimp_sync_error'); - $setup->removeAttribute('catalog_product', 'mailchimp_sync_modified'); - $setup->removeAttribute('customer', 'mailchimp_sync_delta'); - $setup->removeAttribute('customer', 'mailchimp_sync_error'); - $setup->removeAttribute('customer', 'mailchimp_sync_modified'); - } catch (Exception $e) { - $this->logError($e->getMessage()); - } - - $coreResource = $this->getCoreResource(); - try { - $quoteTable = $coreResource->getTableName('sales/quote'); - $setup->getConnection()->dropColumn($quoteTable, 'mailchimp_sync_delta'); - $setup->getConnection()->dropColumn($quoteTable, 'mailchimp_sync_error'); - $setup->getConnection()->dropColumn($quoteTable, 'mailchimp_deleted'); - $setup->getConnection()->dropColumn($quoteTable, 'mailchimp_token'); - } catch (Exception $e) { - $this->logError($e->getMessage()); - } - try { - $orderTable = $coreResource->getTableName('sales/order'); - $setup->getConnection()->dropColumn($orderTable, 'mailchimp_sync_delta'); - $setup->getConnection()->dropColumn($orderTable, 'mailchimp_sync_error'); - $setup->getConnection()->dropColumn($orderTable, 'mailchimp_sync_modified'); - } catch (Exception $e) { - $this->logError($e->getMessage()); - } + if ($finished) { + $this->_migrateFrom115dropColumn($arrayMigrationConfigData); } } } @@ -1977,26 +2162,69 @@ protected function _migrateFrom115($initialTime) } } - /** - * Migrate Customers from version 1.1.5 to the mailchimp_ecommerce_sync_data table. - * - * @param $mailchimpStoreId - * @param $initialTime - * @throws Mage_Core_Exception - */ - protected function _migrateCustomersFrom115($mailchimpStoreId, $initialTime) + protected function _migrateFrom115dropColumn($arrayMigrationConfigData) + { + $this->handleDeleteMigrationConfigData($arrayMigrationConfigData); + + //Remove attributes no longer used + $setup = Mage::getResourceModel('catalog/setup', 'catalog_setup'); + + try { + $setup->removeAttribute('catalog_product', 'mailchimp_sync_delta'); + $setup->removeAttribute('catalog_product', 'mailchimp_sync_error'); + $setup->removeAttribute('catalog_product', 'mailchimp_sync_modified'); + $setup->removeAttribute('customer', 'mailchimp_sync_delta'); + $setup->removeAttribute('customer', 'mailchimp_sync_error'); + $setup->removeAttribute('customer', 'mailchimp_sync_modified'); + } catch (Exception $e) { + $this->logError($e->getMessage()); + } + + $coreResource = $this->getCoreResource(); + + try { + $quoteTable = $coreResource->getTableName('sales/quote'); + $connectionQuote = $setup->getConnection(); + $connectionQuote->dropColumn($quoteTable, 'mailchimp_sync_delta'); + $connectionQuote->dropColumn($quoteTable, 'mailchimp_sync_error'); + $connectionQuote->dropColumn($quoteTable, 'mailchimp_deleted'); + $connectionQuote->dropColumn($quoteTable, 'mailchimp_token'); + } catch (Exception $e) { + $this->logError($e->getMessage()); + } + + try { + $orderTable = $coreResource->getTableName('sales/order'); + $connectionOrder = $setup->getConnection(); + $connectionOrder->dropColumn($orderTable, 'mailchimp_sync_delta'); + $connectionOrder->dropColumn($orderTable, 'mailchimp_sync_error'); + $connectionOrder->dropColumn($orderTable, 'mailchimp_sync_modified'); + } catch (Exception $e) { + $this->logError($e->getMessage()); + } + } + + /** + * Migrate Customers from version 1.1.5 to the mailchimp_ecommerce_sync_data table. + * + * @param $mailchimpStoreId + * @param $initialTime + * @throws Mage_Core_Exception + */ + protected function _migrateCustomersFrom115($mailchimpStoreId, $initialTime) { try { $entityType = Mage::getSingleton('eav/config')->getEntityType('customer'); $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'mailchimp_sync_delta'); + if ($attribute->getId()) { $mailchimpTableName = $this->getCoreResource()->getTableName('mailchimp/ecommercesyncdata'); $customerCollection = Mage::getResourceModel('customer/customer_collection'); $customerCollection->addAttributeToFilter('mailchimp_sync_delta', array('gt' => '0000-00-00 00:00:00')); $customerCollection->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = e.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = e.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); $customerCollection->getSelect()->where( @@ -2012,6 +2240,7 @@ function ($customer, $mailchimpStoreId) { $syncError = null; $syncModified = null; $syncDelta = $customerObject->getMailchimpSyncDelta(); + if ($customer->getMailchimpSyncError()) { $syncError = $customer->getMailchimpSyncError(); } @@ -2020,7 +2249,14 @@ function ($customer, $mailchimpStoreId) { $syncModified = $customer->getMailchimpSyncModified(); } - $this->saveEcommerceSyncData($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified); + $this->saveEcommerceSyncData( + $customerId, + Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified + ); } ); } @@ -2032,8 +2268,8 @@ function ($customer, $mailchimpStoreId) { /** * Migrate Products from version 1.1.5 to the mailchimp_ecommerce_sync_data table. * - * @param $mailchimpStoreId - * @param $initialTime + * @param $mailchimpStoreId + * @param $initialTime * @throws Mage_Core_Exception */ protected function _migrateProductsFrom115($mailchimpStoreId, $initialTime) @@ -2041,21 +2277,19 @@ protected function _migrateProductsFrom115($mailchimpStoreId, $initialTime) try { $entityType = Mage_Catalog_Model_Product::ENTITY; $attributeCode = 'mailchimp_sync_delta'; - $attribute = Mage::getModel('eav/entity_attribute') - ->loadByCode($entityType, $attributeCode); + $attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entityType, $attributeCode); + if ($attribute->getId()) { $mailchimpTableName = $this->getCoreResource()->getTableName('mailchimp/ecommercesyncdata'); $productCollection = Mage::getResourceModel('catalog/product_collection'); $productCollection->addAttributeToFilter('mailchimp_sync_delta', array('gt' => '0000-00-00 00:00:00')); $productCollection->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = e.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = e.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); - $productCollection->getSelect()->where( - "m4m.mailchimp_sync_delta IS null" - ); + $productCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); $this->_makeForCollectionItem( $productCollection, $mailchimpStoreId, @@ -2063,9 +2297,14 @@ protected function _migrateProductsFrom115($mailchimpStoreId, $initialTime) function ($product, $mailchimpStoreId) { $productId = $product->getEntityId(); $_resource = Mage::getResourceSingleton('catalog/product'); - $syncDelta = $_resource->getAttributeRawValue($productId, 'mailchimp_sync_delta', $this->getMageApp()->getStore()); + $syncDelta = $_resource->getAttributeRawValue( + $productId, + 'mailchimp_sync_delta', + $this->getMageApp()->getStore() + ); $syncError = null; $syncModified = null; + if ($product->getMailchimpSyncError()) { $syncError = $product->getMailchimpSyncError(); } @@ -2074,7 +2313,14 @@ function ($product, $mailchimpStoreId) { $syncModified = $product->getMailchimpSyncModified(); } - $this->saveEcommerceSyncData($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, $syncDelta, $syncError, $syncModified); + $this->saveEcommerceSyncData( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified + ); } ); } @@ -2086,8 +2332,8 @@ function ($product, $mailchimpStoreId) { /** * Migrate Orders from version 1.1.5 to the mailchimp_ecommerce_sync_data table. * - * @param $mailchimpStoreId - * @param $initialTime + * @param $mailchimpStoreId + * @param $initialTime * @throws Mage_Core_Exception */ protected function _migrateOrdersFrom115($mailchimpStoreId, $initialTime) @@ -2097,17 +2343,22 @@ protected function _migrateOrdersFrom115($mailchimpStoreId, $initialTime) $readConnection = $resource->getConnection('core_read'); $tableName = $resource->getTableName('sales/order'); $orderFields = $readConnection->describeTable($tableName); + if (isset($orderFields['mailchimp_sync_delta'])) { $mailchimpTableName = $resource->getTableName('mailchimp/ecommercesyncdata'); $orderCollection = Mage::getResourceModel('sales/order_collection'); $orderCollection->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); - $orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS NULL AND main_table.mailchimp_sync_delta > '0000-00-00 00:00:00'"); + $orderCollection->getSelect() + ->where( + "m4m.mailchimp_sync_delta IS NULL AND main_table.mailchimp_sync_delta > '0000-00-00 00:00:00'" + ); $this->_makeForCollectionItem( $orderCollection, $mailchimpStoreId, @@ -2118,6 +2369,7 @@ function ($order, $mailchimpStoreId) { $syncModified = null; $orderObject = $this->getSalesOrderModel()->load($orderId); $syncDelta = $orderObject->getMailchimpSyncDelta(); + if ($order->getMailchimpSyncError()) { $syncError = $order->getMailchimpSyncError(); } @@ -2126,7 +2378,14 @@ function ($order, $mailchimpStoreId) { $syncModified = $order->getMailchimpSyncModified(); } - $this->saveEcommerceSyncData($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified); + $this->saveEcommerceSyncData( + $orderId, + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified + ); } ); } @@ -2138,8 +2397,8 @@ function ($order, $mailchimpStoreId) { /** * Migrate Carts from version 1.1.5 to the mailchimp_ecommerce_sync_data table. * - * @param $mailchimpStoreId - * @param $initialTime + * @param $mailchimpStoreId + * @param $initialTime * @return bool * @throws Mage_Core_Exception */ @@ -2155,12 +2414,16 @@ protected function _migrateCartsFrom115($mailchimpStoreId, $initialTime) $quoteCollection = Mage::getResourceModel('sales/quote_collection'); $quoteCollection->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_QUOTE + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); // be sure that the quotes are already in mailchimp and not deleted - $quoteCollection->getSelect()->where("m4m.mailchimp_sync_delta IS NULL AND main_table.mailchimp_sync_delta > '0000-00-00 00:00:00'"); + $quoteCollection->getSelect() + ->where( + "m4m.mailchimp_sync_delta IS NULL AND main_table.mailchimp_sync_delta > '0000-00-00 00:00:00'" + ); $finished = $this->_makeForCollectionItem( $quoteCollection, $mailchimpStoreId, @@ -2184,7 +2447,16 @@ function ($quote, $mailchimpStoreId) { $token = $quote->getMailchimpToken(); } - $this->saveEcommerceSyncData($quoteId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, null, $syncDeleted, $token); + $this->saveEcommerceSyncData( + $quoteId, + Ebizmarts_MailChimp_Model_Config::IS_QUOTE, + $mailchimpStoreId, + $syncDelta, + $syncError, + null, + $syncDeleted, + $token + ); } ); } else { @@ -2193,7 +2465,13 @@ function ($quote, $mailchimpStoreId) { return $finished; } catch (Exception $e) { - $this->logError($this->__('Unexpected error happened during migration from version 1.1.5 to 1.1.6. Please contact our support at ') . 'mailchimp@ebizmarts-desk.zendesk.com' . $this->__(' See error details below.')); + $this->logError( + $this->__( + 'Unexpected error happened during migration from version 1.1.5 to 1.1.6.' + . 'Please contact our support at ' + ) . 'mailchimp@ebizmarts-desk.zendesk.com' + . $this->__(' See error details below.') + ); $this->logError($e->getMessage()); return false; } @@ -2204,7 +2482,11 @@ function ($quote, $mailchimpStoreId) { */ protected function delete115MigrationConfigData() { - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, 'default', 0); + $this->getConfig()->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, + 'default', + 0 + ); } /** @@ -2213,16 +2495,18 @@ protected function delete115MigrationConfigData() * @param $collection * @param $mailchimpStoreId * @param $initialTime - * @param Closure $callback + * @param Closure $callback * @return bool */ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initialTime, Closure $callback) { + $dateHelper = $this->getDateHelper(); + $finished = false; if (!$collection->getSize()) { $finished = true; } - // $collection->addFieldToFilter('mailchimp_sync_delta', array('gt' => '0000-00-00 00:00:00')); + $collection->setPageSize(100); $pages = $collection->getLastPageNumber(); @@ -2237,9 +2521,11 @@ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initi } $currentPage++; - // clear collection (if not done, the same page will be loaded each loop) - will also free memory + // clear collection, + // if not done, the same page will be loaded each loop + // - will also free memory $collection->clear(); - if ($this->timePassed($initialTime)) { + if ($dateHelper->timePassed($initialTime)) { break; } @@ -2250,29 +2536,6 @@ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initi return $finished; } - /** - * Check if more than 270 seconds passed since the migration started to prevent the job to take too long. - * - * @param $initialTime - * @return bool - */ - public function timePassed($initialTime) - { - $storeCount = count($this->getMageApp()->getStores()); - $timePassed = false; - $finalTime = time(); - $difference = $finalTime - $initialTime; - //Set minimum of 30 seconds per store view. - $timeForAllStores = (30 * $storeCount); - //Set total time in 4:30 minutes if it is lower. - $timeAmount = ($timeForAllStores < 270) ? 270 : $timeForAllStores; - if ($difference > $timeAmount) { - $timePassed = true; - } - - return $timePassed; - } - /** * Migrate data from version 1.1.6. * @@ -2313,8 +2576,9 @@ protected function _setIsSyncingIfFinishedInAllStores($syncValue) */ protected function _migrateOrdersFrom116($initialTime) { + $dateHelper = $this->getDateHelper(); $finished = false; - if (!$this->timePassed($initialTime)) { + if (!$dateHelper->timePassed($initialTime)) { $finished = true; $stores = $this->getMageApp()->getStores(); foreach ($stores as $storeId => $store) { @@ -2322,7 +2586,7 @@ protected function _migrateOrdersFrom116($initialTime) Mage::getModel('mailchimp/api_batches')->replaceAllOrders($initialTime, $storeId); } - if ($this->timePassed($initialTime)) { + if ($dateHelper->timePassed($initialTime)) { $finished = false; break; } @@ -2342,9 +2606,21 @@ public function migrationFinished() { $migrationFinished = false; - $migrateFrom115 = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, 0, 'default'); - $migrateFrom116 = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, 0, 'default'); - $migrateFrom1164 = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, 0, 'default'); + $migrateFrom115 = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, + 0, + 'default' + ); + $migrateFrom116 = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, + 0, + 'default' + ); + $migrateFrom1164 = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, + 0, + 'default' + ); if (!$migrateFrom115 && !$migrateFrom116 && !$migrateFrom1164) { $migrationFinished = true; @@ -2359,9 +2635,17 @@ public function migrationFinished() public function delete116MigrationConfigData() { $stores = $this->getMageApp()->getStores(); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, 'default', 0); + $this->getConfig()->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, + 'default', + 0 + ); foreach ($stores as $storeId => $store) { - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, 'stores', $storeId); + $this->getConfig()->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, + 'stores', + $storeId + ); } } @@ -2372,7 +2656,8 @@ public function delete116MigrationConfigData() */ protected function _migrateFrom1164($initialTime) { - if (!$this->timePassed($initialTime)) { + $dateHelper = $this->getDateHelper(); + if (!$dateHelper->timePassed($initialTime)) { $write_connection = $this->getCoreResource()->getConnection('core_write'); $resource = Mage::getResourceModel('mailchimp/ecommercesyncdata'); $write_connection->update($resource->getMainTable(), array('batch_id' => '1'), "batch_id = 0"); @@ -2386,7 +2671,11 @@ protected function _migrateFrom1164($initialTime) */ protected function delete1164MigrationConfigData() { - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, 'default', 0); + $this->getConfig()->deleteConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, + 'default', + 0 + ); } /** @@ -2415,7 +2704,7 @@ public function handleDeleteMigrationConfigData($arrayMigrationConfigData) * Return the list of magento store IDs configured to synchronise to * the given mailchimp list ID. * - * @param $listId + * @param $listId * @return array|mixed|null * @throws Mage_Core_Exception */ @@ -2427,7 +2716,10 @@ public function getMagentoStoreIdsByListId($listId) $storeIds = array(); foreach ($stores as $storeId => $store) { if ($this->isSubscriptionEnabled($storeId)) { - $storeListId = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $storeId); + $storeListId = $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, + $storeId + ); if ($storeListId == $listId) { $storeIds[] = $storeId; } @@ -2444,8 +2736,8 @@ public function getMagentoStoreIdsByListId($listId) * Return the newsletter subscriber model for the given subscriber email * address for magento stores subscribed to the given Mailchimp List ID. * - * @param $listId - * @param $email + * @param $listId + * @param $email * @return false|Mage_Core_Model_Abstract|null * @throws Mage_Core_Exception */ @@ -2456,7 +2748,7 @@ public function loadListSubscriber($listId, $email) $storeIds = $this->getMagentoStoreIdsByListId($listId); //add store id 0 for those created from the back end. $storeIds[] = 0; - if (count($storeIds) > 0) { + if (!empty($storeIds)) { $subscriber = Mage::getModel('newsletter/subscriber')->getCollection() ->addFieldToFilter('store_id', array('in' => $storeIds)) ->addFieldToFilter('subscriber_email', $email) @@ -2492,8 +2784,8 @@ public function loadListSubscriber($listId, $email) * Return the customer model for the given subscriber email * address for magento stores subscribed to the given Mailchimp List ID. * - * @param $listId - * @param $email + * @param $listId + * @param $email * @return Mage_Core_Model_Abstract|null * @throws Mage_Core_Exception */ @@ -2502,7 +2794,7 @@ public function loadListCustomer($listId, $email) $customer = null; $storeIds = $this->getMagentoStoreIdsByListId($listId); - if (count($storeIds) > 0) { + if (!empty($storeIds)) { $customer = Mage::getResourceModel('customer/customer_collection') ->addFieldToFilter('store_id', array('in' => $storeIds)) ->addFieldToFilter('email', array('eq' => $email)) @@ -2519,11 +2811,15 @@ public function loadListCustomer($listId, $email) /** * @param $scopeId - * @param string $scope + * @param string $scope */ public function handleWebhookChange($scopeId, $scope = 'stores') { - $webhookScope = $this->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $scopeId, $scope); + $webhookScope = $this->getRealScopeForConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, + $scopeId, + $scope + ); $listId = $this->getGeneralList($scopeId, $scope); $this->deleteCurrentWebhook($webhookScope['scope_id'], $webhookScope['scope'], $listId); if ($this->isSubscriptionEnabled($scopeId, $scope)) { @@ -2552,17 +2848,13 @@ protected function deleteCurrentWebhook($scopeId, $scope, $listId) $this->logError($e->getMessage()); } - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $scope, $scopeId); + $this->getConfig() + ->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $scope, $scopeId); } else { $webhookUrl = $this->getWebhookUrl($scopeId, $scope); try { if ($listId) { - $webhooks = $api->lists->webhooks->getAll($listId); - foreach ($webhooks['webhooks'] as $webhook) { - if (strpos($webhook['url'], $webhookUrl) !== false) { - $api->lists->webhooks->delete($listId, $webhook['id']); - } - } + $this->_deletedWebhooksByListId($api, $listId, $webhookUrl); } } catch (MailChimp_Error $e) { $this->logError($e->getFriendlyMessage()); @@ -2575,6 +2867,16 @@ protected function deleteCurrentWebhook($scopeId, $scope, $listId) } } + protected function _deletedWebhooksByListId($api, $listId, $webhookUrl) + { + $webhooks = $api->lists->webhooks->getAll($listId); + foreach ($webhooks['webhooks'] as $webhook) { + if (strpos($webhook['url'], $webhookUrl) !== false) { + $api->lists->webhooks->delete($listId, $webhook['id']); + } + } + } + /** * Returns true on successful creation, or error message if it fails */ @@ -2623,6 +2925,7 @@ public function createNewWebhook($scopeId, $scope, $listId) } } } + if ($createWebhook) { $newWebhook = $api->lists->webhooks->add($listId, $hookUrl, $events, $sources); $newWebhookId = $newWebhook['id']; @@ -2635,9 +2938,13 @@ public function createNewWebhook($scopeId, $scope, $listId) } catch (MailChimp_Error $e) { $errorMessage = $e->getFriendlyMessage(); $this->logError($errorMessage); - $textToCompare = 'The resource submitted could not be validated. For field-specific details, see the \'errors\' array.'; + $textToCompare = 'The resource submitted could not be validated. ' + . 'For field-specific details, see the \'errors\' array.'; + if ($e->getMailchimpDetails() == $textToCompare) { - $errorMessage = 'Your store could not be accessed by MailChimp\'s Api. Please confirm the URL: ' . $hookUrl . ' is accessible externally to allow the webhook creation.'; + $errorMessage = 'Your store could not be accessed by MailChimp\'s Api. ' + . 'Please confirm the URL: ' . $hookUrl + . ' is accessible externally to allow the webhook creation.'; $this->logError($errorMessage); } @@ -2678,7 +2985,7 @@ protected function getWebhookUrl() /** * @param $path * @param $scopeId - * @param string $scope + * @param string $scope * @return array|null */ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') @@ -2717,7 +3024,6 @@ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') } break; } - } return $scopeSoFar; @@ -2726,9 +3032,9 @@ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') /** * Return true if the configPath has been saved specifically for the given scope. * - * @param $configPath - * @param $scopeId - * @param string $scope + * @param $configPath + * @param $scopeId + * @param string $scope * @return bool|mixed * @throws Mage_Core_Exception */ @@ -2736,7 +3042,9 @@ public function getIfConfigExistsForScope($configPath, $scopeId, $scope = 'store { $configPathArray = explode('/', $configPath); $configName = $configPathArray[2]; - $configAssociatedToScope = Mage::registry('mailchimp_' . $configName . '_exists_for_scope_' . $scope . '_' . $scopeId); + $configAssociatedToScope = Mage::registry( + 'mailchimp_' . $configName . '_exists_for_scope_' . $scope . '_' . $scopeId + ); if ($configAssociatedToScope === null) { $configAssociatedToScope = false; $collection = Mage::getResourceModel('core/config_data_collection') @@ -2750,7 +3058,13 @@ public function getIfConfigExistsForScope($configPath, $scopeId, $scope = 'store } } } - Mage::register('mailchimp_' . $configName . '_exists_for_scope_' . $scope . '_' . $scopeId, $configAssociatedToScope); + + Mage::register( + 'mailchimp_' . $configName + . '_exists_for_scope_' . $scope + . '_' . $scopeId, + $configAssociatedToScope + ); } return $configAssociatedToScope; @@ -2759,7 +3073,7 @@ public function getIfConfigExistsForScope($configPath, $scopeId, $scope = 'store /** * Will return the first scope it finds, intended for Api calls usage. * - * @param $mailChimpStoreId + * @param $mailChimpStoreId * @return array */ public function getScopeByMailChimpStoreId($mailChimpStoreId) @@ -2779,8 +3093,8 @@ public function getScopeByMailChimpStoreId($mailChimpStoreId) /** * Will return the first scope it finds,from core_config_data. * - * @param $path - * @param $value + * @param $path + * @param $value * @return array|null */ public function getFirstScopeFromConfig($path, $value) @@ -2800,31 +3114,42 @@ public function getFirstScopeFromConfig($path, $value) /** * Return true if the config entry does not belong to the store required or website that contains that store. * - * @param $config - * @param $scope - * @param $scopeId - * @param $websiteId + * @param $config + * @param $scope + * @param $scopeId + * @param $websiteId * @return bool */ protected function isExtraEntry($config, $scope, $scopeId, $websiteId) { - return $this->isNotDefaultScope($config) && ($this->isIncorrectScope($config, $scope) || $this->isDifferentWebsite($config, $scope, $websiteId) || $this->isDifferentStoreView($config, $scope, $scopeId)); + return $this->isNotDefaultScope($config) + && ($this->isIncorrectScope($config, $scope) + || $this->isDifferentWebsite($config, $scope, $websiteId) + || $this->isDifferentStoreView($config, $scope, $scopeId)); } - public function updateSubscriberSyndData($itemId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncDeleted = null) - { + public function updateSubscriberSyndData( + $itemId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncDeleted = null + ) { $subscriber = Mage::getModel('newsletter/subscriber')->load($itemId); if ($subscriber->getId()) { if ($syncDelta) { $subscriber->setData("mailchimp_sync_delta", $syncDelta); } + if ($syncError) { $subscriber->setData("mailchimp_sync_error", $syncError); } + $subscriber->setData("mailchimp_sync_modified", $syncModified); if ($syncDeleted) { $subscriber->setData("mailchimp_sync_deleted", $syncDeleted); } + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE); $subscriber->save(); } @@ -2833,14 +3158,18 @@ public function updateSubscriberSyndData($itemId, $syncDelta = null, $syncError /** * Get date configured for subscriber data to be sent for the given scope. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getSubMinSyncDateFlag($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, + $scopeId, + $scope + ); } /** @@ -2851,7 +3180,7 @@ public function getSubMinSyncDateFlag($scopeId, $scope = 'stores') */ public function addEntriesToArray($batchArray, $productData, $counter) { - if (count($productData)) { + if (!empty($productData)) { foreach ($productData as $p) { if (!empty($p)) { $batchArray[$counter] = $p; @@ -2873,32 +3202,38 @@ public function getApiStores() /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getCheckoutSubscribeValue($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_CHECKOUT_SUBSCRIBE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_CHECKOUT_SUBSCRIBE, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return bool * @throws Mage_Core_Exception */ public function isCheckoutSubscribeEnabled($scopeId, $scope = 'stores') { - return ($this->isSubscriptionEnabled($scopeId, $scope) && $this->getCheckoutSubscribeValue($scopeId, $scope) != Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::DISABLED); + return ($this->isSubscriptionEnabled($scopeId, $scope) + && $this->getCheckoutSubscribeValue($scopeId, $scope) + != Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::DISABLED); } /** * Modify is_syncing value if initial sync finished in given scope. * - * @param $syncValue - * @param $scopeId - * @param string $scope + * @param $syncValue + * @param $scopeId + * @param string $scope * @throws Mage_Core_Exception */ protected function setIsSyncingIfFinishedPerScope($syncValue, $scopeId, $scope = 'stores') @@ -2918,7 +3253,7 @@ protected function setIsSyncingIfFinishedPerScope($syncValue, $scopeId, $scope = /** * @param $value * @param $scopeId - * @param string $scope + * @param string $scope */ public function setResendTurn($value, $scopeId, $scope = 'stores') { @@ -2928,79 +3263,107 @@ public function setResendTurn($value, $scopeId, $scope = 'stores') /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getResendTurn($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getResendEnabled($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getCustomerResendLastId($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getProductResendLastId($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getOrderResendLastId($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getCartResendLastId($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getPromoCodeResendLastId($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PCD_LAST_ID, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PCD_LAST_ID, + $scopeId, + $scope + ); } /** @@ -3034,11 +3397,16 @@ public function addResendFilter($collection, $magentoStoreId, $itemType) break; default: $lastItemSent = 0; - $this->logError($this->__('The item type sent in the filter does not match any of the available options.')); + $this->logError( + $this->__( + 'The item type sent in the filter does not match any of the available options.' + ) + ); } + if ($resendTurn) { $collection->addFieldToFilter($keyCol, array('lteq' => $lastItemSent)); - } else { + } elseif ($lastItemSent !== null) { $collection->addFieldToFilter($keyCol, array('gt' => $lastItemSent)); } } @@ -3048,7 +3416,7 @@ public function addResendFilter($collection, $magentoStoreId, $itemType) * Check if all items have been sent and delete config values used in the resend process * * @param $scopeId - * @param string $scope + * @param string $scope */ public function handleResendFinish($scopeId, $scope = 'stores') { @@ -3060,23 +3428,24 @@ public function handleResendFinish($scopeId, $scope = 'stores') /** * @param $scopeId - * @param string $scope + * @param string $scope */ protected function deleteResendConfigValues($scopeId, $scope = 'stores') { - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $scope, $scopeId); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $scope, $scopeId); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $scope, $scopeId); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $scope, $scopeId); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PCD_LAST_ID, $scope, $scopeId); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $scope, $scopeId); - $this->getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, $scope, $scopeId); - $this->getConfig()->cleanCache(); + $config = $this->getConfig(); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $scope, $scopeId); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $scope, $scopeId); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $scope, $scopeId); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $scope, $scopeId); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PCD_LAST_ID, $scope, $scopeId); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $scope, $scopeId); + $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, $scope, $scopeId); + $config->cleanCache(); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return bool */ protected function allResendItemsSent($scopeId, $scope = 'stores') @@ -3122,7 +3491,6 @@ public function handleResendDataBefore() public function handleResendDataAfter() { $configCollection = $this->getResendTurnConfigCollection(); - foreach ($configCollection as $config) { $scope = $config->getScope(); $scopeId = $config->getScopeId(); @@ -3135,6 +3503,7 @@ public function handleResendDataAfter() } else { $this->setResendTurn(1, $scopeId, $scope); } + $this->handleResendFinish($scopeId, $scope); } else { //if ecommerce data sync is disabled delete old config values. @@ -3152,25 +3521,44 @@ protected function allResendItemsSentPerStoreView($storeId) { $customerId = $this->getCustomerResendLastId($storeId); if ($customerId) { - $isMissingCustomer = $this->isMissingItemLowerThanId($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $storeId); + $isMissingCustomer = $this->isMissingItemLowerThanId( + $customerId, + Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, + $storeId + ); } else { $isMissingCustomer = false; } + $productId = $this->getProductResendLastId($storeId); if ($productId) { - $isMissingProduct = $this->isMissingItemLowerThanId($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $storeId); + $isMissingProduct = $this->isMissingItemLowerThanId( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $storeId + ); } else { $isMissingProduct = false; } + $orderId = $this->getOrderResendLastId($storeId); if ($orderId) { - $isMissingOrder = $this->isMissingItemLowerThanId($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $storeId); + $isMissingOrder = $this->isMissingItemLowerThanId( + $orderId, + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $storeId + ); } else { $isMissingOrder = false; } + $cartId = $this->getCartResendLastId($storeId); if ($cartId) { - $isMissingCart = $this->isMissingItemLowerThanId($cartId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $storeId); + $isMissingCart = $this->isMissingItemLowerThanId( + $cartId, + Ebizmarts_MailChimp_Model_Config::IS_QUOTE, + $storeId + ); } else { $isMissingCart = false; } @@ -3198,6 +3586,7 @@ protected function allResendItemsSentPerScope($stores) } else { $storeId = $store; } + $allItemsSentInCurrentStore = $this->allResendItemsSentPerStoreView($storeId); if (!$allItemsSentInCurrentStore) { $allItemsSent = false; @@ -3247,8 +3636,10 @@ protected function isMissingCustomerLowerThanId($itemId, $storeId) $customerCollection = Mage::getResourceModel('customer/customer_collection') ->addFieldToFilter('store_id', array('eq' => $storeId)) ->addFieldToFilter('entity_id', array('lteq' => $itemId)); - Mage::getModel('mailchimp/api_customers')->joinMailchimpSyncDataWithoutWhere($customerCollection, $mailchimpStoreId); + Mage::getModel('mailchimp/api_customers') + ->joinMailchimpSyncDataWithoutWhere($customerCollection, $mailchimpStoreId); $customerCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($customerCollection->getSize()) { $isMissing = true; } else { @@ -3270,9 +3661,11 @@ protected function isMissingProductLowerThanId($itemId, $storeId) $productCollection = Mage::getResourceModel('catalog/product_collection') ->addStoreFilter($storeId) ->addFieldToFilter('entity_id', array('lteq' => $itemId)); + $productCollection->addFinalPrice(); $apiProducts->joinQtyAndBackorders($productCollection); - $apiProducts->joinMailchimpSyncDataWithoutWhere($productCollection, $mailchimpStoreId); + $apiProducts->joinMailchimpSyncData($productCollection, $mailchimpStoreId); $productCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($productCollection->getSize()) { $isMissing = true; } else { @@ -3297,7 +3690,9 @@ protected function isMissingOrderLowerThanId($itemId, $storeId) if ($firstDate) { $orderCollection->addFieldToFilter('created_at', array('gt' => $firstDate)); } - Mage::getModel('mailchimp/api_orders')->joinMailchimpSyncDataWithoutWhere($orderCollection, $mailchimpStoreId); + + Mage::getModel('mailchimp/api_orders') + ->joinMailchimpSyncDataWithoutWhere($orderCollection, $mailchimpStoreId); $orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); if ($orderCollection->getSize()) { $isMissing = true; @@ -3326,7 +3721,9 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) if ($firstDate) { $quoteCollection->addFieldToFilter('updated_at', array('gt' => $firstDate)); } - Mage::getModel('mailchimp/api_carts')->joinMailchimpSyncDataWithoutWhere($quoteCollection, $mailchimpStoreId); + + Mage::getModel('mailchimp/api_carts') + ->joinMailchimpSyncDataWithoutWhere($quoteCollection, $mailchimpStoreId); $quoteCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); if ($quoteCollection->getSize()) { $isMissing = true; @@ -3340,7 +3737,7 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) /** * @param $campaignId * @param $scopeId - * @param string $scope + * @param string $scope * @return null */ public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'stores') @@ -3353,6 +3750,7 @@ public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'st if (isset($campaignData['settings']['title'])) { $campaignName = $campaignData['settings']['title']; } + if ($campaignName == '' && isset($campaignData['settings']['subject_line'])) { $campaignName = $campaignData['settings']['subject_line']; } @@ -3374,7 +3772,10 @@ public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'st */ public function getCustomerAmountLimit() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_AMOUNT, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_AMOUNT, + 0, 'default' + ); } /** @@ -3383,7 +3784,11 @@ public function getCustomerAmountLimit() */ public function getProductAmountLimit() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_AMOUNT, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_AMOUNT, + 0, + 'default' + ); } /** @@ -3392,7 +3797,11 @@ public function getProductAmountLimit() */ public function getOrderAmountLimit() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_AMOUNT, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_AMOUNT, + 0, + 'default' + ); } /** @@ -3401,7 +3810,11 @@ public function getOrderAmountLimit() */ public function getPromoRuleAmountLimit() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_AMOUNT, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_AMOUNT, + 0, + 'default' + ); } /** @@ -3410,7 +3823,11 @@ public function getPromoRuleAmountLimit() */ public function getCartAmountLimit() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::CART_AMOUNT, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::CART_AMOUNT, + 0, + 'default' + ); } /** @@ -3419,12 +3836,16 @@ public function getCartAmountLimit() */ public function getSubscriberAmountLimit() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBSCRIBER_AMOUNT, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_SUBSCRIBER_AMOUNT, + 0, + 'default' + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return string * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception @@ -3433,10 +3854,14 @@ public function getStoreLanguageCode($scopeId, $scope = 'stores') { $isAdmin = $this->isAdmin(); $userLangCode = Mage::app()->getLocale()->getLocaleCode(); - if ($isAdmin || '' == $lang = $this->_lang2MCLanguage($userLangCode)) { + if ($isAdmin || '' == $lang = $this->_langToMCLanguage($userLangCode)) { // IS Admin OR if users lang is not supported, try store views default locale - $userLangCode = $this->getConfigValueForScope(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $scopeId, $scope); - $lang = $this->_lang2MCLanguage($userLangCode); + $userLangCode = $this->getConfigValueForScope( + Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, + $scopeId, + $scope + ); + $lang = $this->_langToMCLanguage($userLangCode); } return $lang; @@ -3444,7 +3869,7 @@ public function getStoreLanguageCode($scopeId, $scope = 'stores') /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3455,7 +3880,7 @@ public function getStoreTimeZone($scopeId, $scope = 'stores') /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3482,7 +3907,7 @@ public function getAllMailChimpStoreIds() /** * @param $subscriber - * @param bool $forceUpdateStatus + * @param bool $forceUpdateStatus */ public function subscribeMember($subscriber, $forceUpdateStatus = false) { @@ -3596,7 +4021,11 @@ public function getConfig() */ public function wasProductImageCacheFlushed() { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::PRODUCT_IMAGE_CACHE_FLUSH, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::PRODUCT_IMAGE_CACHE_FLUSH, + 0, + 'default' + ); } /** @@ -3606,21 +4035,24 @@ public function wasProductImageCacheFlushed() */ public function getApiByMailChimpStoreId($mailchimpStoreId) { - $api = null; - $scopeArray = $this->getFirstScopeFromConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $mailchimpStoreId); + $scopeArray = $this->getFirstScopeFromConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, + $mailchimpStoreId + ); try { $api = $this->getApi($scopeArray['scope_id'], $scopeArray['scope']); } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $this->logError($e->getMessage()); } + return $api; } /** * Compare old api key with new one and return true if they belong to the same MailChimp account. * - * @param $oldApiKey - * @param $newApiKey + * @param $oldApiKey + * @param $newApiKey * @return bool */ public function isNewApiKeyForSameAccount($oldApiKey, $newApiKey) @@ -3654,7 +4086,7 @@ public function isNewApiKeyForSameAccount($oldApiKey, $newApiKey) /** * @param $scopeId - * @param string $scope + * @param string $scope */ public function resendSubscribers($scopeId, $scope = 'stores') { @@ -3708,18 +4140,21 @@ protected function makeWhereString($connection, $scopeId, $scope) { $storesForScope = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope); $whereString = "mailchimp_campaign_id IS NOT NULL"; - if (count($storesForScope)) { + if (!empty($storesForScope)) { $whereString .= " AND ("; } + $counter = 0; foreach ($storesForScope as $storeId) { if ($counter) { $whereString .= " OR "; } + $whereString .= $connection->quoteInto("store_id = ?", $storeId); $counter++; } - if (count($storesForScope)) { + + if (!empty($storesForScope)) { $whereString .= ")"; } @@ -3728,19 +4163,20 @@ protected function makeWhereString($connection, $scopeId, $scope) /** * Convert language into Mailchimp compatible language code. - * @param string $languageCode + * + * @param string $languageCode * @return string Returns empty string if not MC Language match found */ - private function _lang2MCLanguage($languageCode = '') + protected function _langToMCLanguage($languageCode = '') { $mailchimpLanguage = ''; if (in_array($languageCode, self::$MAILCHIMP_LANGUAGES)) { $mailchimpLanguage = $languageCode; } else { - $langIso2 = substr($languageCode, 0, 2); - if (in_array($langIso2, self::$MAILCHIMP_LANGUAGES)) { - $mailchimpLanguage = $langIso2; + $langIso = substr($languageCode, 0, 2); + if (in_array($langIso, self::$MAILCHIMP_LANGUAGES)) { + $mailchimpLanguage = $langIso; } } @@ -3749,24 +4185,32 @@ private function _lang2MCLanguage($languageCode = '') /** * @param $scopeId - * @param string $scope + * @param string $scope * @return bool * @throws Mage_Core_Exception */ public function isSubscriptionConfirmationEnabled($scopeId, $scope = 'stores') { - return (bool)$this->getConfigValueForScope(Mage_Newsletter_Model_Subscriber::XML_PATH_CONFIRMATION_FLAG, $scopeId, $scope); + return (bool)$this->getConfigValueForScope( + Mage_Newsletter_Model_Subscriber::XML_PATH_CONFIRMATION_FLAG, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param null $scope + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ public function getPromoConfig($scopeId, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SEND_PROMO, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SEND_PROMO, + $scopeId, + $scope + ); } /** @@ -3777,14 +4221,29 @@ public function getPromoConfig($scopeId, $scope = null) public function getSyncFlagDataHtml($dat, $string) { $syncFlagDataArray = $this->getSyncFlagDataArray($dat); - if ($syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_STATUS] != Ebizmarts_MailChimp_Model_System_Config_Source_Account::IN_PROGRESS) { - if ($syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_STATUS] == Ebizmarts_MailChimp_Model_System_Config_Source_Account::FINISHED) { - $string .= "
  • {$syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_LABEL]} : {$this->__('Finished')}
  • "; + $syncFlagStatus = Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_STATUS; + $inProgress = Ebizmarts_MailChimp_Model_System_Config_Source_Account::IN_PROGRESS; + + if ($syncFlagDataArray[$syncFlagStatus] != $inProgress) { + $FINISHED = Ebizmarts_MailChimp_Model_System_Config_Source_Account::FINISHED; + + if ($syncFlagDataArray[$syncFlagStatus] == $FINISHED) { + $string .= + "
  • {$syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_LABEL]}" + . ": {$this->__('Finished')}
  • "; } else { - $string .= "
  • {$syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_LABEL]} : " . $this->__('Finished at %s', $syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_STATUS]) . "
  • "; + $string .= + "
  • {$syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_LABEL]}" + . ": " + . $this->__( + 'Finished at %s', + $syncFlagDataArray[$syncFlagStatus] + ) . "
  • "; } } else { - $string .= "
  • {$syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_LABEL]} : {$this->__('In Progress')}
  • "; + $string .= + "
  • {$syncFlagDataArray[Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_FLAG_LABEL]}" + . ": {$this->__('In Progress')}
  • "; } return $string; @@ -3880,7 +4339,7 @@ public function getListInterestCategoriesByKeyAndList($apiKey, $listId) /** * @param $scopeId - * @param string $scope + * @param string $scope * @return array * @throws Exception */ @@ -3892,12 +4351,15 @@ public function getListInterestGroups($scopeId, $scope = 'stores') try { $apiInterestCategory = $api->getLists()->getInterestCategory(); $interestCategories = $apiInterestCategory->getAll($listId, 'categories'); + foreach ($interestCategories['categories'] as $interestCategory) { $interestGroups = $apiInterestCategory->getInterests()->getAll($listId, $interestCategory['id']); $groups = array(); + foreach ($interestGroups['interests'] as $interestGroup) { $groups[$interestGroup['id']] = $interestGroup['name']; } + $interestGroupsArray[] = array( 'id' => $interestCategory['id'], 'title' => $interestCategory['title'], @@ -3914,35 +4376,47 @@ public function getListInterestGroups($scopeId, $scope = 'stores') /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getLocalInterestCategories($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_CATEGORIES, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_CATEGORIES, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getCheckoutSuccessHtmlBefore($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_BEFORE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_BEFORE, + $scopeId, + $scope + ); } /** * @param $scopeId - * @param string $scope + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ public function getCheckoutSuccessHtmlAfter($scopeId, $scope = 'stores') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_AFTER, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_AFTER, + $scopeId, + $scope + ); } /** @@ -3954,27 +4428,41 @@ public function getInterest($storeId) { $rc = array(); $interest = $this->getLocalInterestCategories($storeId); + if ($interest != '') { $interest = explode(",", $interest); - } else { $interest = array(); } + $api = $this->getApi($storeId); $listId = $this->getGeneralList($storeId); try { $apiInterestCategory = $api->getLists()->getInterestCategory(); $allInterest = $apiInterestCategory->getAll($listId); + foreach ($allInterest['categories'] as $item) { if (in_array($item['id'], $interest)) { - $rc[$item['id']]['interest'] = array('id' => $item['id'], 'title' => $item['title'], 'type' => $item['type']); + $rc[$item['id']]['interest'] = + array( + 'id' => $item['id'], + 'title' => $item['title'], + 'type' => $item['type'] + ); } } + $apiInterestCategoryInterest = $apiInterestCategory->getInterests(); + foreach ($interest as $interestId) { $mailchimpInterest = $apiInterestCategoryInterest->getAll($listId, $interestId); foreach ($mailchimpInterest['interests'] as $mi) { - $rc[$mi['category_id']]['category'][$mi['display_order']] = array('id' => $mi['id'], 'name' => $mi['name'], 'checked' => false); + $rc[$mi['category_id']]['category'][$mi['display_order']] = + array( + 'id' => $mi['id'], + 'name' => $mi['name'], + 'checked' => false + ); } } } catch (MailChimp_Error $e) { @@ -3988,7 +4476,7 @@ public function getInterest($storeId) * @param $customerId * @param $subscriberId * @param $storeId - * @param null $interest + * @param null $interest * @return array|null * @throws Mage_Core_Exception * @throws MailChimp_Error @@ -4002,31 +4490,9 @@ public function getInterestGroups($customerId, $subscriberId, $storeId, $interes $interestGroup = $this->getInterestGroupModel(); $interestGroup->getByRelatedIdStoreId($customerId, $subscriberId, $storeId); + if ($interestGroup->getId()) { - $groups = $this->arrayDecode($interestGroup->getGroupdata()); - foreach ($groups as $key => $value) { - if (isset($interest[$key])) { - if (is_array($value)) { - foreach ($value as $groupId) { - foreach ($interest[$key]['category'] as $gkey => $gvalue) { - if ($gvalue['id'] == $groupId) { - $interest[$key]['category'][$gkey]['checked'] = true; - } elseif (!isset($interest[$key]['category'][$gkey]['checked'])) { - $interest[$key]['category'][$gkey]['checked'] = false; - } - } - } - } else { - foreach ($interest[$key]['category'] as $gkey => $gvalue) { - if ($gvalue['id'] == $value) { - $interest[$key]['category'][$gkey]['checked'] = true; - } else { - $interest[$key]['category'][$gkey]['checked'] = false; - } - } - } - } - } + $interest = $this->_getInsterestChecked($interestGroup, $interest); } return $interest; @@ -4035,11 +4501,48 @@ public function getInterestGroups($customerId, $subscriberId, $storeId, $interes } } + protected function _getInsterestChecked($interestGroup, $interest) + { + $groups = $this->arrayDecode($interestGroup->getGroupdata()); + + foreach ($groups as $key => $value) { + if (isset($interest[$key])) { + if (is_array($value)) { + foreach ($value as $groupId) { + $interest = $this->_getInterestCheckedByGroupId($interest, $key, $groupId); + } + } else { + foreach ($interest[$key]['category'] as $gkey => $gvalue) { + if ($gvalue['id'] == $value) { + $interest[$key]['category'][$gkey]['checked'] = true; + } else { + $interest[$key]['category'][$gkey]['checked'] = false; + } + } + } + } + } + + return $interest; + } + + protected function _getInterestCheckedByGroupId($interest, $key, $groupId) + { + foreach ($interest[$key]['category'] as $gkey => $gvalue) { + if ($gvalue['id'] == $groupId) { + $interest[$key]['category'][$gkey]['checked'] = true; + } elseif (!isset($interest[$key]['category'][$gkey]['checked'])) { + $interest[$key]['category'][$gkey]['checked'] = false; + } + } + + return $interest; + } /** * Format array to save in database. * - * @param $array + * @param $array * @return string */ public function arrayEncode($array) @@ -4050,7 +4553,7 @@ public function arrayEncode($array) /** * Set database encoded array to normal array * - * @param $encodedArray + * @param $encodedArray * @return mixed */ public function arrayDecode($encodedArray) @@ -4061,13 +4564,15 @@ public function arrayDecode($encodedArray) /** * @param $params * @param $storeId - * @param null $customerId - * @param null $subscriber + * @param null $customerId + * @param null $subscriber * @throws Mage_Core_Model_Store_Exception */ public function saveInterestGroupData($params, $storeId, $customerId = null, $subscriber = null) { + $dateHelper = $this->getDateHelper(); $groups = $this->getInterestGroupsIfAvailable($params); + if ($groups) { if (!$customerId) { $customerSession = $this->getCustomerSession(); @@ -4080,6 +4585,7 @@ public function saveInterestGroupData($params, $storeId, $customerId = null, $su } $subscriberId = null; + if ($subscriber) { $subscriberId = $subscriber->getSubscriberId(); } @@ -4088,6 +4594,7 @@ public function saveInterestGroupData($params, $storeId, $customerId = null, $su $interestGroup->getByRelatedIdStoreId($customerId, $subscriberId, $storeId); $origSubscriberId = $interestGroup->getSubscriberId(); $origCustomerId = $interestGroup->getCustomerId(); + if (!$origSubscriberId || $subscriberId && $origSubscriberId != $subscriberId) { $interestGroup->setSubscriberId($subscriberId); } @@ -4104,7 +4611,7 @@ public function saveInterestGroupData($params, $storeId, $customerId = null, $su $interestGroup->setStoreId($storeId); } - $interestGroup->setUpdatedAt($this->getCurrentDateTime()); + $interestGroup->setUpdatedAt($dateHelper->formatDate(null, 'Y-m-d H:i:s')); $interestGroup->save(); } } @@ -4117,6 +4624,7 @@ public function saveInterestGroupData($params, $storeId, $customerId = null, $su public function getInterestGroupsIfAvailable($params) { $groups = null; + if (isset($params['customer']) && isset($params['customer']['interestgroup'])) { $groups = $params['customer']['interestgroup']; } elseif (isset($params['group'])) { @@ -4151,18 +4659,10 @@ protected function getCustomerSession() return Mage::getSingleton('customer/session'); } - /** - * @return mixed - */ - protected function getCurrentDateTime() - { - return Mage::getModel('core/date')->date('d-m-Y H:i:s'); - } - /** * Return original path for the imageURL (not the catched one) * - * @param $productImage + * @param $productImage * @return string */ protected function getOriginalPath($productImage) @@ -4177,6 +4677,7 @@ public function getAllApiKeys() { $ret = array(); $stores = $this->getMageApp()->getStores(); + foreach ($stores as $storeId => $store) { try { $apiKey = $this->getApiKey($storeId); @@ -4192,19 +4693,22 @@ public function getAllApiKeys() } /** - * - * @param int $scopeId + * @param int $scopeId * @param string $scope * @return bool \ return true if image cache was flushed * @throws Mage_Core_Exception */ public function isImageCacheFlushed($scopeId = 0, $scope = 'default') { - return (bool)$this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::PRODUCT_IMAGE_CACHE_FLUSH, $scopeId, $scope); + return (bool)$this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::PRODUCT_IMAGE_CACHE_FLUSH, + $scopeId, + $scope + ); } /** - * @param $message \ add a warning with the message that receive as param + * @param $message add a warning with the message that receive as param */ public function addAdminWarning($message) { @@ -4225,7 +4729,13 @@ public function getAdminSession() public function getUrlForNotification() { $scopeArray = $this->getCurrentScope(); - $url = Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/resendEcommerceData', array('scope' => $scopeArray['scope'], 'scope_id' => $scopeArray['scope_id'])); + $url = Mage::helper('adminhtml') + ->getUrl( + 'adminhtml/ecommerce/resendEcommerceData', + array('scope' => $scopeArray['scope'], 'scope_id' => $scopeArray['scope_id'] + ) + ); + return $url; } @@ -4235,7 +4745,11 @@ public function getUrlForNotification() public function deleteFlushMagentoCacheFlag() { $config = $this->getConfig(); - $config->deleteConfig(Ebizmarts_MailChimp_Model_Config::PRODUCT_IMAGE_CACHE_FLUSH, 'default', 0); + $config->deleteConfig( + Ebizmarts_MailChimp_Model_Config::PRODUCT_IMAGE_CACHE_FLUSH, + 'default', + 0 + ); $config->cleanCache(); } @@ -4243,21 +4757,28 @@ public function deleteFlushMagentoCacheFlag() * @return bool \ return true if is enabled include the taxes in the price of the products. * @throws Mage_Core_Exception */ - public function isIncludeTaxesEnabled() + public function isIncludeTaxesEnabled($scopeId = 0, $scope = 'default') { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_XML_INCLUDE_TAXES, 0, 'default'); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_XML_INCLUDE_TAXES, + $scopeId, + $scope + ); } /** * @param $scopeId * @param $scope - * * @return bool \ return true if is enabled show interest gruops in the checkout success. * @throws Mage_Core_Exception */ public function isInterestGroupEnabled($scopeId = 0, $scope = null) { - return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_ACTIVE, $scopeId, $scope); + return $this->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_ACTIVE, + $scopeId, + $scope + ); } /** @@ -4270,20 +4791,20 @@ protected function getModelMailchimpEcommerceSyncData() /** * @param $index - * @param int $increment + * @param int $increment */ public function modifyCounterSentPerBatch($index, $increment = 1) { - if (array_key_exists($index, $this->countersSendBatch)) { - $this->countersSendBatch[$index] = $this->countersSendBatch[$index] + $increment; + if (array_key_exists($index, $this->_countersSendBatch)) { + $this->_countersSendBatch[$index] = $this->_countersSendBatch[$index] + $increment; } else { - $this->countersSendBatch[$index] = 1; + $this->_countersSendBatch[$index] = 1; } } public function resetCountersSentPerBatch() { - $this->countersSendBatch = array(); + $this->_countersSendBatch = array(); } /** @@ -4291,25 +4812,25 @@ public function resetCountersSentPerBatch() */ public function getCountersSentPerBatch() { - return $this->countersSendBatch; + return $this->_countersSendBatch; } /** * @param $index - * @param int $increment + * @param int $increment */ public function modifyCounterSubscribers($index, $increment = 1) { - if (array_key_exists($index, $this->countersSubscribers)) { - $this->countersSubscribers[$index] = $this->countersSubscribers[$index] + $increment; + if (array_key_exists($index, $this->_countersSubscribers)) { + $this->_countersSubscribers[$index] = $this->_countersSubscribers[$index] + $increment; } else { - $this->countersSubscribers[$index] = 1; + $this->_countersSubscribers[$index] = 1; } } public function resetCountersSubscribers() { - $this->countersSubscribers = array(); + $this->_countersSubscribers = array(); } /** @@ -4317,34 +4838,36 @@ public function resetCountersSubscribers() */ public function getCountersSubscribers() { - return $this->countersSubscribers; + return $this->_countersSubscribers; } /** * @param $index - * @param bool $hasError - * @param int $increment + * @param bool $hasError + * @param int $increment */ public function modifyCounterDataSentToMailchimp($index, $hasError = false, $increment = 1) { - if (array_key_exists($index, $this->countersGetResponseBatch)) { - if ($hasError) { - $this->countersGetResponseBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP] = $this->countersGetResponseBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP] + $increment; - } else { - $this->countersGetResponseBatch[$index][self::DATA_SENT_TO_MAILCHIMP] = $this->countersGetResponseBatch[$index][self::DATA_SENT_TO_MAILCHIMP] + $increment; - } + $counterGetResponsesBatch = $this->getCountersDataSentToMailchimp(); + $statusChanged = self::DATA_SENT_TO_MAILCHIMP; + + if ($hasError === true) { + $count = isset($counterGetResponsesBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP]) + ? $counterGetResponsesBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP] + : $increment; + $statusChanged = self::DATA_NOT_SENT_TO_MAILCHIMP; } else { - if ($hasError) { - $this->countersGetResponseBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP] = 1; - } else { - $this->countersGetResponseBatch[$index][self::DATA_SENT_TO_MAILCHIMP] = 1; - } + $count = isset($counterGetResponsesBatch[$index][self::DATA_SENT_TO_MAILCHIMP]) + ? $counterGetResponsesBatch[$index][self::DATA_SENT_TO_MAILCHIMP] + : $increment; } + + $this->setCountersDataSentToMailchimp($index, $statusChanged, $count); } public function resetCountersDataSentToMailchimp() { - $this->countersGetResponseBatch = array(); + $this->_countersGetResponseBatch = array(); } /** @@ -4352,56 +4875,49 @@ public function resetCountersDataSentToMailchimp() */ public function getCountersDataSentToMailchimp() { - return $this->countersGetResponseBatch; + return $this->_countersGetResponseBatch; } - public function mask($str) - { - return substr($str, 0, 6) . str_repeat('*', strlen($str) - 4) . substr($str, -4); - } - - public function isApiKeyObscure($apiKey) + /** + * @param $index + * @param $statusChanged + * @param $value + * @return array + */ + public function setCountersDataSentToMailchimp($index, $statusChanged, $value) { - return ($apiKey === '******'); + return $this->_countersGetResponseBatch[$index][$statusChanged] = $value; } - public function getApiKeyValue() + /** + * @param $str + * @param string $prefix + * @return string + */ + public function mask($str, $prefix = '') { - $scopeArray = $this->getCurrentScope(); - return $this->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); + return $prefix . substr($str, 0, 6) + . str_repeat('*', strlen($str) - 4 - strlen($prefix)) + . substr($str, -4); } /** - * Return date in given format and avoid timezone offset when avoidOffset(true) - * - * @param string $format - * @param $date - * @param bool $avoidOffset - * @return mixed - * @throws Mage_Core_Model_Store_Exception + * @param $apiKey + * @return bool */ - public function formatDate($date, $format='Y-m-d', $avoidOffset = 1) + public function isApiKeyObscure($apiKey) { - $gmtTimestamp = Mage::getModel('core/date')->gmtTimestamp($date); - $currentTimestamp = Mage::getModel('core/date')->timestamp($gmtTimestamp); - if ($avoidOffset) { - $currentTimestamp = $this->avoidTimeZoneOffset($currentTimestamp); - } - - $newDate = Mage::getModel('core/date')->gmtDate($format, $currentTimestamp); - return $newDate; + return ($apiKey === '******'); } /** - * @param $timestamp - * @return mixed - * @throws Mage_Core_Model_Store_Exception + * @return string + * @throws Mage_Core_Exception */ - protected function avoidTimeZoneOffset($timestamp) + public function getApiKeyValue() { - $timeZone = Mage::app()->getStore()->getConfig('general/locale/timezone'); - $offSet = Mage::getModel('core/date')->calculateOffset($timeZone); - return ($timestamp + $offSet); + $scopeArray = $this->getCurrentScope(); + return $this->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); } /** @@ -4435,4 +4951,172 @@ protected function getSalesOrderModel() { return Mage::getModel('sales/order'); } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getDateHelper() + { + return Mage::helper('mailchimp/date'); + } + + /** + * @param $scopeId + * @param $scope + * @param $where + * @throws Mage_Core_Exception + */ + protected function removeErrorsFromSubscribers($scopeId, $scope) + { + $where = "mailchimp_sync_error <> ''"; + $storeIdsAsString = null; + + if ($scopeId != 0) { + $storeIds = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope); + + if (!empty($storeIds)) { + $storeIdsAsString = implode(',', $storeIds); + } + } + + $resource = $this->getCoreResource(); + $conn = $resource->getConnection('core_write'); + $where = empty($storeIdsAsString) ? + $where : $conn->quoteInto($where . " AND store_id IN (?)", $storeIdsAsString); + $conn->update( + $resource->getTableName('newsletter/subscriber'), + array( + 'mailchimp_sync_delta' => '0000-00-00 00:00:00', + 'mailchimp_sync_error' => '' + ), + $where + ); + } + + /** + * @param $mailchimpStore + * @param $fromStatus + * @param $toStatus + */ + public function markAllBatchesAs($mailchimpStore, $fromStatus, $toStatus) + { + $resource = $this->getCoreResource(); + $connection = $resource->getConnection('core_write'); + $tableName = $resource->getTableName('mailchimp/synchbatches'); + $connection->update( + $tableName, + array('status' => $toStatus), + "store_id = '" . $mailchimpStore . "' and status = '" . $fromStatus . "'" + ); + } + + /** + * @param $mailchimpStore + */ + public function cancelAllPendingBatches($mailchimpStore) + { + $this->markAllBatchesAs($mailchimpStore, self::BATCH_PENDING, self::BATCH_CANCELED); + } + + /** + * @param $mailchimpStore + */ + public function restoreAllCanceledBatches($mailchimpStore) + { + $this->markAllBatchesAs($mailchimpStore, self::BATCH_CANCELED, self::BATCH_PENDING); + } + + /** + * Generates a storable representation of a value using the default adapter. + * + * @param mixed $value + * @param array $options + * @return string + * @throws Zend_Serializer_Exception + */ + public function serialize($value, array $options = array()) + { + return Zend_Serializer::serialize($value, $options); + } + + /** + * Creates a PHP value from a stored representation using the default adapter. + * + * @param string $serialized + * @param array $options + * @return mixed + * @throws Zend_Serializer_Exception + */ + public function unserialize($serialized, array $options = array()) + { + return Zend_Serializer::unserialize($serialized, $options); + } + + /** + * Check if Mailchimp API is available + * + * @param $storeId + * @return boolean + */ + public function ping($storeId) + { + try { + $api = $this->getApi($storeId); + $api->getRoot()->info(); + } catch (Exception $e) { + return false; + } + + return true; + } + + /** + * @param $itemType + * @param $syncDelta + * @param $syncError + * @param $syncModified + * @param $syncDeleted + * @param $token + * @param $syncedFlag + * @param $deletedRelatedId + * @param $allowBatchRemoval + * @param Varien_Object $ecommerceSyncDataItem + */ + protected function setEcommerceSyncDataItemValues($itemType, $syncDelta, $syncError, $syncModified, $syncDeleted, $token, $syncedFlag, $deletedRelatedId, $allowBatchRemoval, Varien_Object $ecommerceSyncDataItem) + { + if ($syncDelta) { + $ecommerceSyncDataItem->setData("mailchimp_sync_delta", $syncDelta); + } elseif ($allowBatchRemoval === true) { + $ecommerceSyncDataItem->setData("batch_id", null); + } + + if ($allowBatchRemoval === -1) { + $ecommerceSyncDataItem->setData("batch_id", '-1'); + } + + if ($syncError) { + $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); + } + + //Always set modified value to 0 when saving sync delta or errors. + $ecommerceSyncDataItem->setData("mailchimp_sync_modified", $syncModified); + if ($syncDeleted !== null) { + $ecommerceSyncDataItem->setData("mailchimp_sync_deleted", $syncDeleted); + if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT && $syncError == '') { + $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); + } + } + + if ($token) { + $ecommerceSyncDataItem->setData("mailchimp_token", $token); + } + + if ($deletedRelatedId) { + $ecommerceSyncDataItem->setData("deleted_related_id", $deletedRelatedId); + } + + if ($syncedFlag !== null) { + $ecommerceSyncDataItem->setData("mailchimp_synced_flag", $syncedFlag); + } + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Date.php b/app/code/community/Ebizmarts/MailChimp/Helper/Date.php new file mode 100644 index 000000000..b1bfdedb2 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Date.php @@ -0,0 +1,104 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 7/11/19 11:24 AM + * @file: Date.php + */ +class Ebizmarts_MailChimp_Helper_Date extends Mage_Core_Helper_Abstract +{ + + /** + * get Date with Microtime. + * + * @return string + */ + public function getDateMicrotime() + { + $microtime = explode(' ', microtime()); + $msec = $microtime[0]; + $msecArray = explode('.', $msec); + $time = $this->formatDate(null, 'Y-m-d-H-i-s'); + $date = $time . '-' . $msecArray[1]; + return $date; + } + + /** + * Check if more than 270 seconds passed since the migration started to prevent the job to take too long. + * + * @param $initialTime + * @return bool + */ + public function timePassed($initialTime) + { + $storeCount = count(Mage::app()->getStores()); + $timePassed = false; + $finalTime = $this->getTimestamp(); + $difference = $finalTime - $initialTime; + //Set minimum of 30 seconds per store view. + $timeForAllStores = (30 * $storeCount); + //Set total time in 4:30 minutes if it is lower. + $timeAmount = ($timeForAllStores < 270) ? 270 : $timeForAllStores; + if ($difference > $timeAmount) { + $timePassed = true; + } + + return $timePassed; + } + + /** + * @return string + */ + public function getCurrentDateTime() + { + return $this->formatDate(null, 'd-m-Y H:i:s'); + } + + /** + * Return date in given format in UTC + * or the timezone of the current store ($useStoreTime = true). + * + * @param string $format + * @param $date + * @param bool $avoidOffset + * @return mixed + * @throws Mage_Core_Model_Store_Exception + */ + public function formatDate($date = null, $format = 'Y-m-d', $useStoreTime = false) + { + $gmtTimestamp = Mage::getModel('core/date')->gmtTimestamp($date); + $currentTimestamp = $this->getTimestamp($gmtTimestamp); + if ($useStoreTime) { + $currentTimestamp = $this->_convertUTCToStoreTimestamp($currentTimestamp); + } + + $newDate = Mage::getModel('core/date')->gmtDate($format, $currentTimestamp); + return $newDate; + } + + /** + * @param $timestamp + * @return mixed + * @throws Mage_Core_Model_Store_Exception + */ + protected function _convertUTCToStoreTimestamp($timestamp) + { + $timeZone = Mage::app()->getStore()->getConfig('general/locale/timezone'); + $offSet = Mage::getModel('core/date')->calculateOffset($timeZone); + return ($timestamp + $offSet); + } + + /** + * @param null $time + * @return string + */ + public function getTimestamp($time = null) + { + return Mage::getModel('core/date')->timestamp($time); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php b/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php index 3c8e227b6..42717d178 100644 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php @@ -34,7 +34,9 @@ public function getUserAgent() $aux = (array_key_exists('Enterprise_Enterprise', $modulesArray)) ? 'EE' : 'CE'; $v = (string)Mage::getConfig()->getNode('modules/Ebizmarts_Mandrill/version'); - $version = strpos(Mage::getVersion(), '-') ? substr(Mage::getVersion(), 0, strpos(Mage::getVersion(), '-')) : Mage::getVersion(); + $version = strpos(Mage::getVersion(), '-') + ? substr(Mage::getVersion(), 0, strpos(Mage::getVersion(), '-')) + : Mage::getVersion(); return (string)'Ebizmarts_Mandrill' . $v . '/Mage' . $aux . $version; } @@ -47,7 +49,12 @@ public function getUserAgent() */ public function isMandrillLogEnabled($scopeId = 0, $scope = null) { - return Mage::helper('mailchimp')->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::MANDRILL_LOG, $scopeId, $scope); + return Mage::helper('mailchimp') + ->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::MANDRILL_LOG, + $scopeId, + $scope + ); } /** @@ -59,7 +66,12 @@ public function isMandrillLogEnabled($scopeId = 0, $scope = null) */ public function isMandrillEnabled($scopeId = 0, $scope = null) { - return Mage::helper('mailchimp')->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::MANDRILL_ACTIVE, $scopeId, $scope); + return Mage::helper('mailchimp') + ->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::MANDRILL_ACTIVE, + $scopeId, + $scope + ); } /** @@ -72,6 +84,13 @@ public function isMandrillEnabled($scopeId = 0, $scope = null) public function getMandrillApiKey($scopeId = 0, $scope = null) { $mailchimpHelper = Mage::helper('mailchimp'); - return $mailchimpHelper->decryptData($mailchimpHelper->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $scopeId, $scope)); + return $mailchimpHelper->decryptData( + $mailchimpHelper + ->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, + $scopeId, + $scope + ) + ); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Includetaxes/Comment.php b/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Includetaxes/Comment.php index d1ca45e01..8a62e5b60 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Includetaxes/Comment.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Includetaxes/Comment.php @@ -15,6 +15,12 @@ class Ebizmarts_MailChimp_Model_Adminhtml_Includetaxes_Comment public function getCommentText() { $helper = Mage::helper('mailchimp'); - return $helper->__('Send product price including tax if '). ''. $helper->__("display prices") .'' . $helper->__(' are configured in the same way.'); + return $helper->__( + 'Send product price including tax if ' + ) + . ''. $helper->__("display prices") .'' + . $helper->__(' are configured in the same way.'); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Storeid/Comment.php b/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Storeid/Comment.php index 386892ead..fc784fa5d 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Storeid/Comment.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Adminhtml/Storeid/Comment.php @@ -5,6 +5,12 @@ class Ebizmarts_MailChimp_Model_Adminhtml_Storeid_Comment public function getCommentText() { $helper = Mage::helper('mailchimp'); - return $helper->__('Select the Mailchimp store you want to associate with this scope. You can create a new store at ') . ''.$helper->__('Newsletter -> Mailchimp -> Mailchimp Stores').''; + return $helper->__( + 'Select the Mailchimp store you want to associate with this scope. ' + . 'You can create a new store at ' + ) + . ''.$helper->__('Newsletter -> Mailchimp -> Mailchimp Stores').''; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 278806736..6d758c68c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -16,59 +16,59 @@ class Ebizmarts_MailChimp_Model_Api_Batches /** * @var Ebizmarts_MailChimp_Helper_Data */ - private $mailchimpHelper; + protected $_mailchimpHelper; + + /** + * @var Ebizmarts_MailChimp_Helper_Date + */ + protected $_mailchimpDateHelper; /** * @var Ebizmarts_MailChimp_Model_Api_Customers */ - private $apiCustomers; + protected $_apiCustomers; /** * @var Ebizmarts_MailChimp_Model_Api_Products */ - private $apiProducts; + protected $_apiProducts; /** * @var Ebizmarts_MailChimp_Model_Api_Carts */ - private $apiCarts; + protected $_apiCarts; /** * @var Ebizmarts_MailChimp_Model_Api_Orders */ - private $apiOrders; + protected $_apiOrders; /** * @var Ebizmarts_MailChimp_Model_Api_PromoRules */ - private $apiPromoRules; + protected $_apiPromoRules; /** * @var Ebizmarts_MailChimp_Model_Api_PromoCodes */ - private $apiPromoCodes; + protected $_apiPromoCodes; /** * @var Ebizmarts_MailChimp_Model_Api_Subscribers */ - private $apiSubscribers; - - /** - * @var Ebizmarts_MailChimp_Model_Synchbatches - */ - private $syncBatchesModel; + protected $_apiSubscribers; public function __construct() { - $this->mailchimpHelper = Mage::helper('mailchimp'); - $this->apiCustomers = Mage::getModel('mailchimp/api_customers'); - $this->apiProducts = Mage::getModel('mailchimp/api_products'); - $this->apiCarts = Mage::getModel('mailchimp/api_carts'); - $this->apiOrders = Mage::getModel('mailchimp/api_orders'); - $this->apiPromoRules = Mage::getModel('mailchimp/api_promoRules'); - $this->apiPromoCodes = Mage::getModel('mailchimp/api_promoCodes'); - $this->apiSubscribers = Mage::getModel('mailchimp/api_subscribers'); - $this->syncBatchesModel = Mage::getModel('mailchimp/synchbatches'); + $this->_mailchimpHelper = Mage::helper('mailchimp'); + $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); + $this->_apiCustomers = Mage::getModel('mailchimp/api_customers'); + $this->_apiProducts = Mage::getModel('mailchimp/api_products'); + $this->_apiCarts = Mage::getModel('mailchimp/api_carts'); + $this->_apiOrders = Mage::getModel('mailchimp/api_orders'); + $this->_apiPromoRules = Mage::getModel('mailchimp/api_promoRules'); + $this->_apiPromoCodes = Mage::getModel('mailchimp/api_promoCodes'); + $this->_apiSubscribers = Mage::getModel('mailchimp/api_subscribers'); } /** @@ -76,7 +76,15 @@ public function __construct() */ protected function getHelper() { - return $this->mailchimpHelper; + return $this->_mailchimpHelper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getDateHelper() + { + return $this->_mailchimpDateHelper; } /** @@ -92,7 +100,7 @@ protected function getApiStores() */ protected function getApiCustomers() { - return $this->apiCustomers; + return $this->_apiCustomers; } /** @@ -100,7 +108,7 @@ protected function getApiCustomers() */ public function getApiProducts() { - return $this->apiProducts; + return $this->_apiProducts; } /** @@ -108,7 +116,7 @@ public function getApiProducts() */ public function getApiCarts() { - return $this->apiCarts; + return $this->_apiCarts; } /** @@ -116,7 +124,7 @@ public function getApiCarts() */ public function getApiOrders() { - return $this->apiOrders; + return $this->_apiOrders; } /** @@ -124,7 +132,7 @@ public function getApiOrders() */ public function getApiPromoRules() { - return $this->apiPromoRules; + return $this->_apiPromoRules; } /** @@ -132,7 +140,7 @@ public function getApiPromoRules() */ public function getApiPromoCodes() { - return $this->apiPromoCodes; + return $this->_apiPromoCodes; } /** @@ -140,7 +148,7 @@ public function getApiPromoCodes() */ protected function getApiSubscribers() { - return $this->apiSubscribers; + return $this->_apiSubscribers; } /** @@ -148,7 +156,7 @@ protected function getApiSubscribers() */ protected function getSyncBatchesModel() { - return $this->syncBatchesModel; + return Mage::getModel('mailchimp/synchbatches'); } /** @@ -195,43 +203,33 @@ public function handleEcommerceBatches() $helper = $this->getHelper(); $stores = $this->getStores(); $helper->handleResendDataBefore(); + foreach ($stores as $store) { $storeId = $store->getId(); + if ($helper->isEcomSyncDataEnabled($storeId)) { - if ($this->_ping($storeId)) { + if ($helper->ping($storeId)) { $this->_getResults($storeId); $this->_sendEcommerceBatch($storeId); } else { - $helper->logError('Could not connect to MailChimp: Make sure the API Key is correct and there is an internet connection'); + $helper->logError( + "Could not connect to MailChimp: Make sure the API Key is correct " + . "and there is an internet connection" + ); return; } } } - $helper->handleResendDataAfter(); + $helper->handleResendDataAfter(); $syncedDateArray = array(); + foreach ($stores as $store) { $storeId = $store->getId(); $syncedDateArray = $this->addSyncValueToArray($storeId, $syncedDateArray); } - $this->handleSyncingValue($syncedDateArray); - } - /** - * Check if Mailchimp API is available - * @param $storeId - * @return boolean - */ - protected function _ping($storeId) - { - $helper = $this->getHelper(); - try { - $api = $helper->getApi($storeId); - $api->root->info(); - } catch (Exception $e) { - return false; - } - return true; + $this->handleSyncingValue($syncedDateArray); } /** @@ -245,16 +243,21 @@ public function handleSubscriberBatches() /** * Get results of batch operations sent to MailChimp. * - * @param $magentoStoreId - * @param bool $isEcommerceData + * @param $magentoStoreId + * @param bool $isEcommerceData * @throws Mage_Core_Exception */ - public function _getResults($magentoStoreId, $isEcommerceData = true) + public function _getResults( + $magentoStoreId, + $isEcommerceData = true, + $status = Ebizmarts_MailChimp_Helper_Data::BATCH_PENDING + ) { $helper = $this->getHelper(); $mailchimpStoreId = $helper->getMCStoreId($magentoStoreId); $collection = $this->getSyncBatchesModel()->getCollection() - ->addFieldToFilter('status', array('eq' => 'pending')); + ->addFieldToFilter('status', array('eq' => $status)); + if ($isEcommerceData) { $collection->addFieldToFilter('store_id', array('eq' => $mailchimpStoreId)); $enabled = $helper->isEcomSyncDataEnabled($magentoStoreId); @@ -264,12 +267,14 @@ public function _getResults($magentoStoreId, $isEcommerceData = true) } if ($enabled) { - $helper->logBatchStatus('Get results from Mailchimp'); + $helper->logBatchStatus('Get results from Mailchimp for Magento store '.$magentoStoreId); + foreach ($collection as $item) { try { $batchId = $item->getBatchId(); $files = $this->getBatchResponse($batchId, $magentoStoreId); - if (count($files)) { + + if (!empty($files)) { if (isset($files['error'])) { $item->setStatus('error'); $item->save(); @@ -282,6 +287,7 @@ public function _getResults($magentoStoreId, $isEcommerceData = true) } $baseDir = $this->getMagentoBaseDir(); + if ($this->batchDirExists($baseDir, $batchId)) { $this->removeBatchDir($baseDir, $batchId); } @@ -296,7 +302,7 @@ public function _getResults($magentoStoreId, $isEcommerceData = true) * Send Customers, Products, Orders, Carts to MailChimp store for given scope. * Return true if MailChimp store is reset in the process. * - * @param $magentoStoreId + * @param $magentoStoreId * @throws Mage_Core_Exception */ public function _sendEcommerceBatch($magentoStoreId) @@ -343,45 +349,22 @@ public function _sendEcommerceBatch($magentoStoreId) $promoCodesArray = $apiPromoCodes->createBatchJson($mailchimpStoreId, $magentoStoreId); $batchArray['operations'] = array_merge($batchArray['operations'], $promoCodesArray); } + //deleted product operations - $deletedProductsArray = $apiProducts->createDeletedProductsBatchJson($mailchimpStoreId, $magentoStoreId); + $deletedProductsArray = $apiProducts->createDeletedProductsBatchJson( + $mailchimpStoreId, + $magentoStoreId + ); $batchArray['operations'] = array_merge($batchArray['operations'], $deletedProductsArray); $batchJson = null; $batchResponse = null; try { - $mailchimpApi = $helper->getApi($magentoStoreId); - if (!empty($batchArray['operations'])) { - $batchJson = json_encode($batchArray); - if (!$batchJson || $batchJson == '') { - $helper->logRequest('An empty operation was detected'); - } else { - $batchResponse = $mailchimpApi->getBatchOperation()->add($batchJson); - $helper->logRequest($batchJson, $batchResponse['id']); - //save batch id to db - $batch = $this->getSyncBatchesModel(); - $batch->setStoreId($mailchimpStoreId) - ->setBatchId($batchResponse['id']) - ->setStatus($batchResponse['status']); - $batch->save(); - $this->markItemsAsSent($batchResponse['id'], $mailchimpStoreId); - $this->_showResumeEcommerce($batchResponse['id'], $magentoStoreId); - } - } - - $itemAmount = ($customerAmount + $productAmount + $orderAmount); - $syncingFlag = $helper->getMCIsSyncing($mailchimpStoreId, $magentoStoreId); - if ($this->shouldFlagAsSyncing($magentoStoreId, $syncingFlag, $itemAmount, $helper, $mailchimpStoreId)) { - //Set is syncing per scope in 1 until sync finishes. - $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", 1)); - $helper->saveMailchimpConfig($configValue, $magentoStoreId, 'stores'); - } else { - if ($this->shouldFlagAsSynced($syncingFlag, $itemAmount)) { - //Set is syncing per scope to a date because it is not sending any more items. - $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", date('Y-m-d H:i:s'))); - $helper->saveMailchimpConfig($configValue, $magentoStoreId, 'stores'); - } - } + $this->_processBatchOperations($batchArray, $mailchimpStoreId, $magentoStoreId); + $this->_updateSyncingFlag( + $customerAmount, $productAmount, $orderAmount, + $mailchimpStoreId, $magentoStoreId + ); } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $helper->logError($e->getMessage()); } catch (MailChimp_Error $e) { @@ -402,6 +385,101 @@ public function _sendEcommerceBatch($magentoStoreId) } } + /** + * @param $batchArray + * @param $mailchimpStoreId + * @param $magentoStoreId + * @throws Mage_Core_Exception + * @throws MailChimp_Error + */ + protected function _processBatchOperations($batchArray, $mailchimpStoreId, $magentoStoreId) + { + $helper = $this->getHelper(); + $mailchimpApi = $helper->getApi($magentoStoreId); + + if (!empty($batchArray['operations'])) { + $batchJson = json_encode($batchArray); + + if ($batchJson === false) { + $helper->logRequest('Json encode error '.json_last_error_msg()); + } elseif (empty($batchJson)) { + $helper->logRequest('An empty operation was detected'); + } else { + $batchResponse = $mailchimpApi->getBatchOperation()->add($batchJson); + $helper->logRequest($batchJson, $batchResponse['id']); + //save batch id to db + $batch = $this->getSyncBatchesModel(); + $batch->setStoreId($mailchimpStoreId) + ->setBatchId($batchResponse['id']) + ->setStatus($batchResponse['status']); + $batch->save(); + $this->markItemsAsSent($batchResponse['id'], $mailchimpStoreId); + $this->_showResumeEcommerce($batchResponse['id'], $magentoStoreId); + } + } + } + + /** + * @param $customerAmount + * @param $productAmount + * @param $orderAmount + * @param $mailchimpStoreId + * @param $magentoStoreId + * @throws Mage_Core_Exception + */ + protected function _updateSyncingFlag( + $customerAmount, + $productAmount, + $orderAmount, + $mailchimpStoreId, + $magentoStoreId + ) + { + $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); + $itemAmount = ($customerAmount + $productAmount + $orderAmount); + $syncingFlag = $helper->getMCIsSyncing($mailchimpStoreId, $magentoStoreId); + + if ($this->shouldFlagAsSyncing( + $magentoStoreId, + $syncingFlag, + $itemAmount, + $helper, + $mailchimpStoreId + ) + ) { + //Set is syncing per scope in 1 until sync finishes. + $configValue = array( + array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", 1) + ); + $helper->saveMailchimpConfig($configValue, $magentoStoreId, 'stores'); + } else { + if ($this->shouldFlagAsSynced($syncingFlag, $itemAmount)) { + //Set is syncing per scope to a date because it is not sending any more items. + $configValue = array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", + $dateHelper->formatDate(null, 'Y-m-d H:i:s') + ) + ); + $helper->saveMailchimpConfig($configValue, $magentoStoreId, 'stores'); + } + } + } + + /** + * @param $batchId + */ + protected function deleteBatchItems($batchId) + { + $helper = $this->getHelper(); + $resource = $helper->getCoreResource(); + $connection = $resource->getConnection('core_write'); + $tableName = $resource->getTableName('mailchimp/ecommercesyncdata'); + $where = array("batch_id = '$batchId'"); + $connection->delete($tableName, $where); + } + protected function deleteUnsentItems() { $helper = $this->getHelper(); @@ -422,11 +500,20 @@ public function ecommerceDeleteCallback($args) protected function markItemsAsSent($batchResponseId, $mailchimpStoreId) { $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); + $resource = $helper->getCoreResource(); $connection = $resource->getConnection('core_write'); $tableName = $resource->getTableName('mailchimp/ecommercesyncdata'); $where = array("batch_id IS NULL AND mailchimp_store_id = ?" => $mailchimpStoreId); - $connection->update($tableName, array('batch_id' => $batchResponseId, 'mailchimp_sync_delta' => $this->getCurrentDate()), $where); + $connection->update( + $tableName, + array( + 'batch_id' => $batchResponseId, + 'mailchimp_sync_delta' => $dateHelper->formatDate(null, 'Y-m-d H:i:s') + ), + $where + ); } public function ecommerceSentCallback($args) @@ -450,7 +537,18 @@ public function ecommerceSentCallback($args) $writeAdapter->insertOnDuplicate( $resource->getMainTable(), $insertData, - array('id', 'related_id', 'type', 'mailchimp_store_id', 'mailchimp_sync_error', 'mailchimp_sync_delta', 'mailchimp_sync_modified', 'mailchimp_sync_deleted', 'mailchimp_token', 'batch_id') + array( + 'id', + 'related_id', + 'type', + 'mailchimp_store_id', + 'mailchimp_sync_error', + 'mailchimp_sync_delta', + 'mailchimp_sync_modified', + 'mailchimp_sync_deleted', + 'mailchimp_token', + 'batch_id' + ) ); } @@ -516,7 +614,9 @@ public function sendStoreSubscriberBatch($storeId, $limit) if (!empty($batchArray['operations'])) { $batchJson = json_encode($batchArray); - if (!$batchJson || $batchJson == '') { + if ($batchJson === false) { + $helper->logRequest('Json encode error '.json_last_error_msg()); + } elseif ($batchJson == '') { $helper->logRequest('An empty operation was detected'); } else { try { @@ -570,27 +670,23 @@ public function getBatchResponse($batchId, $magentoStoreId) $fileUrl = urldecode($response['response_body_url']); $fileName = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '.tar.gz'; $fd = fopen($fileName, 'w'); + $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $fileUrl); curl_setopt($ch, CURLOPT_FILE, $fd); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects $r = curl_exec($ch); + curl_close($ch); fclose($fd); - mkdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, 0750, true); + mkdir( + $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, + 0750, + true + ); $archive = new Mage_Archive(); if (file_exists($fileName)) { - $archive->unpack($fileName, $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); - $archive->unpack($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar', $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); - $dir = scandir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); - foreach ($dir as $d) { - $name = pathinfo($d); - if ($name['extension'] == 'json') { - $files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d; - } - } - unlink($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar'); - unlink($fileName); + $files = $this->_unpackBatchFile($files, $batchId, $archive, $fileName, $baseDir); } } } @@ -598,6 +694,7 @@ public function getBatchResponse($batchId, $magentoStoreId) $helper->logError($e->getMessage()); $files['error'] = $e->getMessage(); } catch (MailChimp_Error $e) { + $this->deleteBatchItems($batchId); $files['error'] = $e->getFriendlyMessage(); $helper->logError($e->getFriendlyMessage()); } catch (Exception $e) { @@ -608,10 +705,43 @@ public function getBatchResponse($batchId, $magentoStoreId) return $files; } + /** + * @param $files + * @param $batchId + * @param $archive + * @param $fileName + * @param $baseDir + * @return array + */ + protected function _unpackBatchFile($files, $batchId, $archive, $fileName, $baseDir) + { + $archive->unpack($fileName, $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); + $archive->unpack( + $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar', + $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId + ); + $dir = scandir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); + foreach ($dir as $d) { + $name = pathinfo($d); + if ($name['extension'] == 'json') { + $files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d; + } + } + + unlink( + $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar' + ); + unlink($fileName); + + return $files; + } + /** * @param $files * @param $batchId * @param $mailchimpStoreId + * @param $magentoStoreId + * @throws Mage_Core_Exception */ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, $magentoStoreId) { @@ -627,40 +757,33 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, $store = explode('-', $line[0]); $type = $line[1]; $id = $line[3]; + if ($item->status_code != 200) { $mailchimpErrors = Mage::getModel('mailchimp/mailchimperrors'); //parse error $response = json_decode($item->response); - $errorDetails = ""; - if (!empty($response->errors)) { - foreach ($response->errors as $error) { - if (isset($error->field) && isset($error->message)) { - $errorDetails .= $errorDetails != "" ? " / " : ""; - $errorDetails .= $error->field . " : " . $error->message; - } - } - } - - if ($errorDetails == "") { - $errorDetails = $response->detail; - } + $errorDetails = $this->_processFileErrors($response); if (strstr($errorDetails, 'already exists')) { $this->setItemAsModified($helper, $mailchimpStoreId, $id, $type); $helper->modifyCounterDataSentToMailchimp($type); continue; } - $error = $response->title . " : " . $response->detail; - if ($type == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT) { - $dataProduct = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); - if ($dataProduct->getMailchimpSyncDeleted() || $dataProduct->getMailchimpSyncError() == Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO) { - $error = Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO; - } - } - - $this->saveSyncData($id, $type, $mailchimpStoreId, null, $error, 0, null, null, 0, true); + $error = $this->_getError($type, $mailchimpStoreId, $id, $response); + $this->saveSyncData( + $id, + $type, + $mailchimpStoreId, + null, + $error, + 0, + null, + null, + null, + true + ); $mailchimpErrors->setType($response->type); $mailchimpErrors->setTitle($response->title); @@ -680,18 +803,84 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, $helper->logError($error); } else { $syncDataItem = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); + if (!$syncDataItem->getMailchimpSyncModified()) { - $this->saveSyncData($id, $type, $mailchimpStoreId, null, '', 0, null, null, 1, true); + $syncModified = $this->enableMergeFieldsSending($type, $syncDataItem); + + $this->saveSyncData( + $id, + $type, + $mailchimpStoreId, + null, + '', + $syncModified, + null, + null, + 1, + true + ); $helper->modifyCounterDataSentToMailchimp($type); } } } } + unlink($file); } + $this->_showResumeDataSentToMailchimp($magentoStoreId); } + /** + * @param $type + * @param $mailchimpStoreId + * @param $id + * @param $response + * @return string + */ + protected function _getError($type, $mailchimpStoreId, $id, $response) + { + $error = $response->title . " : " . $response->detail; + $helper = $this->getHelper(); + + if ($type == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT) { + $dataProduct = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); + $isProductDisabledInMagento = Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO; + + if ($dataProduct->getMailchimpSyncDeleted() + || $dataProduct->getMailchimpSyncError() == $isProductDisabledInMagento + ) { + $error = $isProductDisabledInMagento; + } + } + + return $error; + } + + /** + * @param $response + * @return string + */ + protected function _processFileErrors($response) + { + $errorDetails = ""; + + if (!empty($response->errors)) { + foreach ($response->errors as $error) { + if (isset($error->field) && isset($error->message)) { + $errorDetails .= $errorDetails != "" ? " / " : ""; + $errorDetails .= $error->field . " : " . $error->message; + } + } + } + + if ($errorDetails == "") { + $errorDetails = $response->detail; + } + + return $errorDetails; + } + /** * Handle batch for order id replacement with the increment id in MailChimp. * @@ -707,15 +896,23 @@ public function replaceAllOrders($initialTime, $magentoStoreId) //handle order replacement $mailchimpStoreId = $helper->getMCStoreId($magentoStoreId); - $batchArray['operations'] = Mage::getModel('mailchimp/api_orders')->replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoStoreId); + $batchArray['operations'] = Mage::getModel('mailchimp/api_orders')->replaceAllOrdersBatch( + $initialTime, + $mailchimpStoreId, + $magentoStoreId + ); try { /** - * @var $mailchimpApi \Ebizmarts_MailChimp + * @var $mailchimpApi Ebizmarts_MailChimp */ $mailchimpApi = $helper->getApi($magentoStoreId); + if (!empty($batchArray['operations'])) { $batchJson = json_encode($batchArray); - if (!$batchJson || $batchJson == '') { + + if ($batchJson === false) { + $helper->logRequest('Json encode error: '.json_last_error_msg()); + } elseif ($batchJson == '') { $helper->logRequest('An empty operation was detected'); } else { $batchResponse = $mailchimpApi->batchOperation->add($batchJson); @@ -744,6 +941,18 @@ public function replaceAllOrders($initialTime, $magentoStoreId) } } + /** + * @param $itemId + * @param $itemType + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param null $syncDeleted + * @param null $token + * @param null $syncedFlag + * @param bool $saveOnlyIfexists + */ protected function saveSyncData( $itemId, $itemType, @@ -755,12 +964,26 @@ protected function saveSyncData( $token = null, $syncedFlag = null, $saveOnlyIfexists = false - ) { + ) + { $helper = $this->getHelper(); if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER) { $helper->updateSubscriberSyndData($itemId, $syncDelta, $syncError, 0, null); } else { - $helper->saveEcommerceSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, $token, $syncedFlag, $saveOnlyIfexists, null, false); + $helper->saveEcommerceSyncData( + $itemId, + $itemType, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified, + $syncDeleted, + $token, + $syncedFlag, + $saveOnlyIfexists, + null, + false + ); } } @@ -799,6 +1022,7 @@ protected function addSyncValueToArray($storeId, $syncedDateArray) } } } + return $syncedDateArray; } @@ -819,7 +1043,12 @@ public function handleSyncingValue($syncedDateArray) $isSyncingDate = $helper->getDateSyncFinishByMailChimpStoreId($mailchimpStoreId); if (!$isSyncingDate && $mailchimpStoreId) { $this->getApiStores()->editIsSyncing($api, false, $mailchimpStoreId); - $config = array(array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", $date)); + $config = array( + array( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", + $date + ) + ); $helper->saveMailchimpConfig($config, 0, 'default'); } } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { @@ -833,14 +1062,6 @@ public function handleSyncingValue($syncedDateArray) } } - /** - * @return string - */ - protected function getCurrentDate() - { - return Varien_Date::now(); - } - /** * @param $helper * @param $mailchimpStoreId @@ -850,17 +1071,52 @@ protected function getCurrentDate() protected function setItemAsModified($helper, $mailchimpStoreId, $id, $type) { $isMarkedAsDeleted = null; + if ($type == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT) { $dataProduct = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); - - if (!$isMarkedAsDeleted || $dataProduct->getMailchimpSyncError() != Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO) { - $this->saveSyncData($id, $type, $mailchimpStoreId, null, null, 1, 0, null, 1, true); + $isProductDisabledInMagento = Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO; + + if (!$isMarkedAsDeleted || $dataProduct->getMailchimpSyncError() != $isProductDisabledInMagento) { + $this->saveSyncData( + $id, + $type, + $mailchimpStoreId, + null, + null, + 1, + 0, + null, + 1, + true + ); } else { - $this->saveSyncData($id, $type, $mailchimpStoreId, null, Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO, 0, 1, null, 0, true); + $this->saveSyncData( + $id, + $type, + $mailchimpStoreId, + null, + $isProductDisabledInMagento, + 0, + 1, + null, + 0, + true + ); } } else { - $this->saveSyncData($id, $type, $mailchimpStoreId, null, null, 1, 0, null, 1, true); + $this->saveSyncData( + $id, + $type, + $mailchimpStoreId, + null, + null, + 1, + 0, + null, + 1, + true + ); } } @@ -874,7 +1130,10 @@ protected function setItemAsModified($helper, $mailchimpStoreId, $id, $type) */ protected function shouldFlagAsSyncing($magentoStoreId, $syncingFlag, $itemAmount, $helper, $mailchimpStoreId) { - return $syncingFlag === null && $itemAmount !== 0 || $helper->validateDate($syncingFlag) && $syncingFlag < $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId); + return $syncingFlag === null + && $itemAmount !== 0 + || $helper->validateDate($syncingFlag) + && $syncingFlag < $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId); } /** @@ -907,8 +1166,10 @@ protected function getDataProduct($helper, $mailchimpStoreId, $id, $type) protected function _showResumeEcommerce($batchId, $storeId) { $helper = $this->getHelper(); - if (!empty($helper->getCountersSentPerBatch()) || $helper->getCountersSentPerBatch() != null) { - $helper->logBatchStatus("Sent batch $batchId for store $storeId"); + $countersSentPerBatch = $helper->getCountersSentPerBatch(); + + if (!empty($countersSentPerBatch) || $helper->getCountersSentPerBatch() != null) { + $helper->logBatchStatus("Sent batch $batchId for Magento store $storeId"); $helper->logBatchQuantity($helper->getCountersSentPerBatch()); } else { $helper->logBatchStatus("Nothing to sync for store $storeId"); @@ -923,8 +1184,10 @@ protected function _showResumeEcommerce($batchId, $storeId) protected function _showResumeSubscriber($batchId, $storeId) { $helper = $this->getHelper(); - if (!empty($helper->getCountersSubscribers()) || $helper->getCountersSubscribers() != null) { - $helper->logBatchStatus("Sent batch $batchId for store $storeId"); + $countersSubscribers = $helper->getCountersSubscribers(); + + if (!empty($countersSubscribers) || $helper->getCountersSubscribers() != null) { + $helper->logBatchStatus("Sent batch $batchId for Magento store $storeId"); $helper->logBatchQuantity($helper->getCountersSubscribers()); } else { $helper->logBatchStatus("Nothing to sync for store $storeId"); @@ -938,15 +1201,21 @@ protected function _showResumeSubscriber($batchId, $storeId) protected function _showResumeDataSentToMailchimp($storeId) { $helper = $this->getHelper(); - if (!empty($helper->getCountersDataSentToMailchimp()) || $helper->getCountersDataSentToMailchimp() != null) { + $countersDataSentToMailchimp = $helper->getCountersDataSentToMailchimp(); + + if (!empty($countersDataSentToMailchimp) || $helper->getCountersDataSentToMailchimp() != null) { $helper->logBatchStatus("Processed data sent to Mailchimp for store $storeId"); $counter = $helper->getCountersDataSentToMailchimp(); $helper->logBatchQuantity($counter); if ($this->isSetAnyCounterSubscriberOrEcommerceNotSent($counter)) { if ($helper->isErrorLogEnabled()) { - $helper->logBatchStatus('Please check Mailchimp Errors grid or MailChimp_Errors.log for more details.'); + $helper->logBatchStatus( + 'Please check Mailchimp Errors grid or MailChimp_Errors.log for more details.' + ); } else { - $helper->logBatchStatus('Please check Mailchimp Errors grid and enable MailChimp_Errors.log for more details.'); + $helper->logBatchStatus( + 'Please check Mailchimp Errors grid and enable MailChimp_Errors.log for more details.' + ); } } } else { @@ -966,4 +1235,29 @@ protected function isSetAnyCounterSubscriberOrEcommerceNotSent($counter) || isset($counter['PRO']['NOT SENT']) || isset($counter['QUO']['NOT SENT']); } + + /** + * @param Varien_Object $syncDataItem + * @return bool + */ + protected function isFirstArrival(Varien_Object $syncDataItem) + { + return (int)$syncDataItem->getMailchimpSyncedFlag() !== 1; + } + + /** + * @param $type + * @param Varien_Object $syncDataItem + * @return int + */ + protected function enableMergeFieldsSending($type, Varien_Object $syncDataItem) + { + $syncModified = 0 ; + if ($type == Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER + && $this->isFirstArrival($syncDataItem)) { + $syncModified = 1; + } + + return $syncModified; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 20f89ce3e..522e1da86 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -27,9 +27,10 @@ class Ebizmarts_MailChimp_Model_Api_Carts */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { - /** @var Ebizmarts_MailChimp_Helper_Data $helper */ $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $allCarts = array(); + if (!$helper->isAbandonedCartEnabled($magentoStoreId)) { return $allCarts; } @@ -37,17 +38,25 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) $this->_firstDate = $helper->getAbandonedCartFirstDate($magentoStoreId); $this->setCounter(0); - $date = $helper->getDateMicrotime(); - $this->setBatchId('storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . '_' . $date); + $date = $dateHelper->getDateMicrotime(); + $this->setBatchId( + 'storeid-' + . $magentoStoreId . '_' + . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . '_' + . $date + ); $resendTurn = $helper->getResendTurn($magentoStoreId); + if (!$resendTurn) { // get all the carts converted in orders (must be deleted on mailchimp) $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId)); // get all the carts modified but not converted in orders $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId)); } + // get new carts $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId)); + return $allCarts; } @@ -68,28 +77,46 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) //join with mailchimp_ecommerce_sync_data table to filter by sync data. $convertedCarts->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id " + . "AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); // be sure that the quotes are already in mailchimp and not deleted $convertedCarts->getSelect()->where("m4m.mailchimp_sync_deleted = 0"); // limit the collection $convertedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); + foreach ($convertedCarts as $cart) { $cartId = $cart->getEntityId(); // we need to delete all the carts associated with this email - $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + $allCartsForEmail = $this->getAllCartsByEmail( + $cart->getCustomerEmail(), + $mailchimpStoreId, + $magentoStoreId + ); + foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); $counter = $this->getCounter(); + if ($alreadySentCartId != $cartId) { $allCarts[$counter]['method'] = 'DELETE'; - $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$counter]['path'] = '/ecommerce/stores/' + . $mailchimpStoreId . '/carts/' + . $alreadySentCartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, null, null, 0, null, 1); - $this->setCounter($this->getCounter()+1); + $this->_updateSyncData( + $alreadySentCartId, + $mailchimpStoreId, + null, + null, + 0, + null, + 1 + ); + $this->setCounter($this->getCounter() + 1); } } @@ -99,8 +126,16 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, 0, null, 1); - $this->setCounter($this->getCounter()+1); + $this->_updateSyncData( + $cartId, + $mailchimpStoreId, + null, + null, + 0, + null, + 1 + ); + $this->setCounter($this->getCounter() + 1); } return $allCarts; @@ -113,6 +148,7 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) */ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) { + $helper = $this->getHelper(); $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); $batchId = $this->getBatchId(); $allCarts = array(); @@ -124,8 +160,9 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) //join with mailchimp_ecommerce_sync_data table to filter by sync data. $modifiedCarts->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_QUOTE + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); // be sure that the quotes are already in mailchimp and not deleted @@ -135,6 +172,7 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) ); // limit the collection $modifiedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); + foreach ($modifiedCarts as $cart) { $cartId = $cart->getEntityId(); /** @@ -143,17 +181,35 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) $customer = $this->getCustomerModel(); $customer->setWebsiteId($this->getWebSiteIdFromMagentoStoreId($magentoStoreId)); $customer->loadByEmail($cart->getCustomerEmail()); + if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + $allCartsForEmail = $this->getAllCartsByEmail( + $cart->getCustomerEmail(), + $mailchimpStoreId, + $magentoStoreId + ); + foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); $counter = $this->getCounter(); + if ($alreadySentCartId != $cartId) { $allCarts[$counter]['method'] = 'DELETE'; - $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$counter]['path'] = '/ecommerce/stores/' + . $mailchimpStoreId + . '/carts/' + . $alreadySentCartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, null, null, 0, null, 1); + $this->_updateSyncData( + $alreadySentCartId, + $mailchimpStoreId, + null, + null, + 0, + null, + 1 + ); $this->setCounter($this->getCounter() + 1); } } @@ -166,22 +222,54 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) $this->_updateSyncData($cartId, $mailchimpStoreId); continue; } + // send the products that not already sent $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts); - $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId, true); - if ($cartJson != "") { - $this->getHelper()->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::QUO_MOD); - $counter = $this->getCounter(); - $allCarts[$counter]['method'] = 'PATCH'; - $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/'.$cartId; - $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; - $allCarts[$counter]['body'] = $cartJson; - $this->setCounter($this->getCounter()+1); - $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, 0, null, null, $this->getToken()); + if ($cartJson !== false) { + if (!empty($cartJson)) { + $this->getHelper()->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::QUO_MOD); + + $counter = $this->getCounter(); + $allCarts[$counter]['method'] = 'PATCH'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; + $allCarts[$counter]['body'] = $cartJson; + $this->setCounter($this->getCounter() + 1); + $this->_updateSyncData( + $cartId, + $mailchimpStoreId, + null, + null, + 0, + null, + null, + $this->getToken() + ); + } else { + $error = $helper->__('There is not supported products in this cart.'); + + $this->_updateSyncData($cartId, $mailchimpStoreId, null, $error, 0); + } } else { - $this->_updateSyncData($cartId, $mailchimpStoreId); + $jsonErrorMessage = json_last_error_msg(); + + $this->_updateSyncData( + $cartId, + $mailchimpStoreId, + null, + $jsonErrorMessage, + 0, + null, + null, + $this->getToken(), + false, + -1 + ); + + //json encode failed + $helper->logError("Carts " . $cart->getId() . " json encode failed (".$jsonErrorMessage.")"); } $this->setToken(null); @@ -192,11 +280,14 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) /** * @param $mailchimpStoreId - * @return array + * @param $magentoStoreId + * @return array|mixed + * @throws Mage_Core_Exception */ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $batchId = $this->getBatchId(); $allCarts = array(); $newCarts = $this->getQuoteCollection(); @@ -221,10 +312,15 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) foreach ($newCarts as $cart) { $cartId = $cart->getEntityId(); $orderCollection = $this->getOrderCollection(); - $orderCollection->addFieldToFilter('main_table.customer_email', array('eq' => $cart->getCustomerEmail())); + $orderCollection->addFieldToFilter( + 'main_table.customer_email', + array('eq' => $cart->getCustomerEmail()) + ); $orderCollection->addFieldToFilter('main_table.updated_at', array('from' => $cart->getUpdatedAt())); //if cart is empty or customer has an order made after the abandonment skip current cart. - if (!count($cart->getAllVisibleItems()) || $orderCollection->getSize()) { + $allVisibleItems = $cart->getAllVisibleItems(); + + if (empty($allVisibleItems) || $orderCollection->getSize()) { $this->_updateSyncData($cartId, $mailchimpStoreId); continue; } @@ -232,17 +328,34 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) $customer = $this->getCustomerModel(); $customer->setWebsiteId($this->getWebSiteIdFromMagentoStoreId($magentoStoreId)); $customer->loadByEmail($cart->getCustomerEmail()); + if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + $allCartsForEmail = $this->getAllCartsByEmail( + $cart->getCustomerEmail(), + $mailchimpStoreId, + $magentoStoreId + ); + foreach ($allCartsForEmail as $cartForEmail) { $counter = $this->getCounter(); $alreadySentCartId = $cartForEmail->getEntityId(); $allCarts[$counter]['method'] = 'DELETE'; - $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$counter]['path'] = '/ecommerce/stores/' + . $mailchimpStoreId + . '/carts/' + . $alreadySentCartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, null, null, 0, null, 1); - $this->setCounter($this->getCounter()+1); + $this->_updateSyncData( + $alreadySentCartId, + $mailchimpStoreId, + null, + null, + 0, + null, + 1 + ); + $this->setCounter($this->getCounter() + 1); } $allCartsForEmail->clear(); @@ -256,20 +369,50 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) // send the products that not already sent $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts); - $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); - if ($cartJson != "") { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::QUO_NEW); - $counter = $this->getCounter(); - $allCarts[$counter]['method'] = 'POST'; - $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; - $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; - $allCarts[$counter]['body'] = $cartJson; - $this->setCounter($this->getCounter()+1); - $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, 0, null, null, $this->getToken()); + if ($cartJson !== false) { + if (!empty($cartJson)) { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::QUO_NEW); + + $counter = $this->getCounter(); + $allCarts[$counter]['method'] = 'POST'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; + $allCarts[$counter]['body'] = $cartJson; + $this->setCounter($this->getCounter() + 1); + $this->_updateSyncData( + $cartId, + $mailchimpStoreId, + null, + null, + 0, + null, + null, + $this->getToken() + ); + } else { + $error = $helper->__('There is not supported products in this cart.'); + $this->_updateSyncData( + $cartId, $mailchimpStoreId, $dateHelper->getCurrentDateTime(), + $error, 0 + ); + } } else { - $this->_updateSyncData($cartId, $mailchimpStoreId); + $jsonErrorMessage = json_last_error_msg(); + $this->_updateSyncData( + $cartId, $mailchimpStoreId, + $dateHelper->getCurrentDateTime(), + $jsonErrorMessage, + 0, + null, + null, + null, + false, + -1 + ); + //json encode failed + $helper->logError("Carts " . $cart->getId() . " json encode failed (".$jsonErrorMessage.")"); } $this->setToken(null); @@ -295,12 +438,17 @@ public function getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) $allCartsForEmail->addFieldToFilter('customer_email', array('eq' => $email)); $allCartsForEmail->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_QUOTE + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); // be sure that the quotes are already in mailchimp and not deleted - $allCartsForEmail->getSelect()->where("m4m.mailchimp_sync_deleted = 0 AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'"); + $allCartsForEmail->getSelect()->where( + "m4m.mailchimp_sync_deleted = 0 " + . "AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'" + ); + return $allCartsForEmail; } @@ -312,16 +460,18 @@ public function getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) */ public function _makeCart($cart, $mailchimpStoreId, $magentoStoreId, $isModified = false) { - $helper = $this->getHelper(); $apiProduct = $this->getApiProducts(); $campaignId = $cart->getMailchimpCampaignId(); $oneCart = array(); $oneCart['id'] = $cart->getEntityId(); $customer = $this->_getCustomer($cart, $magentoStoreId); + if (empty($customer)) { return ""; } + $oneCart['customer'] = $customer; + if ($campaignId) { $oneCart['campaign_id'] = $campaignId; } @@ -330,21 +480,48 @@ public function _makeCart($cart, $mailchimpStoreId, $magentoStoreId, $isModified $oneCart['currency_code'] = $cart->getQuoteCurrencyCode(); $oneCart['order_total'] = $cart->getGrandTotal(); $oneCart['tax_total'] = 0; - $lines = array(); // get all items on the cart - $items = $cart->getAllVisibleItems(); + $lines = $this->_processCartLines( + $cart->getAllVisibleItems(), $mailchimpStoreId, $magentoStoreId, $apiProduct + ); + + $jsonData = ""; + + if ($lines['count']) { + $oneCart['lines'] = $lines['lines']; + //encode to JSON + $jsonData = json_encode($oneCart); + } + + return $jsonData; + } + + /** + * @param $items + * @param $mailchimpStoreId + * @param $magentoStoreId + * @param $apiProduct + * @return array + */ + protected function _processCartLines($items, $mailchimpStoreId, $magentoStoreId, $apiProduct) + { + $helper = $this->getHelper(); + $lines = array(); $itemCount = 0; + foreach ($items as $item) { $productId = $item->getProductId(); $isTypeProduct = $this->isTypeProduct(); $productSyncData = $helper->getEcommerceSyncDataItem($productId, $isTypeProduct, $mailchimpStoreId); $line = array(); + if ($item->getProductType() == 'bundle' || $item->getProductType() == 'grouped') { continue; } if ($this->isProductTypeConfigurable($item)) { $variant = null; + if ($item->getOptionByCode('simple_product')) { $variant = $item->getOptionByCode('simple_product')->getProduct(); } @@ -378,26 +555,14 @@ public function _makeCart($cart, $mailchimpStoreId, $magentoStoreId, $isModified } } - $jsonData = ""; - if ($itemCount) { - $oneCart['lines'] = $lines; - //enconde to JSON - try { - $jsonData = json_encode($oneCart); - } catch (Exception $e) { - //json encode failed - $helper->logError("Carts " . $cart->getId() . " json encode failed"); - } - } - - return $jsonData; + return array('lines' => $lines, 'count' => $itemCount); } /** * Get URL for the cart. * * @param $cart - * @param $isModified + * @param $isModified * @return string */ protected function _getCheckoutUrl($cart, $isModified) @@ -407,7 +572,12 @@ protected function _getCheckoutUrl($cart, $isModified) } else { $token = $cart->getMailchimpToken(); } - $url = Mage::getModel('core/url')->setStore($cart->getStoreId())->getUrl('', array('_nosid' => true, '_secure' => true)) . 'mailchimp/cart/loadquote?id=' . $cart->getEntityId() . '&token=' . $token; + + $url = Mage::getModel('core/url')->setStore($cart->getStoreId())->getUrl( + '', + array('_nosid' => true, '_secure' => true) + ) + . 'mailchimp/cart/loadquote?id=' . $cart->getEntityId() . '&token=' . $token; $this->setToken($token); return $url; } @@ -437,19 +607,23 @@ public function _getCustomer($cart, $magentoStoreId) ); $firstName = $cart->getCustomerFirstname(); + if ($firstName) { $customer["first_name"] = $firstName; } $lastName = $cart->getCustomerLastname(); + if ($lastName) { $customer["last_name"] = $lastName; } $billingAddress = $cart->getBillingAddress(); + if ($billingAddress) { $street = $billingAddress->getStreet(); $address = array(); + if (isset($street[0])) { $address['address1'] = $street[0]; @@ -458,28 +632,9 @@ public function _getCustomer($cart, $magentoStoreId) } } - if ($billingAddress->getCity()) { - $address['city'] = $billingAddress->getCity(); - } - - if ($billingAddress->getRegion()) { - $address['province'] = $billingAddress->getRegion(); - } - - if ($billingAddress->getRegionCode()) { - $address['province_code'] = $billingAddress->getRegionCode(); - } - - if ($billingAddress->getPostcode()) { - $address['postal_code'] = $billingAddress->getPostcode(); - } - - if ($billingAddress->getCountry()) { - $address['country'] = $this->getCountryModel($billingAddress); - $address['country_code'] = $billingAddress->getCountry(); - } + $address = $this->_addBillingAddress($address, $billingAddress); - if (count($address)) { + if (!empty($address)) { $customer['address'] = $address; } } @@ -488,25 +643,80 @@ public function _getCustomer($cart, $magentoStoreId) if ($billingAddress->getCompany()) { $customer["company"] = $billingAddress->getCompany(); } + return $customer; } /** - * update product sync data - * + * @param $address + * @param $billingAddress + * @return array + */ + protected function _addBillingAddress($address, $billingAddress) + { + if ($billingAddress->getCity()) { + $address['city'] = $billingAddress->getCity(); + } + + if ($billingAddress->getRegion()) { + $address['province'] = $billingAddress->getRegion(); + } + + if ($billingAddress->getRegionCode()) { + $address['province_code'] = $billingAddress->getRegionCode(); + } + + if ($billingAddress->getPostcode()) { + $address['postal_code'] = $billingAddress->getPostcode(); + } + + if ($billingAddress->getCountry()) { + $address['country'] = $this->getCountryModel($billingAddress); + $address['country_code'] = $billingAddress->getCountry(); + } + + return $address; + } + + /** * @param $cartId * @param $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncedFlag - * @param int|null $syncDeleted - * @param string|null $token + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param null $syncedFlag + * @param null $syncDeleted + * @param null $token + * @param bool $saveOnlyIfExists + * @param bool $allowBatchRemoval */ - protected function _updateSyncData($cartId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncedFlag = null, $syncDeleted = null, $token = null) - { + protected function _updateSyncData( + $cartId, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncedFlag = null, + $syncDeleted = null, + $token = null, + $saveOnlyIfExists = false, + $allowBatchRemoval = true + ) { $helper = $this->getHelper(); - $helper->saveEcommerceSyncData($cartId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, $token, $syncedFlag); + $helper->saveEcommerceSyncData( + $cartId, + Ebizmarts_MailChimp_Model_Config::IS_QUOTE, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified, + $syncDeleted, + $token, + $syncedFlag, + $saveOnlyIfExists, + null, + $allowBatchRemoval + ); } /** @@ -534,6 +744,14 @@ protected function getHelper() return Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getDateHelper() + { + return Mage::helper('mailchimp/date'); + } + /** * @param $newCarts * @param $mailchimpStoreId @@ -543,8 +761,8 @@ public function joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId) $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); $newCarts->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); } @@ -625,6 +843,7 @@ public function getToken() { return $this->_token; } + /** * @param string $token */ @@ -658,7 +877,7 @@ protected function getOrderCollection() */ protected function getApiCustomersOptIn($magentoStoreId) { - return Mage::getModel('mailchimp/api_customers')->getOptin($magentoStoreId); + return Mage::getModel('mailchimp/api_customers')->getOptIn($magentoStoreId); } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index fcf18c0ef..dc6bb10cf 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -17,26 +17,29 @@ class Ebizmarts_MailChimp_Model_Api_Customers /** * @var Ebizmarts_MailChimp_Helper_Data */ - private $mailchimpHelper; - private $optInConfiguration; - private $optInStatusForStore; - private $locale; - private $directoryRegionModel; - private $magentoStoreId; - private $mailchimpStoreId; - private $batchId; + protected $_mailchimpHelper; + protected $_mailchimpDateHelper; + protected $_optInConfiguration; + protected $_optInStatusForStore; + protected $_locale; + protected $_directoryRegionModel; + protected $_magentoStoreId; + protected $_mailchimpStoreId; + protected $_batchId; public function __construct() { - $this->mailchimpHelper = $this->makeHelper(); - $this->optInConfiguration = array(); - $this->locale = Mage::app()->getLocale(); - $this->directoryRegionModel = Mage::getModel('directory/region'); + $this->_mailchimpHelper = $this->makeHelper(); + $this->_mailchimpDateHelper = $this->makeDateHelper(); + $this->_optInConfiguration = array(); + $this->_locale = Mage::app()->getLocale(); + $this->_directoryRegionModel = Mage::getModel('directory/region'); } /** * Get an array of customer entity IDs of the next batch of customers * to sync. + * * @return int[] Customer IDs to sync * @throws Mage_Core_Exception */ @@ -70,7 +73,6 @@ public function makeCustomersNotSentCollection($customerIdsToSync) $collection->addFieldToFilter('entity_id', array('in' => $customerIdsToSync)); $collection->addNameToSelect(); $this->joinDefaultBillingAddress($collection); - $this->joinSalesData($collection); $collection->getSelect()->group("e.entity_id"); return $collection; @@ -80,70 +82,149 @@ public function makeCustomersNotSentCollection($customerIdsToSync) * @param $mailchimpStoreId * @param $magentoStoreId * @return array + * @throws Mage_Core_Exception */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { $this->setMailchimpStoreId($mailchimpStoreId); $this->setMagentoStoreId($magentoStoreId); + $helper = $this->getMailChimpHelper(); $customersCollection = array(); $customerIds = $this->getCustomersToSync(); - if (count($customerIds) > 0) { + if (!empty($customerIds)) { $customersCollection = $this->makeCustomersNotSentCollection($customerIds); } $customerArray = array(); $this->makeBatchId(); - $this->optInStatusForStore = $this->getOptin($this->getBatchMagentoStoreId()); + $this->setOptInStatusForStore($this->getOptIn($this->getBatchMagentoStoreId())); $subscriber = $this->getSubscriberModel(); + $listId = $helper->getGeneralList($magentoStoreId); $counter = 0; foreach ($customersCollection as $customer) { $data = $this->_buildCustomerData($customer); $customerJson = json_encode($data); + if (false !== $customerJson) { - $helper = $this->getMailChimpHelper(); - $dataCustomer = $helper->getEcommerceSyncDataItem($customer->getId(), Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId); - if ($dataCustomer->getId()) { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::CUS_MOD); + if (!empty($customerJson)) { + $isSubscribed = $this->isSubscribed($subscriber, $customer); + $dataCustomer = $helper->getEcommerceSyncDataItem( + $customer->getId(), + Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, + $mailchimpStoreId + ); + $this->incrementCounterSentPerBatch( + $dataCustomer, + $helper + ); + + $customerArray[$counter] = $this->makePutBatchStructure($customerJson, $customer); + $this->_updateSyncData( + $customer->getId(), $mailchimpStoreId, null, null, 0, null + ); + $counter++; + + if (!$isSubscribed) { + /** + * subscribe all customers to the newsletter + */ + if ($this->getOptInStatusForStore()) { + $subscriber->subscribe($customer->getEmail()); + } else { + /** + * send merge fields for customers currently not subscribed (transactional) + */ + list($customerArray, $counter) = $this->sendMailchimpTags( + $magentoStoreId, $dataCustomer, + $subscriber, $customer, $listId, $counter, $customerArray + ); + } + } } else { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::CUS_NEW); + $this->_updateSyncData( + $customer->getId(), $mailchimpStoreId, + $this->getMailChimpDateHelper()->getCurrentDateTime(), 'Customer with no data', 0 + ); } - - $customerArray[$counter] = $this->makePutBatchStructure($customerJson); - $this->_updateSyncData($customer->getId(), $mailchimpStoreId); } else { - $this->logCouldNotEncodeCustomerError($customer); - } - - if ($this->optInStatusForStore) { - $isSubscribed = $subscriber->loadByEmail($customer->getEmail())->getSubscriberId(); - if (!$isSubscribed) { - $subscriber->subscribe($customer->getEmail()); - } + $jsonErrorMessage = $this->logCouldNotEncodeCustomerError($customer); + $this->_updateSyncData( + $customer->getId(), + $mailchimpStoreId, + $this->getMailChimpDateHelper()->getCurrentDateTime(), + $jsonErrorMessage, + 0, + null, + false, + -1 + ); } - - $counter++; } + return $customerArray; } + /** + * @param $subscriber + * @param $storeId + * @return false|Ebizmarts_MailChimp_Model_Api_Subscribers_MailchimpTags + */ + protected function _buildMailchimpTags($subscriber, $storeId) + { + $mailChimpTags = Mage::getModel('mailchimp/api_subscribers_MailchimpTags'); + $mailChimpTags->setStoreId($storeId); + $mailChimpTags->setSubscriber($subscriber); + $mailChimpTags->setCustomer( + $this->getCustomerByWebsiteAndId() + ->setWebsiteId($this->getWebsiteByStoreId($storeId))->load($subscriber->getCustomerId()) + ); + $mailChimpTags->buildMailChimpTags(); + + return $mailChimpTags; + } + + /** + * @param $storeId + * @return Mage_Core_Model_Abstract + */ + protected function getWebsiteByStoreId($storeId) + { + return Mage::getModel('core/store')->load($storeId)->getWebsiteId(); + } + + /** + * @return false|Mage_Customer_Model_Customer + */ + protected function getCustomerByWebsiteAndId() + { + return Mage::getModel('customer/customer'); + } + /** * @param $customerJson + * @param $customer * @return array */ - protected function makePutBatchStructure($customerJson) + protected function makePutBatchStructure($customerJson, $customer) { - $customerId = json_decode($customerJson)->id; + $customerHash = json_decode($customerJson)->id; + $customerId = $customer->getId(); $batchData = array(); $batchData['method'] = "PUT"; - $batchData['path'] = "/ecommerce/stores/{$this->mailchimpStoreId}/customers/{$customerId}"; - $batchData['operation_id'] = "{$this->batchId}_{$customerId}"; + $batchData['path'] = "/ecommerce/stores/{$this->_mailchimpStoreId}/customers/{$customerHash}"; + $batchData['operation_id'] = "{$this->_batchId}_{$customerId}"; $batchData['body'] = $customerJson; + return $batchData; } + /** + * @param $customer + * @return array + */ protected function _buildCustomerData($customer) { $data = array(); @@ -151,9 +232,6 @@ protected function _buildCustomerData($customer) $data["email_address"] = $this->getCustomerEmail($customer); $data["first_name"] = $this->getCustomerFirstname($customer); $data["last_name"] = $this->getCustomerLastname($customer); - - $data["orders_count"] = (int)$customer->getOrdersCount(); - $data["total_spent"] = (float)$customer->getTotalSpent(); $data["opt_in_status"] = false; $data += $this->getCustomerAddressData($customer); @@ -193,7 +271,7 @@ protected function getCustomerAddressData($customer) } if ($customer->getRegionId()) { - $customerAddress["province_code"] = $this->directoryRegionModel->load($customer->getRegionId())->getCode(); + $customerAddress["province_code"] = $this->_directoryRegionModel->load($customer->getRegionId())->getCode(); if (!$customerAddress["province_code"]) { unset($customerAddress["province_code"]); } @@ -215,9 +293,13 @@ protected function getCustomerAddressData($customer) return $data; } + /** + * @param $countryCode + * @return array + */ protected function getCountryNameByCode($countryCode) { - return $this->locale->getCountryTranslation($countryCode); + return $this->_locale->getCountryTranslation($countryCode); } /** @@ -228,41 +310,70 @@ protected function getCountryNameByCode($countryCode) */ public function update($customerId, $storeId) { - $mailchimpStoreId = $this->mailchimpHelper->getMCStoreId($storeId); + $mailchimpStoreId = $this->_mailchimpHelper->getMCStoreId($storeId); $this->_updateSyncData($customerId, $mailchimpStoreId, null, null, 1, null, true, false); } - public function getOptin($magentoStoreId) + /** + * @param $magentoStoreId + * @return array + */ + public function getOptIn($magentoStoreId) { - return $this->getOptinConfiguration($magentoStoreId); + return $this->getOptInConfiguration($magentoStoreId); } - protected function getOptinConfiguration($magentoStoreId) + /** + * @param $magentoStoreId + * @return array + */ + protected function getOptInConfiguration($magentoStoreId) { - if (array_key_exists($magentoStoreId, $this->optInConfiguration)) { - return $this->optInConfiguration[$magentoStoreId]; + if (array_key_exists($magentoStoreId, $this->_optInConfiguration)) { + return $this->_optInConfiguration[$magentoStoreId]; } $this->checkEcommerceOptInConfigAndUpdateStorage($magentoStoreId); - return $this->optInConfiguration[$magentoStoreId]; + return $this->_optInConfiguration[$magentoStoreId]; } /** * update customer sync data * - * @param int $customerId - * @param string $mailchimpStoreId + * @param int $customerId + * @param string $mailchimpStoreId * @param int|null $syncDelta * @param int|null $syncError * @param int|null $syncModified * @param int|null $syncedFlag - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval + * @param bool $saveOnlyIfexists + * @param bool $allowBatchRemoval */ - protected function _updateSyncData($customerId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncedFlag = null, $saveOnlyIfexists = false, $allowBatchRemoval = true) - { - $this->mailchimpHelper->saveEcommerceSyncData($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, null, null, $syncedFlag, $saveOnlyIfexists, null, $allowBatchRemoval); + protected function _updateSyncData( + $customerId, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncedFlag = null, + $saveOnlyIfexists = false, + $allowBatchRemoval = true + ) { + $this->_mailchimpHelper->saveEcommerceSyncData( + $customerId, + Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified, + null, + null, + $syncedFlag, + $saveOnlyIfexists, + null, + $allowBatchRemoval + ); } /** @@ -270,9 +381,9 @@ protected function _updateSyncData($customerId, $mailchimpStoreId, $syncDelta = */ protected function makeBatchId() { - $this->batchId = "storeid-{$this->getBatchMagentoStoreId()}_"; - $this->batchId .= Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER . '_'; - $this->batchId .= $this->mailchimpHelper->getDateMicrotime(); + $this->_batchId = "storeid-{$this->getBatchMagentoStoreId()}_"; + $this->_batchId .= Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER . '_'; + $this->_batchId .= $this->_mailchimpDateHelper->getDateMicrotime(); } /** @@ -289,29 +400,17 @@ protected function joinDefaultBillingAddress($collection) $collection->joinAttribute('company', 'customer_address/company', 'default_billing', null, 'left'); } - protected function joinSalesData($collection) - { - $collection->getSelect()->joinLeft( - array('s' => $collection->getTable('sales/order')), - 'e.entity_id = s.customer_id', - array( - new Zend_Db_Expr("SUM(s.grand_total) AS total_spent"), - new Zend_Db_Expr("COUNT(s.entity_id) AS orders_count"), - ) - ); - } - /** * @param $collection */ protected function joinMailchimpSyncData($collection) { - $joinCondition = "m4m.related_id = e.entity_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + $joinCondition = "m4m.related_id = e.entity_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; $mailchimpTableName = $this->getSyncdataTableName(); $collection->getSelect()->joinLeft( array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $this->mailchimpStoreId), + sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $this->_mailchimpStoreId), array() ); @@ -323,18 +422,20 @@ protected function joinMailchimpSyncData($collection) */ public function getSyncDataTableName() { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $mailchimpTableName = Mage::getSingleton('core/resource') + ->getTableName('mailchimp/ecommercesyncdata'); return $mailchimpTableName; } /** * @param $magentoStoreId - * @return mixed + * @return bool + * @throws Mage_Core_Exception */ protected function isEcommerceCustomerOptInConfigEnabled($magentoStoreId) { - $configValue = $this->mailchimpHelper->getConfigValueForScope( + $configValue = $this->_mailchimpHelper->getConfigValueForScope( Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMERS_OPTIN, $magentoStoreId ); @@ -347,9 +448,9 @@ protected function isEcommerceCustomerOptInConfigEnabled($magentoStoreId) protected function checkEcommerceOptInConfigAndUpdateStorage($magentoStoreId) { if ($this->isEcommerceCustomerOptInConfigEnabled($magentoStoreId)) { - $this->optInConfiguration[$magentoStoreId] = true; + $this->_optInConfiguration[$magentoStoreId] = true; } else { - $this->optInConfiguration[$magentoStoreId] = false; + $this->_optInConfiguration[$magentoStoreId] = false; } } @@ -358,7 +459,7 @@ protected function checkEcommerceOptInConfigAndUpdateStorage($magentoStoreId) */ protected function getBatchLimitFromConfig() { - $helper = $this->mailchimpHelper; + $helper = $this->_mailchimpHelper; return $helper->getCustomerAmountLimit(); } @@ -391,12 +492,29 @@ protected function getCustomerLastname($customer) /** * @param $customer + * @return string */ protected function logCouldNotEncodeCustomerError($customer) { - $this->mailchimpHelper->logError( - "Customer " . $customer->getId() . " json encode failed on store " . $this->getBatchMagentoStoreId() + $jsonErrorMessage = json_last_error_msg(); + $this->_mailchimpHelper->logError( + "Customer " . $customer->getId() . " json encode failed (".$jsonErrorMessage.") on store " + . $this->getBatchMagentoStoreId() + ); + return $jsonErrorMessage; + } + + /** + * @param $customer + * @param $mailchimpTags + */ + protected function logCouldNotEncodeMailchimpTags($customer, $mailchimpTags) + { + $this->_mailchimpHelper->logError( + "MailChimp tags encode failed, Customer " . $customer->getId() . " on store " . + $this->getBatchMagentoStoreId()." mergeFields:" ); + $this->_mailchimpHelper->logError($mailchimpTags); } /** @@ -412,19 +530,20 @@ protected function getCustomerResourceCollection() */ protected function getBatchMagentoStoreId() { - return $this->magentoStoreId; + return $this->_magentoStoreId; } /** * @param $collection - * @param null $mailchimpStoreId + * @param null $mailchimpStoreId */ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId = null) { if (!$mailchimpStoreId) { - $mailchimpStoreId = $this->mailchimpStoreId; + $mailchimpStoreId = $this->_mailchimpStoreId; } - $joinCondition = "m4m.related_id = e.entity_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + + $joinCondition = "m4m.related_id = e.entity_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; $mailchimpTableName = $this->getSyncDataTableName(); $collection->getSelect()->joinLeft( @@ -445,7 +564,7 @@ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId */ protected function setMailchimpStoreId($mailchimpStoreId) { - $this->mailchimpStoreId = $mailchimpStoreId; + $this->_mailchimpStoreId = $mailchimpStoreId; } /** @@ -453,7 +572,7 @@ protected function setMailchimpStoreId($mailchimpStoreId) */ protected function setMagentoStoreId($magentoStoreId) { - $this->magentoStoreId = $magentoStoreId; + $this->_magentoStoreId = $magentoStoreId; } /** @@ -478,6 +597,169 @@ protected function makeHelper() */ protected function getMailChimpHelper() { - return $this->mailchimpHelper; + return $this->_mailchimpHelper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function makeDateHelper() + { + return Mage::helper('mailchimp/date'); } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getMailChimpDateHelper() + { + return $this->_mailchimpDateHelper; + } + + /** + * @param $customer + * @param $listId + * @param $mergeFields + * @return array|null + */ + protected function makePatchBatchStructure($customer, $listId, $mergeFields) + { + $batchData = null; + $mergeFieldJSON = json_encode($mergeFields); + $customerId = $customer->getId(); + + if ($mergeFieldJSON === false) { + $this->logCouldNotEncodeMailchimpTags($customer, $mergeFields); + } else { + $md5HashEmail = md5(strtolower($customer->getEmail())); + $batchData = array(); + $batchData['method'] = "PATCH"; + $batchData['path'] = "/lists/" . $listId . "/members/" . $md5HashEmail; + $batchData['operation_id'] = "{$this->_batchId}_{$customerId}_SUB"; + $batchData['body'] = $mergeFieldJSON; + } + + return $batchData; + } + + /** + * @param $subscriber + * @param $customer + * @return mixed + */ + protected function isSubscribed($subscriber, $customer) + { + if ($subscriber->loadByEmail($customer->getEmail())->getSubscriberId() + && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED ) { + return true; + } else { + return false; + } + } + + /** + * @param $optInStatus + */ + protected function setOptInStatusForStore($optInStatus) + { + $this->_optInStatusForStore = $optInStatus; + } + + /** + * @return mixed + */ + protected function getOptInStatusForStore() + { + return $this->_optInStatusForStore; + } + + /** + * @param $mergeFields + * @param $customer + * @param $listId + * @return array|null + */ + protected function getCustomerPatchBatch($mergeFields, $customer, $listId) + { + $batchData = null; + + if (!empty($mergeFields["merge_fields"])) { + $batchData = $this->makePatchBatchStructure($customer, $listId, $mergeFields); + } + + return $batchData; + } + + /** + * @param $magentoStoreId + * @param $subscriber + * @param $customer + * @param $listId + * @param $counter + * @return array|null + */ + protected function makeMailchimpTagsBatchStructure($magentoStoreId, $subscriber, $customer, $listId) + { + $subscriber->setSubscriberEmail($customer->getEmail()); + $subscriber->setCustomerId($customer->getId()); + $mailChimpTags = $this->_buildMailchimpTags($subscriber, $magentoStoreId); + $mergeFields["merge_fields"] = $mailChimpTags->getMailchimpTags(); + $batchData = $this->getCustomerPatchBatch($mergeFields, $customer, $listId); + return $batchData; + } + + /** + * @param Varien_Object $dataCustomer + * @param Ebizmarts_MailChimp_Helper_Data $helper + */ + protected function incrementCounterSentPerBatch( + Varien_Object $dataCustomer, + Ebizmarts_MailChimp_Helper_Data $helper + ) { + if ($dataCustomer->getId()) { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::CUS_MOD); + } else { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::CUS_NEW); + } + } + + /** + * Send merge fields for transactional members + * + * @param $magentoStoreId + * @param Varien_Object $dataCustomer + * @param $subscriber + * @param $customer + * @param $listId + * @param $counter + * @param array $customerArray + * @return array + */ + protected function sendMailchimpTags( + $magentoStoreId, + Varien_Object $dataCustomer, + $subscriber, + $customer, + $listId, + $counter, + array $customerArray + ) { + if ($dataCustomer->getMailchimpSyncedFlag()) { + $batchData = $this->makeMailchimpTagsBatchStructure( + $magentoStoreId, + $subscriber, + $customer, + $listId, + $counter + ); + + if ($batchData !== null) { + $customerArray[$counter] = $batchData; + $counter++; + } + } + + return array($customerArray, $counter); + } + } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index ccf9a745a..6af6e227d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -32,32 +32,44 @@ class Ebizmarts_MailChimp_Model_Api_Orders /** * Set the request for orders to be created on MailChimp * - * @param $mailchimpStoreId - * @param $magentoStoreId + * @param $mailchimpStoreId + * @param $magentoStoreId * @return array + * @throws Mage_Core_Exception */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $batchArray = array(); $this->_firstDate = $helper->getEcommerceFirstDate($magentoStoreId); $this->_counter = 0; - $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' . $helper->getDateMicrotime(); + $this->_batchId = 'storeid-' + . $magentoStoreId . '_' + . Ebizmarts_MailChimp_Model_Config::IS_ORDER + . '_' . $dateHelper->getDateMicrotime(); $resendTurn = $helper->getResendTurn($magentoStoreId); + if (!$resendTurn) { // get all the orders modified $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId, $magentoStoreId)); } - // get new orders + // get new orders $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId, $magentoStoreId)); return $batchArray; } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); $batchArray = array(); $modifiedOrders = $this->getResourceModelOrderCollection(); @@ -66,8 +78,9 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) //join with mailchimp_ecommerce_sync_data table to filter by sync data. $modifiedOrders->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_ORDER + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); // be sure that the order are already in mailchimp and not deleted @@ -82,23 +95,46 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) $incrementId = $order->getIncrementId(); //create missing products first $batchArray = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray); - $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); - if (!empty($orderJson)) { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::ORD_MOD); - - $batchArray[$this->_counter]['method'] = "PATCH"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $incrementId; - $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; - $batchArray[$this->_counter]['body'] = $orderJson; - //update order delta - $this->_updateSyncData($orderId, $mailchimpStoreId); - $this->_counter++; + if ($orderJson !== false) { + if (!empty($orderJson)) { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::ORD_MOD); + + $batchArray[$this->_counter]['method'] = "PATCH"; + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId + . '/orders/' . $incrementId; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; + $batchArray[$this->_counter]['body'] = $orderJson; + //update order delta + $this->_updateSyncData($orderId, $mailchimpStoreId); + $this->_counter++; + } else { + $error = $helper->__('Something went wrong when retrieving product information.'); + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error, + 0, + 0 + ); + continue; + } } else { - $error = $helper->__('Something went wrong when retrieving product information.'); - $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now(), $error, 0, 0); - continue; + $jsonErrorMsg = json_last_error_msg(); + $helper->logError("Order " . $order->getEntityId() . " json encode failed (".$jsonErrorMsg.")"); + + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $jsonErrorMsg, + 0, + 0, + false, + -1 + ); } } catch (Exception $e) { $helper->logError($e->getMessage()); @@ -108,9 +144,16 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) return $batchArray; } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + * @throws Mage_Core_Exception + */ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $batchArray = array(); $newOrders = $this->getResourceModelOrderCollection(); @@ -137,20 +180,43 @@ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); - if (!empty($orderJson)) { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::ORD_NEW); - - $batchArray[$this->_counter]['method'] = "POST"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; - $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; - $batchArray[$this->_counter]['body'] = $orderJson; - //update order delta - $this->_updateSyncData($orderId, $mailchimpStoreId); - $this->_counter++; + if ($orderJson !== false) { + if (!empty($orderJson)) { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::ORD_NEW); + + $batchArray[$this->_counter]['method'] = "POST"; + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; + $batchArray[$this->_counter]['body'] = $orderJson; + //update order delta + $this->_updateSyncData($orderId, $mailchimpStoreId); + $this->_counter++; + } else { + $error = $helper->__('Something went wrong when retrieving product information.'); + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error, + 0, + 0 + ); + continue; + } } else { - $error = $helper->__('Something went wrong when retrieving product information.'); - $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now(), $error, 0, 0); - continue; + $jsonErrorMsg = json_last_error_msg(); + $helper->logError("Order " . $order->getEntityId() . " json encode failed (".$jsonErrorMsg.")"); + + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $jsonErrorMsg, + 0, + 0, + false, + -1 + ); } } catch (Exception $e) { $helper->logError($e->getMessage()); @@ -163,10 +229,11 @@ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) /** * Set all the data for each order to be sent * - * @param $order - * @param $mailchimpStoreId - * @param $magentoStoreId - * @return string + * @param $order + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return false|string + * @throws Mage_Core_Model_Store_Exception */ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) { @@ -174,9 +241,83 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) $oldStore = $helper->getCurrentStoreId(); $helper->setCurrentStore($magentoStoreId); - $apiProduct = $this->getApiProduct(); + $data = $this->_getPayloadData($order, $magentoStoreId); + $lines = $this->_getPayloadDataLines($order, $mailchimpStoreId, $magentoStoreId); + $data['lines'] = $lines['lines']; + + if (!$lines['itemsCount']) { + unset($data['lines']); + $helper->setCurrentStore($oldStore); + return ""; + } + + //customer data + $data["customer"]["id"] = md5(strtolower($order->getCustomerEmail())); + $data["customer"]["email_address"] = $order->getCustomerEmail(); + $data["customer"]["opt_in_status"] = false; + + $subscriber = $this->getSubscriberModel(); + + if ($subscriber->getOptIn($magentoStoreId)) { + $isSubscribed = $subscriber->loadByEmail($order->getCustomerEmail())->getSubscriberId(); + + if (!$isSubscribed) { + $subscriber->subscribe($order->getCustomerEmail()); + } + } + + $subscriber = null; + + $store = $this->getStoreModelFromMagentoStoreId($magentoStoreId); + $data['order_url'] = $store->getUrl( + 'sales/order/view/', + array( + 'order_id' => $order->getId(), + '_nosid' => true, + '_secure' => true + ) + ); + + if ($order->getCustomerFirstname()) { + $data["customer"]["first_name"] = $order->getCustomerFirstname(); + } + + if ($order->getCustomerLastname()) { + $data["customer"]["last_name"] = $order->getCustomerLastname(); + } + + $billingAddress = $order->getBillingAddress(); + + if ($billingAddress) { + $street = $billingAddress->getStreet(); + $this->_getPayloadBilling($data, $billingAddress, $street); + } + + $shippingAddress = $order->getShippingAddress(); + + if ($shippingAddress) { + $this->_getPayloadShipping($data, $shippingAddress); + } + + $jsonData = ""; + //encode to JSON + $jsonData = json_encode($data); + + $helper->setCurrentStore($oldStore); + return $jsonData; + } + + /** + * @param $order + * @param $magentoStoreId + * @return array + * @throws Exception + */ + protected function _getPayloadData($order, $magentoStoreId) + { $data = array(); $data['id'] = $order->getIncrementId(); + $dataPromo = $this->getPromoData($order); $mailchimpCampaignId = $order->getMailchimpCampaignId(); if ($this->shouldSendCampaignId($mailchimpCampaignId, $magentoStoreId)) { @@ -192,7 +333,6 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) $data['tax_total'] = $this->returnZeroIfNull($order->getTaxAmount()); $data['discount_total'] = abs($order->getDiscountAmount()); $data['shipping_total'] = $this->returnZeroIfNull($order->getShippingAmount()); - $dataPromo = $this->getPromoData($order); if ($dataPromo !== null) { $data['promos'] = $dataPromo; @@ -212,22 +352,28 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) $data['updated_at_foreign'] = $order->getUpdatedAt(); if ($this->isOrderCanceled($order)) { - $orderCancelDate = null; - $commentCollection = $order->getStatusHistoryCollection(); - - foreach ($commentCollection as $comment) { - if ($this->isTheOrderCommentCanceled($comment)) { - $orderCancelDate = $comment->getCreatedAt(); - } - } + $orderCancelDate = $this->_processCanceledOrder($order); if ($orderCancelDate) { $data['cancelled_at_foreign'] = $orderCancelDate; } } - $data['lines'] = array(); - //order lines + return $data; + } + + /** + * @param $order + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + protected function _getPayloadDataLines($order, $mailchimpStoreId, $magentoStoreId) + { + $helper = $this->getHelper(); + $apiProduct = $this->getApiProduct(); + + $lines = array(); $items = $order->getAllVisibleItems(); $itemCount = 0; @@ -244,7 +390,9 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) if (!$variant) { continue; } - } elseif ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE || $item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED) { + } elseif ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE + || $item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_GROUPED + ) { continue; } else { $variant = $productId; @@ -255,7 +403,7 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) if (!$isProductEnabled || ($productSyncData->getMailchimpSyncDelta() && $productSyncError == '')) { $itemCount++; - $data["lines"][] = array( + $lines[] = array( "id" => (string)$itemCount, "product_id" => $productId, "product_variant_id" => $variant, @@ -271,166 +419,135 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) } } - if (!$itemCount) { - unset($data['lines']); - $helper->setCurrentStore($oldStore); - return ""; - } - - //customer data - $data["customer"]["id"] = md5(strtolower($order->getCustomerEmail())); - $data["customer"]["email_address"] = $order->getCustomerEmail(); - $data["customer"]["opt_in_status"] = false; + return array('lines' => $lines, 'itemsCount' => $itemCount); + } - if($this->getCustomerModel()->getOptin($magentoStoreId)) { - $subscriber = $this->getSubscriberModel(); - $isSubscribed = $subscriber->loadByEmail($order->getCustomerEmail())->getSubscriberId(); - if (!$isSubscribed) { - $subscriber->subscribe($order->getCustomerEmail()); - } - } + /** + * @param $data + * @param $billingAddress + * @param $street + */ + protected function _getPayloadBilling($data, $billingAddress, $street) + { + $address = array(); - $store = $this->getStoreModelFromMagentoStoreId($magentoStoreId); - $data['order_url'] = $store->getUrl( - 'sales/order/view/', - array( - 'order_id' => $order->getId(), - '_nosid' => true, - '_secure' => true - ) - ); + $this->_getPayloadBillingStreet($data, $address, $street); - if ($order->getCustomerFirstname()) { - $data["customer"]["first_name"] = $order->getCustomerFirstname(); + if ($billingAddress->getCity()) { + $address["city"] = $data['billing_address']["city"] = $billingAddress->getCity(); } - if ($order->getCustomerLastname()) { - $data["customer"]["last_name"] = $order->getCustomerLastname(); + if ($billingAddress->getRegion()) { + $address["province"] = $data['billing_address']["province"] = $billingAddress->getRegion(); } - $billingAddress = $order->getBillingAddress(); - - if ($billingAddress) { - $street = $billingAddress->getStreet(); - $address = array(); - - if ($street[0]) { - $address["address1"] = $data['billing_address']["address1"] = $street[0]; - } - - if (count($street) > 1) { - $address["address2"] = $data['billing_address']["address2"] = $street[1]; - } - - if ($billingAddress->getCity()) { - $address["city"] = $data['billing_address']["city"] = $billingAddress->getCity(); - } - - if ($billingAddress->getRegion()) { - $address["province"] = $data['billing_address']["province"] = $billingAddress->getRegion(); - } - - if ($billingAddress->getRegionCode()) { - $address["province_code"] = $data['billing_address']["province_code"] = $billingAddress->getRegionCode(); - } + if ($billingAddress->getRegionCode()) { + $address["province_code"] = + $data['billing_address']["province_code"] = + $billingAddress->getRegionCode(); + } - if ($billingAddress->getPostcode()) { - $address["postal_code"] = $data['billing_address']["postal_code"] = $billingAddress->getPostcode(); - } + if ($billingAddress->getPostcode()) { + $address["postal_code"] = $data['billing_address']["postal_code"] = $billingAddress->getPostcode(); + } - if ($billingAddress->getCountry()) { - $countryName = $this->getCountryModelNameFromBillingAddress($billingAddress); - $address["country"] = $data['billing_address']["country"] = $countryName; - $address["country_code"] = $data['billing_address']["country_code"] = $billingAddress->getCountry(); - } + if ($billingAddress->getCountry()) { + $countryName = $this->getCountryModelNameFromBillingAddress($billingAddress); + $address["country"] = $data['billing_address']["country"] = $countryName; + $address["country_code"] = $data['billing_address']["country_code"] = $billingAddress->getCountry(); + } - if (count($address)) { - $data["customer"]["address"] = $address; - } + if (!empty($address)) { + $data["customer"]["address"] = $address; + } - if ($billingAddress->getName()) { - $data['billing_address']['name'] = $billingAddress->getName(); - } + if ($billingAddress->getName()) { + $data['billing_address']['name'] = $billingAddress->getName(); + } - //company - if ($billingAddress->getCompany()) { - $data["customer"]["company"] = $data["billing_address"]["company"] = $billingAddress->getCompany(); - } + //company + if ($billingAddress->getCompany()) { + $data["customer"]["company"] = $data["billing_address"]["company"] = $billingAddress->getCompany(); } + } - $shippingAddress = $order->getShippingAddress(); - if ($shippingAddress) { - $street = $shippingAddress->getStreet(); + /** + * @param $data + * @param $address + * @param $street + */ + protected function _getPayloadBillingStreet($data, $address, $street) + { + if ($street[0]) { + $address["address1"] = $data['billing_address']["address1"] = $street[0]; + } - if ($shippingAddress->getName()) { - $data['shipping_address']['name'] = $shippingAddress->getName(); - } + if (count($street) > 1) { + $address["address2"] = $data['billing_address']["address2"] = $street[1]; + } + } - if (isset($street[0]) && $street[0]) { - $data['shipping_address']['address1'] = $street[0]; - } + /** + * @param $data + * @param $shippingAddress + */ + protected function _getPayloadShipping($data, $shippingAddress) + { + $street = $shippingAddress->getStreet(); - if (isset($street[1]) && $street[1]) { - $data['shipping_address']['address2'] = $street[1]; - } + if ($shippingAddress->getName()) { + $data['shipping_address']['name'] = $shippingAddress->getName(); + } - if ($shippingAddress->getCity()) { - $data['shipping_address']['city'] = $shippingAddress->getCity(); - } + if (isset($street[0]) && $street[0]) { + $data['shipping_address']['address1'] = $street[0]; + } - if ($shippingAddress->getRegion()) { - $data['shipping_address']['province'] = $shippingAddress->getRegion(); - } + if (isset($street[1]) && $street[1]) { + $data['shipping_address']['address2'] = $street[1]; + } - if ($shippingAddress->getRegionCode()) { - $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); - } + if ($shippingAddress->getCity()) { + $data['shipping_address']['city'] = $shippingAddress->getCity(); + } - if ($shippingAddress->getPostcode()) { - $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); - } + if ($shippingAddress->getRegion()) { + $data['shipping_address']['province'] = $shippingAddress->getRegion(); + } - if ($shippingAddress->getCountry()) { - $data['shipping_address']['country'] = $this->getCountryModelNameFromShippingAddress($shippingAddress); - $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); - } + if ($shippingAddress->getRegionCode()) { + $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); + } - if ($shippingAddress->getCompamy()) { - $data["shipping_address"]["company"] = $shippingAddress->getCompany(); - } + if ($shippingAddress->getPostcode()) { + $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); } - //customer orders data - $orderCollection = $this->getResourceModelOrderCollection() - ->addFieldToFilter( - 'state', - array( - array('neq' => Mage_Sales_Model_Order::STATE_CANCELED), - array('neq' => Mage_Sales_Model_Order::STATE_CLOSED) - ) - ) - ->addAttributeToFilter('customer_email', array('eq' => $order->getCustomerEmail())); - $totalOrders = 0; - $totalAmountSpent = 0; + if ($shippingAddress->getCountry()) { + $data['shipping_address']['country'] = $this->getCountryModelNameFromShippingAddress($shippingAddress); + $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); + } - foreach ($orderCollection as $customerOrder) { - $totalOrders++; - $totalAmountSpent += ($customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded() - $customerOrder->getTotalCanceled()); + if ($shippingAddress->getCompamy()) { + $data["shipping_address"]["company"] = $shippingAddress->getCompany(); } + } - $data["customer"]["orders_count"] = (int)$totalOrders; - $data["customer"]["total_spent"] = $totalAmountSpent; - $jsonData = ""; - //enconde to JSON - try { - $jsonData = json_encode($data); - } catch (Exception $e) { - //json encode failed - $helper->logError("Order " . $order->getEntityId() . " json encode failed"); + /** + * @return mixed + */ + protected function _processCanceledOrder($order) + { + $orderCancelDate = null; + $commentCollection = $order->getStatusHistoryCollection(); + + foreach ($commentCollection as $comment) { + if ($this->isTheOrderCommentCanceled($comment)) { + $orderCancelDate = $comment->getCreatedAt(); + } } - $helper->setCurrentStore($oldStore); - return $jsonData; + return $orderCancelDate; } /** @@ -442,6 +559,10 @@ protected function getBatchLimitFromConfig() return $helper->getOrderAmountLimit(); } + /** + * @param $value + * @return int + */ protected function returnZeroIfNull($value) { $returnValue = $value; @@ -452,65 +573,90 @@ protected function returnZeroIfNull($value) return $returnValue; } + /** + * @param $order + * @return array + */ protected function _getMailChimpStatus($order) { - $mailChimpFinancialStatus = null; - $mailChimpFulfillmentStatus = null; $totalItemsOrdered = $order->getData('total_qty_ordered'); - $shippedItemAmount = 0; - $invoicedItemAmount = 0; - $refundedItemAmount = 0; $mailChimpStatus = array(); - foreach ($order->getAllVisibleItems() as $item) { - $shippedItemAmount += $item->getQtyShipped(); - $invoicedItemAmount += $item->getQtyInvoiced(); - $refundedItemAmount += $item->getQtyRefunded(); + $financialFulfillment = $this->_getFinancialFulfillmentStatus( + $order->getAllVisibleItems(), $totalItemsOrdered + ); + + if (!$financialFulfillment['financialStatus'] && $this->isOrderCanceled($order)) { + $financialFulfillment['financialStatus'] = self::CANCELED; } - if ($shippedItemAmount > 0) { - if ($totalItemsOrdered > $shippedItemAmount) { - $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED; - } else { - $mailChimpFulfillmentStatus = self::SHIPPED; - } + if (!$financialFulfillment['financialStatus']) { + $financialFulfillment['financialStatus'] = self::PENDING; } - if ($refundedItemAmount > 0) { - if ($totalItemsOrdered > $refundedItemAmount) { - $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED; - } else { - $mailChimpFinancialStatus = self::REFUNDED; - } + if ($financialFulfillment['financialStatus']) { + $mailChimpStatus['financial_status'] = $financialFulfillment['financialStatus']; } - if ($invoicedItemAmount > 0) { - if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) { - if ($totalItemsOrdered > $invoicedItemAmount) { - $mailChimpFinancialStatus = self::PARTIALLY_PAID; - } else { - $mailChimpFinancialStatus = self::PAID; - } - } + if ($financialFulfillment['fulfillmentStatus']) { + $mailChimpStatus['fulfillment_status'] = $financialFulfillment['fulfillmentStatus']; } - if (!$mailChimpFinancialStatus && $this->isOrderCanceled($order)) { - $mailChimpFinancialStatus = self::CANCELED; + return $mailChimpStatus; + } + + /** + * @param $orderItems + * @param $totalItemsOrdered + * @return array + */ + protected function _getFinancialFulfillmentStatus($orderItems, $totalItemsOrdered) + { + $items = array( + 'shippedItemAmount' => 0, + 'invoicedItemAmount' => 0, + 'refundedItemAmount' => 0 + ); + $mailchimpStatus = array( + 'financialStatus' => null, + 'fulfillmentStatus' => null + ); + + foreach ($orderItems as $item) { + $items['invoicedItemAmount'] += $item->getQtyShipped(); + $items['invoicedItemAmount'] += $item->getQtyInvoiced(); + $items['refundedItemAmount'] += $item->getQtyRefunded(); } - if (!$mailChimpFinancialStatus) { - $mailChimpFinancialStatus = self::PENDING; + if ($items['shippedItemAmount'] > 0) { + if ($totalItemsOrdered > $items['shippedItemAmount']) { + $mailchimpStatus['fulfillmentStatus'] = self::PARTIALLY_SHIPPED; + } else { + $mailchimpStatus['fulfillmentStatus'] = self::SHIPPED; + } } - if ($mailChimpFinancialStatus) { - $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus; + if ($items['refundedItemAmount'] > 0) { + if ($mailchimpStatus > $items['refundedItemAmount']) { + $mailchimStatus['financialStatus'] = self::PARTIALLY_REFUNDED; + } else { + $mailchimpStatus['financialStatus'] = self::REFUNDED; + } } - if ($mailChimpFulfillmentStatus) { - $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus; + if ($items['invoicedItemAmount'] > 0) { + if ($items['refundedItemAmount'] == 0 + || $items['refundedItemAmount'] != $items['invoicedItemAmount'] + ) { + if ($totalItemsOrdered > $items['invoicedItemAmount']) { + $mailchimpStatus['financialStatus'] = self::PARTIALLY_PAID; + } else { + $mailchimpStatus['financialStatus'] = self::PAID; + } + } } - return $mailChimpStatus; + return $mailchimpStatus; } /** @@ -522,26 +668,56 @@ public function update($orderId, $magentoStoreId) $helper = $this->getHelper(); if ($helper->isEcomSyncDataEnabled($magentoStoreId)) { $mailchimpStoreId = $helper->getMCStoreId($magentoStoreId); - $this->_updateSyncData($orderId, $mailchimpStoreId, null, null, 1, null, true, false); + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + null, + null, + 1, + null, + true, + false + ); } } /** * update customer sync data * - * @param int $orderId - * @param string $mailchimpStoreId + * @param int $orderId + * @param string $mailchimpStoreId * @param int|null $syncDelta * @param int|null $syncError * @param int|null $syncModified * @param int|null $syncedFlag - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval + * @param bool $saveOnlyIfexists + * @param bool $allowBatchRemoval */ - protected function _updateSyncData($orderId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncedFlag = null, $saveOnlyIfexists = false, $allowBatchRemoval = true) - { + protected function _updateSyncData( + $orderId, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncedFlag = null, + $saveOnlyIfexists = false, + $allowBatchRemoval = true + ) { $helper = $this->getHelper(); - $helper->saveEcommerceSyncData($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, null, null, $syncedFlag, $saveOnlyIfexists, null, $allowBatchRemoval); + $helper->saveEcommerceSyncData( + $orderId, + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $mailchimpStoreId, + $syncDelta, + $syncError, + $syncModified, + null, + null, + $syncedFlag, + $saveOnlyIfexists, + null, + $allowBatchRemoval + ); } /** @@ -555,9 +731,17 @@ protected function _updateSyncData($orderId, $mailchimpStoreId, $syncDelta = nul public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $this->_counter = 0; - $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' . $helper->getDateMicrotime(); - $lastId = $helper->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, $magentoStoreId, 'stores'); + $this->_batchId = 'storeid-' + . $magentoStoreId . '_' + . Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' + . $dateHelper->getDateMicrotime(); + $lastId = $helper->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, + $magentoStoreId, + 'stores' + ); $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); $batchArray = array(); $config = array(); @@ -570,18 +754,21 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS $orderCollection->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_ORDER + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); // be sure that the orders are not in mailchimp - $orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS NOT NULL AND m4m.mailchimp_sync_error = ''"); + $orderCollection->getSelect()->where( + "m4m.mailchimp_sync_delta IS NOT NULL AND m4m.mailchimp_sync_error = ''" + ); $orderCollection->getSelect()->limit(self::BATCH_LIMIT_ONLY_ORDERS); foreach ($orderCollection as $order) { //Delete order $orderId = $order->getEntityId(); $config = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, $orderId)); - if (!$helper->timePassed($initialTime)) { + if (!$dateHelper->timePassed($initialTime)) { $batchArray[$this->_counter]['method'] = "DELETE"; $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $orderId; $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; @@ -590,19 +777,42 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS //Create order $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); - if (!empty($orderJson)) { - $batchArray[$this->_counter]['method'] = "POST"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; - $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; - $batchArray[$this->_counter]['body'] = $orderJson; - $this->_counter += 1; + + if ($orderJson !== false) { + if (!empty($orderJson)) { + $batchArray[$this->_counter]['method'] = "POST"; + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; + $batchArray[$this->_counter]['body'] = $orderJson; + $this->_counter += 1; + } else { + $error = $helper->__( + 'Something went wrong when retrieving product information during migration from 1.1.6.' + ); + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error, + 0, + 0 + ); + continue; + } } else { - $error = $helper->__('Something went wrong when retrieving product information during migration from 1.1.6.'); - $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now(), $error, 0, 0); + $error = $helper->__("Json error during migration from 1.1.6"); + $this->_updateSyncData( + $orderId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error, + 0, + 0 + ); continue; } } else { - if (!count($batchArray)) { + if (empty($batchArray)) { $batchArray[] = $helper->__('Time passed.'); } @@ -641,6 +851,14 @@ protected function getHelper() return Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getDateHelper() + { + return Mage::helper('mailchimp/date'); + } + /** * @param $newOrders * @param $mailchimpStoreId @@ -650,8 +868,9 @@ public function joinMailchimpSyncDataWithoutWhere($newOrders, $mailchimpStoreId) $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); $newOrders->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_ORDER + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); } @@ -689,6 +908,7 @@ public function getPromoData($order) } } } + return $promo; } @@ -716,7 +936,11 @@ protected function makeSalesRule() public function getSyncedOrder($orderId, $mailchimpStoreId) { $helper = $this->getHelper(); - $result = $helper->getEcommerceSyncDataItem($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId); + $result = $helper->getEcommerceSyncDataItem( + $orderId, + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $mailchimpStoreId + ); $mailchimpSyncedFlag = $result->getMailchimpSyncedFlag(); $mailchimpOrderId = $result->getId(); @@ -829,10 +1053,16 @@ public function shouldSendCampaignId($mailchimpCampaignId, $magentoStoreId) } else { $api = $helper->getApi($magentoStoreId); $campaignData = $api->getCampaign()->get($mailchimpCampaignId, 'recipients'); - if (isset($campaignData['recipients']['list_id']) && $campaignData['recipients']['list_id'] == $listId) { - $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = $isCampaingFromCurrentList = true; + if (isset($campaignData['recipients']['list_id']) + && $campaignData['recipients']['list_id'] == $listId + ) { + $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = + $isCampaingFromCurrentList = + true; } else { - $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = $isCampaingFromCurrentList = false; + $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = + $isCampaingFromCurrentList = + false; } } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 253af5d2b..0a1fbf4bb 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -14,83 +14,139 @@ class Ebizmarts_MailChimp_Model_Api_Products const PRODUCT_IS_ENABLED = 1; const PRODUCT_IS_DISABLED = 2; const BATCH_LIMIT = 100; - private $_parentImageUrl = null; - private $_parentId = null; - private $_parentUrl = null; - private $_parentPrice = null; - private $_visibility = null; - /** @var Mage_Catalog_Model_Product_Type_Configurable */ - private $productTypeConfigurable; + protected $_parentImageUrl = null; + protected $_parentId = null; + protected $_parentUrl = null; + protected $_parentPrice = null; + protected $_visibility = null; + + /** + * @var Mage_Catalog_Model_Product_Type_Configurable + */ + protected $_productTypeConfigurable; /** * @var Ebizmarts_MailChimp_Helper_Data */ - private $mailchimpHelper; - private $visibilityOptions; - private $productTypeConfigurableResource; + protected $_mailchimpHelper; + protected $_mailchimpDateHelper; + protected $_visibilityOptions; + protected $_productTypeConfigurableResource; public static $noChildrenIds = array(0 => array()); const PRODUCT_DISABLED_IN_MAGENTO = 'This product was deleted because it is disabled in Magento.'; public function __construct() { - $this->productTypeConfigurable = Mage::getModel('catalog/product_type_configurable'); - $this->productTypeConfigurableResource = Mage::getResourceSingleton('catalog/product_type_configurable'); - $this->mailchimpHelper = Mage::helper('mailchimp'); - $this->visibilityOptions = Mage::getModel('catalog/product_visibility')->getOptionArray(); + $this->_productTypeConfigurable = Mage::getModel('catalog/product_type_configurable'); + $this->_productTypeConfigurableResource = Mage::getResourceSingleton( + 'catalog/product_type_configurable' + ); + $this->_mailchimpHelper = Mage::helper('mailchimp'); + $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); + $this->_visibilityOptions = Mage::getModel('catalog/product_visibility')->getOptionArray(); } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception + */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { - $helper = $this->getMailChimpHelper(); - $oldStore = $helper->getCurrentStoreId(); + $helper = $this->getMailChimpHelper(); + $dateHelper = $this->getMailChimpDateHelper(); + $oldStore = $helper->getCurrentStoreId(); $helper->setCurrentStore($magentoStoreId); if ($this->isProductFlatTableEnabled()) { $helper->getMageApp()->getStore($magentoStoreId) - ->setConfig(Mage_Catalog_Helper_Category_Flat::XML_PATH_IS_ENABLED_FLAT_CATALOG_CATEGORY, 0) - ->setConfig(Mage_Catalog_Helper_Product_Flat::XML_PATH_USE_PRODUCT_FLAT, 0); + ->setConfig( + Mage_Catalog_Helper_Category_Flat::XML_PATH_IS_ENABLED_FLAT_CATALOG_CATEGORY, + 0 + ) + ->setConfig( + Mage_Catalog_Helper_Product_Flat::XML_PATH_USE_PRODUCT_FLAT, + 0 + ); } + $this->_markSpecialPrices($mailchimpStoreId, $magentoStoreId); $collection = $this->makeProductsNotSentCollection($magentoStoreId); $this->joinMailchimpSyncData($collection, $mailchimpStoreId); $batchArray = array(); - $batchId = $this->makeBatchId($magentoStoreId); $counter = 0; + foreach ($collection as $product) { $productId = $product->getId(); if ($this->shouldSendProductUpdate($mailchimpStoreId, $magentoStoreId, $product)) { - $batchArray = array_merge($this->_buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId), $batchArray); + $buildUpdateOperations = $this->_buildUpdateProductRequest( + $product, + $batchId, + $mailchimpStoreId, + $magentoStoreId + ); + + if ($buildUpdateOperations !== false) { + $batchArray = array_merge( + $buildUpdateOperations, + $batchArray + ); + $this->_updateSyncData($productId, $mailchimpStoreId); + } + $counter = count($batchArray); - $this->_updateSyncData($productId, $mailchimpStoreId); continue; } else { $data = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); } - if (!empty($data)) { - $batchArray[$counter] = $data; - $counter++; + if ($data !== false) { + if (!empty($data)) { + $batchArray[$counter] = $data; + $counter++; + + $dataProduct = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); + if ($dataProduct->getId()) { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::PRO_MOD); + } else { + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::PRO_NEW); + } - $dataProduct = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); - if ($dataProduct->getId()) { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::PRO_MOD); + //update product delta + $this->_updateSyncData($productId, $mailchimpStoreId); } else { - $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::PRO_NEW); + $this->_updateSyncData( + $productId, + $mailchimpStoreId, + $dateHelper->formatDate(null, 'Y-m-d H:i:s'), + "This product type is not supported on MailChimp.", + 0, + null, + 0 + ); } - - //update product delta - $this->_updateSyncData($productId, $mailchimpStoreId); - } else { - $this->_updateSyncData($productId, $mailchimpStoreId, $this->getCurrentDate(), "This product type is not supported on MailChimp.", 0, null, 0); } } + $helper->setCurrentStore($oldStore); + return $batchArray; } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ public function createDeletedProductsBatchJson($mailchimpStoreId, $magentoStoreId) { $deletedProducts = $this->getProductResourceCollection(); @@ -101,21 +157,36 @@ public function createDeletedProductsBatchJson($mailchimpStoreId, $magentoStoreI $batchId = $this->makeBatchId($magentoStoreId); $counter = 0; foreach ($deletedProducts as $product) { - $data = $this->_buildDeleteProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + $data = $this->_buildDeleteProductRequest($product, $batchId, $mailchimpStoreId); if (!empty($data)) { $batchArray[$counter] = $data; $counter++; } - $this->_updateSyncData($product->getId(), $mailchimpStoreId, null, self::PRODUCT_DISABLED_IN_MAGENTO, 0, null, 0); + + $this->_updateSyncData( + $product->getId(), + $mailchimpStoreId, + null, + self::PRODUCT_DISABLED_IN_MAGENTO, + 0, + null, + 0 + ); } + return $batchArray; } - protected function _buildDeleteProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) + /** + * @param $product + * @param $batchId + * @param $mailchimpStoreId + * @return array + */ + protected function _buildDeleteProductRequest($product, $batchId, $mailchimpStoreId) { if ($this->isBundleProduct($product)) { - //@TODO bundle return array(); } else { $data = array(); @@ -127,6 +198,13 @@ protected function _buildDeleteProductRequest($product, $batchId, $mailchimpStor return $data; } + /** + * @param $product + * @param $batchId + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array|bool + */ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) { $variantProducts = array(); @@ -137,17 +215,33 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId } elseif ($this->isVirtualProduct($product) || $this->isDownloadableProduct($product)) { $variantProducts[] = $product; } else { - //@TODO bundle return array(); } $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts); - try { - $body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT); - } catch (Exception $e) { + + $body = json_encode($bodyData, JSON_HEX_APOS | JSON_HEX_QUOT); + if ($body === false) { //json encode failed - $this->getMailChimpHelper()->logError("Product " . $product->getId() . " json encode failed"); - return array(); + $jsonErrorMsg = json_last_error_msg(); + $this->getMailChimpHelper()->logError( + "Product " . $product->getId() + . " json encode failed (".$jsonErrorMsg.")" + ); + + $this->_updateSyncData( + $product->getId(), + $mailchimpStoreId, + $this->getMailChimpDateHelper()->getCurrentDateTime(), + $jsonErrorMsg, + 0, + null, + null, + false, + -1 + ); + + return false; } $data = array(); @@ -155,28 +249,66 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId $data['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products"; $data['operation_id'] = $batchId . '_' . $product->getId(); $data['body'] = $body; + return $data; } + /** + * @param $product + * @param $batchId + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array|bool + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception + */ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) { $variantProducts = array(); - if ($this->isSimpleProduct($product) || $this->isVirtualProduct($product) || $this->isDownloadableProduct($product)) { + $operations = array(); + + if ($this->isSimpleProduct($product) + || $this->isVirtualProduct($product) + || $this->isDownloadableProduct($product) + ) { $variantProducts[] = $product; - $parentIds = $this->productTypeConfigurableResource->getParentIdsByChild($product->getId()); + $parentIds = $this->_productTypeConfigurableResource->getParentIdsByChild($product->getId()); + foreach ($parentIds as $parentId) { $helper = $this->getMailChimpHelper(); - $productSyncDataItem = $helper->getEcommerceSyncDataItem($parentId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $productSyncDataItem = $helper->getEcommerceSyncDataItem( + $parentId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); if ($productSyncDataItem->getMailchimpSyncDelta()) { $parent = Mage::getModel('catalog/product')->load($parentId); - $variantProducts = $this->makeProductChildrenArray($product, $magentoStoreId, true); + $variantProducts = $this->makeProductChildrenArray( + $product, + $magentoStoreId, + true + ); $bodyData = $this->_buildProductData($parent, $magentoStoreId, false, $variantProducts); - try { - $body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT); - } catch (Exception $e) { - //json encode failed - $this->getMailChimpHelper()->logError("Product " . $product->getId() . " json encode failed"); - return array(); + + $body = json_encode($bodyData, JSON_HEX_APOS | JSON_HEX_QUOT); + if ($body === false) { + $jsonErrorMsg = json_last_error_msg(); + $this->getMailChimpHelper()->logError( + "Product " . $parent->getId() + . " json encode failed (".$jsonErrorMsg.")" + ); + $this->_updateSyncData( + $parent->getId(), + $mailchimpStoreId, + $this->getMailChimpDateHelper()->getCurrentDateTime(), + $jsonErrorMsg, + 0, + null, + null, + false, + -1 + ); + return false; } $data = array(); @@ -188,18 +320,43 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor } } } elseif ($this->isConfigurableProduct($product)) { - $variantProducts = $this->makeProductChildrenArray($product, $magentoStoreId, true); + $variantProducts = $this->makeProductChildrenArray( + $product, + $magentoStoreId, + true + ); } else { - //@TODO bundle return array(); } + $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts); - try { - $body = json_encode($bodyData, JSON_HEX_APOS|JSON_HEX_QUOT); - } catch (Exception $e) { + + $body = json_encode($bodyData, JSON_HEX_APOS | JSON_HEX_QUOT); + if ($body === false) { //json encode failed - $this->getMailChimpHelper()->logError("Product " . $product->getId() . " json encode failed"); - return array(); + $this->getMailChimpHelper()->logError( + "Product " . $product->getId() + . " json encode failed (".json_last_error_msg().")" + ); + + $jsonErrorMsg = json_last_error_msg(); + $this->getMailChimpHelper()->logError( + "Product " . $product->getId() + . " json encode failed (".$jsonErrorMsg.")" + ); + $this->_updateSyncData( + $product->getId(), + $mailchimpStoreId, + $this->getMailChimpDateHelper()->getCurrentDateTime(), + $jsonErrorMsg, + 0, + null, + null, + false, + -1 + ); + + return false; } $data = array(); @@ -208,9 +365,19 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor $data['operation_id'] = $batchId . '_' . $product->getId(); $data['body'] = $body; $operations[] = $data; + return $operations; } + /** + * @param $product + * @param $magentoStoreId + * @param bool $isVariant + * @param array $variants + * @return array + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception + */ protected function _buildProductData($product, $magentoStoreId, $isVariant = true, $variants = array()) { $data = array(); @@ -223,18 +390,21 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $data["title"] = $rc->getAttributeRawValue($productId, 'name', $magentoStoreId); $this->_visibility = $rc->getAttributeRawValue($productId, 'visibility', $magentoStoreId); $url = null; + if (!$this->currentProductIsVisible()) { $url = $this->getNotVisibleProductUrl($product->getId(), $magentoStoreId); } else { $url = $this->getProductUrl($product); } + if (!$url) { $url = Mage::app()->getStore($magentoStoreId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); } - $data["url"] = $url; + $data["url"] = $url; //image $imageUrl = $this->getMailChimpImageUrl($product, $magentoStoreId); + if ($imageUrl) { $data["image_url"] = $imageUrl; } @@ -252,6 +422,7 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru //mailchimp product type and vendor (magento category) $categoryName = $this->getProductCategories($product, $magentoStoreId); + if ($categoryName) { $data["type"] = $categoryName; $data["vendor"] = $data["type"]; @@ -261,31 +432,49 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $data["handle"] = ""; //variants - if (count($variants)) { - $data["variants"] = array(); - if (isset($data["image_url"])) { - $this->_parentImageUrl = $data["image_url"]; - } - $this->_parentId = $product->getId(); - if ($this->currentProductIsVisible()) { - $this->_parentUrl = $data['url']; - } - $price = $this->getMailchimpFinalPrice($product); - if ($price) { - $this->_parentPrice = $price; - } + if (!empty($variants)) { + $data = $this->_processVariants($data, $variants, $product, $magentoStoreId); + } + } - foreach ($variants as $variant) { - $data["variants"][] = $this->_buildProductData($variant, $magentoStoreId); - } + return $data; + } - $this->_parentImageUrl = null; - $this->_parentPrice = null; - $this->_parentId = null; - $this->_parentUrl = null; - } + /** + * @param $data + * @param $variants + * @param $product + * @param $magentoStoreId + * @return array + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception + */ + protected function _processVariants($data, $variants, $product, $magentoStoreId) + { + $data["variants"] = array(); + if (isset($data["image_url"])) { + $this->_parentImageUrl = $data["image_url"]; } + $this->_parentId = $product->getId(); + if ($this->currentProductIsVisible()) { + $this->_parentUrl = $data['url']; + } + + $price = $this->getMailchimpFinalPrice($product, $magentoStoreId); + if ($price) { + $this->_parentPrice = $price; + } + + foreach ($variants as $variant) { + $data["variants"][] = $this->_buildProductData($variant, $magentoStoreId); + } + + $this->_parentImageUrl = null; + $this->_parentPrice = null; + $this->_parentId = null; + $this->_parentUrl = null; + return $data; } @@ -299,11 +488,31 @@ public function update($productId, $mailchimpStoreId) { $parentIdArray = $this->getAllParentIds($productId); foreach ($parentIdArray as $parentId) { - $this->_updateSyncData($parentId, $mailchimpStoreId, null, null, 1, 0, null, true, false); + $this->_updateSyncData( + $parentId, + $mailchimpStoreId, + null, + null, + 1, + 0, + null, + true, + false + ); } - $this->_updateSyncData($productId, $mailchimpStoreId, null, null, 1, 0, null, true, false); - } + $this->_updateSyncData( + $productId, + $mailchimpStoreId, + null, + null, + 1, + 0, + null, + true, + false + ); + } /** * Get stores to update and call update function after product is disabled. @@ -313,10 +522,19 @@ public function update($productId, $mailchimpStoreId) */ public function updateDisabledProducts($productId, $mailchimpStoreId) { - $this->_updateSyncData($productId, $mailchimpStoreId, null, '', 0, 1, null, false, false); + $this->_updateSyncData( + $productId, + $mailchimpStoreId, + null, + '', + 0, + 1, + 0, + false, + false + ); } - /** * Return products belonging to an order or a cart in a valid format to be sent to MailChimp. * @@ -331,16 +549,33 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) $batchId = $this->makeBatchId($magentoStoreId); $items = $order->getAllVisibleItems(); $helper = $this->getMailChimpHelper(); + $dateHelper = $this->getMailChimpDateHelper(); $syncDateFlag = $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId); foreach ($items as $item) { $itemProductId = $item->getProductId(); $product = $this->loadProductById($itemProductId); $productId = $product->getId(); - $productSyncData = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); - if ($productId != $itemProductId || $this->isBundleProduct($product) || $this->isGroupedProduct($product)) { + $productSyncData = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); + if ($productId != $itemProductId + || $this->isBundleProduct($product) + || $this->isGroupedProduct($product) + ) { if ($productId) { - $this->_updateSyncData($productId, $mailchimpStoreId, $this->getCurrentDate(), "This product type is not supported on MailChimp.", 0, null, 0); + $this->_updateSyncData( + $productId, + $mailchimpStoreId, + $dateHelper->formatDate(null, 'Y-m-d H:i:s'), + "This product type is not supported on MailChimp.", + 0, + null, + 0 + ); } + continue; } @@ -349,14 +584,31 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) $isProductEnabled = $this->isProductEnabled($productId, $magentoStoreId); if ($syncModified && $syncDelta > $syncDateFlag && $isProductEnabled) { - $data = array_merge($this->_buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId), $data); - $this->_updateSyncData($productId, $mailchimpStoreId); - } elseif (!$syncDelta || $syncDelta < $syncDateFlag || !$isProductEnabled) { - $data[] = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); - // avoid update for disabled products to prevent send the product as modified - if ($isProductEnabled) { + $buildUpdateOperations = $this->_buildUpdateProductRequest( + $product, + $batchId, + $mailchimpStoreId, + $magentoStoreId + ); + + if ($buildUpdateOperations !== false) { + // json correctly encoded + $data = array_merge( + $buildUpdateOperations, + $data + ); $this->_updateSyncData($productId, $mailchimpStoreId); } + } elseif (!$syncDelta || $syncDelta < $syncDateFlag || !$isProductEnabled) { + $bodyData = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + + if ($bodyData !== false) { + $data[] = $bodyData; + // avoid update for disabled products to prevent send the product as modified + if ($isProductEnabled) { + $this->_updateSyncData($productId, $mailchimpStoreId); + } + } } } @@ -368,16 +620,25 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) * * @param $productId * @param $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncDeleted - * @param int|null $syncedFlag - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval + * @param int|null $syncDelta + * @param int|null $syncError + * @param int|null $syncModified + * @param int|null $syncDeleted + * @param int|null $syncedFlag + * @param bool $saveOnlyIfexists + * @param bool $allowBatchRemoval */ - protected function _updateSyncData($productId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncDeleted = null, $syncedFlag = null, $saveOnlyIfexists = false, $allowBatchRemoval = true) - { + protected function _updateSyncData( + $productId, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncDeleted = null, + $syncedFlag = null, + $saveOnlyIfexists = false, + $allowBatchRemoval = true + ) { $this->getMailChimpHelper()->saveEcommerceSyncData( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, @@ -401,7 +662,7 @@ protected function _updateSyncData($productId, $mailchimpStoreId, $syncDelta = n public function makeBatchId($magentoStoreId) { $batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT; - $batchId .= '_' . Mage::helper('mailchimp')->getDateMicrotime(); + $batchId .= '_' . $this->getMailChimpDateHelper()->getDateMicrotime(); return $batchId; } @@ -419,8 +680,13 @@ public function makeProductsNotSentCollection($magentoStoreId, $isParentProduct if (!$isParentProduct) { $collection->addFinalPrice(); } + $collection->addStoreFilter($magentoStoreId); - $this->mailchimpHelper->addResendFilter($collection, $magentoStoreId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT); + $this->_mailchimpHelper->addResendFilter( + $collection, + $magentoStoreId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT + ); $this->joinQtyAndBackorders($collection); @@ -436,7 +702,7 @@ public function makeProductsNotSentCollection($magentoStoreId, $isParentProduct */ protected function getBatchLimitFromConfig() { - $helper = $this->mailchimpHelper; + $helper = $this->_mailchimpHelper; return $helper->getProductAmountLimit(); } @@ -445,7 +711,8 @@ protected function getBatchLimitFromConfig() */ public function getSyncDataTableName() { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $mailchimpTableName = Mage::getSingleton('core/resource') + ->getTableName('mailchimp/ecommercesyncdata'); return $mailchimpTableName; } @@ -459,9 +726,10 @@ public function getSyncDataTableName() */ protected function shouldSendProductUpdate($mailchimpStoreId, $magentoStoreId, $product) { - $helper = $this->getMailChimpHelper(); - $resendTurn = $helper->getResendTurn($magentoStoreId); - return !$resendTurn && $product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId) && $product->getMailchimpSyncError() == ''; + return $product->getMailchimpSyncModified() + && $product->getMailchimpSyncDelta() + && $product->getMailchimpSyncedFlag() + && $product->getMailchimpSyncError() == ''; } /** @@ -542,9 +810,6 @@ public function joinQtyAndBackorders($collection) ); } - - - /** * @param $product * @param $magentoStoreId @@ -596,7 +861,7 @@ protected function getConfigurableChildrenIds($product) /** * @param $product * @param $magentoStoreId - * @param bool $isBuildUpdateProductRequest + * @param bool $isBuildUpdateProductRequest * @return array | return an array with the childs of the product passed by parameter */ public function makeProductChildrenArray($product, $magentoStoreId, $isBuildUpdateProductRequest = false) @@ -629,7 +894,7 @@ public function makeProductChildrenArray($product, $magentoStoreId, $isBuildUpda */ protected function getChildrenIdsForConfigurable($product) { - return $this->productTypeConfigurable->getChildrenIds($product->getId()); + return $this->_productTypeConfigurable->getChildrenIds($product->getId()); } /** @@ -637,12 +902,21 @@ protected function getChildrenIdsForConfigurable($product) */ protected function getMailChimpHelper() { - return $this->mailchimpHelper; + return $this->_mailchimpHelper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getMailChimpDateHelper() + { + return $this->_mailchimpDateHelper; } /** - * This function will perform the join of the collection with the table mailchimp_ecommerce_sync_data when the program - * creates the batch json to send the product data to mailchimp + * This function will perform the join of the collection with the table + * mailchimp_ecommerce_sync_data when the programcreates the batch json + * to send the product data to mailchimp * * @param $collection * @param $mailchimpStoreId @@ -652,6 +926,7 @@ public function joinMailchimpSyncData($collection, $mailchimpStoreId) $joinCondition = $this->buildMailchimpDataJoin(); $this->executeMailchimpDataJoin($collection, $mailchimpStoreId, $joinCondition); $this->buildMailchimpDataWhere($collection); + } /** @@ -682,7 +957,7 @@ public function joinMailchimpSyncDataForSpecialPrices($collection, $mailchimpSto */ protected function builMailchimpDataJoinForSpecialPrices() { - $joinCondition = $this->buildMailchimpDataJoin(). " AND m4m.mailchimp_sync_modified = 0"; + $joinCondition = $this->buildMailchimpDataJoin() . " AND m4m.mailchimp_sync_modified = 0"; return $joinCondition; } @@ -702,7 +977,8 @@ protected function executeMailchimpDataJoin($collection, $mailchimpStoreId, $joi "m4m.type", "m4m.mailchimp_store_id", "m4m.mailchimp_sync_delta", - "m4m.mailchimp_sync_modified" + "m4m.mailchimp_sync_modified", + "m4m.mailchimp_synced_flag" ) ); } @@ -730,6 +1006,7 @@ public function getNotVisibleProductUrl($childId, $magentoStoreId) } else { $parentId = $this->_parentId; } + if ($parentId) { $collection = $this->getProductWithAttributesById($magentoStoreId, $parentId); @@ -740,28 +1017,43 @@ public function getNotVisibleProductUrl($childId, $magentoStoreId) $path = $rc->getAttributeRawValue($parentId, 'url_path', $magentoStoreId); $url = $this->getUrlByPath($path, $magentoStoreId); } + $tailUrl = '#'; $count = 0; foreach ($collection as $attribute) { if ($attribute->getAttributeId()) { $attributeId = $attribute->getAttributeId(); - $attributeValue = $rc->getAttributeRawValue($childId, $attribute->getAttributeId(), $magentoStoreId); + $attributeValue = $rc->getAttributeRawValue( + $childId, + $attribute->getAttributeId(), + $magentoStoreId + ); if ($count > 0) { $tailUrl .= '&'; } + $tailUrl .= $attributeId . '=' . $attributeValue; } + $count++; } + if ($tailUrl != '#') { $url .= $tailUrl; } } else { $url = null; } + return $url; } + /** + * @param $childId + * @param $magentoStoreId + * @return string|null + * @throws Mage_Core_Model_Store_Exception + */ public function getParentImageUrl($childId, $magentoStoreId) { $imageUrl = null; @@ -771,10 +1063,12 @@ public function getParentImageUrl($childId, $magentoStoreId) } else { $parentId = $this->_parentId; } + if ($parentId) { $helper = $this->getMailChimpHelper(); $imageUrl = $helper->getImageUrlById($parentId, $magentoStoreId); } + return $imageUrl; } @@ -787,13 +1081,17 @@ protected function getProductUrl($product) return $product->getProductUrl(); } + /** + * @param $product + * @param $magentoStoreId + * @return string|null + */ public function getProductCategories($product, $magentoStoreId) { $categoryIds = $product->getResource()->getCategoryIds($product); $categoryNames = array(); $categoryName = null; - if (is_array($categoryIds) && count($categoryIds)) { - /* @var $collection Mage_Catalog_Model_Resource_Category_Collection */ + if (is_array($categoryIds) && !empty($categoryIds)) { $collection = $this->makeCatalogCategory()->getCollection(); $collection->addAttributeToSelect(array('name')) ->setStoreId($magentoStoreId) @@ -802,12 +1100,13 @@ public function getProductCategories($product, $magentoStoreId) ->addAttributeToSort('level', 'asc') ->addAttributeToSort('name', 'asc'); - /* @var $category Mage_Catalog_Model_Category */ foreach ($collection as $category) { $categoryNames[] = $category->getName(); } + $categoryName = (count($categoryNames)) ? implode(" - ", $categoryNames) : 'None'; } + return $categoryName; } @@ -819,9 +1118,10 @@ protected function getParentId($childId) { $parentId = null; $parentIds = $this->getAllParentIds($childId); - if (count($parentIds)) { + if (!empty($parentIds)) { $parentId = $parentIds[0]; } + return $parentId; } @@ -831,7 +1131,8 @@ protected function getParentId($childId) */ protected function getAllParentIds($childId) { - $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($childId); + $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable') + ->getParentIdsByChild($childId); return $parentIds; } @@ -869,10 +1170,18 @@ protected function getProductWithAttributesById($magentoStoreId, $parentId) */ protected function getMailChimpImageUrl($product, $magentoStoreId) { - $imageUrl = $this->getMailChimpHelper()->getMailChimpProductImageUrl($this->_parentImageUrl, $this->getMailChimpHelper()->getImageUrlById($product->getId(), $magentoStoreId)); + $imageUrl = $this->getMailChimpHelper() + ->getMailChimpProductImageUrl( + $this->_parentImageUrl, + $this->getMailChimpHelper()->getImageUrlById( + $product->getId(), + $magentoStoreId + ) + ); if (!$imageUrl) { $imageUrl = $this->getParentImageUrl($product->getId(), $magentoStoreId); } + return $imageUrl; } @@ -895,6 +1204,7 @@ protected function getMailChimpProductPrice($product, $magentoStoreId) $price = $this->_parentPrice; } } + return $price; } @@ -906,11 +1216,16 @@ protected function currentProductIsVisible() return $this->_visibility != Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE; } + /** + * @param $product + * @return float + * @throws Mage_Core_Exception + */ protected function getProductPrice($product, $magentoStoreId) { $helper = $this->getMailChimpHelper(); $rc = $helper->getProductResourceModel(); - $price = $this->getMailchimpFinalPrice($product); + $price = $this->getMailchimpFinalPrice($product, $magentoStoreId); return $price; } @@ -933,14 +1248,6 @@ protected function isProductFlatTableEnabled() return Mage::helper('catalog/category_flat')->isEnabled(); } - /** - * @return string - */ - protected function getCurrentDate() - { - return Varien_Date::now(); - } - /** * @return false|Mage_Core_Model_Abstract */ @@ -968,8 +1275,8 @@ protected function joinMailchimpSyncDataDeleted($mailchimpStoreId, $deletedProdu $mailchimpTableName = $this->getSyncDataTableName(); $deletedProducts->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), - "m4m.related_id = e.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + "m4m.related_id = e.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT + . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", array('m4m.*') ); $deletedProducts->getSelect()->where("m4m.mailchimp_sync_deleted = 1"); @@ -984,8 +1291,8 @@ protected function joinMailchimpSyncDataDeleted($mailchimpStoreId, $deletedProdu */ protected function getVisibility($visibility) { - if (array_key_exists($visibility, $this->visibilityOptions)) { - return $this->visibilityOptions[$visibility]; + if (array_key_exists($visibility, $this->_visibilityOptions)) { + return $this->_visibilityOptions[$visibility]; } return null; @@ -994,14 +1301,20 @@ protected function getVisibility($visibility) /** * Return price with tax if setting enabled. * - * @param $product + * @param $product + * @param $magentoStoreId * @return float \ return the price of the product * @throws Mage_Core_Exception */ - protected function getMailchimpFinalPrice($product) + protected function getMailchimpFinalPrice($product, $magentoStoreId) { $helper = $this->getMailChimpHelper(); - $price = Mage::helper('tax')->getPrice($product, $product->getFinalPrice(), $helper->isIncludeTaxesEnabled()); + $price = Mage::helper('tax') + ->getPrice( + $product, + $product->getFinalPrice(), + $helper->isIncludeTaxesEnabled($magentoStoreId) + ); return $price; } @@ -1039,7 +1352,7 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) 'left' )->addAttributeToFilter( 'special_from_date', - array('lteq' => date('Y-m-d', time())." 23:59:59"), + array('lteq' => $this->getMailChimpDateHelper()->formatDate() . " 23:59:59"), 'left' )->addAttributeToFilter( 'special_from_date', @@ -1047,7 +1360,11 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) 'left' ); - $whereCondition = $connection->quoteInto('m4m.mailchimp_sync_delta IS NOT NULL AND m4m.mailchimp_sync_delta < ?', date('Y-m-d', time())." 00:00:00"); + $whereCondition = $connection->quoteInto( + 'm4m.mailchimp_sync_delta IS NOT NULL ' + . 'AND m4m.mailchimp_sync_delta < ?', + $this->getMailChimpDateHelper()->formatDate() . " 00:00:00" + ); $collection->getSelect()->where($whereCondition); foreach ($collection as $item) { @@ -1057,17 +1374,17 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) /** * get the products that was synced when it have special price and have no more special price */ - $collection2 = $this->getProductResourceCollection(); - $collection2->addStoreFilter($magentoStoreId); - $this->joinMailchimpSyncDataForSpecialPrices($collection2, $mailchimpStoreId); + $collectionNoSpecialPrice = $this->getProductResourceCollection(); + $collectionNoSpecialPrice->addStoreFilter($magentoStoreId); + $this->joinMailchimpSyncDataForSpecialPrices($collectionNoSpecialPrice, $mailchimpStoreId); - $collection2->addAttributeToFilter( + $collectionNoSpecialPrice->addAttributeToFilter( 'special_price', array('gt' => 0), 'left' )->addAttributeToFilter( 'special_to_date', - array('lt' => date('Y-m-d', time())." 00:00:00"), + array('lt' => $this->getMailChimpDateHelper()->formatDate() . " 00:00:00"), 'left' )->addAttributeToFilter( 'special_to_date', @@ -1075,8 +1392,8 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) 'left' ); - $collection2->getSelect()->where($whereCondition); - foreach ($collection2 as $item) { + $collectionNoSpecialPrice->getSelect()->where($whereCondition); + foreach ($collectionNoSpecialPrice as $item) { $this->update($item->getEntityId(), $mailchimpStoreId); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php index 08059c6da..9d8aec2a3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php @@ -19,27 +19,41 @@ class Ebizmarts_MailChimp_Model_Api_PromoCodes const TARGET_SHIPPING = 'shipping'; protected $_batchId; - protected $mailchimpHelper; + protected $_mailchimpHelper; + protected $_mailchimpDateHelper; /** * @var Ebizmarts_MailChimp_Model_Api_PromoRules */ - protected $apiPromoRules; + protected $_apiPromoRules; public function __construct() { - $this->mailchimpHelper = Mage::helper('mailchimp'); + $this->_mailchimpHelper = Mage::helper('mailchimp'); + $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { $batchArray = array(); - $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE . '_' . Mage::helper('mailchimp')->getDateMicrotime(); + $this->_batchId = 'storeid-' + . $magentoStoreId . '_' + . Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE . '_' + . Mage::helper('mailchimp/date')->getDateMicrotime(); $batchArray = array_merge($batchArray, $this->_getDeletedPromoCodes($mailchimpStoreId)); $batchArray = array_merge($batchArray, $this->_getNewPromoCodes($mailchimpStoreId, $magentoStoreId)); return $batchArray; } + /** + * @param $mailchimpStoreId + * @return array + */ protected function _getDeletedPromoCodes($mailchimpStoreId) { $batchArray = array(); @@ -50,7 +64,9 @@ protected function _getDeletedPromoCodes($mailchimpStoreId) $promoCodeId = $promoCode->getRelatedId(); $promoRuleId = $promoCode->getDeletedRelatedId(); $batchArray[$counter]['method'] = "DELETE"; - $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/promo-rules/' . $promoRuleId . '/promo-codes/' . $promoCodeId; + $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId + . '/promo-rules/' . $promoRuleId + . '/promo-codes/' . $promoCodeId; $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $promoCodeId; $batchArray[$counter]['body'] = ''; $this->deletePromoCodeSyncData($promoCodeId, $mailchimpStoreId); @@ -60,10 +76,16 @@ protected function _getDeletedPromoCodes($mailchimpStoreId) return $batchArray; } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ protected function _getNewPromoCodes($mailchimpStoreId, $magentoStoreId) { $batchArray = array(); $helper = $this->getMailChimpHelper(); + $dateHelper = $this->getMailChimpDateHelper(); $newPromoCodes = $this->makePromoCodesCollection($magentoStoreId); $this->joinMailchimpSyncDataWithoutWhere($newPromoCodes, $mailchimpStoreId); @@ -71,7 +93,10 @@ protected function _getNewPromoCodes($mailchimpStoreId, $magentoStoreId) $websiteId = Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId(); $autoGeneratedCondition = "salesrule.use_auto_generation = 1 AND main_table.is_primary IS NULL"; $notAutoGeneratedCondition = "salesrule.use_auto_generation = 0 AND main_table.is_primary = 1"; - $newPromoCodes->getSelect()->where("m4m.mailchimp_sync_delta IS NULL AND website.website_id = " . $websiteId . " AND ( " . $autoGeneratedCondition . " OR " . $notAutoGeneratedCondition . ")"); + $newPromoCodes->getSelect()->where( + "m4m.mailchimp_sync_delta IS NULL AND website.website_id = " . $websiteId + . " AND ( " . $autoGeneratedCondition . " OR " . $notAutoGeneratedCondition . ")" + ); // send most recently created first $newPromoCodes->getSelect()->order(array('salesrule.rule_id DESC')); // limit the collection @@ -81,9 +106,21 @@ protected function _getNewPromoCodes($mailchimpStoreId, $magentoStoreId) $codeId = $promoCode->getCouponId(); $ruleId = $promoCode->getRuleId(); try { - $promoRuleSyncData = $this->getMailChimpHelper()->getEcommerceSyncDataItem($ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, $mailchimpStoreId); - if (!$promoRuleSyncData->getId() || $promoRuleSyncData->getMailchimpSyncDelta() < $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId)) { - $promoRuleMailchimpData = $this->getApiPromoRules()->getNewPromoRule($ruleId, $this->_batchId, $mailchimpStoreId, $magentoStoreId); + $promoRuleSyncData = $this->getMailChimpHelper()->getEcommerceSyncDataItem( + $ruleId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, + $mailchimpStoreId + ); + if (!$promoRuleSyncData->getId() + || $promoRuleSyncData->getMailchimpSyncDelta() < $helper->getEcommMinSyncDateFlag( + $mailchimpStoreId, $magentoStoreId + ) + ) { + $promoRuleMailchimpData = $this->getApiPromoRules()->getNewPromoRule( + $ruleId, + $mailchimpStoreId, + $magentoStoreId + ); if (!empty($promoRuleMailchimpData)) { $batchArray[$counter] = $promoRuleMailchimpData; $counter++; @@ -100,18 +137,50 @@ protected function _getNewPromoCodes($mailchimpStoreId, $magentoStoreId) $promoCodeData = $this->generateCodeData($promoCode, $magentoStoreId); $promoCodeJson = json_encode($promoCodeData); - if (!empty($promoCodeData)) { - $batchArray[$counter]['method'] = "POST"; - $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/promo-rules/' . $ruleId . '/promo-codes'; - $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $codeId; - $batchArray[$counter]['body'] = $promoCodeJson; - - $this->_updateSyncData($codeId, $mailchimpStoreId, null, null, 0, null, $promoCode->getToken()); - $counter++; + + if ($promoCodeJson !== false) { + if (!empty($promoCodeData)) { + $batchArray[$counter]['method'] = "POST"; + $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId + . '/promo-rules/' . $ruleId . '/promo-codes'; + $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $codeId; + $batchArray[$counter]['body'] = $promoCodeJson; + + $this->_updateSyncData( + $codeId, + $mailchimpStoreId, + null, + null, + 0, + null, + $promoCode->getToken() + ); + $counter++; + } else { + $error = $helper->__('Something went wrong when retrieving the information.'); + $this->_updateSyncData( + $codeId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error + ); + continue; + } } else { - $error = $helper->__('Something went wrong when retrieving the information.'); - $this->_updateSyncData($codeId, $mailchimpStoreId, Varien_Date::now(), $error); - continue; + $jsonErrorMsg = json_last_error_msg(); + $helper->logError("Promo code" . $codeId . " json encode failed (".$jsonErrorMsg.")"); + $this->_updateSyncData( + $codeId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $jsonErrorMsg, + 0, + null, + null, + false, + null, + -1 + ); } } catch (Exception $e) { $helper->logError($e->getMessage()); @@ -149,16 +218,28 @@ public function makePromoCodesCollection($magentoStoreId) * @var Mage_SalesRule_Model_Resource_Coupon_Collection $collection */ $collection = $this->getPromoCodeResourceCollection(); - $helper->addResendFilter($collection, $magentoStoreId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE); + $helper->addResendFilter( + $collection, + $magentoStoreId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE + ); $this->addWebsiteColumn($collection); $this->joinPromoRuleData($collection); return $collection; } + /** + * @param $mailchimpStoreId + * @return object + */ protected function makeDeletedPromoCodesCollection($mailchimpStoreId) { $deletedPromoCodes = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection(); - $deletedPromoCodes->getSelect()->where("mailchimp_store_id = '" . $mailchimpStoreId . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE . "' AND mailchimp_sync_deleted = 1"); + $deletedPromoCodes->getSelect()->where( + "mailchimp_store_id = '" . $mailchimpStoreId + . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE + . "' AND mailchimp_sync_deleted = 1" + ); $deletedPromoCodes->getSelect()->limit($this->getBatchLimitFromConfig()); return $deletedPromoCodes; } @@ -179,7 +260,7 @@ public function getSyncDataTableName() */ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId) { - $joinCondition = "m4m.related_id = main_table.coupon_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + $joinCondition = "m4m.related_id = main_table.coupon_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; $mailchimpTableName = $this->getSyncDataTableName(); $collection->getSelect()->joinLeft( array("m4m" => $mailchimpTableName), @@ -199,17 +280,27 @@ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId * * @param $codeId * @param $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncDeleted - * @param int|null $token - * @param bool $saveOnlyIfexists - * @param null $deletedRelatedId - * @param bool $allowBatchRemoval + * @param int|null $syncDelta + * @param int|null $syncError + * @param int|null $syncModified + * @param int|null $syncDeleted + * @param int|null $token + * @param bool $saveOnlyIfexists + * @param null $deletedRelatedId + * @param bool $allowBatchRemoval */ - protected function _updateSyncData($codeId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncDeleted = null, $token = null, $saveOnlyIfexists = false, $deletedRelatedId = null, $allowBatchRemoval = true) - { + protected function _updateSyncData( + $codeId, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncDeleted = null, + $token = null, + $saveOnlyIfexists = false, + $deletedRelatedId = null, + $allowBatchRemoval = true + ) { $this->getMailChimpHelper()->saveEcommerceSyncData( $codeId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, @@ -244,7 +335,15 @@ protected function generateCodeData($promoCode, $magentoStoreId) */ protected function getMailChimpHelper() { - return $this->mailchimpHelper; + return $this->_mailchimpHelper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getMailChimpDateHelper() + { + return $this->_mailchimpDateHelper; } protected function addWebsiteColumn($collection) @@ -275,10 +374,25 @@ protected function getRedemptionUrl($promoCode, $magentoStoreId) { $token = $this->getToken(); $promoCode->setToken($token); - $url = Mage::getModel('core/url')->setStore($magentoStoreId)->getUrl('mailchimp/cart/loadcoupon', array('_nosid' => true, '_secure' => true, 'coupon_id' =>$promoCode->getCouponId(), 'coupon_token' => $token)) . 'mailchimp/cart/loadcoupon?coupon_id=' . $promoCode->getCouponId() . '&coupon_token=' . $token; + $url = Mage::getModel('core/url')->setStore($magentoStoreId)->getUrl( + 'mailchimp/cart/loadcoupon', + array( + '_nosid' => true, + '_secure' => true, + 'coupon_id' =>$promoCode->getCouponId(), + 'coupon_token' => $token + ) + ) + . 'mailchimp/cart/loadcoupon?coupon_id=' + . $promoCode->getCouponId() + . '&coupon_token=' + . $token; return $url; } + /** + * @return string + */ protected function getToken() { $token = md5(rand(0, 9999999)); @@ -290,24 +404,47 @@ protected function getToken() */ public function getApiPromoRules() { - if (!$this->apiPromoRules) { - $this->apiPromoRules = Mage::getModel('mailchimp/api_promoRules'); + if (!$this->_apiPromoRules) { + $this->_apiPromoRules = Mage::getModel('mailchimp/api_promoRules'); } - return $this->apiPromoRules; + + return $this->_apiPromoRules; } + /** + * @param $codeId + * @param $promoRuleId + */ public function markAsDeleted($codeId, $promoRuleId) { $this->_setDeleted($codeId, $promoRuleId); } + /** + * @param $codeId + * @param $promoRuleId + */ protected function _setDeleted($codeId, $promoRuleId) { $helper = $this->getMailChimpHelper(); - $promoCodes = $helper->getAllEcommerceSyncDataItemsPerId($codeId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE); + $promoCodes = $helper->getAllEcommerceSyncDataItemsPerId( + $codeId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE + ); foreach ($promoCodes as $promoCode) { $mailchimpStoreId = $promoCode->getMailchimpStoreId(); - $this->_updateSyncData($codeId, $mailchimpStoreId, null, null, 0, 1, null, true, $promoRuleId, false); + $this->_updateSyncData( + $codeId, + $mailchimpStoreId, + null, + null, + 0, + 1, + null, + true, + $promoRuleId, + false + ); } } @@ -317,15 +454,52 @@ protected function _setDeleted($codeId, $promoRuleId) */ public function deletePromoCodesSyncDataByRule($promoRule) { - $promoRuleId = $promoRule->getRelatedId(); + $promoCodeIds = $this->getPromoCodesForRule($promoRule->getRelatedId()); + foreach ($promoCodeIds as $promoCodeId) { + $promoCodeSyncDataItems = $this->getMailChimpHelper()->getAllEcommerceSyncDataItemsPerId( + $promoCodeId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE + ); + foreach ($promoCodeSyncDataItems as $promoCodeSyncDataItem) { + $promoCodeSyncDataItem->delete(); + } + } + } + + /** + * @param $promoCodeId + * @param $mailchimpStoreId + */ + public function deletePromoCodeSyncData($promoCodeId, $mailchimpStoreId) + { + $promoCodeSyncDataItem = $this->getMailChimpHelper()->getEcommerceSyncDataItem( + $promoCodeId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, + $mailchimpStoreId + ); + $promoCodeSyncDataItem->delete(); + } + + /** + * @param $promoRuleId + * @return array + */ + protected function getPromoCodesForRule($promoRuleId) + { + $promoCodes = array(); $helper = $this->getMailChimpHelper(); - $promoRules = $helper->getAllEcommerceSyncDataItemsPerId($promoRuleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE); + $promoRules = $helper->getAllEcommerceSyncDataItemsPerId( + $promoRuleId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE + ); foreach ($promoRules as $promoRule) { $mailchimpStoreId = $promoRule->getMailchimpStoreId(); $api = $helper->getApiByMailChimpStoreId($mailchimpStoreId); if ($api !== null) { try { - $mailChimpPromoCodes = $api->ecommerce->promoRules->promoCodes->getAll($mailchimpStoreId, $promoRuleId); + $mailChimpPromoCodes = $api->ecommerce->promoRules->promoCodes + ->getAll($mailchimpStoreId, $promoRuleId); + foreach ($mailChimpPromoCodes['promo_codes'] as $promoCode) { $this->deletePromoCodeSyncData($promoCode['id'], $mailchimpStoreId); } @@ -335,14 +509,13 @@ public function deletePromoCodesSyncDataByRule($promoRule) } } + return $promoCodes; } - public function deletePromoCodeSyncData($promoCodeId, $mailchimpStoreId) - { - $promoCodeSyncDataItem = $this->getMailChimpHelper()->getEcommerceSyncDataItem($promoCodeId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, $mailchimpStoreId); - $promoCodeSyncDataItem->delete(); - } - + /** + * @param $promoCodeId + * @return string + */ protected function getPromoRuleIdByCouponId($promoCodeId) { $coupon = Mage::getModel('salesrule/coupon')->load($promoCodeId); @@ -356,8 +529,16 @@ protected function getPromoRuleIdByCouponId($promoCodeId) */ protected function setCodeWithParentError($mailchimpStoreId, $ruleId, $codeId) { - $error = Mage::helper('mailchimp')->__('Parent rule with id ' . $ruleId . ' has not been correctly sent.'); - $this->_updateSyncData($codeId, $mailchimpStoreId, Varien_Date::now(), $error); + $dateHelper = $this->getMailChimpDateHelper(); + $error = Mage::helper('mailchimp')->__( + 'Parent rule with id ' . $ruleId . ' has not been correctly sent.' + ); + $this->_updateSyncData( + $codeId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error + ); } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php index f302c34dd..3ff05e956 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php @@ -22,27 +22,44 @@ class Ebizmarts_MailChimp_Model_Api_PromoRules /** * @var Ebizmarts_MailChimp_Helper_Data */ - protected $mailchimpHelper; + protected $_mailchimpHelper; + /** + * @var Ebizmarts_MailChimp_Helper_Date + */ + protected $_mailchimpDateHelper; /** * @var Ebizmarts_MailChimp_Model_Api_PromoCodes */ - protected $promoCodes; + protected $_promoCodes; public function __construct() { - $this->mailchimpHelper = Mage::helper('mailchimp'); - $this->promoCodes = Mage::getModel('mailchimp/api_promoCodes'); + $this->_mailchimpHelper = Mage::helper('mailchimp'); + $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); + $this->_promoCodes = Mage::getModel('mailchimp/api_promoCodes'); } + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { $batchArray = array(); - $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE . '_' . $this->getMailChimpHelper()->getDateMicrotime(); + $this->_batchId = 'storeid-' + . $magentoStoreId . '_' + . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE . '_' + . $this->getMailChimpDateHelper()->getDateMicrotime(); $batchArray = array_merge($batchArray, $this->_getModifiedAndDeletedPromoRules($mailchimpStoreId)); return $batchArray; } + /** + * @param $mailchimpStoreId + * @return array + */ protected function _getModifiedAndDeletedPromoRules($mailchimpStoreId) { $batchArray = array(); @@ -63,27 +80,60 @@ protected function _getModifiedAndDeletedPromoRules($mailchimpStoreId) return $batchArray; } - public function getNewPromoRule($ruleId, $batchId, $mailchimpStoreId, $magentoStoreId) + /** + * @param $ruleId + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + public function getNewPromoRule($ruleId, $mailchimpStoreId, $magentoStoreId) { $promoData = array(); $promoRule = $this->getPromoRule($ruleId); $helper = $this->getMailChimpHelper(); + $dateHelper = $this->getMailChimpDateHelper(); try { $ruleData = $this->generateRuleData($promoRule); $promoRuleJson = json_encode($ruleData); - if (!empty($ruleData)) { - $promoData['method'] = "POST"; - $promoData['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/promo-rules'; - $promoData['operation_id'] = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE . '_' . $helper->getDateMicrotime() . '_' . $ruleId; - $promoData['body'] = $promoRuleJson; - //update promo rule delta - $this->_updateSyncData($ruleId, $mailchimpStoreId); - } else { - $error = $promoRule->getMailchimpSyncError(); - if (!$error) { - $error = $helper->__('Something went wrong when retrieving the information.'); + + if ($promoRuleJson !== false) { + if (!empty($ruleData)) { + $promoData['method'] = "POST"; + $promoData['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/promo-rules'; + $promoData['operation_id'] = 'storeid-' + . $magentoStoreId . '_' + . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE . '_' + . $dateHelper->getDateMicrotime() . '_' . $ruleId; + $promoData['body'] = $promoRuleJson; + //update promo rule delta + $this->_updateSyncData($ruleId, $mailchimpStoreId); + } else { + $error = $promoRule->getMailchimpSyncError(); + if (!$error) { + $error = $helper->__('Something went wrong when retrieving the information.'); + } + + $this->_updateSyncData( + $ruleId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $error + ); } - $this->_updateSyncData($ruleId, $mailchimpStoreId, Varien_Date::now(), $error); + } else { + $jsonErrorMsg = json_last_error_msg(); + $helper->logError("Promo rule " . $ruleId . " json encode failed (".$jsonErrorMsg.")"); + + $this->_updateSyncData( + $ruleId, + $mailchimpStoreId, + $dateHelper->formatDate(null, "Y-m-d H:i:s"), + $jsonErrorMsg, + 0, + null, + false, + -1 + ); } } catch (Exception $e) { $helper->logError($e->getMessage()); @@ -101,6 +151,10 @@ protected function getBatchLimitFromConfig() return $batchLimit; } + /** + * @param $ruleId + * @return Mage_Core_Model_Abstract + */ protected function getPromoRule($ruleId) { return Mage::getModel('salesrule/rule')->load($ruleId); @@ -136,7 +190,11 @@ public function makePromoRulesCollection($magentoStoreId) protected function makeModifiedAndDeletedPromoRulesCollection($mailchimpStoreId) { $deletedPromoRules = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection(); - $deletedPromoRules->getSelect()->where("mailchimp_store_id = '" . $mailchimpStoreId . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE . "' AND (mailchimp_sync_modified = 1 OR mailchimp_sync_deleted = 1)"); + $deletedPromoRules->getSelect()->where( + "mailchimp_store_id = '" . $mailchimpStoreId + . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE + . "' AND (mailchimp_sync_modified = 1 OR mailchimp_sync_deleted = 1)" + ); $deletedPromoRules->getSelect()->limit($this->getBatchLimitFromConfig()); return $deletedPromoRules; } @@ -157,7 +215,7 @@ public function getSyncDataTableName() */ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId) { - $joinCondition = "m4m.related_id = main_table.rule_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + $joinCondition = "m4m.related_id = main_table.rule_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; $mailchimpTableName = $this->getSyncDataTableName(); $collection->getSelect()->joinLeft( array("m4m" => $mailchimpTableName), @@ -175,17 +233,25 @@ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId /** * update promo rule sync data * - * @param int $ruleId - * @param string $mailchimpStoreId + * @param int $ruleId + * @param string $mailchimpStoreId * @param int|null $syncDelta * @param int|null $syncError * @param int|null $syncModified * @param int|null $syncDeleted - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval + * @param bool $saveOnlyIfexists + * @param bool $allowBatchRemoval */ - protected function _updateSyncData($ruleId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncDeleted = null, $saveOnlyIfexists = false, $allowBatchRemoval = true) - { + protected function _updateSyncData( + $ruleId, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncDeleted = null, + $saveOnlyIfexists = false, + $allowBatchRemoval = true + ) { $this->getMailChimpHelper()->saveEcommerceSyncData( $ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, @@ -202,12 +268,24 @@ protected function _updateSyncData($ruleId, $mailchimpStoreId, $syncDelta = null ); } + /** + * @param $ruleId + * @param $mailchimpStoreId + */ protected function deletePromoRuleSyncData($ruleId, $mailchimpStoreId) { - $ruleSyncDataItem = $this->getMailChimpHelper()->getEcommerceSyncDataItem($ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, $mailchimpStoreId); + $ruleSyncDataItem = $this->getMailChimpHelper()->getEcommerceSyncDataItem( + $ruleId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, + $mailchimpStoreId + ); $ruleSyncDataItem->delete(); } + /** + * @param $promoRule + * @return array + */ protected function generateRuleData($promoRule) { $error = null; @@ -256,69 +334,127 @@ protected function generateRuleData($promoRule) */ protected function getMailChimpHelper() { - return $this->mailchimpHelper; + return $this->_mailchimpHelper; } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getMailChimpDateHelper() + { + return $this->_mailchimpDateHelper; + } + + /** + * @param $promoAction + * @return string|null + */ protected function getMailChimpType($promoAction) { $mailChimpType = null; switch ($promoAction) { - case Mage_SalesRule_Model_Rule::BY_PERCENT_ACTION: - $mailChimpType = self::TYPE_PERCENTAGE; - break; - case Mage_SalesRule_Model_Rule::BY_FIXED_ACTION: - case Mage_SalesRule_Model_Rule::CART_FIXED_ACTION: - $mailChimpType = self::TYPE_FIXED; - break; + case Mage_SalesRule_Model_Rule::BY_PERCENT_ACTION: + $mailChimpType = self::TYPE_PERCENTAGE; + break; + case Mage_SalesRule_Model_Rule::BY_FIXED_ACTION: + case Mage_SalesRule_Model_Rule::CART_FIXED_ACTION: + $mailChimpType = self::TYPE_FIXED; + break; } + return $mailChimpType; } + /** + * @param $promoAction + * @return string|null + */ protected function getMailChimpTarget($promoAction) { $mailChimpTarget = null; switch ($promoAction) { - case Mage_SalesRule_Model_Rule::CART_FIXED_ACTION: - case Mage_SalesRule_Model_Rule::BY_PERCENT_ACTION: - $mailChimpTarget = self::TARGET_TOTAL; - break; - case Mage_SalesRule_Model_Rule::BY_FIXED_ACTION: - $mailChimpTarget = self::TARGET_PER_ITEM; - break; + case Mage_SalesRule_Model_Rule::CART_FIXED_ACTION: + case Mage_SalesRule_Model_Rule::BY_PERCENT_ACTION: + $mailChimpTarget = self::TARGET_TOTAL; + break; + case Mage_SalesRule_Model_Rule::BY_FIXED_ACTION: + $mailChimpTarget = self::TARGET_PER_ITEM; + break; } + return $mailChimpTarget; } + /** + * @param $ruleId + */ public function update($ruleId) { $this->_setModified($ruleId); } + /** + * @param $ruleId + */ protected function _setModified($ruleId) { $helper = $this->getMailChimpHelper(); - $promoRules = $helper->getAllEcommerceSyncDataItemsPerId($ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE); + $promoRules = $helper->getAllEcommerceSyncDataItemsPerId( + $ruleId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE + ); foreach ($promoRules as $promoRule) { $mailchimpStoreId = $promoRule->getMailchimpStoreId(); - $this->_updateSyncData($ruleId, $mailchimpStoreId, null, null, 1, null, true, false); + $this->_updateSyncData( + $ruleId, + $mailchimpStoreId, + null, + null, + 1, + null, + true, + false + ); } } + /** + * @param $ruleId + */ public function markAsDeleted($ruleId) { $this->_setDeleted($ruleId); } + /** + * @param $ruleId + */ protected function _setDeleted($ruleId) { $helper = $this->getMailChimpHelper(); - $promoRules = $helper->getAllEcommerceSyncDataItemsPerId($ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE); + $promoRules = $helper->getAllEcommerceSyncDataItemsPerId( + $ruleId, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE + ); foreach ($promoRules as $promoRule) { $mailchimpStoreId = $promoRule->getMailchimpStoreId(); - $this->_updateSyncData($ruleId, $mailchimpStoreId, null, null, 0, 1, true, false); + $this->_updateSyncData( + $ruleId, + $mailchimpStoreId, + null, + null, + 0, + 1, + true, + false + ); } } + /** + * @param $promoRule + * @return float|int + */ protected function getMailChimpDiscountAmount($promoRule) { $action = $promoRule->getSimpleAction(); @@ -327,6 +463,7 @@ protected function getMailChimpDiscountAmount($promoRule) } else { $mailChimpDiscount = $promoRule->getDiscountAmount(); } + return $mailChimpDiscount; } @@ -335,7 +472,7 @@ protected function getMailChimpDiscountAmount($promoRule) */ protected function getPromoCodes() { - return $this->promoCodes; + return $this->_promoCodes; } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index d8cc9dada..4b7052a6f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -15,16 +15,16 @@ class Ebizmarts_MailChimp_Model_Api_Stores /** * Create Mailchimp store. * - * @param $apiKey - * @param $listId - * @param $storeName - * @param $currencyCode - * @param $storeDomain - * @param $storeEmail - * @param $primaryLocale - * @param $timeZone - * @param $storePhone - * @param $address + * @param $apiKey + * @param $listId + * @param $storeName + * @param $currencyCode + * @param $storeDomain + * @param $storeEmail + * @param $primaryLocale + * @param $timeZone + * @param $storePhone + * @param $address * @return mixed * @throws Exception */ @@ -41,16 +41,34 @@ public function createMailChimpStore( $address ) { $helper = $this->makeHelper(); - $date = $helper->getDateMicrotime(); + $dateHelper = $this->makeDateHelper(); + $date = $dateHelper->getDateMicrotime(); $mailchimpStoreId = md5($storeName . '_' . $date); try { $api = $helper->getApiByKey($apiKey); $isSyncing = true; $currencySymbol = $helper->getMageApp()->getLocale()->currency($currencyCode)->getSymbol(); - $response = $this->addStore($api, $mailchimpStoreId, $listId, $storeName, $currencyCode, $isSyncing, $storeDomain, $storeEmail, $currencySymbol, $primaryLocale, $timeZone, $storePhone, $address); + $response = $this->addStore( + $api, + $mailchimpStoreId, + $listId, + $storeName, + $currencyCode, + $isSyncing, + $storeDomain, + $storeEmail, + $currencySymbol, + $primaryLocale, + $timeZone, + $storePhone, + $address + ); $configValues = array( - array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", $response['connected_site']['site_script']['url']) + array( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", + $response['connected_site']['site_script']['url'] + ) ); $helper->saveMailchimpConfig($configValues, 0, 'default'); $successMessage = $helper->__("The Mailchimp store was successfully created."); @@ -73,22 +91,23 @@ public function createMailChimpStore( $adminSession = $this->getAdminSession(); $adminSession->addError($errorMessage); } + return $response; } /** * Edit Mailchimp store. * - * @param $mailchimpStoreId - * @param $apiKey - * @param $storeName - * @param $currencyCode - * @param $storeDomain - * @param $storeEmail - * @param $primaryLocale - * @param $timeZone - * @param $storePhone - * @param $address + * @param $mailchimpStoreId + * @param $apiKey + * @param $storeName + * @param $currencyCode + * @param $storeDomain + * @param $storeEmail + * @param $primaryLocale + * @param $timeZone + * @param $storePhone + * @param $address * @return mixed|string * @throws Mage_Core_Exception */ @@ -109,7 +128,20 @@ public function editMailChimpStore( try { $api = $helper->getApiByKey($apiKey); $currencySymbol = $helper->getMageApp()->getLocale()->currency($currencyCode)->getSymbol(); - $response = $api->getEcommerce()->getStores()->edit($mailchimpStoreId, $storeName, 'Magento', $storeDomain, null, $storeEmail, $currencyCode, $currencySymbol, $primaryLocale, $timeZone, $storePhone, $address); + $response = $api->getEcommerce()->getStores()->edit( + $mailchimpStoreId, + $storeName, + 'Magento', + $storeDomain, + null, + $storeEmail, + $currencyCode, + $currencySymbol, + $primaryLocale, + $timeZone, + $storePhone, + $address + ); $successMessage = $helper->__("The Mailchimp store was successfully edited."); $adminSession = $this->getAdminSession(); $adminSession->addSuccess($successMessage); @@ -130,6 +162,7 @@ public function editMailChimpStore( $adminSession = $this->getAdminSession(); $adminSession->addError($errorMessage); } + return $response; } @@ -143,7 +176,15 @@ private function getUserFriendlyMessage($e) $errorMessage = $e->getFriendlyMessage(); if (strstr($errorMessage, 'A store with the domain')) { - $errorMessage = $helper->__('A Mailchimp store with the same domain already exists in this account. You need to have a different URLs for each scope you set up the ecommerce data. Possible solutions ') . "HERE and HERE"; + $errorMessage = $helper->__( + 'A Mailchimp store with the same domain already exists in this account. ' + . 'You need to have a different URLs for each scope you set up the ecommerce data. ' + . 'Possible solutions ' + ) + . "" + . "HERE and " + . "" + . "HERE"; } else { if (is_array($e->getMailchimpErrors())) { $errorDetail = ""; @@ -152,6 +193,7 @@ private function getUserFriendlyMessage($e) if (isset($error['field'])) { $errorDetail .= "
    Field: " . $error['field']; } + if (isset($error['message'])) { $errorDetail .= " Message: " . $error['message']; } @@ -162,14 +204,15 @@ private function getUserFriendlyMessage($e) } } } + return $errorMessage; } /** * Delete MailChimp store. * - * @param $mailchimpStoreId - * @param $apiKey + * @param $mailchimpStoreId + * @param $apiKey * @return mixed|string * @throws Mage_Core_Exception */ @@ -179,6 +222,7 @@ public function deleteMailChimpStore($mailchimpStoreId, $apiKey) try { $api = $helper->getApiByKey($apiKey); $response = $api->getEcommerce()->getStores()->delete($mailchimpStoreId); + $helper->cancelAllPendingBatches($mailchimpStoreId); $successMessage = $helper->__("The Mailchimp store was successfully deleted."); $adminSession = $this->getAdminSession(); $adminSession->addSuccess($successMessage); @@ -216,14 +260,20 @@ protected function deleteLocalMCStoreData($mailchimpStoreId) /** * Set is_syncing value for the given scope. * - * @param $mailchimpApi Ebizmarts_MailChimp - * @param $isSincingValue - * @param $mailchimpStoreId + * @param $mailchimpApi Ebizmarts_MailChimp + * @param $isSincingValue + * @param $mailchimpStoreId * @throws MailChimp_Error */ public function editIsSyncing($mailchimpApi, $isSincingValue, $mailchimpStoreId) { - $mailchimpApi->getEcommerce()->getStores()->edit($mailchimpStoreId, null, null, null, $isSincingValue); + $mailchimpApi->getEcommerce()->getStores()->edit( + $mailchimpStoreId, + null, + null, + null, + $isSincingValue + ); } /** @@ -234,6 +284,14 @@ protected function makeHelper() return Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Dat3 + */ + protected function makeDateHelper() + { + return Mage::helper('mailchimp/date'); + } + /** * @return Mage_Adminhtml_Model_Session */ @@ -258,8 +316,35 @@ protected function getAdminSession() * @param $address * @return mixed */ - protected function addStore($api, $mailchimpStoreId, $listId, $storeName, $currencyCode, $isSyncing, $storeDomain, $storeEmail, $currencySymbol, $primaryLocale, $timeZone, $storePhone, $address) - { - return $api->getEcommerce()->getStores()->add($mailchimpStoreId, $listId, $storeName, $currencyCode, $isSyncing, 'Magento', $storeDomain, $storeEmail, $currencySymbol, $primaryLocale, $timeZone, $storePhone, $address); + protected function addStore( + $api, + $mailchimpStoreId, + $listId, + $storeName, + $currencyCode, + $isSyncing, + $storeDomain, + $storeEmail, + $currencySymbol, + $primaryLocale, + $timeZone, + $storePhone, + $address + ) { + return $api->getEcommerce()->getStores()->add( + $mailchimpStoreId, + $listId, + $storeName, + $currencyCode, + $isSyncing, + 'Magento', + $storeDomain, + $storeEmail, + $currencySymbol, + $primaryLocale, + $timeZone, + $storePhone, + $address + ); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 21f0c3ed3..fcc3e5a08 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -16,13 +16,16 @@ class Ebizmarts_MailChimp_Model_Api_Subscribers /** * Ebizmarts_MailChimp_Helper_Data */ - private $mcHelper; - private $_storeId; + protected $_mcHelper; + protected $_mcDateHelper; + protected $_storeId; public function __construct() { $mageMCHelper = Mage::helper('mailchimp'); $this->setMailchimpHelper($mageMCHelper); + $mageMCDateHelper = Mage::helper('mailchimp/date'); + $this->setMailchimpDateHelper($mageMCDateHelper); } /** @@ -53,13 +56,30 @@ public function createBatchJson($listId, $storeId, $limit) { $this->setStoreId($storeId); $helper = $this->getMailchimpHelper(); - $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $this->getStoreId()); - $thisScopeHasList = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $this->getStoreId()); + $dateHelper = $this->getMailchimpDateHelper(); + $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, + $this->getStoreId() + ); + $thisScopeHasList = $helper->getIfConfigExistsForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, + $this->getStoreId() + ); $subscriberArray = array(); - if ($thisScopeHasList && !$thisScopeHasSubMinSyncDateFlag || !$helper->getSubMinSyncDateFlag($this->getStoreId())) { - $realScope = $helper->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $this->getStoreId()); - $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, Varien_Date::now())); + if ($thisScopeHasList && !$thisScopeHasSubMinSyncDateFlag + || !$helper->getSubMinSyncDateFlag($this->getStoreId()) + ) { + $realScope = $helper->getRealScopeForConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, + $this->getStoreId() + ); + $configValues = array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, + $this->_mcDateHelper->formatDate(null, 'Y-m-d H:i:s') + ) + ); $helper->saveMailchimpConfig($configValues, $realScope['scope_id'], $realScope['scope']); } @@ -83,41 +103,47 @@ public function createBatchJson($listId, $storeId, $limit) ); $collection->addFieldToFilter('mailchimp_sync_error', array('eq' => '')); $collection->getSelect()->limit($limit); - $date = $helper->getDateMicrotime(); + $date = $dateHelper->getDateMicrotime(); $batchId = 'storeid-'.$this->getStoreId(). '_' .Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_'.$date; - $counter = 0; + foreach ($collection as $subscriber) { $data = $this->_buildSubscriberData($subscriber); - $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); + $emailHash = md5(strtolower($subscriber->getSubscriberEmail())); $subscriberJson = ""; - //enconde to JSON - try { - $subscriberJson = json_encode($data); - } catch (Exception $e) { - //json encode failed - $errorMessage = "Subscriber " . $subscriber->getSubscriberId() . " json encode failed"; - $helper->logError($errorMessage); - } + //encode to JSON + $subscriberJson = json_encode($data); - if (!empty($subscriberJson)) { - if ($subscriber->getMailchimpSyncModified()) { - $helper->modifyCounterSubscribers(Ebizmarts_MailChimp_Helper_Data::SUB_MOD); - } else { - $helper->modifyCounterSubscribers(Ebizmarts_MailChimp_Helper_Data::SUB_NEW); - } + if ($subscriberJson !== false) { + if (!empty($subscriberJson)) { + if ($subscriber->getMailchimpSyncModified()) { + $helper->modifyCounterSubscribers(Ebizmarts_MailChimp_Helper_Data::SUB_MOD); + } else { + $helper->modifyCounterSubscribers(Ebizmarts_MailChimp_Helper_Data::SUB_NEW); + } - $subscriberArray[$counter]['method'] = "PUT"; - $subscriberArray[$counter]['path'] = "/lists/" . $listId . "/members/" . $md5HashEmail; - $subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId(); - $subscriberArray[$counter]['body'] = $subscriberJson; + $subscriberArray[$counter]['method'] = "PUT"; + $subscriberArray[$counter]['path'] = "/lists/" . $listId . "/members/" . $emailHash; + $subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId(); + $subscriberArray[$counter]['body'] = $subscriberJson; + + //update subscribers delta + $subscriber->setData("mailchimp_sync_delta", $this->_mcDateHelper->formatDate(null, 'Y-m-d H:i:s')); + $subscriber->setData("mailchimp_sync_error", ""); + $subscriber->setData("mailchimp_sync_modified", 0); + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE); + $subscriber->save(); + } + } else { + //json encode failed + $jsonErrorMsg = json_last_error_msg(); + $errorMessage = "Subscriber " . $subscriber->getSubscriberId() + . " json encode failed (".$jsonErrorMsg.")"; + $helper->logError($errorMessage); - //update subscribers delta - $subscriber->setData("mailchimp_sync_delta", Varien_Date::now()); - $subscriber->setData("mailchimp_sync_error", ""); + $subscriber->setData("mailchimp_sync_error", $jsonErrorMsg); $subscriber->setData("mailchimp_sync_modified", 0); - $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE); $subscriber->save(); } @@ -154,7 +180,7 @@ protected function _buildSubscriberData($subscriber) $data["language"] = $helper->getStoreLanguageCode($storeId); $interest = $this->_getInterest($subscriber); - if (count($interest)) { + if (!empty($interest)) { $data['interests'] = $interest; } @@ -184,9 +210,9 @@ protected function _getInterest($subscriber) } /** - * @param $subscriber - * @param bool $updateStatus If set to true, it will force the status update even for those already subscribed. - */ + * @param $subscriber + * @param bool $updateStatus If set to true, it will force the status update even for those already subscribed. + */ public function updateSubscriber($subscriber, $updateStatus = false) { $saveSubscriber = false; @@ -207,15 +233,14 @@ public function updateSubscriber($subscriber, $updateStatus = false) $mailChimpTags = $this->_buildMailchimpTags($subscriber, $storeId); - $language = $helper->getStoreLanguageCode($storeId); $interest = $this->_getInterest($subscriber); - $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); + $emailHash = md5(strtolower($subscriber->getSubscriberEmail())); try { $api->lists->members->addOrUpdate( $listId, - $md5HashEmail, + $emailHash, $subscriber->getSubscriberEmail(), $newStatus, null, @@ -226,62 +251,32 @@ public function updateSubscriber($subscriber, $updateStatus = false) null, null ); - $subscriber->setData("mailchimp_sync_delta", Varien_Date::now()); + $subscriber->setData("mailchimp_sync_delta", $this->_mcDateHelper->formatDate(null, 'Y-m-d H:i:s')); $subscriber->setData("mailchimp_sync_error", ""); $subscriber->setData("mailchimp_sync_modified", 0); $saveSubscriber = true; } catch (MailChimp_Error $e) { if ($this->isSubscribed($newStatus) && $subscriber->getIsStatusChanged() - && !$helper->isSubscriptionConfirmationEnabled($storeId)) { + && !$helper->isSubscriptionConfirmationEnabled($storeId) + ) { if (strstr($e->getMailchimpDetails(), 'is in a compliance state')) { try { - $api->getLists()->getMembers()->update( - $listId, $md5HashEmail, null, 'pending', $mailChimpTags->getMailchimpTags(), $interest + $this->_catchMailchimpNewstellerConfirm( + $api, $listId, $emailHash, $mailChimpTags, $subscriber, $interest ); - $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); $saveSubscriber = true; - $message = - $helper->__('To begin receiving the newsletter, you must first confirm your subscription'); - Mage::getSingleton('core/session')->addWarning($message); } catch (MailChimp_Error $e) { - $errorMessage = $e->getFriendlyMessage(); - $helper->logError($errorMessage); - if ($isAdmin) { - $this->addError($errorMessage); - } else { - $errorMessage = $helper->__("The subscription could not be applied."); - $this->addError($errorMessage); - } - - $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + $this->_catchMailchimpException($e, $subscriber, $isAdmin); $saveSubscriber = true; } catch (Exception $e) { $helper->logError($e->getMessage()); } } else { - $errorMessage = $e->getFriendlyMessage(); - $helper->logError($errorMessage); - if ($isAdmin) { - $this->addError($errorMessage); - } else { - $errorMessage = $helper->__("The subscription could not be applied."); - $this->addError($errorMessage); - } - - $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + $this->_catchMailchimpSubsNotAppliedIf($e, $isAdmin, $subscriber); $saveSubscriber = true; } } else { - $errorMessage = $e->getFriendlyMessage(); - $helper->logError($errorMessage); - if ($isAdmin) { - $this->addError($errorMessage); - } else { - $errorMessage = $helper->__("The subscription could not be applied."); - $this->addError($errorMessage); - } - - $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + $this->_catchMailchimpSubsNotAppliedElse($e, $isAdmin, $subscriber); } } catch (Exception $e) { $helper->logError($e->getMessage()); @@ -294,6 +289,94 @@ public function updateSubscriber($subscriber, $updateStatus = false) } } + /** + * @param $e + * @param $isAdmin + * @param $subscriber + */ + protected function _catchMailchimpSubsNotAppliedIf($e, $isAdmin, $subscriber) + { + $helper = $this->getMailchimpHelper(); + $errorMessage = $e->getFriendlyMessage(); + $helper->logError($errorMessage); + if ($isAdmin) { + $this->addError($errorMessage); + } else { + $errorMessage = $helper->__("The subscription could not be applied."); + $this->addError($errorMessage); + } + + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + } + + /** + * @param $e + * @param $isAdmin + * @param $subscriber + */ + protected function _catchMailchimpSubsNotAppliedElse($e, $isAdmin, $subscriber) + { + $helper = $this->getMailchimpHelper(); + $errorMessage = $e->getFriendlyMessage(); + $helper->logError($errorMessage); + if ($isAdmin) { + $this->addError($errorMessage); + } else { + $errorMessage = $helper->__("The subscription could not be applied."); + $this->addError($errorMessage); + } + + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + } + + /** + * @param $api + * @param $listId + * @param $emailHash + * @param $mailChimpTags + * @param $subscriber + * @param $interest + */ + protected function _catchMailchimpNewstellerConfirm( + $api, + $listId, + $emailHash, + $mailChimpTags, + $subscriber, + $interest + ) { + $helper = $this->getMailchimpHelper(); + $api->getLists()->getMembers()->update( + $listId, $emailHash, null, 'pending', $mailChimpTags->getMailchimpTags(), $interest + ); + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); + $message = $helper->__( + 'To begin receiving the newsletter, you must first confirm your subscription' + ); + Mage::getSingleton('core/session')->addWarning($message); + } + + /** + * @param $e + * @param $subscriber + * @param $isAdmin + */ + protected function _catchMailchimpException($e, $subscriber, $isAdmin) + { + $helper = $this->getMailchimpHelper(); + $errorMessage = $e->getFriendlyMessage(); + $helper->logError($errorMessage); + + if ($isAdmin) { + $this->addError($errorMessage); + } else { + $errorMessage = $helper->__("The subscription could not be applied."); + $this->addError($errorMessage); + } + + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + } + /** * @param $status * @return string @@ -358,8 +441,8 @@ public function deleteSubscriber($subscriber) $listId = $helper->getGeneralList($storeId); try { $api = $helper->getApi($storeId); - $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); - $api->getLists()->getMembers()->update($listId, $md5HashEmail, null, 'unsubscribed'); + $emailHash = md5(strtolower($subscriber->getSubscriberEmail())); + $api->getLists()->getMembers()->update($listId, $emailHash, null, 'unsubscribed'); } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $helper->logError($e->getMessage()); } catch (MailChimp_Error $e) { @@ -412,7 +495,7 @@ protected function getCustomerByWebsiteAndId() */ public function setMailchimpHelper($mageMCHelper) { - $this->mcHelper = $mageMCHelper; + $this->_mcHelper = $mageMCHelper; } /** @@ -420,7 +503,23 @@ public function setMailchimpHelper($mageMCHelper) */ protected function getMailchimpHelper() { - return $this->mcHelper; + return $this->_mcHelper; + } + + /** + * @param $mageMCDateHelper + */ + public function setMailchimpDateHelper($mageMCDateHelper) + { + $this->_mcDateHelper = $mageMCDateHelper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getMailchimpDateHelper() + { + return $this->_mcDateHelper; } /** @@ -480,8 +579,8 @@ protected function _buildMailchimpTags($subscriber, $storeId) $mailChimpTags->setStoreId($storeId); $mailChimpTags->setSubscriber($subscriber); $mailChimpTags->setCustomer( - $this->getCustomerByWebsiteAndId()-> - setWebsiteId($this->getWebsiteByStoreId($storeId))->load($subscriber->getCustomerId()) + $this->getCustomerByWebsiteAndId() + ->setWebsiteId($this->getWebsiteByStoreId($storeId))->load($subscriber->getCustomerId()) ); $mailChimpTags->buildMailChimpTags(); return $mailChimpTags; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php index 508a4ae88..4e9fc2301 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php @@ -17,31 +17,36 @@ class Ebizmarts_MailChimp_Model_Api_Subscribers_MailchimpTags /** * @var int */ - private $_storeId; + protected $_storeId; /** * @var array */ - private $_mailChimpTags; + protected $_mailChimpTags; /** * @var Mage_Newsletter_Model_Subscriber */ - private $_subscriber; + protected $_subscriber; /** * @var Mage_Customer_Model_Customer */ - private $_customer; + protected $_customer; /** * @var Ebizmarts_MailChimp_Helper_Data */ - private $_mcHelper; + protected $_mcHelper; + /** + * @var Ebizmarts_MailChimp_Helper_Date + */ + protected $_mcDateHelper; /** * @var Mage_Sales_Model_Order */ - private $_lastOrder; + protected $_lastOrder; public function __construct() { $this->setMailChimpHelper(); + $this->setMailChimpDateHelper(); } /** @@ -198,9 +203,27 @@ protected function customerAttributes($attributeCode, $key, $attribute) $eventValue = null; - if ($attributeCode == 'email') { - return $eventValue; - } elseif ($attributeCode == 'default_billing' || $attributeCode == 'default_shipping') { + if ($attributeCode != 'email') { + $this->_addTags($attributeCode, $subscriber, $customer, $key, $attribute); + } + + if ($this->getMailChimpTagValue($key) !== null) { + $eventValue = $this->getMailChimpTagValue($key); + } + + return $eventValue; + } + + /** + * @param $attributeCode + * @param $subscriber + * @param $customer + * @param $key + * @param $attribute + */ + protected function _addTags($attributeCode, $subscriber, $customer, $key, $attribute) + { + if ($attributeCode == 'default_billing' || $attributeCode == 'default_shipping') { $this->addDefaultShipping($attributeCode, $key, $customer); } elseif ($attributeCode == 'gender') { $this->addGender($attributeCode, $key, $customer); @@ -221,12 +244,6 @@ protected function customerAttributes($attributeCode, $key, $attribute) } else { $this->addUnknownMergeField($attributeCode, $key, $attribute, $customer); } - - if ($this->getMailChimpTagValue($key) !== null) { - $eventValue = $this->getMailChimpTagValue($key); - } - - return $eventValue; } /** @@ -235,9 +252,12 @@ protected function customerAttributes($attributeCode, $key, $attribute) */ protected function unserializeMapFields($mapFields) { - return unserialize($mapFields); + return $this->_mcHelper->unserialize($mapFields); } + /** + * @return Object + */ protected function getEntityAttributeCollection() { return Mage::getResourceModel('eav/entity_attribute_collection'); @@ -518,7 +538,7 @@ protected function getUnknownMergeField($attributeCode, $customer, $attribute) */ protected function getDateOfBirth($attributeCode, $customer) { - return $this->getMailchimpHelper()->formatDate( + return $this->getMailchimpDateHelper()->formatDate( $this->getCustomerGroupLabel($attributeCode, $customer), 'm/d', 1 ); @@ -562,6 +582,7 @@ protected function addCompany($customAtt, $customer, $key) /** * return the latest order for this subscriber + * * @return Mage_Sales_Model_Order */ protected function getLastOrderByEmail() @@ -604,6 +625,22 @@ protected function setMailChimpHelper() $this->_mcHelper = Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + public function getMailchimpDateHelper() + { + return $this->_mcDateHelper; + } + + /** + * @param $mageMCDateHelper + */ + protected function setMailChimpDateHelper() + { + $this->_mcDateHelper = Mage::helper('mailchimp/date'); + } + /** * @param $key * @return bool @@ -663,7 +700,7 @@ protected function addDefaultShipping($attributeCode, $key, $customer) $address = $customer->getPrimaryAddress($attributeCode); $addressData = $this->getAddressData($address); - if (count($addressData)) { + if (!empty($addressData)) { $this->addMailChimpTag($key, $addressData); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php b/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php new file mode 100755 index 000000000..f7a09c7a6 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php @@ -0,0 +1,440 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 7/24/19 2:47 PM + * @file: ClearEcommerce.php + */ +class Ebizmarts_MailChimp_Model_ClearEcommerce +{ + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $_helper; + + /** + * @var Ebizmarts_MailChimp_Helper_Date + */ + protected $_dateHelper; + + /** + * @var Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata_Collection + */ + protected $_ecommerceData; + + public function __construct() + { + $this->_helper = Mage::helper('mailchimp'); + $this->_dateHelper = Mage::helper('mailchimp/date'); + + $this->_ecommerceData = Mage::getModel('mailchimp/ecommercesyncdata') + ->getCollection() + ->addFieldToSelect('related_id') + ->setPageSize(100); + } + + /** + * @return Ebizmarts_MailChimp_Helper_Data|Mage_Core_Helper_Abstract + */ + protected function getHelper() + { + return $this->_helper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date|Mage_Core_Helper_Abstract + */ + protected function getDateHelper() + { + return $this->_dateHelper; + } + + /** + * Process all types of data from eCommerce data to delete + * non active products, quotes, customers, etc. from the table. + */ + public function clearEcommerceData() + { + $itemsPRO = $this->getItemsToDelete(Ebizmarts_MailChimp_Model_Config::IS_PRODUCT); + $itemsCUS = $this->getItemsToDelete(Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER); + $itemsQUO = $this->getItemsToDelete(Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $itemsPRL = $this->getItemsToDelete(Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE); + $itemsPCD = $this->getItemsToDelete(Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE); + + $this->processData($itemsPRO, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT); + $this->processData($itemsCUS, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER); + $this->processData($itemsQUO, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $this->processData($itemsPRL, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE); + $this->processData($itemsPCD, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE); + } + + /** + * @param $data + * @param $type + */ + public function processData($data, $type) + { + $ids = array(); + foreach ($data as $item) { + $ids [] = $item->getId(); + } + + $reverseIds = $this->processDeletedData($type); + $ids = array_merge($ids, $reverseIds); + + if (!empty($ids)) { + $this->deleteEcommerceRows($ids, $type); + } else { + $this->clearEcommerceCollection(); + } + } + + /** + * @param $type + * @return array + */ + public function processDeletedData($type) + { + $ids = array(); + $eData = $this->getDeletedRows($type); + + foreach ($eData as $eItem) { + $ids [] = $eItem['related_id']; + } + + return $ids; + } + + /** + * Get the items from eCommerce data that had been disabled. + * + * @param $type + * @param bool $filter + * @return array + * @throws Mage_Core_Model_Store_Exception + */ + protected function getItemsToDelete($type) + { + $items = array(); + switch ($type) { + case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: + $items = $this->getProductItems(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: + $items = $this->getQuoteItems(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: + $items = $this->getCustomerItems(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE: + $items = $this->getPromoRuleItems(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE: + $items = $this->getPromoCodeItems(); + break; + } + + return $items; + } + + /** + * @param $filter + * @return array + */ + protected function getProductItems() + { + $collection = Mage::getModel('catalog/product') + ->getCollection() + ->setPageSize(100) + ->setCurPage(1) + ->addFieldToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED)); + + return $collection->getItems(); + } + + /** + * @param $filter + * @return array + */ + protected function getQuoteItems() + { + $collection = Mage::getModel('sales/quote') + ->getCollection() + ->setPageSize(100) + ->setCurPage(1) + ->addFieldToFilter('is_active', array('eq' => 0)); + + return $collection->getItems(); + } + + /** + * @param $filter + * @return array + */ + protected function getCustomerItems() + { + $items = array(); + $collection = Mage::getModel('customer/customer') + ->getCollection() + ->setPageSize(100) + ->setCurPage(1); + + $customers = $collection->getItems(); + foreach ($customers as $item) { + if ($item->getIsActive() == 0) { + $items [] = $item; + } + } + + return $items; + } + + /** + * @param $filter + * @return array + */ + protected function getPromoRuleItems() + { + $collection = Mage::getModel('salesrule/rule') + ->getCollection() + ->setPageSize(100) + ->setCurPage(1) + ->addFieldToFilter('is_active', array('eq' => 0)); + + return $collection->getItems(); + } + + /** + * @param $filter + * @return mixed + * @throws Mage_Core_Model_Store_Exception + */ + protected function getPromoCodeItems() + { + $collection = Mage::getModel('salesrule/coupon') + ->getCollection() + ->setPageSize(100) + ->setCurPage(1); + + $date = $this->getDateHelper()->formatDate(null, 'YYYY-mm-dd H:i:s'); + $collection->addFieldToFilter('expiration_date', array('lteq' => $date)); + + return $collection->getItems(); + } + + /** + * Returns the rows that still exist in eCommerce data but + * that had been deleted in it respective entity (product, + * quote, promo code, etc.) + * + * @param $type + * @return array + */ + protected function getDeletedRows($type) + { + switch ($type) { + case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: + $this->addProductDeletedRowsToFilter(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: + $this->addQuoteDeletedRowsToFilter(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: + $this->addCustomerDeletedRowsToFilter(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE: + $this->addRuleDeletedRowsToFilter(); + break; + case Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE: + $this->addCouponDeletedRowsToFilter(); + break; + } + + return $this->getData(); + } + + /** + * Gets the deleted rows from Collection + * + * @return array + */ + protected function getData() + { + $data = array(); + + foreach ($this->_ecommerceData as $item) { + $data [] = $item->getData(); + } + + return $data; + } + + /** + * @param $ids + * @param $type + */ + public function deleteEcommerceRows($ids, $type) + { + $ids = implode($ids, ', '); + $where = array( + "related_id IN ($ids)", + "type = '$type'" + ); + + $helper = $this->getHelper(); + $resource = $helper->getCoreResource(); + $connection = $resource->getConnection('core_write'); + $tableName = $resource->getTableName('mailchimp/ecommercesyncdata'); + $connection->delete($tableName, $where); + + $this->clearEcommerceCollection(); + } + + /** + * @return Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata_Collection + */ + protected function getEcommerceCollection() + { + return $this->_ecommerceData; + } + + /** + * Deletes entity type filters and joins + * + * @throws Zend_Db_Select_Exception + */ + protected function clearEcommerceCollection() + { + $selectPart = $this->_ecommerceData->getSelect()->getPart(Zend_Db_Select::COLUMNS); + + if (empty($selectPart)) { + $this->_ecommerceData->addFieldToSelect('related_id'); + } + + $fromPart = $this->_ecommerceData->getSelect()->getPart(Zend_Db_Select::FROM); + unset($fromPart['ent']); + + $this->_ecommerceData->getSelect()->setPart(Zend_Db_Select::FROM, $fromPart); + $this->_ecommerceData->getSelect()->setPart(Zend_Db_Select::WHERE, array()); + $this->_ecommerceData->clear(); + } + + /** + * @param string $entityTable + * @param string $entity + * @throws Zend_Db_Select_Exception + */ + protected function joinMagentoEntityTable($entityTable, $entity = 'entity') + { + $cols = '*'; + $selectPart = $this->_ecommerceData->getSelect()->getPart(Zend_Db_Select::COLUMNS); + + foreach ($selectPart as $p) { + if (in_array('ent', $p)) { + $cols = null; + } + } + + $this->_ecommerceData->getSelect()->joinLeft( + array('ent' => $entityTable), + 'main_table.related_id = ent.' . $entity . '_id', + $cols + ); + } + + /** + * Adds filter to get only deleted Products + */ + protected function addProductDeletedRowsToFilter() + { + $resource = Mage::getSingleton('core/resource'); + $ecommerceData = $this->getEcommerceCollection(); + $ecommerceData->addFieldToFilter( + 'main_table.type', + array('eq' => Ebizmarts_MailChimp_Model_Config::IS_PRODUCT) + ); + + $entityTable = $resource->getTableName('catalog/product'); + $ecommerceData->addFieldToFilter('ent.entity_id', array('null' => true)); + + $this->joinMagentoEntityTable($entityTable, 'entity'); + } + + /** + * Adds filter to get only deleted Quotes + */ + protected function addQuoteDeletedRowsToFilter() + { + $resource = Mage::getSingleton('core/resource'); + $ecommerceData = $this->getEcommerceCollection(); + $ecommerceData->addFieldToFilter( + 'main_table.type', + array('eq' => Ebizmarts_MailChimp_Model_Config::IS_QUOTE) + ); + + $entityTable = $resource->getTableName('sales/quote'); + $ecommerceData->addFieldToFilter('ent.entity_id', array('null' => true)); + + $this->joinMagentoEntityTable($entityTable, 'entity'); + } + + /** + * Adds filter to get only deleted Customers + */ + protected function addCustomerDeletedRowsToFilter() + { + $resource = Mage::getSingleton('core/resource'); + $ecommerceData = $this->getEcommerceCollection(); + $ecommerceData->addFieldToFilter( + 'main_table.type', + array('eq' => Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER) + ); + + $entityTable = $resource->getTableName('customer/entity'); + $ecommerceData->addFieldToFilter('ent.entity_id', array('null' => true)); + + $this->joinMagentoEntityTable($entityTable, 'entity'); + } + + /** + * Adds filter to get only deleted Rules + */ + protected function addRuleDeletedRowsToFilter() + { + $resource = Mage::getSingleton('core/resource'); + $ecommerceData = $this->getEcommerceCollection(); + $ecommerceData->addFieldToFilter( + 'main_table.type', + array('eq' => Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE) + ); + + $entityTable = $resource->getTableName('salesrule/rule'); + $ecommerceData->addFieldToFilter('ent.rule_id', array('null' => true)); + + $this->joinMagentoEntityTable($entityTable, 'rule'); + } + + /** + * Adds filter to get only deleted Coupons + */ + protected function addCouponDeletedRowsToFilter() + { + $resource = Mage::getSingleton('core/resource'); + $ecommerceData = $this->getEcommerceCollection(); + $ecommerceData->addFieldToFilter( + 'main_table.type', + array('eq' => Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE) + ); + + $entityTable = $resource->getTableName('salesrule/coupon'); + $ecommerceData->addFieldToFilter('ent.coupon_id', array('null' => true)); + + $this->joinMagentoEntityTable($entityTable, 'coupon'); + } +} + diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Cron.php b/app/code/community/Ebizmarts/MailChimp/Model/Cron.php index 5a66f0af9..bc1c0f657 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Cron.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Cron.php @@ -13,16 +13,16 @@ class Ebizmarts_MailChimp_Model_Cron { /** - * @var Ebizmarts_MailChimp_Helper_Data -*/ - private $mailChimpHelper; + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $_mailChimpHelper; public function __construct() { - $this->mailChimpHelper = Mage::helper('mailchimp'); + $this->_mailChimpHelper = Mage::helper('mailchimp'); } - public function syncEcommerceBatchData(Mage_Cron_Model_Schedule $schedule) + public function syncEcommerceBatchData() { if ($this->getHelper()->migrationFinished()) { Mage::getModel('mailchimp/api_batches')->handleEcommerceBatches(); @@ -31,23 +31,28 @@ public function syncEcommerceBatchData(Mage_Cron_Model_Schedule $schedule) } } - public function syncSubscriberBatchData(Mage_Cron_Model_Schedule $schedule) + public function syncSubscriberBatchData() { Mage::getModel('mailchimp/api_batches')->handleSubscriberBatches(); } - public function processWebhookData($cron) + public function processWebhookData() { Mage::getModel('mailchimp/processWebhook')->processWebhookData(); } - public function deleteWebhookRequests($cron) + public function deleteWebhookRequests() { Mage::getModel('mailchimp/processWebhook')->deleteProcessed(); } - private function getHelper() + public function clearEcommerceData() { - return $this->mailChimpHelper; + Mage::getModel('mailchimp/clearEcommerce')->clearEcommerceData(); + } + + protected function getHelper() + { + return $this->_mailChimpHelper; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php index 70240361e..bc73a2d0f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php @@ -12,6 +12,7 @@ */ class Ebizmarts_MailChimp_Model_Email_Queue extends Mage_Core_Model_Email_Queue { + /** * Send all messages in a queue via mandrill * @@ -19,6 +20,9 @@ class Ebizmarts_MailChimp_Model_Email_Queue extends Mage_Core_Model_Email_Queue */ public function send() { + $mageMCHelper = Mage::helper('mailchimp'); + $mageMCDateHelper = Mage::helper('mailchimp/date'); + /** * @var $collection Mage_Core_Model_Resource_Email_Queue_Collection */ @@ -42,54 +46,10 @@ public function send() if (Mage::helper('mailchimp/mandrill')->isMandrillEnabled($storeId)) { $parameters = new Varien_Object($message->getMessageParameters()); - $mailer = $this->getMail($storeId); - $mailer->setFrom($parameters->getFromEmail(), $parameters->getFromName()); - $mailer->setSubject($parameters->getSubject()); - if ($parameters->getIsPlain()) { - $mailer->setBodyText($message->getMessageBody()); - } else { - $mailer->setBodyHtml($message->getMessageBody()); - } try { - foreach ($message->getRecipients() as $recipient) { - list($email, $name, $type) = $recipient; - switch ($type) { - case self::EMAIL_TYPE_TO: - case self::EMAIL_TYPE_CC: - $mailer->addTo($email, $name); - break; - case self::EMAIL_TYPE_BCC: - $mailer->addBcc($email); - break; - } - } - - if ($parameters->getReplyTo() !== null) { - $mailer->setReplyTo($parameters->getReplyTo()); - } - - if ($parameters->getReturnTo() !== null) { - $mailer->setReturnPath($parameters->getReturnTo()); - } - - try { - Mage::dispatchEvent( - 'fooman_emailattachments_before_send_queue', - array( - 'mailer' => $mailer, - 'message' => $message, - 'mail_transport' => false - - ) - ); - $mailer->send(); - } catch (Exception $e) { - Mage::logException($e); - } - - unset($mailer); - $message->setProcessedAt(Varien_Date::formatDate(true)); + $this->_sendMandrillEnabled($message, $parameters, $storeId); + $message->setProcessedAt($mageMCDateHelper->formatDate(null, 'Y-m-d H:i:s')); $message->save(); } catch (Exception $e) { Mage::logException($e); @@ -101,60 +61,126 @@ public function send() Zend_Mail::setDefaultTransport($mailTransport); } - $mailer = new Zend_Mail('utf-8'); - foreach ($message->getRecipients() as $recipient) { - list($email, $name, $type) = $recipient; - switch ($type) { - case self::EMAIL_TYPE_BCC: - $mailer->addBcc($email, '=?utf-8?B?' . base64_encode($name) . '?='); - break; - case self::EMAIL_TYPE_TO: - case self::EMAIL_TYPE_CC: - default: - $mailer->addTo($email, '=?utf-8?B?' . base64_encode($name) . '?='); - break; - } - } + $this->_sendMandrillNotEnabled($message, $parameters); + $message->setProcessedAt($mageMCDateHelper->formatDate(null, 'Y-m-d H:i:s')); + $message->save(); + } + } + } - if ($parameters->getIsPlain()) { - $mailer->setBodyText($message->getMessageBody()); - } else { - $mailer->setBodyHTML($message->getMessageBody()); - } + return $this; + } - $mailer->setSubject('=?utf-8?B?' . base64_encode($parameters->getSubject()) . '?='); - $mailer->setFrom($parameters->getFromEmail(), $parameters->getFromName()); - if ($parameters->getReplyTo() !== null) { - $mailer->setReplyTo($parameters->getReplyTo()); - } + /** + * @param $message + * @param $parameters + * @param $storeId + * @throws Zend_Mail_Exception + */ + protected function _sendMandrillEnabled($message, $parameters, $storeId) + { + $mailer = $this->getMail($storeId); + $mailer->setFrom($parameters->getFromEmail(), $parameters->getFromName()); + $mailer->setSubject($parameters->getSubject()); + if ($parameters->getIsPlain()) { + $mailer->setBodyText($message->getMessageBody()); + } else { + $mailer->setBodyHtml($message->getMessageBody()); + } - if ($parameters->getReturnTo() !== null) { - $mailer->setReturnPath($parameters->getReturnTo()); - } + foreach ($message->getRecipients() as $recipient) { + list($email, $name, $type) = $recipient; + switch ($type) { + case self::EMAIL_TYPE_TO: + case self::EMAIL_TYPE_CC: + $mailer->addTo($email, $name); + break; + case self::EMAIL_TYPE_BCC: + $mailer->addBcc($email); + break; + } + } - try { - Mage::dispatchEvent( - 'fooman_emailattachments_before_send_queue', - array( - 'mailer' => $mailer, - 'message' => $message, - 'mail_transport' => false - - ) - ); - $mailer->send(); - } catch (Exception $e) { - Mage::logException($e); - } + if ($parameters->getReplyTo() !== null) { + $mailer->setReplyTo($parameters->getReplyTo()); + } - unset($mailer); - $message->setProcessedAt(Varien_Date::formatDate(true)); - $message->save(); - } + if ($parameters->getReturnTo() !== null) { + $mailer->setReturnPath($parameters->getReturnTo()); + } + + try { + Mage::dispatchEvent( + 'fooman_emailattachments_before_send_queue', + array( + 'mailer' => $mailer, + 'message' => $message, + 'mail_transport' => false + + ) + ); + $mailer->send(); + } catch (Exception $e) { + Mage::logException($e); + } + + unset($mailer); + } + + /** + * @param $message + * @param $parameters + * @throws Zend_Mail_Exception + */ + protected function _sendMandrillNotEnabled($message, $parameters) + { + $mailer = new Zend_Mail('utf-8'); + foreach ($message->getRecipients() as $recipient) { + list($email, $name, $type) = $recipient; + switch ($type) { + case self::EMAIL_TYPE_BCC: + $mailer->addBcc($email, '=?utf-8?B?' . base64_encode($name) . '?='); + break; + case self::EMAIL_TYPE_TO: + case self::EMAIL_TYPE_CC: + default: + $mailer->addTo($email, '=?utf-8?B?' . base64_encode($name) . '?='); + break; } } - return $this; + if ($parameters->getIsPlain()) { + $mailer->setBodyText($message->getMessageBody()); + } else { + $mailer->setBodyHTML($message->getMessageBody()); + } + + $mailer->setSubject('=?utf-8?B?' . base64_encode($parameters->getSubject()) . '?='); + $mailer->setFrom($parameters->getFromEmail(), $parameters->getFromName()); + if ($parameters->getReplyTo() !== null) { + $mailer->setReplyTo($parameters->getReplyTo()); + } + + if ($parameters->getReturnTo() !== null) { + $mailer->setReturnPath($parameters->getReturnTo()); + } + + try { + Mage::dispatchEvent( + 'fooman_emailattachments_before_send_queue', + array( + 'mailer' => $mailer, + 'message' => $message, + 'mail_transport' => false + + ) + ); + $mailer->send(); + } catch (Exception $e) { + Mage::logException($e); + } + + unset($mailer); } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php index 16cd34898..222f8b799 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php @@ -16,15 +16,15 @@ class Ebizmarts_MailChimp_Model_Email_Template extends Ebizmarts_MailChimp_Model /** * @param array|string $email - * @param null $name - * @param array $variables + * @param null $name + * @param array $variables * @return bool * @throws Exception */ public function send($email, $name = null, array $variables = array()) { - $email_config = $this->getDesignConfig(); - $storeId = (integer) $email_config->getStore(); + $emailConfig = $this->getDesignConfig(); + $storeId = (integer) $emailConfig->getStore(); $mandrillHelper = $this->makeMandrillHelper(); if (!$mandrillHelper->isMandrillEnabled($storeId)) { return $this->parentSend($email, $name, $variables); @@ -36,13 +36,7 @@ public function send($email, $name = null, array $variables = array()) } $emails = array_values((array)$email); - $names = is_array($name) ? $name : (array)$name; - $names = array_values($names); - foreach ($emails as $key => $email) { - if (!isset($names[$key])) { - $names[$key] = substr($email, 0, strpos($email, '@')); - } - } + $names = $this->_getEmailsNames($emails, $name); // Get message $this->setUseAbsoluteLinks(true); @@ -54,27 +48,104 @@ public function send($email, $name = null, array $variables = array()) $email = array('subject' => $subject, 'to' => array()); $setReturnPath = $this->getSendingSetReturnPath(); switch ($setReturnPath) { - case 1: - $returnPathEmail = $this->getSenderEmail(); - break; - case 2: - $returnPathEmail = $this->getSendingReturnPathEmail(); - break; - default: - $returnPathEmail = null; - break; + case 1: + $returnPathEmail = $this->getSenderEmail(); + break; + case 2: + $returnPathEmail = $this->getSendingReturnPathEmail(); + break; + default: + $returnPathEmail = null; + break; } $mail = $this->getMail(); + $email['to'] = $this->_getEmailsTo($emails, $names, $mail); + $email['from_email'] = $this->_getEmailFrom($mail); + $email['from_name'] = $this->getSenderName(); + $email['tags'] = $this->_getEmailsTags($variables); + + $headers = $mail->getHeaders(); + $headers[] = $mandrillHelper->getUserAgent(); + $email['headers'] = $headers; + + if ($att = $mail->getAttachments()) { + $email['attachments'] = $att; + } + + if ($this->isPlain()) { + $email['text'] = $message; + } else { + $email['html'] = $message; + } + + if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) { + $emailQueue = $this->getQueue(); + $emailQueue->clearRecipients(); + $emailQueue->setMessageBody($message); + $emailQueue->setMessageParameters( + array( + 'subject' => $subject, + 'return_path_email' => $returnPathEmail, + 'is_plain' => $this->isPlain(), + 'from_email' => $this->getSenderEmail(), + 'from_name' => $this->getSenderName() + ) + ) + ->addRecipients($emails, $names, Mage_Core_Model_Email_Queue::EMAIL_TYPE_TO) + ->addRecipients($this->_bccEmails, array(), Mage_Core_Model_Email_Queue::EMAIL_TYPE_BCC); + $emailQueue->addMessageToQueue(); + return true; + } + + try { + $result = $this->sendMail($email, $mail); + $this->_mail = null; + } catch (Exception $e) { + $this->_mail = null; + Mage::logException($e); + return false; + } + + return true; + } + + /** + * @param $emails + * @param $name + * @return array + */ + protected function _getEmailsNames($emails, $name) + { + $names = is_array($name) ? $name : (array)$name; + $names = array_values($names); + foreach ($emails as $key => $email) { + if (!isset($names[$key])) { + $names[$key] = substr($email, 0, strpos($email, '@')); + } + } + + return $names; + } + + /** + * @param $emails + * @param $names + * @param $mail + * @return array + */ + protected function _getEmailsTo($emails, $names, $mail) + { + $to = array(); $max = count($emails); for ($i = 0; $i < $max; $i++) { if (isset($names[$i])) { - $email['to'][] = array( + $to[] = array( 'email' => $emails[$i], 'name' => $names[$i] ); } else { - $email['to'][] = array( + $to[] = array( 'email' => $emails[$i], 'name' => '' ); @@ -82,19 +153,29 @@ public function send($email, $name = null, array $variables = array()) } foreach ($mail->getBcc() as $bcc) { - $email['to'][] = array( + $to[] = array( 'email' => $bcc, 'type' => 'bcc' ); } - $email['from_name'] = $this->getSenderName(); - $email['from_email'] = $this->getSenderEmail(); + return $to; + } + + /** + * @param $mail + * @return mixed + */ + protected function _getEmailFrom($mail) + { + $fromEmail = $this->getSenderEmail(); $mandrillSenders = $this->getSendersDomains($mail); $senderExists = false; + foreach ($mandrillSenders as $sender) { if (isset($sender['domain'])) { - $emailArray = explode('@', $email['from_email']); + $emailArray = explode('@', $fromEmail); + if (count($emailArray) > 1 && $emailArray[1] == $sender['domain']) { $senderExists = true; } @@ -102,75 +183,42 @@ public function send($email, $name = null, array $variables = array()) } if (!$senderExists) { - $email['from_email'] = $this->getGeneralEmail(); + $fromEmail = $this->getGeneralEmail(); } - $headers = $mail->getHeaders(); - $headers[] = $mandrillHelper->getUserAgent(); - $email['headers'] = $headers; - if (isset($variables['tags']) && count($variables['tags'])) { - $email ['tags'] = $variables['tags']; - } + return $fromEmail; + } - if (isset($variables['tags']) && count($variables['tags'])) { - $email ['tags'] = $variables['tags']; + /** + * @param $variables + * @return array|null + */ + protected function _getEmailsTags($variables) + { + $tags = null; + + if (isset($variables['tags']) && !empty($variables['tags'])) { + $tags = $variables['tags']; } else { $templateId = (string)$this->getId(); $templates = parent::getDefaultTemplates(); + if (isset($templates[$templateId]) && isset($templates[$templateId]['label'])) { - $email ['tags'] = array(substr($templates[$templateId]['label'], 0, 50)); + $tags = array(substr($templates[$templateId]['label'], 0, 50)); } else { if ($this->getTemplateCode()) { - $email ['tags'] = array(substr($this->getTemplateCode(), 0, 50)); + $tags = array(substr($this->getTemplateCode(), 0, 50)); } else { if ($templateId) { - $email ['tags'] = array(substr($templateId, 0, 50)); + $tags = array(substr($templateId, 0, 50)); } else { - $email['tags'] = array('default_tag'); + $tags = array('default_tag'); } } } } - if ($att = $mail->getAttachments()) { - $email['attachments'] = $att; - } - - if ($this->isPlain()) { - $email['text'] = $message; - } else { - $email['html'] = $message; - } - - if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) { - $emailQueue = $this->getQueue(); - $emailQueue->clearRecipients(); - $emailQueue->setMessageBody($message); - $emailQueue->setMessageParameters( - array( - 'subject' => $subject, - 'return_path_email' => $returnPathEmail, - 'is_plain' => $this->isPlain(), - 'from_email' => $this->getSenderEmail(), - 'from_name' => $this->getSenderName() - ) - ) - ->addRecipients($emails, $names, Mage_Core_Model_Email_Queue::EMAIL_TYPE_TO) - ->addRecipients($this->_bccEmails, array(), Mage_Core_Model_Email_Queue::EMAIL_TYPE_BCC); - $emailQueue->addMessageToQueue(); - return true; - } - - try { - $result = $this->sendMail($email, $mail); - $this->_mail = null; - } catch (Exception $e) { - $this->_mail = null; - Mage::logException($e); - return false; - } - - return true; + return $tags; } /** @@ -181,8 +229,9 @@ public function send($email, $name = null, array $variables = array()) public function getMail() { $helper = $this->makeMandrillHelper(); - $email_config = $this->getDesignConfig(); - $storeId = (integer) $email_config->getStore(); + $emailConfig = $this->getDesignConfig(); + $storeId = (integer) $emailConfig->getStore(); + if (!$this->isMandrillEnabled($storeId)) { return parent::getMail(); } @@ -234,6 +283,7 @@ protected function getSendersDomains($mail) } catch (Exception $e) { Mage::log($e->getMessage(), null, 'Mandrill.log', true); } + return $mandrillSenders; } @@ -250,6 +300,7 @@ protected function sendMail($email, $mail) } catch (Exception $e) { Mage::log($e->getMessage(), null, 'Mandrill.log', true); } + return $mailSent; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php index 746001e44..fb41f3b95 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php @@ -23,13 +23,24 @@ public function _construct() $this->_init('mailchimp/interestgroup', 'id'); } - public function getByRelatedIdStoreId($customerId = 0, $subscriberId = 0, $storeId) + /** + * @param int $customerId + * @param int $subscriberId + * @param int $storeId + * @return array + */ + public function getByRelatedIdStoreId($customerId = 0, $subscriberId = 0, $storeId = 0) { $read = $this->_getReadAdapter(); $select = $read->select() ->from($this->getMainTable()) ->where('store_id = ?', $storeId) - ->where('(' . $read->quoteInto('customer_id = ?', $customerId) . ' OR ' . $read->quoteInto('subscriber_id = ?', $subscriberId) . ')'); + ->where( + '(' + . $read->quoteInto('customer_id = ?', $customerId) + . ' OR ' . $read->quoteInto('subscriber_id = ?', $subscriberId) + . ')' + ); $result = $read->fetchRow($select); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 64a69ca43..ae82b3638 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -107,7 +107,7 @@ protected function getCustomerModel() /** * Handle save of System -> Configuration, section * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer * @throws Mage_Core_Exception */ @@ -119,32 +119,46 @@ public function saveConfigBefore(Varien_Event_Observer $observer) $configDataChanged = false; $helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); - $mailchimpStoreId = (isset($configData['groups']['general']['fields']['storeid']['value'])) ? $configData['groups']['general']['fields']['storeid']['value'] : null; + $mailchimpStoreId = (isset($configData['groups']['general']['fields']['storeid']['value'])) + ? $configData['groups']['general']['fields']['storeid']['value'] + : null; $oldMailchimpStoreId = $helper->getMCStoreId($scopeArray['scope_id'], $scopeArray['scope']); - if (isset($configData['groups']['general']['fields']['apikey']['value']) && !$helper->isApiKeyObscure($configData['groups']['general']['fields']['apikey']['value'])) { + if (isset($configData['groups']['general']['fields']['apikey']['value']) + && !$helper->isApiKeyObscure($configData['groups']['general']['fields']['apikey']['value']) + ) { $apiKey = $configData['groups']['general']['fields']['apikey']['value']; } else { $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); } - // If ecommerce data section is enabled only allow inheriting both entries (list and MC Store) at the same time. + // If ecommerce data section is enabled only allow inheriting both entries + // (list and MC Store) at the same time. if ($this->isListXorStoreInherited($configData)) { if (isset($configData['groups']['general']['fields']['list']['inherit'])) { unset($configData['groups']['general']['fields']['list']['inherit']); $mcStoreListId = $helper->getListIdByApiKeyAndMCStoreId($apiKey, $mailchimpStoreId); - $previouslyConfiguredListId = $helper->getGeneralList($scopeArray['scope_id'], $scopeArray['scope']); + $previouslyConfiguredListId = $helper->getGeneralList( + $scopeArray['scope_id'], + $scopeArray['scope'] + ); $listId = (!empty($previouslyConfiguredListId)) ? $previouslyConfiguredListId : $mcStoreListId; $configData['groups']['general']['fields']['list']['value'] = $listId; $configDataChanged = true; - $message = $helper->__('The audience configuration was automatically modified to show the audience associated to the selected Mailchimp store.'); + $message = $helper->__( + 'The audience configuration was automatically modified to show the audience ' + . 'associated to the selected Mailchimp store.' + ); $this->getAdminSession()->addError($message); } elseif (isset($configData['groups']['general']['fields']['storeid']['inherit'])) { unset($configData['groups']['general']['fields']['storeid']['inherit']); $configData['groups']['general']['fields']['storeid']['value'] = $oldMailchimpStoreId; $configDataChanged = true; - $message = $helper->__('The Mailchimp store configuration was not modified. There is a Mailchimp audience configured for this scope. Both must be set to inherit at the same time.'); + $message = $helper->__( + 'The Mailchimp store configuration was not modified. There is a Mailchimp audience configured ' + . 'for this scope. Both must be set to inherit at the same time.' + ); $this->getAdminSession()->addError($message); } @@ -160,19 +174,22 @@ public function saveConfigBefore(Varien_Event_Observer $observer) /** * return true if list or store is selected but the other one is inheriting. * - * @param $configData + * @param $configData * @return bool */ protected function isListXorStoreInherited($configData) { - return (!isset($configData['groups']['general']['fields']['list']['inherit']) && isset($configData['groups']['general']['fields']['storeid']['value']) - || !isset($configData['groups']['general']['fields']['storeid']['inherit']) && isset($configData['groups']['general']['fields']['list']['value'])); + return ( + !isset($configData['groups']['general']['fields']['list']['inherit']) + && isset($configData['groups']['general']['fields']['storeid']['value']) + || !isset($configData['groups']['general']['fields']['storeid']['inherit']) + && isset($configData['groups']['general']['fields']['list']['value'])); } /** * Handle confirmation emails and subscription to Mailchimp * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer * @throws Mage_Core_Exception */ @@ -188,8 +205,9 @@ public function subscriberSaveBefore(Varien_Event_Observer $observer) $statusChanged = $subscriber->getIsStatusChanged(); //Override Magento status to always send double opt-in confirmation. - if ($statusChanged && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED && - $helper->isSubscriptionConfirmationEnabled($storeId) && !$helper->isUseMagentoEmailsEnabled($storeId)) { + if ($statusChanged && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED + && $helper->isSubscriptionConfirmationEnabled($storeId) && !$helper->isUseMagentoEmailsEnabled($storeId) + ) { $subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); $this->addSuccessIfRequired($helper); } @@ -201,7 +219,7 @@ public function subscriberSaveBefore(Varien_Event_Observer $observer) /** * Handle interest groups for subscriber and allow Magento email to be sent if configured that way. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception @@ -224,7 +242,8 @@ public function subscriberSaveAfter(Varien_Event_Observer $observer) if ($helper->isUseMagentoEmailsEnabled($storeViewId) !== 1 && $this->isMagentoSubscription($subscriberSource) - || $this->isEmailConfirmationRequired($subscriberSource)) { + || $this->isEmailConfirmationRequired($subscriberSource) + ) { if ($subscriber->getIsStatusChanged()) { $apiSubscriber->updateSubscriber($subscriber, true); } else { @@ -247,7 +266,7 @@ public function subscriberSaveAfter(Varien_Event_Observer $observer) /** * Handle subscriber deletion from back end. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer */ public function handleSubscriberDeletion(Varien_Event_Observer $observer) @@ -281,9 +300,9 @@ public function alterNewsletterGrid(Varien_Event_Observer $observer) $block->addColumnAfter( 'firstname', array( - 'header' => Mage::helper('newsletter')->__('Customer First Name'), - 'index' => 'customer_firstname', - 'renderer' => 'mailchimp/adminhtml_newsletter_subscriber_renderer_firstname', + 'header' => Mage::helper('newsletter')->__('Customer First Name'), + 'index' => 'customer_firstname', + 'renderer' => 'mailchimp/adminhtml_newsletter_subscriber_renderer_firstname', ), 'type' ); @@ -291,9 +310,9 @@ public function alterNewsletterGrid(Varien_Event_Observer $observer) $block->addColumnAfter( 'lastname', array( - 'header' => Mage::helper('newsletter')->__('Customer Last Name'), - 'index' => 'customer_lastname', - 'renderer' => 'mailchimp/adminhtml_newsletter_subscriber_renderer_lastname' + 'header' => Mage::helper('newsletter')->__('Customer Last Name'), + 'index' => 'customer_lastname', + 'renderer' => 'mailchimp/adminhtml_newsletter_subscriber_renderer_lastname' ), 'firstname' ); @@ -420,7 +439,11 @@ public function newOrder(Varien_Event_Observer $observer) $mailchimpStoreId = $helper->getMCStoreId($storeId); $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $dataProduct = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); if (!$isMarkedAsDeleted) { $this->makeApiProduct()->update($productId, $mailchimpStoreId); @@ -455,7 +478,7 @@ public function orderSaveBefore(Varien_Event_Observer $observer) /** * When Order object is saved add the campaign id if available in the cookies. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer */ public function saveCampaignData(Varien_Event_Observer $observer) @@ -514,13 +537,15 @@ protected function _getLandingCookie() /** * Add section in order view with MailChimp campaign data if available. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer */ public function addOrderViewMonkey(Varien_Event_Observer $observer) { $block = $observer->getBlock(); - if (($block->getNameInLayout() == 'order_info') && ($child = $block->getChild('mailchimp.order.info.monkey.block'))) { + if (($block->getNameInLayout() == 'order_info') + && ($child = $block->getChild('mailchimp.order.info.monkey.block')) + ) { $order = $block->getOrder(); $storeId = $order->getStoreId(); $helper = $this->makeHelper(); @@ -542,7 +567,7 @@ public function addOrderViewMonkey(Varien_Event_Observer $observer) /** * Add column to associate orders in grid gained from MailChimp campaigns and automations. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer * @throws Mage_Core_Exception */ @@ -555,33 +580,37 @@ public function addColumnToSalesOrderGrid(Varien_Event_Observer $observer) if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Grid && $ecommEnabledAnyScope && $addColumnConfig ) { - if ($addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_MAILCHIMP_LOGO_TO_GRID || $addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_BOTH_TO_GRID) { + if ($addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_MAILCHIMP_LOGO_TO_GRID + || $addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_BOTH_TO_GRID + ) { $block->addColumnAfter( 'mailchimp_campaign_id', array( - 'header' => $helper->__('MailChimp'), - 'index' => 'mailchimp_campaign_id', - 'align' => 'center', - 'filter' => false, - 'renderer' => 'mailchimp/adminhtml_sales_order_grid_renderer_mailchimp', - 'sortable' => false, - 'width' => 70 + 'header' => $helper->__('MailChimp'), + 'index' => 'mailchimp_campaign_id', + 'align' => 'center', + 'filter' => false, + 'renderer' => 'mailchimp/adminhtml_sales_order_grid_renderer_mailchimp', + 'sortable' => false, + 'width' => 70 ), 'created_at' ); } - if ($addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_SYNC_STATUS_TO_GRID || $addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_BOTH_TO_GRID) { + if ($addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_SYNC_STATUS_TO_GRID + || $addColumnConfig == Ebizmarts_MailChimp_Model_Config::ADD_BOTH_TO_GRID + ) { $block->addColumnAfter( 'mailchimp_synced_flag', array( - 'header' => $helper->__('Synced to MailChimp'), - 'index' => 'mailchimp_synced_flag', - 'align' => 'center', - 'filter' => false, - 'renderer' => 'mailchimp/adminhtml_sales_order_grid_renderer_mailchimpOrder', - 'sortable' => true, - 'width' => 70 + 'header' => $helper->__('Synced to MailChimp'), + 'index' => 'mailchimp_synced_flag', + 'align' => 'center', + 'filter' => false, + 'renderer' => 'mailchimp/adminhtml_sales_order_grid_renderer_mailchimpOrder', + 'sortable' => true, + 'width' => 70 ), 'created_at' ); @@ -614,7 +643,14 @@ public function addColumnToSalesOrderGridCollection(Varien_Event_Observer $obser } $adapter = $this->getCoreResource()->getConnection('core_write'); - $select->joinLeft(array('mc' => $collection->getTable('mailchimp/ecommercesyncdata')), $adapter->quoteInto('mc.related_id=main_table.entity_id AND type = ?', Ebizmarts_MailChimp_Model_Config::IS_ORDER), array('mc.mailchimp_synced_flag', 'mc.id')); + $select->joinLeft( + array('mc' => $collection->getTable('mailchimp/ecommercesyncdata')), + $adapter->quoteInto( + 'mc.related_id=main_table.entity_id AND type = ?', + Ebizmarts_MailChimp_Model_Config::IS_ORDER + ), + array('mc.mailchimp_synced_flag', 'mc.id') + ); $select->group("main_table.entity_id"); $direction = $this->getRegistry(); if ($direction) { @@ -675,7 +711,7 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) /** * Set the products included in the credit memo to be updated on MailChimp on the next cron job run. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer */ public function newCreditMemo(Varien_Event_Observer $observer) @@ -699,7 +735,11 @@ public function newCreditMemo(Varien_Event_Observer $observer) } $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $dataProduct = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); if (!$isMarkedAsDeleted) { $apiProduct->update($productId, $mailchimpStoreId); @@ -715,7 +755,7 @@ public function newCreditMemo(Varien_Event_Observer $observer) /** * Set the products included in the credit memo to be updated on MailChimp on the next cron job run. * - * @param Varien_Event_Observer $observer + * @param Varien_Event_Observer $observer * @return Varien_Event_Observer */ public function cancelCreditMemo(Varien_Event_Observer $observer) @@ -738,7 +778,11 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) } $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $dataProduct = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); if (!$isMarkedAsDeleted) { $apiProduct->update($productId, $mailchimpStoreId); @@ -770,7 +814,11 @@ public function itemCancel(Varien_Event_Observer $observer) $mailchimpStoreId = $helper->getMCStoreId($storeId); $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $dataProduct = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); if (!$this->isBundleItem($item) && !$this->isConfigurableItem($item) && !$isMarkedAsDeleted) { $apiProduct->update($productId, $mailchimpStoreId); @@ -801,10 +849,16 @@ public function productSaveAfter(Varien_Event_Observer $observer) $status = $this->getCatalogProductStatusModel()->getProductStatus($product->getId(), $storeId); if ($status[$product->getId()] == self::PRODUCT_IS_ENABLED) { - $dataProduct = $helper->getEcommerceSyncDataItem($product->getId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $dataProduct = $helper->getEcommerceSyncDataItem( + $product->getId(), + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); $errorMessage = $dataProduct->getMailchimpSyncError(); - if ($isMarkedAsDeleted || $errorMessage == Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO) { + if ($isMarkedAsDeleted + || $errorMessage == Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO + ) { $dataProduct->delete(); } else { $apiProduct->update($product->getId(), $mailchimpStoreId); @@ -835,7 +889,11 @@ public function productAttributeUpdate(Varien_Event_Observer $observer) if ($ecommEnabled) { foreach ($productIds as $productId) { - $dataProduct = $helper->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + $dataProduct = $helper->getEcommerceSyncDataItem( + $productId, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $mailchimpStoreId + ); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); if (!$isMarkedAsDeleted) { $apiProduct->update($productId, $mailchimpStoreId); @@ -938,7 +996,9 @@ public function cleanProductImagesCacheAfter(Varien_Event_Observer $observer) protected function markProductsAsModified() { $tableName = $mailchimpTableName = $this->getCoreResource()->getTableName('mailchimp/ecommercesyncdata'); - $sqlQuery = "UPDATE " . $tableName . " SET mailchimp_sync_modified = 1 WHERE type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . "';"; + $sqlQuery = "UPDATE " . $tableName . " " + . "SET mailchimp_sync_modified = 1 " + . "WHERE type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . "';"; $connection = $this->getCoreResource()->getConnection('core_write'); $connection->query($sqlQuery); } @@ -964,7 +1024,7 @@ protected function isConfigurableItem($item) /** * Transform array in format scope_scopeId to array. * - * @param $scopeData + * @param $scopeData * @return array */ protected function getScopeArrayFromString($scopeData) @@ -995,11 +1055,13 @@ protected function addSuccessIfRequired($helper) { $request = Mage::app()->getRequest(); $module = $request->getControllerModule(); - $module_controller = $request->getControllerName(); - $module_controller_action = $request->getActionName(); - $fullActionName = $module . '_' . $module_controller . '_' . $module_controller_action; + $moduleController = $request->getControllerName(); + $moduleControllerAction = $request->getActionName(); + $fullActionName = $module . '_' . $moduleController . '_' . $moduleControllerAction; if (strstr($fullActionName, 'Mage_Newsletter_manage_save')) { - Mage::getSingleton('customer/session')->addSuccess($helper->__('Confirmation request has been sent.')); + Mage::getSingleton('customer/session')->addSuccess( + $helper->__('Confirmation request has been sent.') + ); } } @@ -1036,12 +1098,15 @@ public function addCustomerTab(Varien_Event_Observer $observer) $storeId = $customer->getMailchimpStoreView(); } - if ($helper->getLocalInterestCategories($storeId) && ($this->getRequest()->getActionName() == 'edit' || $this->getRequest()->getParam('type'))) { + if ($helper->getLocalInterestCategories($storeId) + && ($this->getRequest()->getActionName() == 'edit' + || $this->getRequest()->getParam('type')) + ) { $block->addTab( 'mailchimp', array( - 'label' => $helper->__('MailChimp'), - 'url' => $block->getUrl('adminhtml/mailchimp/index', array('_current' => true)), - 'class' => 'ajax' + 'label' => $helper->__('MailChimp'), + 'url' => $block->getUrl('adminhtml/mailchimp/index', array('_current' => true)), + 'class' => 'ajax' ) ); } @@ -1058,10 +1123,10 @@ protected function getRequest() /** * Handle frontend customer interest groups only if is not subscribed and all admin customer groups. * - * @param $subscriberEmail - * @param $params - * @param $storeId - * @param null $customerId + * @param $subscriberEmail + * @param $params + * @param $storeId + * @param null $customerId * @return Mage_Newsletter_Model_Subscriber * @throws Mage_Core_Model_Store_Exception */ @@ -1126,7 +1191,9 @@ protected function getRequestActionName() */ protected function getWarningMessageAdminHtmlSession($helper) { - return Mage::getSingleton('adminhtml/session')->addWarning($helper->__('The customer must be subscribed for this change to apply.')); + return Mage::getSingleton('adminhtml/session')->addWarning( + $helper->__('The customer must be subscribed for this change to apply.') + ); } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index a6adc577f..f4f95f02a 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -16,7 +16,7 @@ class Ebizmarts_MailChimp_Model_ProcessWebhook /** * @var Ebizmarts_MailChimp_Helper_Data */ - private $helper; + protected $_helper; /** * Webhooks request url path * @@ -27,7 +27,7 @@ class Ebizmarts_MailChimp_Model_ProcessWebhook public function __construct() { - $this->helper = Mage::helper('mailchimp'); + $this->_helper = Mage::helper('mailchimp'); } /** @@ -35,7 +35,7 @@ public function __construct() */ protected function getHelper() { - return $this->helper; + return $this->_helper; } public function saveWebhookRequest(array $data) @@ -43,7 +43,7 @@ public function saveWebhookRequest(array $data) Mage::getModel('mailchimp/webhookrequest') ->setType($data['type']) ->setFiredAt($data['fired_at']) - ->setDataRequest(serialize($data['data'])) + ->setDataRequest($this->_helper->serialize($data['data'])) ->save(); } @@ -57,28 +57,30 @@ public function processWebhookData() $collection = Mage::getModel('mailchimp/webhookrequest')->getCollection(); $collection->addFieldToFilter('processed', array('eq' => 0)); $collection->getSelect()->limit(self::BATCH_LIMIT); + foreach ($collection as $webhookRequest) { - $data = unserialize($webhookRequest->getDataRequest()); + $data = $this->_helper->unserialize($webhookRequest->getDataRequest()); + if ($data) { switch ($webhookRequest->getType()) { - case 'subscribe': - $this->_subscribe($data); - break; - case 'unsubscribe': - $this->_unsubscribe($data); - break; - case 'cleaned': - $this->_clean($data); - break; - case 'upemail': - $this->_updateEmail($data); - break; - case 'profile': - $this->_profile($data); + case 'subscribe': + $this->_subscribe($data); + break; + case 'unsubscribe': + $this->_unsubscribe($data); + break; + case 'cleaned': + $this->_clean($data); + break; + case 'upemail': + $this->_updateEmail($data); + break; + case 'profile': + $this->_profile($data); } } - $webhookRequest->setProcessed(1) - ->save(); + + $webhookRequest->setProcessed(1)->save(); } } @@ -160,6 +162,7 @@ protected function _subscribe(array $data) $subscriberLname = filter_var($data['merges']['LNAME'], FILTER_SANITIZE_STRING); $subscriber->setSubscriberLastname($subscriberLname); } + $helper->subscribeMember($subscriber); } } @@ -181,20 +184,27 @@ protected function _unsubscribe(array $data) if ($subscriber && $subscriber->getId()) { try { $action = isset($data['action']) ? $data['action'] : 'delete'; + $subscriberStatus = $subscriber->getSubscriberStatus(); + $statusUnsubscribed = Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED; + switch ($action) { - case 'delete': - //if config setting "Webhooks Delete action" is set as "Delete customer account" - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_UNSUBSCRIBE, $subscriber->getStoreId())) { - $subscriber->delete(); - } elseif ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { - $helper->unsubscribeMember($subscriber); - } - break; - case 'unsub': - if ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { - $helper->unsubscribeMember($subscriber); - } - break; + case 'delete': + //if config setting "Webhooks Delete action" is set as "Delete customer account" + + if (Mage::getStoreConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_UNSUBSCRIBE, $subscriber->getStoreId() + ) + ) { + $subscriber->delete(); + } elseif ($subscriberStatus != $statusUnsubscribed) { + $helper->unsubscribeMember($subscriber); + } + break; + case 'unsub': + if ($subscriberStatus != $statusUnsubscribed) { + $helper->unsubscribeMember($subscriber); + } + break; } } catch (Exception $e) { Mage::logException($e); @@ -202,6 +212,10 @@ protected function _unsubscribe(array $data) } } + /** + * @param array $data + * @throws Mage_Core_Exception + */ public function _profile(array $data) { $helper = $this->getHelper(); @@ -216,10 +230,12 @@ public function _profile(array $data) $customer->setFirstname($fname); $saveRequired = true; } + if ($lname && $lname !== $customer->getLastname()) { $customer->setLastname($lname); $saveRequired = true; } + if ($saveRequired) { $customer->save(); } @@ -231,10 +247,12 @@ public function _profile(array $data) $subscriber->setSubscriberFirstname($fname); $saveRequired = true; } + if ($lname && $lname !== $subscriber->getSubscriberLastname()) { $subscriber->setSubscriberLastname($lname); $saveRequired = true; } + if ($saveRequired) { $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE); $subscriber->save(); @@ -244,27 +262,49 @@ public function _profile(array $data) * Mailchimp subscriber not currently in magento newsletter subscribers. * Get mailchimp subscriber status and add missing newsletter subscriber. */ - $scopeArray = $helper->getFirstScopeFromConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $listId); - $api = $helper->getApi($scopeArray['scope_id'], $scopeArray['scope']); - try { - $subscriber->setSubscriberFirstname($fname); - $subscriber->setSubscriberLastname($lname); - $md5HashEmail = md5(strtolower($email)); - $member = $api->getLists()->getMembers()->get($listId, $md5HashEmail, null, null); - if ($member['status'] == 'subscribed') { - $helper->subscribeMember($subscriber); - } elseif ($member['status'] == 'unsubscribed') { - if (!$helper->getWebhookDeleteAction($subscriber->getStoreId())) { - $helper->unsubscribeMember($subscriber); - } - } - } catch (MailChimp_Error $e) { - $helper->logError($e->getFriendlyMessage()); - } catch (Exception $e) { - $helper->logError($e->getMessage()); - } + $this->_addSubscriberData($subscriber, $fname, $lname, $email, $listId); + } + } + } + } + + /** + * @param $subscriber + * @param $fname + * @param $lname + * @param $email + * @param $listId + * @throws Exception + */ + protected function _addSubscriberData($subscriber, $fname, $lname, $email, $listId) + { + $helper = $this->getHelper(); + $scopeArray = $helper->getFirstScopeFromConfig( + Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, + $listId + ); + $api = $helper->getApi($scopeArray['scope_id'], $scopeArray['scope']); + try { + $subscriber->setSubscriberFirstname($fname); + $subscriber->setSubscriberLastname($lname); + $md5HashEmail = md5(strtolower($email)); + $member = $api->getLists()->getMembers()->get( + $listId, + $md5HashEmail, + null, + null + ); + if ($member['status'] == 'subscribed') { + $helper->subscribeMember($subscriber); + } elseif ($member['status'] == 'unsubscribed') { + if (!$helper->getWebhookDeleteAction($subscriber->getStoreId())) { + $helper->unsubscribeMember($subscriber); } } + } catch (MailChimp_Error $e) { + $helper->logError($e->getFriendlyMessage()); + } catch (Exception $e) { + $helper->logError($e->getMessage()); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php b/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php index 26c69186b..3cba28cdd 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php @@ -11,33 +11,52 @@ class Ebizmarts_MailChimp_Model_Subscriber extends Mage_Newsletter_Model_Subscri const MAILCHIMP_SUBSCRIBE = 'MailChimp'; const SUBSCRIBE_CONFIRMATION = 'MailChimp_Confirmation'; + /** + * @return $this|Mage_Newsletter_Model_Subscriber + */ public function sendUnsubscriptionEmail() { - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1) { + if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) + && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1 + ) { return $this; } else { return parent::sendUnsubscriptionEmail(); } } + /** + * @return $this|Mage_Newsletter_Model_Subscriber + */ public function sendConfirmationRequestEmail() { - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1) { + if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) + && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1 + ) { return $this; } else { return parent::sendConfirmationRequestEmail(); } } + /** + * @return $this|Mage_Newsletter_Model_Subscriber + */ public function sendConfirmationSuccessEmail() { - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1) { + if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) + && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1 + ) { return $this; } else { return parent::sendConfirmationSuccessEmail(); } } + /** + * @param string $code + * @return bool + */ public function confirm($code) { if ($this->getCode()==$code) { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php index 723600f61..c69624bc0 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php @@ -20,7 +20,9 @@ protected function _afterSave() $scope = $this->getScope(); $groups = $this->getData('groups'); - $apiKey = (isset($groups['general']['fields']['apikey']['value'])) ? $groups['general']['fields']['apikey']['value'] : $helper->getApiKey($scopeId, $scope); + $apiKey = (isset($groups['general']['fields']['apikey']['value'])) + ? $groups['general']['fields']['apikey']['value'] + : $helper->getApiKey($scopeId, $scope); //If settings are inherited get from config. if (isset($groups['general']['fields']['list']) && isset($groups['general']['fields']['list']['value'])) { $listId = $groups['general']['fields']['list']['value']; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Apikey.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Apikey.php index 9b774fdf0..a58562d46 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Apikey.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Apikey.php @@ -22,7 +22,9 @@ protected function _afterSave() if ($valueChanged && !$this->getValue()) { $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE, false)); $helper->saveMailchimpConfig($configValue, $scopeId, $scope); - $message = $helper->__('Please note the extension has been disabled due to the lack of an api key or audience configured.'); + $message = $helper->__( + 'Please note the extension has been disabled due to the lack of an api key or audience configured.' + ); $this->getAdminSession()->addWarning($message); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Ecommerce.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Ecommerce.php index 2765830bf..ce574a104 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Ecommerce.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Ecommerce.php @@ -19,8 +19,12 @@ protected function _afterSave() $helper = $this->makeHelper(); $groups = $this->getData('groups'); //If settings are inherited get from config. - $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : $helper->isMailChimpEnabled($this->getScopeId(), $this->getScope()); - $apiKey = (isset($groups['general']['fields']['apikey']['value'])) ? $groups['general']['fields']['apikey']['value'] : $helper->getApiKey($this->getScopeId(), $this->getScope()); + $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) + ? $groups['general']['fields']['active']['value'] + : $helper->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + $apiKey = (isset($groups['general']['fields']['apikey']['value'])) + ? $groups['general']['fields']['apikey']['value'] + : $helper->getApiKey($this->getScopeId(), $this->getScope()); if (isset($groups['general']['fields']['list']) && isset($groups['general']['fields']['list']['value'])) { $listId = $groups['general']['fields']['list']['value']; } else { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/List.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/List.php index 7cd7beb2e..3ebcc265f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/List.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/List.php @@ -16,23 +16,39 @@ protected function _afterSave() { $groups = $this->getData('groups'); $helper = $this->getMailchimpHelper(); + $dateHelper = $this->getMailchimpDateHelper(); $scopeId = $this->getScopeId(); $scope = $this->getScope(); $valueChanged = $this->isValueChanged(); - $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : $helper->isMailChimpEnabled($scopeId, $scope); - $apiKey = (isset($groups['general']['fields']['apikey']['value'])) ? $groups['general']['fields']['apikey']['value'] : $helper->getApiKey($scopeId, $scope); - $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $scopeId, $scope); + $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) + ? $groups['general']['fields']['active']['value'] + : $helper->isMailChimpEnabled($scopeId, $scope); + $apiKey = (isset($groups['general']['fields']['apikey']['value'])) + ? $groups['general']['fields']['apikey']['value'] + : $helper->getApiKey($scopeId, $scope); + $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope( + Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, + $scopeId, + $scope + ); if ($valueChanged && !$this->getValue()) { $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE, false)); $helper->saveMailchimpConfig($configValue, $scopeId, $scope); - $message = $helper->__('Please note the extension has been disabled due to the lack of an api key or audience configured.'); + $message = $helper->__( + 'Please note the extension has been disabled due to the lack of an api key or audience configured.' + ); $this->getAdminSession()->addWarning($message); } if ($valueChanged && ($moduleIsActive || $thisScopeHasSubMinSyncDateFlag) && $this->getValue()) { - $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, Varien_Date::now())); + $configValues = array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, + $dateHelper->formatDate(null, "Y-m-d H:i:s") + ) + ); $helper->saveMailchimpConfig($configValues, $scopeId, $scope); } @@ -49,6 +65,14 @@ protected function getMailchimpHelper() return Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getMailchimpDateHelper() + { + return Mage::helper('mailchimp/date'); + } + /** * @return Mage_Adminhtml_Model_Session */ diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Mapfield.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Mapfield.php index 1e89f74ee..f5a38b3d6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Mapfield.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Mapfield.php @@ -10,10 +10,18 @@ * @date: 8/4/16 5:56 PM * @file: Apikey.php */ -class Ebizmarts_MailChimp_Model_System_Config_Backend_Mapfield extends Mage_Adminhtml_Model_System_Config_Backend_Serialized_Array +class Ebizmarts_MailChimp_Model_System_Config_Backend_Mapfield + extends Mage_Adminhtml_Model_System_Config_Backend_Serialized_Array { + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $_helper; + protected function _afterLoad() { + $this->_helper = Mage::helper('mailchimp'); + if (!is_array($this->getValue())) { if (is_object($this->getValue())) { $serializedValue = $this->getValue()->asArray(); @@ -22,9 +30,10 @@ protected function _afterLoad() } $unserializedValue = false; + if (!empty($serializedValue)) { try { - $unserializedValue = unserialize($serializedValue); + $unserializedValue = $this->_helper->unserialize($serializedValue); } catch (Exception $e) { Mage::logException($e); } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php index 29823831b..d1b1d215a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php @@ -16,23 +16,39 @@ class Ebizmarts_MailChimp_Model_System_Config_Backend_Store extends Mage_Core_Mo protected function _afterSave() { $helper = $this->makeHelper(); + $dateHelper = $this->makeDateHelper(); $scopeId = $this->getScopeId(); $scope = $this->getScope(); $groups = $this->getData('groups'); - $newMailchimpStoreId = (isset($groups['general']['fields']['storeid']['value'])) ? $groups['general']['fields']['storeid']['value'] : null; + $newMailchimpStoreId = (isset($groups['general']['fields']['storeid']['value'])) + ? $groups['general']['fields']['storeid']['value'] + : null; $oldMailchimpStoreId = $helper->getMCStoreId($scopeId, $scope); $isSyncing = $helper->getMCIsSyncing($newMailchimpStoreId, $scopeId, $scope); $ecommMinSyncDate = $helper->getEcommMinSyncDateFlag($newMailchimpStoreId, $scopeId, $scope); + $helper->cancelAllPendingBatches($oldMailchimpStoreId); + $helper->restoreAllCanceledBatches($newMailchimpStoreId); if ($this->isValueChanged() && $this->getValue()) { $helper->deletePreviousConfiguredMCStoreLocalData($oldMailchimpStoreId, $scopeId, $scope); if ($ecommMinSyncDate === null) { - $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG."_$newMailchimpStoreId", Varien_Date::now())); + $configValues = array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG."_$newMailchimpStoreId", + $dateHelper->formatDate(null, "Y-m-d H:i:s") + ) + ); $helper->saveMailchimpConfig($configValues, 0, 'default'); } + if ($isSyncing === null) { - $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$newMailchimpStoreId", true)); + $configValues = array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$newMailchimpStoreId", + true + ) + ); $helper->saveMailchimpConfig($configValues, $scopeId, $scope); } } @@ -46,6 +62,14 @@ protected function makeHelper() return Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function makeDateHelper() + { + return Mage::helper('mailchimp/date'); + } + /** * @return Mage_Adminhtml_Model_Session */ diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php index aa26d6ebd..67debe300 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php @@ -17,8 +17,12 @@ protected function _afterSave() { $helper = $this->makeHelper(); $groups = $this->getData('groups'); - $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : $helper->isMailChimpEnabled($this->getScopeId(), $this->getScope()); - $apiKey = (isset($groups['general']['fields']['apikey']['value'])) ? $groups['general']['fields']['apikey']['value'] : $helper->getApiKey($this->getScopeId(), $this->getScope()); + $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) + ? $groups['general']['fields']['active']['value'] + : $helper->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + $apiKey = (isset($groups['general']['fields']['apikey']['value'])) + ? $groups['general']['fields']['apikey']['value'] + : $helper->getApiKey($this->getScopeId(), $this->getScope()); $listId = $helper->getGeneralList($this->getScopeId(), $this->getScope()); if ($apiKey && $moduleIsActive && $listId && $this->isValueChanged()) { $helper->handleWebhookChange($this->getScopeId(), $this->getScope()); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Account.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Account.php index cfd745f9e..813f1978b 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Account.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Account.php @@ -24,7 +24,7 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Account /** * @var Ebizmarts_MailChimp_Helper_Data */ - protected $helper; + protected $_helper; const USERNAME_KEY = 0; const TOTAL_ACCOUNT_SUB_KEY = 1; @@ -48,35 +48,47 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Account /** * Ebizmarts_MailChimp_Model_System_Config_Source_Account constructor. - * @param $params + * + * @param $params * @throws Exception */ public function __construct($params) { $mcStore = null; - $helper = $this->helper = $this->makeHelper(); + $helper = $this->_helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); - $apiKey = (empty($params)) ? $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']) : $params['api_key']; + $apiKey = (empty($params)) + ? $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']) + : $params['api_key']; if ($apiKey) { try { $api = $helper->getApiByKey($apiKey); try { $this->_accountDetails = $api->getRoot()->info('account_name,total_subscribers'); - $mcStoreId = (empty($params)) ? $helper->getMCStoreId($scopeArray['scope_id'], $scopeArray['scope']) : $params['mailchimp_store_id']; + $mcStoreId = (empty($params)) + ? $helper->getMCStoreId($scopeArray['scope_id'], $scopeArray['scope']) + : $params['mailchimp_store_id']; try { - $mcStore = (!empty($mcStoreId)) ? $api->getEcommerce()->getStores()->get($mcStoreId, 'list_id,name,is_syncing') : array(); + $mcStore = (!empty($mcStoreId)) + ? $api->getEcommerce()->getStores()->get($mcStoreId, 'list_id,name,is_syncing') + : array(); if (empty($mcStore)) { $this->_accountDetails['store_exists'] = false; } } catch (MailChimp_Error $e) { if ($helper->isEcomSyncDataEnabled($scopeArray['scope_id'], $scopeArray['scope'])) { - $message = $helper->__('Looks like your Mailchimp store was deleted. Please create a new one and associate it in order to get your Ecommerce data synced.'); + $message = $helper->__( + 'Looks like your Mailchimp store was deleted. Please create a new one and associate ' + . 'it in order to get your Ecommerce data synced.' + ); Mage::getSingleton('adminhtml/session')->addWarning($message); } + $this->_accountDetails['store_exists'] = false; } + try { $listId = (isset($mcStore['list_id']) && $mcStore['list_id']) ? $mcStore['list_id'] : null; @@ -125,7 +137,7 @@ public function __construct($params) */ public function toOptionArray() { - $helper = $this->helper; + $helper = $this->_helper; $scopeArray = $helper->getCurrentScope(); if (is_array($this->_accountDetails)) { $totalAccountSubscribersText = $helper->__('Total Account Subscribers:'); @@ -135,6 +147,7 @@ public function toOptionArray() $totalListSubscribersText = $helper->__('Total Audience Subscribers:'); $totalListSubscribers = $totalListSubscribersText . ' ' . $this->_accountDetails['list_subscribers']; } + $username = $helper->__('Username:') . ' ' . $this->_accountDetails['account_name']; $returnArray = array( array('value' => self::USERNAME_KEY, 'label' => $username), @@ -143,6 +156,7 @@ public function toOptionArray() if ($totalListSubscribers) { $returnArray[] = array('value' => self::TOTAL_LIST_SUB_KEY, 'label' => $totalListSubscribers); } + if ($this->_accountDetails['store_exists']) { $totalCustomersText = $helper->__(' Total Customers:'); $totalCustomers = $totalCustomersText . ' ' . $this->_accountDetails['total_customers']; @@ -152,8 +166,13 @@ public function toOptionArray() $totalOrders = $totalOrdersText . ' ' . $this->_accountDetails['total_orders']; $totalCartsText = $helper->__(' Total Carts:'); $totalCarts = $totalCartsText . ' ' . $this->_accountDetails['total_carts']; - $title = $helper->__('Ecommerce Data uploaded to Mailchimp store ') . $this->_accountDetails['store_name'] . ':'; - if ($this->_accountDetails['store_sync_flag'] && !$this->_accountDetails['store_sync_date'] && !$helper->getResendEnabled($scopeArray['scope_id'], $scopeArray['scope'])) { + $title = $helper->__('Ecommerce Data uploaded to Mailchimp store ') + . $this->_accountDetails['store_name'] + . ':'; + if ($this->_accountDetails['store_sync_flag'] + && !$this->_accountDetails['store_sync_date'] + && !$helper->getResendEnabled($scopeArray['scope_id'], $scopeArray['scope']) + ) { $syncValue = self::IN_PROGRESS; } else { $syncData = $this->_accountDetails['store_sync_date']; @@ -163,6 +182,7 @@ public function toOptionArray() $syncValue = self::FINISHED; } } + $syncLabel = $helper->__('Initial sync') . ': ' . $syncValue; $returnArray = array_merge( $returnArray, @@ -176,7 +196,10 @@ public function toOptionArray() ) ); } elseif ($helper->isEcomSyncDataEnabled($scopeArray['scope_id'], $scopeArray['scope'], true)) { - $noStoreText = $helper->__('No MailChimp store was configured for this scope, parent scopes might be sending data for this store anyways.'); + $noStoreText = $helper->__( + 'No MailChimp store was configured for this scope, parent scopes might be ' + . 'sending data for this store anyways.' + ); $returnArray = array_merge( $returnArray, array( @@ -185,8 +208,13 @@ public function toOptionArray() ); } - if (!$helper->migrationFinished() && $helper->isEcommerceEnabled($scopeArray['scope_id'], $scopeArray['scope'])) { - $storeMigrationText = $helper->__('The store data is currently being migrated to the new version. This process might take a while depending on the amount of data in Magento.'); + if (!$helper->migrationFinished() + && $helper->isEcommerceEnabled($scopeArray['scope_id'], $scopeArray['scope']) + ) { + $storeMigrationText = $helper->__( + 'The store data is currently being migrated to the new version. This process ' + . 'might take a while depending on the amount of data in Magento.' + ); $returnArray = array_merge( $returnArray, array( @@ -211,9 +239,18 @@ protected function makeHelper() return Mage::helper('mailchimp'); } + /** + * @param $mailchimpStoreId + * @return string + * @throws Mage_Core_Exception + */ protected function getDateSync($mailchimpStoreId) { - $date = $this->makeHelper()->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", 0, 'default'); + $date = $this->makeHelper()->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", + 0, + 'default' + ); return $date; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php index fc73bda1a..d1602b0e4 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php @@ -2,10 +2,10 @@ /** * Cron Process available count limits options source * - * @category Ebizmarts - * @package Ebizmarts_MageMonkey - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MageMonkey + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Model_System_Config_Source_BatchLimit { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php index 65bb4b398..022ba50be 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php @@ -3,10 +3,10 @@ /** * Checkout subscribe available status options source * - * @category Ebizmarts - * @package Ebizmarts_MailChimp - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MailChimp + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ConnectionTimeout.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ConnectionTimeout.php index 1b10dd2c7..c6a1c3fd6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ConnectionTimeout.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ConnectionTimeout.php @@ -2,10 +2,10 @@ /** * Cron Process available count limits options source * - * @category Ebizmarts - * @package Ebizmarts_MageMonkey - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MageMonkey + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Model_System_Config_Source_ConnectionTimeout { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php index b1189cb15..23b55b356 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php @@ -14,16 +14,19 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_CustomerGroup /** * Ebizmarts_MailChimp_Model_System_Config_Source_CustomerGroup constructor. * - * Ebizmarts_MailChimp_Model_System_Config_Source_CustomerGroup constructor. - * @param $params + * @param $params * @throws Mage_Core_Exception */ public function __construct($params) { $helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); - $apiKey = (!empty($params)) ? $params['api_key'] : $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); - $listId = (!empty($params)) ? $params['list_id'] : $helper->getGeneralList($scopeArray['scope_id'], $scopeArray['scope']); + $apiKey = (!empty($params)) + ? $params['api_key'] + : $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); + $listId = (!empty($params)) + ? $params['list_id'] + : $helper->getGeneralList($scopeArray['scope_id'], $scopeArray['scope']); if (!empty($apiKey) && !empty($listId)) { $this->_categories = $helper->getListInterestCategoriesByKeyAndList($apiKey, $listId); @@ -46,6 +49,7 @@ public function toOptionArray() } else { $groups[] = array('value' => '', 'label' => $helper->__('--- No data ---')); } + return $groups; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php index 98da5f791..fb924a52d 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php @@ -2,10 +2,10 @@ /** * Cron Process available count limits options source * - * @category Ebizmarts - * @package Ebizmarts_MailChimp - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MailChimp + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Model_System_Config_Source_ImageSize { @@ -14,7 +14,6 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_ImageSize const THUMBNAIL = 2; const ORIGINAL = 3; - /** * Options getter * diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/List.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/List.php index e844568fa..c60f2703f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/List.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/List.php @@ -29,7 +29,8 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_List /** * Ebizmarts_MailChimp_Model_System_Config_Source_List constructor. - * @param $params + * + * @param $params * @throws Exception */ public function __construct($params) @@ -37,20 +38,24 @@ public function __construct($params) $helper = $this->_helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); if (empty($this->_lists)) { - $apiKey = (empty($params)) ? $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']) : $params['api_key']; + $apiKey = (empty($params)) + ? $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']) + : $params['api_key']; if ($apiKey) { try { $api = $helper->getApiByKey($apiKey); //Add filter to only show the lists for the selected store when MC store selected. - $mcStoreId = (!empty($params)) ? $params['mailchimp_store_id'] : $helper->getMCStoreId($scopeArray['scope_id'], $scopeArray['scope']); + $mcStoreId = (!empty($params)) + ? $params['mailchimp_store_id'] + : $helper->getMCStoreId($scopeArray['scope_id'], $scopeArray['scope']); if ($mcStoreId !== '' && $mcStoreId !== null) { $listId = $helper->getListIdByApiKeyAndMCStoreId($apiKey, $mcStoreId); if ($listId !== false) { $this->_lists['lists'][0] = $api->getLists()->getLists($listId); } } else { - $this->_lists = $api->getLists()->getLists(null, 'lists', null, 100); + $this->_lists = $api->getLists()->getLists(null, 'lists'); } if (isset($this->_lists['lists']) && count($this->_lists['lists']) == 0) { @@ -83,6 +88,7 @@ public function toOptionArray() if (count($mcLists['lists']) > 1) { $lists[] = array('value' => '', 'label' => $helper->__('--- Select a Mailchimp Audience ---')); } + foreach ($mcLists['lists'] as $list) { $memberCount = $list['stats']['member_count']; $memberText = $helper->__('members'); @@ -92,6 +98,7 @@ public function toOptionArray() } else { $lists[] = array('value' => '', 'label' => $helper->__('--- No data ---')); } + return $lists; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Log.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Log.php index 6f04cc4c9..099b05a68 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Log.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Log.php @@ -2,10 +2,10 @@ /** * Cron Process available count limits options source * - * @category Ebizmarts - * @package Ebizmarts_MailChimp - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MailChimp + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Model_System_Config_Source_Log { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/MailchimpStoreView.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/MailchimpStoreView.php index 52726a8fb..5e4aca985 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/MailchimpStoreView.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/MailchimpStoreView.php @@ -2,12 +2,13 @@ /** * Cron Process available count limits options source * - * @category Ebizmarts - * @package Ebizmarts_MailChimp - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MailChimp + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ -class Ebizmarts_MailChimp_Model_System_Config_Source_MailchimpStoreView extends Mage_Eav_Model_Entity_Attribute_Source_Abstract +class Ebizmarts_MailChimp_Model_System_Config_Source_MailchimpStoreView + extends Mage_Eav_Model_Entity_Attribute_Source_Abstract { public function getAllOptions() diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php index b804a738c..96a7699b3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php @@ -2,10 +2,10 @@ /** * Cron Process available count limits options source * - * @category Ebizmarts - * @package Ebizmarts_MailChimp - * @author Ebizmarts Team - * @license http://opensource.org/licenses/osl-3.0.php + * @category Ebizmarts + * @package Ebizmarts_MailChimp + * @author Ebizmarts Team + * @license http://opensource.org/licenses/osl-3.0.php */ class Ebizmarts_MailChimp_Model_System_Config_Source_OrderGrid { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php index ed9d60fc8..5f1cca3e3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php @@ -23,7 +23,8 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Store /** * Ebizmarts_MailChimp_Model_System_Config_Source_Store constructor. - * @param $params + * + * @param $params * @throws Exception */ public function __construct($params) @@ -31,7 +32,9 @@ public function __construct($params) $helper = $this->_helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); if (empty($this->_stores)) { - $apiKey = (empty($params)) ? $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']) : $params['api_key']; + $apiKey = (empty($params)) + ? $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']) + : $params['api_key']; if ($apiKey) { try { @@ -58,6 +61,7 @@ public function toOptionArray() if ($store['list_id']=='') { continue; } + if (isset($store['connected_site'])) { $label = $store['name']; } else { @@ -70,6 +74,7 @@ public function toOptionArray() } else { $stores[] = array('value' => '', 'label' => $helper->__('--- No data ---')); } + return $stores; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php index 0cc010c42..9151d5994 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php @@ -16,7 +16,7 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Userinfo * @access protected * @var bool|array */ - protected $_account_details = "--- Enter your API KEY first ---"; + protected $_accountDetails = "--- Enter your API KEY first ---"; /** * Set AccountDetails on class attribute if not already set @@ -37,12 +37,15 @@ public function __construct() } } - if ((!is_array($this->_account_details) || isset($this->_account_details['status'])) && $mandillHelper->getMandrillApiKey($storeId)) { + if ((!is_array($this->_accountDetails) + || isset($this->_accountDetails['status'])) + && $mandillHelper->getMandrillApiKey($storeId) + ) { $api = new Mandrill_Message($mandillHelper->getMandrillApiKey($storeId)); try { - $this->_account_details = $api->users->info(); + $this->_accountDetails = $api->users->info(); } catch (Exception $e) { - $this->_account_details = "--- Invalid API key ---"; + $this->_accountDetails = "--- Invalid API key ---"; } } } @@ -55,22 +58,49 @@ public function __construct() public function toOptionArray() { $helper = Mage::helper('mailchimp'); - if (is_array($this->_account_details)) { - if (!isset($this->_account_details['status'])) { + if (is_array($this->_accountDetails)) { + if (!isset($this->_accountDetails['status'])) { return array( - array('value' => 0, 'label' => $helper->__("Username: %s %s", $this->_account_details["username"], "used for SMTP authentication")), - - array('value' => 1, 'label' => $helper->__('Reputation: %s %s', $this->_account_details['reputation'], "scale from 0 to 100, with 75 generally being a \"good\" reputation")), - - array('value' => 2, 'label' => $helper->__('Hourly Quota: %s %s', $this->_account_details['hourly_quota'], "the maximum number of emails Mandrill will deliver for this user each hour. Any emails beyond that will be accepted and queued for later delivery. Users with higher reputations will have higher hourly quotas")), - - array('value' => 3, 'label' => $helper->__('Backlog: %s %s', $this->_account_details['backlog'], "the number of emails that are queued for delivery due to exceeding your monthly or hourly quotas")) + array( + 'value' => 0, + 'label' => $helper->__( + "Username: %s %s", + $this->_accountDetails["username"], + "used for SMTP authentication" + ) + ), + array( + 'value' => 1, + 'label' => $helper->__( + 'Reputation: %s %s', + $this->_accountDetails['reputation'], + "scale from 0 to 100, with 75 generally being a \"good\" reputation" + ) + ), + array( + 'value' => 2, + 'label' => $helper->__( + 'Hourly Quota: %s %s', + $this->_accountDetails['hourly_quota'], + "the maximum number of emails Mandrill will deliver for this user each hour. " + . "Any emails beyond that will be accepted and queued for later delivery. " + . "Users with higher reputations will have higher hourly quotas" + ) + ), + array( + 'value' => 3, + 'label' => $helper->__( + 'Backlog: %s %s', + $this->_accountDetails['backlog'], + "the number of emails that are queued for delivery due to exceeding " + . "your monthly or hourly quotas" + )) ); } else { return array(array('value' => '', 'label' => $helper->__('--- Invalid API KEY ---'))); } } else { - return array(array('value' => '', 'label' => $helper->__($this->_account_details))); + return array(array('value' => '', 'label' => $helper->__($this->_accountDetails))); } } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php index 10730185a..349298e3d 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php @@ -33,6 +33,7 @@ public function resetLocalErrorsAction() $helper->resetErrors($store->getId()); } } + $helper->resetErrors($scopeId, $scope); } catch (Exception $e) { $helper->logError($e->getMessage()); @@ -48,18 +49,21 @@ public function resendEcommerceDataAction() $mageApp = $helper->getMageApp(); $request = $this->getRequest(); $filters = $request->getParam('filter'); - $scopeArray = $helper->getCurrentScope(); - $success = 0; + $scope = $request->getParam('scope'); + $scopeId = $request->getParam('scope_id'); + $success = 0; if (is_array($filters) && empty($filters)) { $this->addWarning($helper->__('At least one type of eCommerce data should be selected to Resend.')); - $success = $helper->__('Redirecting... ') . ''; + $success = $helper->__('Redirecting... ') + . ''; } else { try { - $helper->resendMCEcommerceData($scopeArray['scope_id'], $scopeArray['scope'], $filters); + $helper->resendMCEcommerceData($scopeId, $scope, $filters); $this->addSuccess($helper->__('Ecommerce data resent succesfully')); - $success = $helper->__('Redirecting... ') . ''; + $success = $helper->__('Redirecting... ') + . ''; } catch (MailChimp_Error $e) { $helper->logError($e->getFriendlyMessage()); $this->addError($e->getFriendlyMessage()); @@ -68,6 +72,7 @@ public function resendEcommerceDataAction() $this->addError($e->getMessage()); } } + $mageApp->getResponse()->setBody($success); } @@ -81,14 +86,7 @@ public function createMergeFieldsAction() $success = 0; $subEnabled = $helper->isSubscriptionEnabled($scopeId, $scope); if ($subEnabled) { - try { - $helper->createMergeFields($scopeId, $scope); - $success = 1; - } catch (MailChimp_Error $e) { - $helper->logError($e->getFriendlyMessage()); - } catch (Exception $e) { - $helper->logError($e->getMessage()); - } + $success = $helper->createMergeFields($scopeId, $scope); } $mageApp->getResponse()->setBody($success); @@ -97,12 +95,12 @@ public function createMergeFieldsAction() protected function _isAllowed() { switch ($this->getRequest()->getActionName()) { - case 'resetLocalErrors': - case 'renderresendecom': - case 'resendEcommerceData': - case 'createMergeFields': - $acl = 'system/config/mailchimp'; - break; + case 'resetLocalErrors': + case 'renderresendecom': + case 'resendEcommerceData': + case 'createMergeFields': + $acl = 'system/config/mailchimp'; + break; } return $this->getAdminSession()->isAllowed($acl); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php index efb093f0a..4426ab087 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php @@ -27,7 +27,10 @@ public function indexAction() $customerId = (int)$this->getRequest()->getParam('id'); if ($customerId) { $block = $this->getLayout() - ->createBlock('mailchimp/adminhtml_customer_edit_tab_mailchimp', 'admin.customer.mailchimp') + ->createBlock( + 'mailchimp/adminhtml_customer_edit_tab_mailchimp', + 'admin.customer.mailchimp' + ) ->setCustomerId($customerId) ->setUseAjax(true); $html = $this->getHtml($block); @@ -103,6 +106,7 @@ public function getInfoAction() $data[$key]['label'] = $liElement; } } + $jsonData = json_encode($data); $response = $this->getResponse(); @@ -155,7 +159,12 @@ public function getInterestAction() */ protected function _getDateSync($mailchimpStoreId) { - return $this->makeHelper()->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", 0, 'default'); + return $this->makeHelper() + ->getConfigValueForScope( + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", + 0, + 'default' + ); } /** @@ -165,15 +174,15 @@ protected function _isAllowed() { $acl = null; switch ($this->getRequest()->getActionName()) { - case 'index': - case 'resendSubscribers': - case 'createWebhook': - case 'getStores': - case 'getList': - case 'getInfo': - case 'getInterest': - $acl = 'system/config/mailchimp'; - break; + case 'index': + case 'resendSubscribers': + case 'createWebhook': + case 'getStores': + case 'getList': + case 'getInfo': + case 'getInterest': + $acl = 'system/config/mailchimp'; + break; } return Mage::getSingleton('admin/session')->isAllowed($acl); @@ -207,7 +216,10 @@ protected function getHtml($block) */ protected function getSourceStoreOptions($apiKey) { - return Mage::getModel('Ebizmarts_MailChimp_Model_System_Config_Source_Store', array('api_key' => $apiKey))->toOptionArray(); + return Mage::getModel( + 'Ebizmarts_MailChimp_Model_System_Config_Source_Store', + array('api_key' => $apiKey) + )->toOptionArray(); } /** @@ -217,7 +229,10 @@ protected function getSourceStoreOptions($apiKey) */ protected function getSourceAccountInfoOptions($apiKey, $mcStoreId) { - return Mage::getModel('Ebizmarts_MailChimp_Model_System_Config_Source_Account', array('api_key' => $apiKey, 'mailchimp_store_id' => $mcStoreId))->toOptionArray(); + return Mage::getModel( + 'Ebizmarts_MailChimp_Model_System_Config_Source_Account', + array('api_key' => $apiKey, 'mailchimp_store_id' => $mcStoreId) + )->toOptionArray(); } /** @@ -227,7 +242,10 @@ protected function getSourceAccountInfoOptions($apiKey, $mcStoreId) */ protected function getSourceListOptions($apiKey, $mcStoreId) { - return Mage::getModel('Ebizmarts_MailChimp_Model_System_Config_Source_List', array('api_key' => $apiKey, 'mailchimp_store_id' => $mcStoreId))->toOptionArray(); + return Mage::getModel( + 'Ebizmarts_MailChimp_Model_System_Config_Source_List', + array('api_key' => $apiKey, 'mailchimp_store_id' => $mcStoreId) + )->toOptionArray(); } /** @@ -237,9 +255,15 @@ protected function getSourceListOptions($apiKey, $mcStoreId) */ protected function getSourceInterestOptions($apiKey, $listId) { - return Mage::getModel('Ebizmarts_MailChimp_Model_System_Config_Source_CustomerGroup', array('api_key' => $apiKey, 'list_id' => $listId))->toOptionArray(); + return Mage::getModel( + 'Ebizmarts_MailChimp_Model_System_Config_Source_CustomerGroup', + array('api_key' => $apiKey, 'list_id' => $listId) + )->toOptionArray(); } + /** + * @return string + */ protected function getApiKeyValue() { $helper = $this->getHelper(); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php index 481311da8..74df0c9c4 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php @@ -59,10 +59,15 @@ public function downloadresponseAction() $fileContent = $this->__("Response was deleted from MailChimp server."); break; } + foreach ($files as $file) { $items = $this->getFileContent($file); foreach ($items as $item) { - $fileContent[] = array('status_code' => $item->status_code, 'operation_id' => $item->operation_id, 'response' => json_decode($item->response)); + $fileContent[] = array( + 'status_code' => $item->status_code, + 'operation_id' => $item->operation_id, + 'response' => json_decode($item->response) + ); } $this->unlink($file); @@ -76,17 +81,18 @@ public function downloadresponseAction() $response->setBody(json_encode($fileContent, JSON_PRETTY_PRINT)); } + return; } protected function _isAllowed() { switch ($this->getRequest()->getActionName()) { - case 'index': - case 'grid': - case 'downloadresponse': - $acl = 'newsletter/mailchimp/mailchimperrors'; - break; + case 'index': + case 'grid': + case 'downloadresponse': + $acl = 'newsletter/mailchimp/mailchimperrors'; + break; } return Mage::getSingleton('admin/session')->isAllowed($acl); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php index e5efe361d..7a99fbdad 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php @@ -67,7 +67,9 @@ public function editAction() $title = $id ? $this->__('Edit Store') : $this->__('New Store'); $this->_initAction(); - $block = $this->getLayout()->createBlock('mailchimp/adminhtml_mailchimpstores_edit')->setData('action', $this->getUrl('*/*/save')); + $block = $this->getLayout() + ->createBlock('mailchimp/adminhtml_mailchimpstores_edit') + ->setData('action', $this->getUrl('*/*/save')); $this->_addBreadcrumb($title, $title) ->_addContent($block) @@ -156,6 +158,7 @@ protected function _loadStores() $helper->logError($e->getMessage()); continue; } + try { $root = $api->getRoot()->info(); $stores = $api->getEcommerce()->getStores()->get(null, null, null, 100); @@ -270,15 +273,15 @@ protected function _isAllowed() { $acl = ''; switch ($this->getRequest()->getActionName()) { - case 'index': - case 'grid': - case 'edit': - case 'new': - case 'save': - case 'getstores': - case 'delete': - $acl = 'newsletter/mailchimp/mailchimpstores'; - break; + case 'index': + case 'grid': + case 'edit': + case 'new': + case 'save': + case 'getstores': + case 'delete': + $acl = 'newsletter/mailchimp/mailchimpstores'; + break; } return Mage::getSingleton('admin/session')->isAllowed($acl); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php index b58d90807..078c9366e 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php @@ -30,15 +30,37 @@ public function saveaddAction() $blankSpacesAmount = (count(explode(' ', $value)) - 1); if (is_numeric($value)) { - Mage::getSingleton('adminhtml/session')->addError($this->__('There was an error processing the new field. MailChimp tag value can not be numeric.')); + Mage::getSingleton('adminhtml/session') + ->addError( + $this->__( + 'There was an error processing the new field. ' + . 'MailChimp tag value can not be numeric.' + ) + ); } elseif ($helper->customMergeFieldAlreadyExists($value, $scopeArray['scope_id'], $scopeArray['scope'])) { - Mage::getSingleton('adminhtml/session')->addError($this->__('There was an error processing the new field. MailChimp tag value already exists.')); + Mage::getSingleton('adminhtml/session') + ->addError( + $this->__( + 'There was an error processing the new field. ' + . 'MailChimp tag value already exists.' + ) + ); } elseif ($blankSpacesAmount > 0) { - Mage::getSingleton('adminhtml/session')->addError($this->__('There was an error processing the new field. MailChimp tag value can not contain blank spaces.')); + Mage::getSingleton('adminhtml/session') + ->addError( + $this->__( + 'There was an error processing the new field. ' + . 'MailChimp tag value can not contain blank spaces.' + ) + ); } else { $customMergeFields = $helper->getCustomMergeFields($scopeArray['scope_id'], $scopeArray['scope']); $customMergeFields[] = array('label' => $label, 'value' => $value, 'field_type' => $fieldType); - $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, serialize($customMergeFields))); + $configValues = array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, $helper->serialize($customMergeFields) + ) + ); $helper->saveMailchimpConfig($configValues, $scopeArray['scope_id'], $scopeArray['scope']); Mage::getSingleton('core/session')->setMailChimpValue($value); Mage::getSingleton('core/session')->setMailChimpLabel($label); @@ -51,10 +73,10 @@ public function saveaddAction() protected function _isAllowed() { switch ($this->getRequest()->getActionName()) { - case 'addmergevar': - case 'saveadd': - $acl = 'system/config/mailchimp'; - break; + case 'addmergevar': + case 'saveadd': + $acl = 'system/config/mailchimp'; + break; } return Mage::getSingleton('admin/session')->isAllowed($acl); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php index ddc6a5690..35fe96fcb 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php @@ -23,7 +23,12 @@ public function loadquoteAction() $quote = Mage::getModel('sales/quote')->load($params['id']); $storeId = $quote->getStoreId(); $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId); - $quoteSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($params['id'], Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId); + $quoteSyncData = Mage::helper('mailchimp') + ->getEcommerceSyncDataItem( + $params['id'], + Ebizmarts_MailChimp_Model_Config::IS_QUOTE, + $mailchimpStoreId + ); $url = Mage::getUrl(Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_PAGE, $storeId)); if (isset($params['mc_cid'])) { $url .= '?mc_cid='.$params['mc_cid']; @@ -61,7 +66,6 @@ public function loadquoteAction() } $this->getResponse()->setRedirect($url, 301); - //$this->_redirect('customer/account/login',array('?','mc_cid='.$params['mc_cid'])); } } } @@ -79,7 +83,11 @@ public function loadcouponAction() $mailchimpStoreId = $helper->getMCStoreId($storeId); $url = Mage::getUrl('checkout/cart'); - $promoCodeSyncData = $helper->getEcommerceSyncDataItem($id, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, $mailchimpStoreId); + $promoCodeSyncData = $helper->getEcommerceSyncDataItem( + $id, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, + $mailchimpStoreId + ); $couponId = $promoCodeSyncData->getRelatedId(); if ($couponId && $promoCodeSyncData->getMailchimpToken() == $token) { $coupon = Mage::getModel('salesrule/coupon')->load($couponId); @@ -90,15 +98,32 @@ public function loadcouponAction() $quote->setCouponCode($code)->save(); Mage::getSingleton('core/session')->addSuccess($this->__('Coupon was automatically applied.')); if (!$quote->getItemsCount()) { - Mage::getSingleton('core/session')->addWarning($this->__('If you log in without adding any item to the cart, you will need to re-apply the coupon code manually.')); + Mage::getSingleton('core/session') + ->addWarning( + $this->__( + 'If you log in without adding any item to the cart, ' + . 'you will need to re-apply the coupon code manually.' + ) + ); } } else { - Mage::getSingleton('core/session')->addError($this->__('Something went wrong when trying to apply the coupon code.')); + Mage::getSingleton('core/session') + ->addError( + $this->__( + 'Something went wrong when trying to apply the coupon code.' + ) + ); } $this->getResponse()->setRedirect($url, 301); } else { - Mage::getSingleton('customer/session')->addNotice($this->__("The coupon code could not be applied for the current store. Please try to apply it manually.")); + Mage::getSingleton('customer/session') + ->addNotice( + $this->__( + "The coupon code could not be applied for the current store. " + . "Please try to apply it manually." + ) + ); $this->getResponse() ->setRedirect($url); } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php b/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php index 7044662ba..5f093c6a4 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php @@ -33,6 +33,7 @@ public function indexAction() $subscriber->setSubscriberLastname($order->getCustomerLastname()); $subscriber->subscribe($customerEmail); } + $subscriberId = $subscriber->getSubscriberId(); $interestGroup->getByRelatedIdStoreId($customerId, $subscriberId, $storeId); $encodedGroups = $helper->arrayEncode($params); @@ -48,8 +49,14 @@ public function indexAction() $session->addSuccess($this->__('Thanks for sharing your interest with us.')); } catch (Exception $e) { $helper->logError($e->getMessage()); - $session->addWarning($this->__('Something went wrong with the interests subscription. Please go to the account subscription menu to subscriber to the interests successfully.')); + $session->addWarning( + $this->__( + 'Something went wrong with the interests subscription. ' + . 'Please go to the account subscription menu to subscriber to the interests successfully.' + ) + ); } + $this->_redirect('/'); } @@ -61,6 +68,14 @@ protected function getHelper() return Mage::helper('mailchimp'); } + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getDateHelper() + { + return Mage::helper('mailchimp/date'); + } + /** * @return Ebizmarts_MailChimp_Model_Api_Subscribers */ @@ -102,10 +117,10 @@ protected function getSubscriberModel() } /** - * @return mixed + * @return string */ protected function getCurrentDateTime() { - return Mage::getModel('core/date')->date('d-m-Y H:i:s'); + return $this->getDateHelper()->formatDate(null, 'd-m-Y H:i:s'); } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php b/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php index e429dc8ef..91e9381e3 100755 --- a/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php @@ -12,17 +12,18 @@ */ class Ebizmarts_MailChimp_WebhookController extends Mage_Core_Controller_Front_Action { - private $mailchimpHelper = null; + protected $_mailchimpHelper = null; /** * @return Ebizmarts_MailChimp_Helper_Data|Mage_Core_Helper_Abstract */ protected function getHelper() { - if (!$this->mailchimpHelper) { - $this->mailchimpHelper = Mage::helper('mailchimp'); + if (!$this->_mailchimpHelper) { + $this->_mailchimpHelper = Mage::helper('mailchimp'); } - return $this->mailchimpHelper; + + return $this->_mailchimpHelper; } /** @@ -39,27 +40,10 @@ public function indexAction() if (isset($data['data']['list_id'])) { $listId = $data['data']['list_id']; $storeIds = $helper->getMagentoStoreIdsByListId($listId); - if (count($storeIds)) { + if (!empty($storeIds)) { $storeId = $storeIds[0]; if ($helper->isSubscriptionEnabled($storeId)) { - try { - $api = $helper->getApi($storeId); - } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { - $helper->logError($e->getMessage()); - $api = null; - } - if (!$api) { - try { - $webhooks = $api->lists->webhooks->getAll($listId); - foreach ($webhooks['webhooks'] as $webhook) { - if (strpos($webhook['url'], 'monkey/webhook') !== false) { - $api->lists->webhooks->delete($listId, $webhook['id']); - } - } - } catch (MailChimp_Error $e) { - $helper->logError($e->getFriendlyMessage()); - } - } + $this->_deleteWebhook($storeId, $listId); } } } @@ -88,4 +72,34 @@ public function indexAction() } } } + + /** + * @param $storeId + * @param $listId + * @throws Exception + */ + protected function _deleteWebhook($storeId, $listId) + { + $helper = $this->getHelper(); + + try { + $api = $helper->getApi($storeId); + } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { + $helper->logError($e->getMessage()); + $api = null; + } + + if (!$api) { + try { + $webhooks = $api->lists->webhooks->getAll($listId); + foreach ($webhooks['webhooks'] as $webhook) { + if (strpos($webhook['url'], 'monkey/webhook') !== false) { + $api->lists->webhooks->delete($listId, $webhook['id']); + } + } + } catch (MailChimp_Error $e) { + $helper->logError($e->getFriendlyMessage()); + } + } + } } diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index 45fa9e9bf..1225d8f8e 100644 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -1,12 +1,11 @@ - - 1.1.17 + 1.1.18 - 1.1.17 + 1.1.18 @@ -437,6 +436,15 @@ ebizmarts_mailchimp + + + 0 0 * * 0 + + + mailchimp/cron::clearEcommerceData + + ebizmarts_mailchimp + diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 4d437ed34..493df1e91 100644 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -354,17 +354,6 @@ 1 - - button - mailchimp/adminhtml_system_config_resetEcommerceData - 220 - 1 - 1 - 1 - - 1 - - button mailchimp/adminhtml_system_config_resendEcommerceData diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php index eba25f786..e48c71f1b 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php @@ -2,7 +2,9 @@ $installer = $this; -/** @var Mage_Eav_Model_Entity_Setup $installer */ +/** + * @var Mage_Eav_Model_Entity_Setup $installer + */ $installer->startSetup(); try { @@ -18,23 +20,26 @@ } catch (Exception $e) { Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } + $setup = new Mage_Eav_Model_Entity_Setup('core_setup'); -$entityTypeId = $setup->getEntityTypeId('customer'); -$attributeSetId = $setup->getDefaultAttributeSetId($entityTypeId); +$entityTypeId = $setup->getEntityTypeId('customer'); +$attributeSetId = $setup->getDefaultAttributeSetId($entityTypeId); $attributeGroupId = $setup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId); -$setup->addAttribute("customer", "mailchimp_store_view", array( - "type" => "int", - "label" => "Store View (For MailChimp)", - "input" => "select", - "source" => "mailchimp/system_config_source_mailchimpStoreView", - "visible" => true, - "required" => false, - "unique" => false, - "note" => "A store view must be specified to sync this customer to MailChimp" +$setup->addAttribute( + "customer", "mailchimp_store_view", array( + "type" => "int", + "label" => "Store View (For MailChimp)", + "input" => "select", + "source" => "mailchimp/system_config_source_mailchimpStoreView", + "visible" => true, + "required" => false, + "unique" => false, + "note" => "A store view must be specified to sync this customer to MailChimp" -)); + ) +); try { $attribute = Mage::getSingleton("eav/config")->getAttribute("customer", "mailchimp_store_view"); @@ -48,11 +53,11 @@ '999' //sort_order ); - $used_in_forms = array(); + $usedInForms = array(); - $used_in_forms[] = "adminhtml_customer"; + $usedInForms[] = "adminhtml_customer"; - $attribute->setData("used_in_forms", $used_in_forms) + $attribute->setData("used_in_forms", $usedInForms) ->setData("is_used_for_customer_segment", true) ->setData("is_system", 0) ->setData("is_user_defined", 1) diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.5.6.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.5.6.php index 155e263d0..dabd2cd19 100755 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.5.6.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.5.6.php @@ -43,7 +43,16 @@ Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } -Mage::helper('mailchimp')->saveMailChimpConfig(array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, 1)), 0, 'default'); +Mage::helper('mailchimp') + ->saveMailChimpConfig( + array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_115, + 1) + ), + 0, + 'default' + ); $installer->endSetup(); diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.3-1.1.6.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.3-1.1.6.4.php index 4cab6df68..3efa5c120 100755 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.3-1.1.6.4.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.3-1.1.6.4.php @@ -2,6 +2,15 @@ $installer = $this; -Mage::helper('mailchimp')->saveMailChimpConfig(array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, 1)), 0, 'default'); +Mage::helper('mailchimp') + ->saveMailChimpConfig( + array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, + 1) + ), + 0, + 'default' + ); $installer->endSetup(); diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.4-1.1.6.5.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.4-1.1.6.5.php index b1c1e7b2c..097456daa 100755 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.4-1.1.6.5.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.4-1.1.6.5.php @@ -10,7 +10,16 @@ " ); - Mage::helper('mailchimp')->saveMailChimpConfig(array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, 1)), 0, 'default'); + Mage::helper('mailchimp') + ->saveMailChimpConfig( + array( + array( + Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, + 1) + ), + 0, + 'default' + ); } catch (Exception $e) { Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml index 4a08493c4..8276f3d8f 100644 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml @@ -3,14 +3,17 @@ $interest = $this->getInterest(); ?>
    - __('Mailchimp Information') ?> + + quoteEscape($this->__('Mailchimp Information')) ?> +
    -