From 3596bd52c9c13e97d8310cf64127aedc92f0d98b Mon Sep 17 00:00:00 2001 From: Richard Brown Date: Mon, 13 Feb 2017 21:37:18 +0000 Subject: [PATCH 01/43] Stop calling getLifetime Mage::getModel('core/cookie')->getLifetime doesn't have any parameters, and returns Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId()) so the comparisons in _getCampaignCookie and _getLandingCookie always return true. Both functions are tested for truthiness when they're used, and Mage::getModel('core/cookie')->get returns false when the cookie isn't set, so both function should be able to return the ->get call --- .../Ebizmarts/MailChimp/Model/Observer.php | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index b30de65f7..009f93f26 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -260,7 +260,7 @@ public function removeCampaignData(Varien_Event_Observer $observer) Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); } - if(($this->_getLandingCookie())) { + if ($this->_getLandingCookie()) { Mage::getModel('core/cookie')->delete('mailchimp_landing_page'); } @@ -268,32 +268,28 @@ public function removeCampaignData(Varien_Event_Observer $observer) } /** - * Get campaign cooke if available. + * Get campaign cookie if available. * - * @return null + * @return mixed */ protected function _getCampaignCookie() { $landingCookie = $this->_getLandingCookie(); if (preg_match("/utm_source=mailchimp/", $landingCookie)) { - return null; + return false; } - $cookie = Mage::getModel('core/cookie')->get('mailchimp_campaign_id'); - if ($cookie && Mage::getModel('core/cookie')->getLifetime('mailchimp_campaign_id') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { - return $cookie; - } else { - return null; - } + return Mage::getModel('core/cookie')->get('mailchimp_campaign_id'); } + + /** + * Get landing cookie if available. + * + * @return mixed + */ protected function _getLandingCookie() { - $cookie = Mage::getModel('core/cookie')->get('mailchimp_landing_page'); - if ($cookie && Mage::getModel('core/cookie')->getLifetime('mailchimp_landing_page') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { - return $cookie; - } else { - return null; - } + return Mage::getModel('core/cookie')->get('mailchimp_landing_page'); } /** From 1b6e71ea820dafe7ef810de0262e606f01f5b016 Mon Sep 17 00:00:00 2001 From: Tom Lankhorst Date: Wed, 15 Feb 2017 20:14:29 +0100 Subject: [PATCH 02/43] Added instruction to clone the module with modman Explicitly specifying the branch (master) because development is the default. --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 68c38c9fc..20f66ff5c 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,11 @@ Magento Community Edition (1.7 or above) or Magento Enterprise (1.11 or above) To get a copy of the project up and running on your local machine for development and testing purposes, just clone this repository on your Magento’s root directory and flush the Magento’s cache. +Alternatively, use modman to install this module. + +``modman clone https://github.com/mailchimp/mc-magento.git -b 'master'`` + + ## Module Configuriation To enable MailChimp For Magento: From 821047262ace1892287e09fa5dfde6aef80ec616 Mon Sep 17 00:00:00 2001 From: Tom Lankhorst Date: Thu, 16 Feb 2017 22:16:40 +0100 Subject: [PATCH 03/43] Added missing lib files to modman They are present in the master branch... --- modman | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modman b/modman index e5cee9e17..e09f0d3f9 100644 --- a/modman +++ b/modman @@ -5,6 +5,9 @@ app/design/frontend/base/default/layout/* app/design/frontend/base/default app/design/frontend/base/default/template/* app/design/frontend/base/default/template/ app/etc/modules/* app/etc/modules/ js/ebizmarts/mailchimp/* js/ebizmarts/mailchimp/ +lib/Ebizmarts/Mailchimp.php lib/Ebizmarts/Mailchimp.php +lib/Ebizmarts/Mailchimp lib/Ebizmarts/Mailchimp +lib/Mandrill lib/Mandrill skin/adminhtml/default/default/ebizmarts/* skin/adminhtml/default/default/ebizmarts/ getMailchimpResponse.php getMailchimpResponse.php m4mlogs.sh m4mlogs.sh From c7e6b1b2488f9dd6ffecf9879a49aac6f9902c38 Mon Sep 17 00:00:00 2001 From: Tom Lankhorst Date: Thu, 16 Feb 2017 22:30:24 +0100 Subject: [PATCH 04/43] Revised modman file --- modman | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/modman b/modman index e09f0d3f9..57f0879a9 100644 --- a/modman +++ b/modman @@ -1,13 +1,15 @@ -app/code/community/* app/code/community/ -app/design/adminhtml/default/default/layout/* app/design/adminhtml/default/default/layout/ -app/design/adminhtml/default/default/template/* app/design/adminhtml/default/default/template/ -app/design/frontend/base/default/layout/* app/design/frontend/base/default/layout/ -app/design/frontend/base/default/template/* app/design/frontend/base/default/template/ -app/etc/modules/* app/etc/modules/ -js/ebizmarts/mailchimp/* js/ebizmarts/mailchimp/ -lib/Ebizmarts/Mailchimp.php lib/Ebizmarts/Mailchimp.php -lib/Ebizmarts/Mailchimp lib/Ebizmarts/Mailchimp -lib/Mandrill lib/Mandrill -skin/adminhtml/default/default/ebizmarts/* skin/adminhtml/default/default/ebizmarts/ -getMailchimpResponse.php getMailchimpResponse.php -m4mlogs.sh m4mlogs.sh +app/code/community/Ebizmarts/MailChimp app/code/community/Ebizmarts/MailChimp +app/design/adminhtml/default/default/layout/ebizmarts/mailchimp.xml app/design/adminhtml/default/default/layout/ebizmarts/mailchimp.xml +app/design/adminhtml/default/default/template/ebizmarts/mandrill app/design/adminhtml/default/default/template/ebizmarts/mandrill +app/design/adminhtml/default/default/template/ebizmarts/mailchimp app/design/adminhtml/default/default/template/ebizmarts/mailchimp +app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml +app/design/frontend/base/default/template/ebizmarts/mailchimp app/design/frontend/base/default/template/ebizmarts/mailchimp +app/etc/modules/Ebizmarts_MailChimp.xml app/etc/modules/Ebizmarts_MailChimp.xml +js/ebizmarts/mailchimp js/ebizmarts/mailchimp +lib/Ebizmarts/Mailchimp.php lib/Ebizmarts/Mailchimp.php +lib/Ebizmarts/Mailchimp lib/Ebizmarts/Mailchimp +lib/Mandrill lib/Mandrill +skin/adminhtml/default/default/ebizmarts/mailchimp skin/adminhtml/default/default/ebizmarts/mailchimp +skin/adminhtml/default/default/ebizmarts/mandrill skin/adminhtml/default/default/ebizmarts/mandrill +m4mlogs.sh m4mlogs.sh +getMailchimpResponse.php getMailchimpResponse.php From 43290fa2b4dc20b2830281f10b6fdcde9c7fdadb Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 24 Feb 2017 15:51:18 -0300 Subject: [PATCH 05/43] Fixed typo in Api/Subscribers class. closes #145 --- .../community/Ebizmarts/MailChimp/Model/Api/Subscribers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 638b49bfb..82b37aa69 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -10,7 +10,7 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_subscribers +class Ebizmarts_MailChimp_Model_Api_Subscribers { const BATCH_LIMIT = 100; From 834ab9883717bc1655cb2c79bb16b2dd9ec22ab4 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 2 Mar 2017 12:59:51 -0300 Subject: [PATCH 06/43] Added getRecipients() function to fix cart2quote conflict. closes #152 --- lib/Mandrill/Message.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/Mandrill/Message.php b/lib/Mandrill/Message.php index dd19ac8fb..bf54c1964 100755 --- a/lib/Mandrill/Message.php +++ b/lib/Mandrill/Message.php @@ -83,6 +83,11 @@ public function getTo() return $this->_to; } + public function getRecipients() + { + return $this->getTo(); + } + public function setBodyHtml($html, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE) { $this->_bodyHtml = $html; From eadd05aab3a161798da89da85c01bc3e443c2dee Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 3 Mar 2017 17:37:37 -0300 Subject: [PATCH 07/43] closes #155 --- modman | 4 ++-- getMailchimpResponse.php => shell/getMailchimpResponse.php | 0 m4mlogs.sh => shell/m4mlogs.sh | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) rename getMailchimpResponse.php => shell/getMailchimpResponse.php (100%) rename m4mlogs.sh => shell/m4mlogs.sh (77%) diff --git a/modman b/modman index e5cee9e17..e9f34d8ba 100644 --- a/modman +++ b/modman @@ -6,5 +6,5 @@ app/design/frontend/base/default/template/* app/design/frontend/base/default app/etc/modules/* app/etc/modules/ js/ebizmarts/mailchimp/* js/ebizmarts/mailchimp/ skin/adminhtml/default/default/ebizmarts/* skin/adminhtml/default/default/ebizmarts/ -getMailchimpResponse.php getMailchimpResponse.php -m4mlogs.sh m4mlogs.sh +shell/getMailchimpResponse.php shell/getMailchimpResponse.php +shell/m4mlogs.sh shell/m4mlogs.sh diff --git a/getMailchimpResponse.php b/shell/getMailchimpResponse.php similarity index 100% rename from getMailchimpResponse.php rename to shell/getMailchimpResponse.php diff --git a/m4mlogs.sh b/shell/m4mlogs.sh similarity index 77% rename from m4mlogs.sh rename to shell/m4mlogs.sh index 05cf258b3..9768cf19d 100755 --- a/m4mlogs.sh +++ b/shell/m4mlogs.sh @@ -13,14 +13,14 @@ case "$#" in echo $"Usage: $0 apikey option [id]" exit 1 esac -batches=$(grep -l $2_.*$id var/log/*.Request.log | cut -d'/' -f3 $a | cut -d'.' -f1) +batches=$(grep -l $2_.*$id ../var/log/*.Request.log | cut -d'/' -f3 $a | cut -d'.' -f1) allresponses="" allrequests="" for a in ${batches}; do echo $"Downloading response for batch $a" allresponses="$allresponses $(php getMailchimpResponse.php $apikey $a)" - allrequests="$allrequests var/log/$a.Request.log" + allrequests="$allrequests ../var/log/$a.Request.log" done; resp=$(tar cvzf responses.tgz $allresponses) req=$(tar cvzf requests.tgz $allrequests) From b6b7f5d6d9c3b756033a1ab50f963e77f234818e Mon Sep 17 00:00:00 2001 From: Ihor Sviziev Date: Mon, 6 Mar 2017 09:32:13 +0200 Subject: [PATCH 08/43] Use https protocol for redirect url Use https protocol as redirect url, because original url has http to https redirect. --- app/code/community/Ebizmarts/MailChimp/Helper/Oauth2.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Oauth2.php b/app/code/community/Ebizmarts/MailChimp/Helper/Oauth2.php index da11b8427..4adad5963 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Oauth2.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Oauth2.php @@ -14,7 +14,7 @@ class Ebizmarts_MailChimp_Helper_Oauth2 extends Mage_Core_Helper_Abstract protected $_authorizeUri = "https://login.mailchimp.com/oauth2/authorize"; protected $_accessTokenUri = "https://login.mailchimp.com/oauth2/token"; - protected $_redirectUri = "http://ebizmarts.com/magento/mc-magento/oauth2/complete.php"; + protected $_redirectUri = "https://ebizmarts.com/magento/mc-magento/oauth2/complete.php"; protected $_clientId = 200573319150; public function authorizeRequestUrl() From ed7ff245b1817463af0c161edc74dab12f23456a Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 9 Mar 2017 15:55:44 -0300 Subject: [PATCH 09/43] Add multi-store compatibility. closes #103 --- .../Block/Adminhtml/Mailchimperrors/Grid.php | 7 + .../System/Config/CreateMergeFields.php | 3 +- .../System/Config/Form/Field/Mapfields.php | 6 +- .../System/Config/ResetEcommerceData.php | 3 +- .../Adminhtml/System/Config/ResetErrors.php | 3 +- .../Ebizmarts/MailChimp/Helper/Data.php | 770 ++++++++++++++---- .../Ebizmarts/MailChimp/Helper/Mandrill.php | 17 +- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 229 +++--- .../Ebizmarts/MailChimp/Model/Api/Carts.php | 254 +++--- .../MailChimp/Model/Api/Customers.php | 154 ++-- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 305 +++---- .../MailChimp/Model/Api/Products.php | 156 ++-- .../Ebizmarts/MailChimp/Model/Api/Stores.php | 118 +-- .../MailChimp/Model/Api/Subscribers.php | 45 +- .../Ebizmarts/MailChimp/Model/Cron.php | 2 +- .../MailChimp/Model/Ecommercesyncdata.php | 26 + .../Ebizmarts/MailChimp/Model/Email/Queue.php | 2 +- .../MailChimp/Model/Email/Template.php | 2 +- .../Model/Mysql4/Ecommercesyncdata.php | 25 + .../Mysql4/Ecommercesyncdata/Collection.php | 27 + .../Ebizmarts/MailChimp/Model/Observer.php | 186 +++-- .../Model/System/Config/Backend/Apikey.php | 10 +- .../Model/System/Config/Backend/Ecommerce.php | 11 +- .../Model/System/Config/Backend/List.php | 28 +- .../Model/System/Config/Backend/Mapfield.php | 36 + .../Model/System/Config/Backend/Name.php | 2 +- .../Model/System/Config/Source/Account.php | 17 +- .../Model/System/Config/Source/List.php | 5 +- .../Adminhtml/EcommerceController.php | 22 +- .../Adminhtml/MailchimperrorsController.php | 5 +- .../Adminhtml/MergevarsController.php | 9 +- .../MailChimp/controllers/CartController.php | 7 +- .../Ebizmarts/MailChimp/etc/config.xml | 23 +- .../Ebizmarts/MailChimp/etc/system.xml | 73 +- .../mailchimp_setup/mysql4-install-0.0.1.php | 86 -- .../mysql4-upgrade-1.0.1-1.0.2.php | 2 - .../mysql4-upgrade-1.0.3-1.0.4.php | 27 - .../mysql4-upgrade-1.0.5-1.0.6.php | 4 - .../mysql4-upgrade-1.1.3.1-1.1.4.php | 42 - .../mysql4-upgrade-1.1.4-1.1.5.php | 2 - .../mysql4-upgrade-1.1.5-1.1.6.php | 151 ++++ composer.json | 8 +- 42 files changed, 1793 insertions(+), 1117 deletions(-) create mode 100755 app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php create mode 100755 app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php create mode 100755 app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata/Collection.php create mode 100644 app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Mapfield.php delete mode 100644 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php create mode 100755 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.6.php diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php index c39f12955..3eb7d5c55 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php @@ -68,6 +68,13 @@ protected function _prepareColumns() 'sortable' => true ) ); + $this->addColumn( + 'store_id', array( + 'header' => Mage::helper('mailchimp')->__('Store Id'), + 'index' => 'store_id', + 'sortable' => false + ) + ); $this->addColumn( 'errors', array( 'header' => Mage::helper('mailchimp')->__('Error'), 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 715e5e221..2f014e7cb 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 @@ -39,7 +39,8 @@ public function getButtonHtml() } public function getAjaxCheckUrl() { - return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/createMergeFields'); + $scopeString = Mage::helper('mailchimp')->getScopeString(); + return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/createMergeFields', array('scope' => $scopeString)); } } \ No newline at end of file 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 2bf29fe2c..3ac453a6c 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 @@ -44,9 +44,9 @@ public function __construct() } } - $customFieldTypes = unserialize( - Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS) - ); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + $mapFields = Mage::helper('mailchimp')->getCustomMapFields($scopeArray[1], $scopeArray[0]); + $customFieldTypes = unserialize($mapFields); if(is_array($customFieldTypes)) { foreach ($customFieldTypes as $customFieldType) { $label = $customFieldType['label']; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php index 98739fb8b..7f709a038 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php @@ -39,7 +39,8 @@ public function getButtonHtml() } public function getAjaxCheckUrl() { - return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/resetEcommerceData'); + $scopeString = Mage::helper('mailchimp')->getScopeString(); + return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/resetEcommerceData', array('scope' => $scopeString)); } } \ No newline at end of file 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 cd112f90b..3a1c613cf 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 @@ -39,7 +39,8 @@ public function getButtonHtml() } public function getAjaxCheckUrl() { - return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/resetLocalErrors'); + $scopeString = Mage::helper('mailchimp')->getScopeString(); + return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/resetLocalErrors', array('scope' => $scopeString)); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 48e969891..b2c9be9bc 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -12,6 +12,25 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract { + /** + * Get Config value for certain scope. + * + * @param $path + * @param $scopeId + * @param null $scope + * @return mixed + * @throws Mage_Core_Exception + */ + public function getConfigValueForScope($path, $scopeId, $scope = null) + { + if ($scope == 'websites') { + $configValue = Mage::app()->getWebsite($scopeId)->getConfig($path); + } else { + $configValue = Mage::getStoreConfig($path, $scopeId); + } + return $configValue; + } + /** * Get storeId and/or websiteId if scope selected on back end * @@ -19,7 +38,7 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract * @param null $websiteId * @return array */ - protected function _getConfigScopeId($storeId = null, $websiteId = null) + public function getConfigScopeId($storeId = null, $websiteId = null) { $scopeArray = array(); if ($code = Mage::getSingleton('adminhtml/config_data')->getStore()) { @@ -30,140 +49,362 @@ protected function _getConfigScopeId($storeId = null, $websiteId = null) $websiteId = Mage::getModel('core/website')->load($code)->getId(); $storeId = Mage::app()->getWebsite($websiteId)->getDefaultStore()->getId(); } - $scopeArray['websiteId'] = $websiteId; $scopeArray['storeId'] = $storeId; return $scopeArray; } /** - * Get configuration value from back end and front end unless storeId is sent, in this last case it gets the configuration from the store Id sent + * Create string for current scope with format scope-scopeId. * - * @param $path - * @param null $storeId If this is null it gets the config for the current store (works for back end and front end) - * @param bool $returnParentValueIfNull - * @return mixed|null + * @return string + */ + public function getScopeString() { + $scopeArray = $this->getConfigScopeId(); + if (isset($scopeArray['websiteId'])) { + $scopeString = 'websites-'.$scopeArray['websiteId']; + } elseif (isset($scopeArray['storeId'])) { + $scopeString = 'stores-'.$scopeArray['storeId']; + } else { + $scopeString = 'default-0'; + } + return $scopeString; + } + + /** + * Get MC store name for given scope. + * + * @param $scopeId + * @param $scope + * @return null|string * @throws Mage_Core_Exception */ - public function getConfigValue($path, $storeId = null, $returnParentValueIfNull = false) + public function getMCStoreName($scopeId, $scope) { - $scopeArray = array(); - $configValue = null; - - //Get store scope for back end or front end - if (!$storeId) { - $scopeArray = $this->_getConfigScopeId(); - } else { - $scopeArray['storeId'] = $storeId; + $storeName = null; + switch ($scope) { + case 'stores': + $store = Mage::app()->getStore($scopeId); + $storeName = $store->getFrontendName(); + break; + case 'websites': + $website = Mage::app()->getWebsite($scopeId); + $storeName = $website->getDefaultStore()->getFrontendName(); + break; + case 'default': + $storeView = Mage::app()->getDefaultStoreView(); + $storeName = $storeView->getWebsite()->getDefaultStore()->getFrontendName(); + break; } + return $storeName; + } - if (!$returnParentValueIfNull) { - if (isset($scopeArray['websiteId']) && $scopeArray['websiteId']) { - //Website scope - if (Mage::app()->getWebsite($scopeArray['websiteId'])->getConfig($path) !== null) { - $configValue = Mage::app()->getWebsite($scopeArray['websiteId'])->getConfig($path); - } - } elseif (isset($scopeArray['storeId']) && $scopeArray['storeId']) { - //Store view scope - if (Mage::getStoreConfig($path, $scopeArray['storeId']) !== null) { - $configValue = Mage::getStoreConfig($path, $scopeArray['storeId']); + /** + * Get local store_id value of the MC store. + * + * @return string + */ + public function getStoreRelation() + { + $stores = Mage::app()->getStores(); + $storeRelation = array(); + foreach ($stores as $storeId => $store) { + $mcStoreId = $this->getMCStoreId($storeId); + if ($mcStoreId) { + if (!array_key_exists($mcStoreId, $storeRelation)) { + $storeRelation[$mcStoreId] = array(); } - } else { - //Default config scope - if (Mage::getStoreConfig($path) !== null) { - $configValue = Mage::getStoreConfig($path); + $storeRelation[$mcStoreId][] = $storeId; + } + } + return $storeRelation; + } + + + /** + * Get all Magento stores associated to the MailChimp store configured for the given scope. + * + * @param $scopeId + * @param $scope + * @return null + */ + public function getMagentoStoresForMCStoreIdByScope($scopeId, $scope) + { + $ret = array(); + $storeRelation = $this->getStoreRelation(); + $mailchimpStoreIdForScope = $this->getMCStoreId($scopeId, $scope); + if ($mailchimpStoreIdForScope) { + foreach ($storeRelation as $mailchimpStoreId => $magentoStoreIds) { + if ($mailchimpStoreIdForScope == $mailchimpStoreId) { + $ret = $magentoStoreIds; } } } + return $ret; + } - return $configValue; + /** + * Return if module is enabled for given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function isMailChimpEnabled($scopeId, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE, $scopeId, $scope); } /** - * Get MC store name + * Return Api Key if exists for given scope. * - * @return string + * @param $scope + * @param $scopeId + * @return mixed */ - public function getMCStoreName() + public function getApiKey($scopeId, $scope = null) { - $storeView = Mage::app()->getDefaultStoreView(); - return $storeView->getWebsite()->getDefaultStore()->getFrontendName(); + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_APIKEY, $scopeId, $scope); } /** - * Get local store_id value of the MC store. + * Get local store_id value of the MC store for given scope. * - * @return string + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function getMCStoreId($scopeId, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeId, $scope); + } + + /** + * Return if Ecommerce configuration is enabled for given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed */ - public function getMCStoreId() + public function isEcommerceEnabled($scopeId, $scope = null) { - return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID); + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ACTIVE, $scopeId, $scope); } /** - * Get local is_syncing value of the MC store. + * Get general list configured for the given scope. * + * @param $scopeId + * @param null $scope * @return mixed */ - public function getMCIsSyncing() + public function getGeneralList($scopeId, $scope = null) { - return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING); + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $scopeId, $scope); } /** - * Minimum date for which ecommerce data needs to be re-uploaded. + * Get map fields configured for the given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed */ - public function getMCMinSyncDateFlag() + public function getMapFields($scopeId, $scope = null) { - return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG); + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MAP_FIELDS, $scopeId, $scope); } /** - * delete MC ecommerce store - * reset mailchimp store id in the config - * reset all deltas + * Get custom map fields configured for the given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function getCustomMapFields($scopeId, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, $scopeId, $scope); + } + + /** + * Get if store has been reseted for given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function getIsReseted($scopeId, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, $scopeId, $scope); + } + + /** + * Get if Abandoned Cart module is enabled. + * + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function isAbandonedCartEnabled($scopeId, $scope = null) + { + 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 + * @return mixed + */ + public function getAbandonedCartFirstDate($scopeId, $scope = null) + { + 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 + * @return mixed + */ + public function getEcommerceFirstDate($scopeId, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE, $scopeId, $scope); + } + + /** + * Get local is_syncing value of the MC store for given scope. * - * @param bool|false $deleteDataInMailchimp + * @param $scopeId + * @param null $scope + * @return mixed */ - public function resetMCEcommerceData($deleteDataInMailchimp=false) + public function getMCIsSyncing($scopeId, $scope = null) { - $ecommerceEnabled = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ACTIVE); - $apikey = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_APIKEY); - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); - //delete store id and data from mailchimp - if ($deleteDataInMailchimp && $this->getMCStoreId() && $this->getMCStoreId() != "") { - try { - Mage::getModel('mailchimp/api_stores')->deleteStore($this->getMCStoreId()); - } catch(Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); - } + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, $scopeId, $scope); + } - //clear store config values - Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID); + /** + * Minimum date for which ecommerce data needs to be re-uploaded for given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function getMCMinSyncDateFlag($scopeId, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG, $scopeId, $scope); + } + + /** + * Get if logs are enabled for given scope. + * + * @param int $scopeId + * @param null $scope + * @return mixed + */ + public function getLogsEnabled($scopeId = 0, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_LOG, $scopeId, $scope); + } + + /** + * Get if two way sync is enabled for given scope. + * + * @param int $scopeId + * @param null $scope + * @return mixed + */ + public function getTwoWaySyncEnabled($scopeId = 0, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_TWO_WAY_SYNC, $scopeId, $scope); + } + + /** + * Get if monkey should be displayed in order grid. + * + * @param int $scopeId + * @param null $scope + * @return mixed + */ + public function getMonkeyInGrid($scopeId = 0, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::MONKEY_GRID, $scopeId, $scope); + } + + /** + * Get if Email Catcher popup is enabled for given scope. + * + * @param int $scopeId + * @param null $scope + * @return mixed + */ + public function isEmailCatcherEnabled($scopeId = 0, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ENABLE_POPUP, $scopeId, $scope); + } + + /** + * Call deleteStore and CreateStore functions. + * Update config values. + * + * @param bool $deleteDataInMailchimp + * @param $scopeId + * @param $scope + */ + public function resetMCEcommerceData($scopeId, $scope, $deleteDataInMailchimp = false) + { + $listId = $this->getGeneralList($scopeId, $scope); + //delete store id and data from mailchimp + if ($deleteDataInMailchimp && $this->getMCStoreId($scopeId, $scope) && $this->getMCStoreId($scopeId, $scope) != "") { + $this->removeEcommerceSyncData($scopeId, $scope); + $this->deleteStore($scopeId, $scope); } + $this->clearErrorGrid($scopeId, $scope, true); - if ($ecommerceEnabled && $apikey && $listId) { - $this->createStore($listId); + if ($this->isEcomSyncDataEnabled($scopeId, $scope, true)) { + $this->createStore($listId, $scopeId, $scope); } + } - //reset mailchimp minimum date to sync flag - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG, Varien_Date::now()); - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 1); - Mage::getConfig()->cleanCache(); + /** + * Remove items from mailchimp_ecommerce_sync_data table to allow them to be sent + * + * @param $scopeId + * @param $scope + * @param bool $deleteErrorsOnly + */ + public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = false) + { + $collection = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection() + ->addFieldToFilter('mailchimp_store_id', array('eq' => $this->getMCStoreId($scopeId, $scope))); + if ($deleteErrorsOnly) { + $collection->addFieldToFilter('mailchimp_sync_error', array('neq' => '')); + } + foreach ($collection as $item) { + $item->delete(); + } } /** - * Check if API key is set and the mailchimp store id was configured + * Check if Ecommerce data is configured to be sent. * + * @param $scopeId + * @param null $scope + * @param bool $isStoreCreation * @return bool */ - public function isEcomSyncDataEnabled() + public function isEcomSyncDataEnabled($scopeId, $scope = null, $isStoreCreation = false) { - $apiKey = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_APIKEY); - $moduleEnabled = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE); - $ecommerceEnabled = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ACTIVE); - $ret = !is_null($this->getMCStoreId()) && $this->getMCStoreId() != null - && !is_null($apiKey) && $apiKey != "" && $moduleEnabled && $ecommerceEnabled; + $apiKey = $this->getApiKey($scopeId, $scope); + $moduleEnabled = $this->isMailChimpEnabled($scopeId, $scope); + $ecommerceEnabled = $this->isEcommerceEnabled($scopeId, $scope); + $generalList = $this->getGeneralList($scopeId, $scope); + $ret = (!is_null($this->getMCStoreId($scopeId, $scope)) || $isStoreCreation) && !is_null($apiKey) + && $apiKey != "" && $moduleEnabled && $ecommerceEnabled && $generalList; return $ret; } @@ -171,28 +412,34 @@ public function isEcomSyncDataEnabled() * Save error response from MailChimp's API in "MailChimp_Error.log" file. * * @param $message + * @param $scopeId + * @param null $scope */ - public function logError($message) + public function logError($message, $scopeId, $scope = null) { - if ($this->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LOG)) { + if ($this->getLogsEnabled($scopeId, $scope)) { Mage::log($message, null, 'MailChimp_Errors.log', true); } } /** * Save request made to MailChimp's API in "MailChimp_Requests.log" file. - * + * * @param $message + * @param $scopeId + * @param null $batchId */ - public function logRequest($message, $batchId=null) + public function logRequest($message, $scopeId, $batchId=null) { - if ($this->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LOG)) { + if ($this->getLogsEnabled($scopeId)) { if (!$batchId) { Mage::log($message, null, 'MailChimp_Requests.log', true); } else { $logDir = Mage::getBaseDir('var') . DS . 'log'; $fileName = $logDir.DS.$batchId.'.Request.log'; + $oldPermission = umask(0046); file_put_contents($fileName, $message); + umask($oldPermission); } } } @@ -209,69 +456,59 @@ public function getWebhooksKey() } /** - * Reset error messages from Products, Subscribers, Customers, Orders, Quotes and set them to be sent again. + * Reset error messages from Products, Subscribers, Customers, Orders, Quotes and set them to be sent again for given scope. + * + * @param $scopeId + * @param $scope */ - public function resetErrors() + public function resetErrors($scopeId, $scope) { - // reset products with errors - $collection = Mage::getModel('catalog/product')->getCollection() - ->addAttributeToFilter( - array( - array('attribute' => 'mailchimp_sync_error', 'neq' => '') - ), '', 'left' - ); - foreach ($collection as $product) { - $product->setData("mailchimp_sync_delta", null); - $product->setData("mailchimp_sync_error", ''); - $resource = $product->getResource(); - $resource->saveAttribute($product, 'mailchimp_sync_delta'); - $resource->saveAttribute($product, 'mailchimp_sync_error'); -// $product->setMailchimpUpdateObserverRan(true); -// $product->save(); - } // reset subscribers with errors $collection = Mage::getModel('newsletter/subscriber')->getCollection() ->addFieldToFilter('mailchimp_sync_error', array('neq' => '')); + $collection = $this->addStoresToFilter($collection, $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 customers with errors - $collection = Mage::getModel('customer/customer')->getCollection() -// ->addAttributeToSelect('mailchimp_sync_delta') - ->addAttributeToFilter( - array( - array('attribute' => 'mailchimp_sync_error', 'neq' => '') - ) - ); - foreach ($collection as $customer) { - $customer->setData("mailchimp_sync_delta", '0000-00-00 00:00:00'); - $customer->setData("mailchimp_sync_error", ''); - $resource = $customer->getResource(); - $resource->saveAttribute($customer, 'mailchimp_sync_delta'); - $resource->saveAttribute($customer, 'mailchimp_sync_error'); -// $customer->setMailchimpUpdateObserverRan(true); -// $customer->save(); - } - - // reset orders with errors - $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); + // reset ecommerce data with errors + $this->removeEcommerceSyncData($scopeId, $scope, true); + $this->clearErrorGrid($scopeId, $scope); + } - $resource = Mage::getResourceModel('sales/order'); - $connection->update($resource->getMainTable(), array('mailchimp_sync_error'=>'','mailchimp_sync_delta'=>'0000-00-00 00:00:00'), "mailchimp_sync_error <> ''"); - // reset quotes with errors - $resource = Mage::getResourceModel('sales/quote'); - $connection->update($resource->getMainTable(), array('mailchimp_sync_error'=>'','mailchimp_sync_delta'=>'0000-00-00 00:00:00'), "mailchimp_sync_error <> ''"); - $errorCollection = Mage::getModel('mailchimp/mailchimperrors')->getCollection(); - foreach ($errorCollection as $item) { - $item->delete(); + /** + * Clear mailchimp_errors grid for given scope. + * Exclude subscriber if flag set to true. + * + * @param $scopeId + * @param $scope + * @param bool $excludeSubscribers + */ + public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false) + { + $storesForScope = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope); + foreach ($storesForScope as $storeId) { + $errorCollection = Mage::getModel('mailchimp/mailchimperrors')->getCollection() + ->addFieldToFilter('store_id', array('eq' => $storeId)); + if ($excludeSubscribers) { + $errorCollection->addFieldToFilter('regtype', array('neq' => Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER)); + } + foreach ($errorCollection as $item) { + $item->delete(); + } } } - public function resetCampaign() + /** + * Set mailchimp_campaign_id field to 0 for all orders. + * + * @param $scopeId + * @param $scope + */ + public function resetCampaign($scopeId, $scope) { $orderCollection = Mage::getModel('sales/order')->getCollection() ->addFieldToFilter( @@ -283,56 +520,84 @@ public function resetCampaign() array('notnull'=>true) ) ); + $orderCollection = $this->addStoresToFilter($orderCollection, $scopeId, $scope); foreach ($orderCollection as $order) { $order->setMailchimpCampaignId(0); $order->save(); } } - public function createStore($listId) + + /** + * Call createMailChimpStore function and save configuration values associated to the new store. + * + * @param $listId + * @param $scopeId + * @param $scope + * @param bool $clearConfig + */ + public function createStore($listId, $scopeId, $scope) { if ($listId) { //generate store id - $date = date('Y-m-d-His'); - $storeId = md5(parse_url(Mage::getBaseUrl(), PHP_URL_HOST) . '_' . $date); + $date = $this->getDateMicrotime(); + $mailchimpStoreId = md5($this->getMCStoreName($scopeId, $scope). '_' . $date); //create store in mailchimp try { - Mage::getModel('mailchimp/api_stores')->createMailChimpStore($storeId, $listId); + Mage::getModel('mailchimp/api_stores')->createMailChimpStore($mailchimpStoreId, $listId, $scopeId, $scope); //save in config - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $storeId); - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 1); + $configValues = array( + array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $mailchimpStoreId), + array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 1), + array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG, Varien_Date::now()), + array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 1) + ); + $this->saveMailchimpConfig($configValues, $scopeId, $scope); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } } } - public function deleteStore() + + /** + * Call deleteMailChimpStore store function and delete configurations associated to the new store. + * + * @param $scopeId + * @param $scope + */ + public function deleteStore($scopeId, $scope) { - $MCStoreId = $this->getMCStoreId(); - if (!empty($MCStoreId)) { + $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); + if (!empty($mailchimpStoreId)) { try { - Mage::getModel('mailchimp/api_stores')->deleteStore($MCStoreId); + Mage::getModel('mailchimp/api_stores')->deleteMailChimpStore($mailchimpStoreId, $scopeId, $scope); } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope); } //clear store config values - Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 1, $scope, $scopeId); } } - public function createMergeFields() + /** + * Create MailChimp merge fields existing in the extension configuration page. + * + * @param $scopeId + * @param $scope + */ + public function createMergeFields($scopeId, $scope) { - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); - $maps = unserialize(Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_MAP_FIELDS)); - $customFieldTypes = unserialize( - Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS) - ); - $api = Mage::helper('mailchimp')->getApi(); + $listId = $this->getGeneralList($scopeId, $scope); + $maps = unserialize($this->getMapFields($scopeId, $scope)); + $customFieldTypes = unserialize($this->getCustomMapFields($scopeId, $scope)); + $api = $this->getApi($scopeId, $scope); + $mailchimpFields = array(); if ($api) { try { $mailchimpFields = $api->lists->mergeFields->getAll($listId, null, null, 50); } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope); } if (count($mailchimpFields) > 0) { @@ -353,9 +618,8 @@ public function createMergeFields() try { $api->lists->mergeFields->add($listId, $customFieldType['label'], $customFieldType['field_type'], null, $chimpTag); } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope); } - $created = true; } } @@ -385,7 +649,7 @@ public function createMergeFields() } } } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope); } } } @@ -394,6 +658,11 @@ public function createMergeFields() } } + /** + * get Date with Microtime. + * + * @return string + */ public function getDateMicrotime() { $microtime = explode(' ', microtime()); @@ -403,9 +672,16 @@ public function getDateMicrotime() return $date; } - public function getApi() + /** + * Get Api object for given scope. + * + * @param $scopeId + * @param null $scope + * @return Ebizmarts_Mailchimp|null + */ + public function getApi($scopeId, $scope = null) { - $apiKey = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_APIKEY); + $apiKey = $this->getApiKey($scopeId, $scope); $api = null; if ($apiKey != null && $apiKey != "") { $api = new Ebizmarts_Mailchimp($apiKey, null, 'Mailchimp4Magento' . (string)Mage::getConfig()->getNode('modules/Ebizmarts_MailChimp/version')); @@ -413,14 +689,194 @@ public function getApi() return $api; } - public function changeName($name) + + /** + * If conditions are met call the modifyName function to modify the name of the MailChimp store for given scope. + * + * @param $name + * @param $scopeId + * @param $scope + */ + public function changeName($name, $scopeId, $scope) { - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE)) { + if ($this->getMCStoreId($scopeId, $scope) && $this->getIfMCStoreIdExistsForScope($scopeId, $scope)) { try { - Mage::getModel('mailchimp/api_stores')->modifyName($name); + Mage::getModel('mailchimp/api_stores')->modifyName($name, $scopeId, $scope); } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope); + } + } + } + + /** + * Save entry for ecommerce_sync_data table overwriting old item if exists or creating a new one if it does not. + * + * @param $itemId + * @param $itemType + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param null $syncModified + * @param null $syncDeleted + * @param null $token + * @param bool $saveOnlyIfexists + */ + public function saveEcommerceSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelta = null, $syncError = null, + $syncModified = null, $syncDeleted = null, $token = null, $saveOnlyIfexists = false) + { + $ecommerceSyncDataItem = $this->getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId); + if (!$saveOnlyIfexists || $ecommerceSyncDataItem->getMailchimpSyncDelta()) { + if ($syncDelta) { + $ecommerceSyncDataItem->setData("mailchimp_sync_delta", $syncDelta); + } + if ($syncError) { + $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); + } + if ($syncModified) { + $ecommerceSyncDataItem->setData("mailchimp_sync_modified", $syncModified); } + if ($syncDeleted) { + $ecommerceSyncDataItem->setData("mailchimp_sync_deleted", $syncDeleted); + } + if ($token) { + $ecommerceSyncDataItem->setData("mailchimp_token", $token); + } + $ecommerceSyncDataItem->save(); } } + + /** + * Load Ecommerce Sync Data Item if exists or set the values for a new one and return it. + * + * @param $itemId + * @param $itemType + * @param $mailchimpStoreId + * @return Varien_Object + */ + public function getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId) + { + $collection = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection() + ->addFieldToFilter('related_id', array('eq' => $itemId)) + ->addFieldToFilter('type', array('eq' => $itemType)) + ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId)); + if (count($collection)) { + $ecommerceSyndDataItem = $collection->getFirstItem(); + } else { + $ecommerceSyndDataItem = Mage::getModel('mailchimp/ecommercesyncdata') + ->setData("related_id", $itemId) + ->setData("type", $itemType) + ->setData("mailchimp_store_id", $mailchimpStoreId); + } + return $ecommerceSyndDataItem; + } + + /** + * Filter collection by all the stores associated to MailChimp for given scope. + * + * @param $collection + * @param $scopeId + * @param $scope + * @return mixed + */ + public function addStoresToFilter($collection, $scopeId, $scope) + { + $filterArray = array(); + $storesForScope = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope); + if ($storesForScope) { + if ($scopeId === 0) { + $filterArray[] = array('eq' => 0); + } + foreach ($storesForScope as $storeId) { + $filterArray[] = array('eq' => $storeId); + } + } + if (count($filterArray)) { + $collection->addFieldToFilter('store_id', $filterArray); + } + return $collection; + } + + /** + * Return true if a MailChimp store has been created specifically for the given scope. + * + * @param $scopeId + * @param $scope + * @return mixed|null + */ + public function getIfMCStoreIdExistsForScope($scopeId, $scope) + { + $mcStoreAssociatedToScope = false; + $collection = Mage::getModel('core/config_data')->getCollection() + ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID)) + ->addFieldToFilter('scope', array('eq' => $scope)) + ->addFieldToFilter('scope_id', array('eq' => $scopeId)); + if (count($collection)) { + $mcStoreAssociatedToScope = true; + } + + return $mcStoreAssociatedToScope; + } + + /** + * Get actual scope where the MailChimp store was created if exists. + * + * @param $storeId + * @return array|null + */ + public function getMailChimpScopeByStoreId($storeId) + { + $scope = null; + $mailChimpStoreId = $this->getMCStoreId($storeId); + $collection = Mage::getModel('core/config_data')->getCollection() + ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID)) + ->addFieldToFilter('value', array('eq' => $mailChimpStoreId)); + if (count($collection)) { + $configEntry = $collection->getFirstItem(); + $scope = array('scope' => $configEntry->getScope(), 'scope_id' => $configEntry->getScopeId()); + } + return $scope; + } + + /** + * Return default store id for the configured scope on MailChimp. + * + * @param $magentoStoreId + * @return mixed + * @throws Mage_Core_Exception + */ + public function getDefaultStoreIdForMailChimpScope($magentoStoreId) + { + $scopeArray = $this->getMailChimpScopeByStoreId($magentoStoreId); + if ($scopeArray) { + if ($scopeArray['scope'] == 'websites') { + $magentoStoreId = Mage::app() + ->getWebsite($scopeArray['scope_id']) + ->getDefaultGroup() + ->getDefaultStoreId(); + } elseif ($scopeArray['scope'] == 'default') { + $magentoStoreId = Mage::app() + ->getWebsite(true) + ->getDefaultGroup() + ->getDefaultStoreId(); + } + } else { + $magentoStoreId = null; + } + return $magentoStoreId; + } + + /** + * Save configValues on core_config_data for given scope. + * + * @param $configValues + * @param $scopeId + * @param $scope + */ + public function saveMailchimpConfig($configValues, $scopeId, $scope) + { + foreach ($configValues as $configValue) { + Mage::getConfig()->saveConfig($configValue[0], $configValue[1], $scope, $scopeId); + } + Mage::getConfig()->cleanCache(); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php b/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php index 3f1279e23..9da147842 100644 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php @@ -14,10 +14,11 @@ class Ebizmarts_MailChimp_Helper_Mandrill extends Mage_Core_Helper_Abstract { /** * @param $message + * @param $storeId */ - public function log($message) + public function log($message, $storeId) { - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::MANDRILL_LOG)) { + if (Mage::helper('mailchimp/mandrill')->isMandrillLogEnabled($storeId)) { Mage::log($message, null, 'Mandrill_Request.log', true); } } @@ -36,4 +37,16 @@ public function getUserAgent() $version = strpos(Mage::getVersion(), '-') ? substr(Mage::getVersion(), 0, strpos(Mage::getVersion(), '-')) : Mage::getVersion(); return (string)'Ebizmarts_Mandrill' . $v . '/Mage' . $aux . $version; } + + /** + * Get if Mandrill logs are enabled for given scope. + * + * @param int $scopeId + * @param null $scope + * @return mixed + */ + public function isMandrillLogEnabled($scopeId = 0, $scope = null) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::MANDRILL_LOG, $scopeId, $scope); + } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 073ba4e89..ee30c55e8 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -16,9 +16,21 @@ class Ebizmarts_MailChimp_Model_Api_Batches */ public function handleEcommerceBatches() { - $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId(); - $this->_getResults($mailchimpStoreId, true); - $this->_sendEcommerceBatch($mailchimpStoreId); + $stores = Mage::app()->getStores(); + foreach ($stores as $store) { + $this->_getResults($store->getId()); + $this->_sendEcommerceBatch($store->getId()); + } + foreach ($stores as $store) { + if (Mage::helper('mailchimp')->getIsReseted($store->getId())) { + $scopeToReset = Mage::helper('mailchimp')->getMailChimpScopeByStoreId($store->getId()); + if ($scopeToReset) { + Mage::helper('mailchimp')->resetMCEcommerceData($scopeToReset['scope_id'], $scopeToReset['scope'], true); + $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 0, $scopeToReset['scope'], $scopeToReset['scope_id'])); + Mage::helper('mailchimp')->saveMailchimpConfig($configValue, $scopeToReset['scope_id'], $scopeToReset['scope']); + } + } + } } /** @@ -32,24 +44,24 @@ public function handleSubscriberBatches() /** * Get results of batch operations sent to MailChimp. * - * @param $storeId - * @param bool $isMailChimpStoreId + * @param $magentoStoreId */ - protected function _getResults($storeId, $isMailChimpStoreId = false) + protected function _getResults($magentoStoreId) { + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($magentoStoreId); $collection = Mage::getModel('mailchimp/synchbatches')->getCollection() - ->addFieldToFilter('store_id', array('eq' => $storeId)) + ->addFieldToFilter('store_id', array('eq' => $mailchimpStoreId)) ->addFieldToFilter('status', array('eq' => 'pending')); foreach ($collection as $item) { try { - $storeId = ($isMailChimpStoreId) ? 0 : $storeId; - $files = $this->getBatchResponse($item->getBatchId(), $storeId); + + $files = $this->getBatchResponse($item->getBatchId(), $magentoStoreId); if (count($files)) { if (isset($files['error'])) { $item->setStatus('error'); $item->save(); } else { - $this->processEachResponseFile($files, $item->getBatchId()); + $this->processEachResponseFile($files, $item->getBatchId(), $mailchimpStoreId); $item->setStatus('completed'); $item->save(); } @@ -66,78 +78,70 @@ protected function _getResults($storeId, $isMailChimpStoreId = false) } /** - * Send Customers, Products, Orders, Carts to MailChimp store. + * Send Customers, Products, Orders, Carts to MailChimp store for given scope. + * Return true if MailChimp store is reseted in the process. * - * @param $mailchimpStoreId - * @return mixed|null + * @param $magentoStoreId + * @return null */ - public function _sendEcommerceBatch($mailchimpStoreId) + public function _sendEcommerceBatch($magentoStoreId) { + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($magentoStoreId); try { - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { + if (Mage::helper('mailchimp')->isMailChimpEnabled($magentoStoreId) && Mage::helper('mailchimp')->isEcomSyncDataEnabled($magentoStoreId)) { $batchArray = array(); - //customer operations - $customersArray = Mage::getModel('mailchimp/api_customers')->createBatchJson($mailchimpStoreId); + $customersArray = Mage::getModel('mailchimp/api_customers')->createBatchJson($mailchimpStoreId, $magentoStoreId); $batchArray['operations'] = $customersArray; //product operations - $productsArray = Mage::getModel('mailchimp/api_products')->createBatchJson($mailchimpStoreId); + $productsArray = Mage::getModel('mailchimp/api_products')->createBatchJson($mailchimpStoreId, $magentoStoreId); $batchArray['operations'] = array_merge($batchArray['operations'], $productsArray); //order operations - $cartsArray = Mage::getModel('mailchimp/api_carts')->createBatchJson($mailchimpStoreId); + $cartsArray = Mage::getModel('mailchimp/api_carts')->createBatchJson($mailchimpStoreId, $magentoStoreId); $batchArray['operations'] = array_merge($batchArray['operations'], $cartsArray); - $ordersArray = Mage::getModel('mailchimp/api_orders')->createBatchJson($mailchimpStoreId); + $ordersArray = Mage::getModel('mailchimp/api_orders')->createBatchJson($mailchimpStoreId, $magentoStoreId); $batchArray['operations'] = array_merge($batchArray['operations'], $ordersArray); -// if (empty($ordersArray)) { -// $ordersCanceledArray = Mage::getModel('mailchimp/api_orders')->createCanceledBatchJson($mailchimpStoreId); -// $batchArray['operations'] = array_merge($batchArray['operations'], $ordersCanceledArray); -// } try { /** * @var $mailchimpApi \Ebizmarts_Mailchimp */ - $mailchimpApi = Mage::helper('mailchimp')->getApi(); + $mailchimpApi = Mage::helper('mailchimp')->getApi($magentoStoreId); if (!empty($batchArray['operations'])) { $batchJson = json_encode($batchArray); if (!$batchJson || $batchJson == '') { - Mage::helper('mailchimp')->logRequest('An empty operation was detected'); + Mage::helper('mailchimp')->logRequest('An empty operation was detected', $magentoStoreId); } else { - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED)) { - Mage::helper('mailchimp')->resetMCEcommerceData(true); - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 0); - Mage::getConfig()->cleanCache(); - } else { + if (!Mage::helper('mailchimp')->getIsReseted($magentoStoreId)) { $batchResponse = $mailchimpApi->batchOperation->add($batchJson); - Mage::helper('mailchimp')->logRequest($batchJson, $batchResponse['id']); + Mage::helper('mailchimp')->logRequest($batchJson, $magentoStoreId, $batchResponse['id']); //save batch id to db $batch = Mage::getModel('mailchimp/synchbatches'); $batch->setStoreId($mailchimpStoreId) ->setBatchId($batchResponse['id']) ->setStatus($batchResponse['status']); $batch->save(); - return $batchResponse; } } - } elseif (Mage::helper('mailchimp')->getMCIsSyncing()) { + } elseif (Mage::helper('mailchimp')->getMCIsSyncing($magentoStoreId)) { $isSyncing = false; $mailchimpApi->ecommerce->stores->edit($mailchimpStoreId, null, null, null, $isSyncing); - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 0); - Mage::getConfig()->cleanCache(); + $scopeToEdit = Mage::helper('mailchimp')->getMailChimpScopeByStoreId($magentoStoreId); + $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 0)); + Mage::helper('mailchimp')->saveMailchimpConfig($configValue, $scopeToEdit['scope_id'], $scopeToEdit['scope']); } } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $magentoStoreId); } catch (Exception $e) { - Mage::log("Json encode fails"); - Mage::log($batchArray); + Mage::helper('mailchimp')->logError($e->getMessage(), $magentoStoreId); + Mage::helper('mailchimp')->logError("Json encode fails", $magentoStoreId); + Mage::helper('mailchimp')->logError($batchArray, $magentoStoreId); } } } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $magentoStoreId); } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $magentoStoreId); } - - return null; } /** @@ -179,8 +183,8 @@ public function sendStoreSubscriberBatch($storeId, $limit) { try { $subscribersArray = array(); - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE, $storeId)) { - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $storeId); + if (Mage::helper('mailchimp')->isMailChimpEnabled($storeId)) { + $listId = Mage::helper('mailchimp')->getGeneralList($storeId); $batchArray = array(); @@ -194,11 +198,11 @@ public function sendStoreSubscriberBatch($storeId, $limit) if (!empty($batchArray['operations'])) { $batchJson = json_encode($batchArray); if (!$batchJson || $batchJson == '') { - Mage::helper('mailchimp')->logRequest('An empty operation was detected'); + Mage::helper('mailchimp')->logRequest('An empty operation was detected', $storeId); } else { - $mailchimpApi = Mage::helper('mailchimp')->getApi(); + $mailchimpApi = Mage::helper('mailchimp')->getApi($storeId); $batchResponse = $mailchimpApi->batchOperation->add($batchJson); - Mage::helper('mailchimp')->logRequest($batchJson, $batchResponse['id']); + Mage::helper('mailchimp')->logRequest($batchJson, $storeId, $batchResponse['id']); //save batch id to db $batch = Mage::getModel('mailchimp/synchbatches'); @@ -210,9 +214,9 @@ public function sendStoreSubscriberBatch($storeId, $limit) } } } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId); } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $storeId); } return null; @@ -220,14 +224,15 @@ public function sendStoreSubscriberBatch($storeId, $limit) /** * @param $batchId + * @param $magentoStoreId * @return array */ - public function getBatchResponse($batchId) + public function getBatchResponse($batchId, $magentoStoreId) { $files = array(); try { $baseDir = Mage::getBaseDir(); - $api = Mage::helper('mailchimp')->getApi(); + $api = Mage::helper('mailchimp')->getApi($magentoStoreId); // check the status of the job $response = $api->batchOperation->status($batchId); if (isset($response['status']) && $response['status'] == 'finished') { @@ -259,9 +264,9 @@ public function getBatchResponse($batchId) } } catch (Mailchimp_Error $e) { $files['error'] = $e->getFriendlyMessage(); - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $magentoStoreId); } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $magentoStoreId); } return $files; @@ -270,16 +275,18 @@ public function getBatchResponse($batchId) /** * @param $files * @param $batchId + * @param $mailchimpStoreId */ - protected function processEachResponseFile($files, $batchId) + protected function processEachResponseFile($files, $batchId, $mailchimpStoreId) { foreach ($files as $file) { $items = json_decode(file_get_contents($file)); foreach ($items as $item) { if ($item->status_code != 200) { $line = explode('_', $item->operation_id); - $type = $line[0]; - $id = $line[2]; + $store = explode('-', $line[0]); + $type = $line[1]; + $id = $line[3]; $mailchimpErrors = Mage::getModel('mailchimp/mailchimperrors'); @@ -301,58 +308,59 @@ protected function processEachResponseFile($files, $batchId) $error = $response->title . " : " . $response->detail; - switch ($type) { - case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: - $p = Mage::getModel('catalog/product')->load($id); - if ($p->getId() == $id) { - $p->setData("mailchimp_sync_error", $error); - $p->getResource()->saveAttribute($p, 'mailchimp_sync_error'); - } else { - Mage::helper('mailchimp')->logError("Error: product " . $id . " not found"); - } - break; - case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: - $c = Mage::getModel('customer/customer')->load($id); - if ($c->getId() == $id) { - $c->setData("mailchimp_sync_error", $error); - $c->getResource()->saveAttribute($c, 'mailchimp_sync_error'); - } else { - Mage::helper('mailchimp')->logError("Error: customer " . $id . " not found"); - } - break; - case Ebizmarts_MailChimp_Model_Config::IS_ORDER: - $o = Mage::getModel('sales/order')->load($id); - if ($o->getId() == $id) { - $o->setData("mailchimp_sync_error", $error); - $o->setMailchimpSyncModified(0); - $o->setMailchimpUpdateObserverRan(true); - $o->save(); - } else { - Mage::helper('mailchimp')->logError("Error: order " . $id . " not found"); - } - break; - case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: - $q = Mage::getModel('sales/quote')->load($id); - if ($q->getId() == $id) { - $q->setData("mailchimp_sync_error", $error); - $q->save(); - } else { - Mage::helper('mailchimp')->logError("Error: quote " . $id . " not found"); - } - break; - case Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER: - $s = Mage::getModel('newsletter/subscriber')->load($id); - if ($s->getId() == $id) { - $s->setData("mailchimp_sync_error", $error); - $s->save(); - } else { - Mage::helper('mailchimp')->logError("Error: subscriber " . $id . " not found"); - } - break; - default: - Mage::helper('mailchimp')->logError("Error: no identification " . $type . " found"); - break; - } + Mage::helper('mailchimp')->saveEcommerceSyncData($id, $type, $mailchimpStoreId, null, $error, null, null, null, true); +// switch ($type) { +// case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: +// $p = Mage::getModel('catalog/product')->load($id); +// if ($p->getId() == $id) { +// $p->setData("mailchimp_sync_error", $error); +// $p->getResource()->saveAttribute($p, 'mailchimp_sync_error'); +// } else { +// Mage::helper('mailchimp')->logError("Error: product " . $id . " not found"); +// } +// break; +// case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: +// $c = Mage::getModel('customer/customer')->load($id); +// if ($c->getId() == $id) { +// $c->setData("mailchimp_sync_error", $error); +// $c->getResource()->saveAttribute($c, 'mailchimp_sync_error'); +// } else { +// Mage::helper('mailchimp')->logError("Error: customer " . $id . " not found"); +// } +// break; +// case Ebizmarts_MailChimp_Model_Config::IS_ORDER: +// $o = Mage::getModel('sales/order')->load($id); +// if ($o->getId() == $id) { +// $o->setData("mailchimp_sync_error", $error); +// $o->setMailchimpSyncModified(0); +// $o->setMailchimpUpdateObserverRan(true); +// $o->save(); +// } else { +// Mage::helper('mailchimp')->logError("Error: order " . $id . " not found"); +// } +// break; +// case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: +// $q = Mage::getModel('sales/quote')->load($id); +// if ($q->getId() == $id) { +// $q->setData("mailchimp_sync_error", $error); +// $q->save(); +// } else { +// Mage::helper('mailchimp')->logError("Error: quote " . $id . " not found"); +// } +// break; +// case Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER: +// $s = Mage::getModel('newsletter/subscriber')->load($id); +// if ($s->getId() == $id) { +// $s->setData("mailchimp_sync_error", $error); +// $s->save(); +// } else { +// Mage::helper('mailchimp')->logError("Error: subscriber " . $id . " not found"); +// } +// break; +// default: +// Mage::helper('mailchimp')->logError("Error: no identification " . $type . " found"); +// break; +// } $mailchimpErrors->setType($response->type); $mailchimpErrors->setTitle($response->title); @@ -361,8 +369,9 @@ protected function processEachResponseFile($files, $batchId) $mailchimpErrors->setRegtype($type); $mailchimpErrors->setOriginalId($id); $mailchimpErrors->setBatchId($batchId); + $mailchimpErrors->setStoreId($store[1]); $mailchimpErrors->save(); - Mage::helper('mailchimp')->logError($error); + Mage::helper('mailchimp')->logError($error, $store[1]); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 188d3b3be..f982b2f95 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -18,57 +18,62 @@ class Ebizmarts_MailChimp_Model_Api_Carts protected $_counter; protected $_batchId; protected $_api = null; + + protected $_token = null; /** * @param $mailchimpStoreId + * @param $magentoStoreId * @return array */ - public function createBatchJson($mailchimpStoreId) + public function createBatchJson($mailchimpStoreId, $magentoStoreId) { $allCarts = array(); if (!Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_ACTIVE)) { return $allCarts; } - $this->_firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_FIRSTDATE); + $this->_firstDate = Mage::helper('mailchimp')->getAbandonedCartFirstDate($magentoStoreId); $this->_counter = 0; $date = Mage::helper('mailchimp')->getDateMicrotime(); - $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_QUOTE.'_'.$date; + $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_QUOTE.'_'.$date; // get all the carts converted in orders (must be deleted on mailchimp) - $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId)); + $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)); + $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId)); // get new carts - $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId)); + $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId)); return $allCarts; } /** * @param $mailchimpStoreId + * @param $magentoStoreId * @return array */ - protected function _getConvertedQuotes($mailchimpStoreId) + protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) { $allCarts = array(); $convertedCarts = Mage::getModel('sales/quote')->getCollection(); // get only the converted quotes - $convertedCarts->addFieldToFilter('is_active', array('eq'=>0)); - // be sure that the quote are already in mailchimp - $convertedCarts->addFieldToFilter('mailchimp_sync_delta', array('neq' => '0000-00-00 00:00:00')); - $convertedCarts->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())); - // and not deleted - $convertedCarts->addFieldToFilter('mailchimp_deleted', array('eq'=>0)); - if ($this->_firstDate) { - $convertedCarts->addFieldToFilter('created_at', array('from' => $this->_firstDate)); - } - + $convertedCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + $convertedCarts->addFieldToFilter('is_active', array('eq' => 0)); + //join with mailchimp_ecommerce_sync_data table to filter by sync data. + $convertedCarts->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = main_table.entity_id and m4m.type = '".Ebizmarts_MailChimp_Model_Config::IS_QUOTE."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $convertedCarts->getSelect()->where("m4m.mailchimp_sync_deleted = 0"); // limit the collection $convertedCarts->getSelect()->limit(self::BATCH_LIMIT); foreach ($convertedCarts as $cart) { $cartId = $cart->getEntityId(); // we need to delete all the carts associated with this email - $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail()); + $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); if ($alreadySentCartId != $cartId) { @@ -76,9 +81,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; $allCarts[$this->_counter]['body'] = ''; - $cartForEmail->setData("mailchimp_sync_delta", Varien_Date::now()); - $cartForEmail->setMailchimpDeleted(1); - $this->_saveCart($cartForEmail); + $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, Varien_Date::now(), null, null, 1); $this->_counter += 1; } } @@ -88,9 +91,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; $allCarts[$this->_counter]['body'] = ''; - $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $cart->setMailchimpDeleted(1); - $this->_saveCart($cart); + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now(), null, null, 1); $this->_counter += 1; } @@ -99,20 +100,28 @@ protected function _getConvertedQuotes($mailchimpStoreId) /** * @param $mailchimpStoreId + * @param $magentoStoreId * @return array */ - protected function _getModifiedQuotes($mailchimpStoreId) + protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) { $allCarts = array(); $modifiedCarts = Mage::getModel('sales/quote')->getCollection(); // select carts with no orders $modifiedCarts->addFieldToFilter('is_active', array('eq'=>1)); - // select carts already sent to mailchimp and moodifief after - $modifiedCarts->addFieldToFilter('mailchimp_sync_delta', array('neq' => '0000-00-00 00:00:00')); - $modifiedCarts->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())); - $modifiedCarts->addFieldToFilter('mailchimp_sync_delta', array('lt'=>new Zend_Db_Expr('updated_at'))); - // and not deleted in mailchimp - $modifiedCarts->addFieldToFilter('mailchimp_deleted', array('eq'=>0)); + // select carts for the current Magento store id + $modifiedCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + //join with mailchimp_ecommerce_sync_data table to filter by sync data. + $modifiedCarts->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = main_table.entity_id and m4m.type = '".Ebizmarts_MailChimp_Model_Config::IS_QUOTE."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $modifiedCarts->getSelect()->where("m4m.mailchimp_sync_modified = 1 AND m4m.mailchimp_sync_deleted = 0 + AND m4m.mailchimp_sync_delta < '" . new Zend_Db_Expr('updated_at') . "'"); + // limit the collection $modifiedCarts->getSelect()->limit(self::BATCH_LIMIT); foreach ($modifiedCarts as $cart) { $cartId = $cart->getEntityId(); @@ -125,10 +134,10 @@ protected function _getModifiedQuotes($mailchimpStoreId) * @var $customer Mage_Customer_Model_Customer */ $customer = Mage::getModel("customer/customer"); - $customer->setWebsiteId(Mage::getModel('core/store')->load($cart->getStoreId())->getWebsiteId()); + $customer->setWebsiteId(Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId()); $customer->loadByEmail($cart->getCustomerEmail()); if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail()); + $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); if($alreadySentCartId != $cartId) { @@ -136,24 +145,21 @@ protected function _getModifiedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; $allCarts[$this->_counter]['body'] = ''; - $cartForEmail->setData("mailchimp_sync_delta", Varien_Date::now()); - $cartForEmail->setMailchimpDeleted(1); - $this->_saveCart($cartForEmail); + $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, Varien_Date::now(), null, null, 1); $this->_counter += 1; } } $allCartsForEmail->clear(); } - - if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { - $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $this->_saveCart($cart); + // avoid carts abandoned as guests when customer email associated to a registered customer. + if (!$cart->getCustomerId() && $customer->getEmail()==$cart->getCustomerEmail()) { + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now()); continue; } // send the products that not already sent - $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId); + $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId); if (count($productData)) { foreach($productData as $p) { $allCarts[$this->_counter] = $p; @@ -161,19 +167,19 @@ protected function _getModifiedQuotes($mailchimpStoreId) } } - if (count($cart->getAllVisibleItems())) { - $cartJson = $this->_makeCart($cart, $mailchimpStoreId); - if ($cartJson!="") { - $allCarts[$this->_counter]['method'] = 'POST'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; - $allCarts[$this->_counter]['body'] = $cartJson; - $this->_counter += 1; - } + $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); + if ($cartJson!="") { + $allCarts[$this->_counter]['method'] = 'POST'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; + $allCarts[$this->_counter]['body'] = $cartJson; + $this->_counter += 1; + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now(), null, null, null, $this->_token); + } else { + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now()); } + $this->_token = null; - $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $this->_saveCart($cart); } return $allCarts; @@ -183,41 +189,54 @@ protected function _getModifiedQuotes($mailchimpStoreId) * @param $mailchimpStoreId * @return array */ - protected function _getNewQuotes($mailchimpStoreId) + protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) { $allCarts = array(); $newCarts = Mage::getModel('sales/quote')->getCollection(); - $newCarts->addFieldToFilter('is_active', array('eq'=>1)) - ->addFieldToFilter( - 'mailchimp_sync_delta', array( - array('eq' => '0000-00-00 00:00:00'), - array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) - ) - ); - $newCarts->addFieldToFilter('created_at', array('from'=>$this->_firstDate)); + $newCarts->addFieldToFilter('is_active', array('eq'=>1)); $newCarts->addFieldToFilter('customer_email', array('notnull'=>true)); $newCarts->addFieldToFilter('items_count', array('gt'=>0)); + // select carts for the current Magento store id + $newCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + // filter by first date if exists. + if ($this->_firstDate) { + $newCarts->addFieldToFilter('created_at', array('gt' => $this->_firstDate)); + } + //join with mailchimp_ecommerce_sync_data table to filter by sync data. + $newCarts->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $newCarts->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); + // limit the collection $newCarts->getSelect()->limit(self::BATCH_LIMIT); + foreach ($newCarts as $cart) { - if (!count($cart->getAllVisibleItems())) { - $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $this->_saveCart($cart); + $cartId = $cart->getEntityId(); + $orderCollection = Mage::getModel('sales/order')->getCollection(); + $orderCollection->addFieldToFilter('main_table.customer_email', array('eq' => $cart->getCustomerEmail())) + ->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()) { + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now()); continue; } $customer = Mage::getModel("customer/customer"); - $customer->setWebsiteId(Mage::getModel('core/store')->load($cart->getStoreId())->getWebsiteId()); + $customer->setWebsiteId(Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId()); $customer->loadByEmail($cart->getCustomerEmail()); if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail()); + $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); foreach ($allCartsForEmail as $cartForEmail) { + $alreadySentCartId = $cartForEmail->getEntityId(); $allCarts[$this->_counter]['method'] = 'DELETE'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartForEmail->getEntityId(); - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartForEmail->getEntityId(); + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; $allCarts[$this->_counter]['body'] = ''; - $cartForEmail->setData("mailchimp_sync_delta", Varien_Date::now()); - $cartForEmail->setMailchimpDeleted(1); - $this->_saveCart($cartForEmail); + $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, Varien_Date::now(), null, null, 1); $this->_counter += 1; } @@ -226,13 +245,12 @@ protected function _getNewQuotes($mailchimpStoreId) // don't send the carts for guest customers who are registered if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { - $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $this->_saveCart($cart); + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now()); continue; } // send the products that not already sent - $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId); + $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId); if (count($productData)) { foreach($productData as $p) { $allCarts[$this->_counter] = $p; @@ -240,48 +258,60 @@ protected function _getNewQuotes($mailchimpStoreId) } } - $cartJson = $this->_makeCart($cart, $mailchimpStoreId); + $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); if ($cartJson!="") { $allCarts[$this->_counter]['method'] = 'POST'; $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cart->getEntityId(); + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; $allCarts[$this->_counter]['body'] = $cartJson; - $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $this->_saveCart($cart); $this->_counter += 1; + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now(), null, null, null, $this->_token); + } else { + $this->_updateSyncData($cartId, $mailchimpStoreId, Varien_Date::now()); } + $this->_token = null; } return $allCarts; } /** + * Get all existing carts in the current store view for a given email address. * * @param $email + * @param $mailchimpStoreId + * @param $magentoStoreId * @return object */ - protected function _getAllCartsByEmail($email) + protected function _getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) { $allCartsForEmail = Mage::getModel('sales/quote')->getCollection(); - $allCartsForEmail->addFieldToFilter('is_active', array('eq'=>1)); - $allCartsForEmail->addFieldToFilter('mailchimp_sync_delta', array('neq' => '0000-00-00 00:00:00')); - $allCartsForEmail->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())); - $allCartsForEmail->addFieldToFilter('mailchimp_deleted', array('eq'=>0)); - $allCartsForEmail->addFieldToFilter('customer_email', array('eq'=>$email)); + $allCartsForEmail->addFieldToFilter('is_active', array('eq' => 1)); + $allCartsForEmail->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + $allCartsForEmail->addFieldToFilter('customer_email', array('eq' => $email)); + $allCartsForEmail->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = main_table.entity_id and m4m.type = '".Ebizmarts_MailChimp_Model_Config::IS_QUOTE."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $allCartsForEmail->getSelect()->where("m4m.mailchimp_sync_deleted = 0 AND m4m.mailchimp_store_id = '".$mailchimpStoreId."'"); return $allCartsForEmail; } /** * @param $cart * @param $mailchimpStoreId + * @param $magentoStoreId * @return string */ - protected function _makeCart($cart,$mailchimpStoreId) + protected function _makeCart($cart, $mailchimpStoreId, $magentoStoreId) { $campaignId = $cart->getMailchimpCampaignId(); $oneCart = array(); $oneCart['id'] = $cart->getEntityId(); - $oneCart['customer'] = $this->_getCustomer($cart, $mailchimpStoreId); + $oneCart['customer'] = $this->_getCustomer($cart, $mailchimpStoreId, $magentoStoreId); if ($campaignId) { $oneCart['campaign_id'] = $campaignId; } @@ -333,28 +363,43 @@ protected function _makeCart($cart,$mailchimpStoreId) $jsonData = json_encode($oneCart); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Carts " . $cart->getId() . " json encode failed"); + Mage::helper('mailchimp')->logError("Carts " . $cart->getId() . " json encode failed", $magentoStoreId); } } return $jsonData; } - // @todo calculate the checkout url for the cart + + /** + * Get URL for the cart. + * + * @param $cart + * @return string + */ protected function _getCheckoutUrl($cart) { $token = md5(rand(0, 9999999)); $url = Mage::getModel('core/url')->setStore($cart->getStoreId())->getUrl('', array('_nosid' => true,'_secure' => true)) . 'mailchimp/cart/loadquote?id=' . $cart->getEntityId() . '&token=' . $token; - $cart->setMailchimpToken($token); + $this->_token = $token; return $url; } - protected function _getCustomer($cart,$mailchimpStoreId) + + /** + * Get Customer data for the cart. + * + * @param $cart + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + protected function _getCustomer($cart, $mailchimpStoreId, $magentoStoreId) { - $api = $this->_getApi(); + $api = Mage::helper('mailchimp')->getApi($magentoStoreId); $customers = array(); try { $customers = $api->ecommerce->customers->getByEmail($mailchimpStoreId, $cart->getCustomerEmail()); } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $magentoStoreId); } if (isset($customers['total_items']) && $customers['total_items'] > 0) { @@ -364,7 +409,6 @@ protected function _getCustomer($cart,$mailchimpStoreId) } else { if (!$cart->getCustomerId()) { $date = Mage::helper('mailchimp')->getDateMicrotime(); - $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_QUOTE.'_'.$date; $customer = array( "id" => "GUEST-" . $date, "email_address" => $cart->getCustomerEmail(), @@ -374,7 +418,7 @@ protected function _getCustomer($cart,$mailchimpStoreId) $customer = array( "id" => $cart->getCustomerId(), "email_address" => $cart->getCustomerEmail(), - "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin() + "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin($magentoStoreId) ); } } @@ -434,21 +478,19 @@ protected function _getCustomer($cart,$mailchimpStoreId) return $customer; } - protected function _getApi() - { - if (!$this->_api) { - $this->_api = Mage::helper('mailchimp')->getApi(); - } - - return $this->_api; - } /** - * @param $cart Mage_Sales_Model_Quote + * update product sync data + * + * @param $cartId + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param null $syncModified + * @param null $syncDeleted */ - protected function _saveCart($cart) + protected function _updateSyncData($cartId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = null, $syncDeleted = null, $token = null) { - - $cart->save(); + Mage::helper('mailchimp')->saveEcommerceSyncData($cartId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, $token); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index f45c2ce51..a5653e428 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -15,29 +15,29 @@ class Ebizmarts_MailChimp_Model_Api_Customers const BATCH_LIMIT = 100; - public function createBatchJson($mailchimpStoreId) + public function createBatchJson($mailchimpStoreId, $magentoStoreId) { //get customers - $collection = Mage::getModel('customer/customer')->getCollection() - ->addAttributeToSelect('id') - ->addAttributeToFilter( - array( - array('attribute' => 'mailchimp_sync_delta', 'null' => true), - array('attribute' => 'mailchimp_sync_delta', 'eq' => ''), - array('attribute' => 'mailchimp_sync_delta', 'lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()), - array('attribute' => 'mailchimp_sync_modified', 'eq'=> 1) - ), '', 'left' - ); + $collection = Mage::getModel('customer/customer')->getCollection(); + $collection->addFieldToFilter('store_id',array('eq' => $magentoStoreId)); + $collection->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = e.entity_id and m4m.type = '".Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null ". + "OR m4m.mailchimp_sync_modified = 1"); $collection->getSelect()->limit(self::BATCH_LIMIT); - $customerArray = array(); - $batchId = Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER . '_' . Mage::helper('mailchimp')->getDateMicrotime(); + $batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER . '_' . Mage::helper('mailchimp')->getDateMicrotime(); $counter = 0; foreach ($collection as $item) { - $customer = Mage::getModel('customer/customer')->load($item->getId()); - $data = $this->_buildCustomerData($customer); + $customerId = $item->getId(); + $customer = Mage::getModel('customer/customer')->load($customerId); + $data = $this->_buildCustomerData($customer, $magentoStoreId); $customerJson = ""; //enconde to JSON @@ -45,20 +45,17 @@ public function createBatchJson($mailchimpStoreId) $customerJson = json_encode($data); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Customer ".$customer->getId()." json encode failed"); + Mage::helper('mailchimp')->logError("Customer ".$customer->getId()." json encode failed on store ".$magentoStoreId, $magentoStoreId); } if (!empty($customerJson)) { $customerArray[$counter]['method'] = "PUT"; - $customerArray[$counter]['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/customers/" . $customer->getId(); - $customerArray[$counter]['operation_id'] = $batchId . '_' . $customer->getId(); + $customerArray[$counter]['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/customers/" . $customerId; + $customerArray[$counter]['operation_id'] = $batchId . '_' . $customerId; $customerArray[$counter]['body'] = $customerJson; //update customers delta - $customer->setData("mailchimp_sync_delta", Varien_Date::now()); - $customer->setData("mailchimp_sync_error", ""); - $customer->setData("mailchimp_sync_modified", 0); - $this->_saveCustomer($customer); + $this->_updateSyncData($customerId, $mailchimpStoreId, Varien_Date::now()); } $counter++; @@ -67,29 +64,29 @@ public function createBatchJson($mailchimpStoreId) return $customerArray; } - protected function _buildCustomerData($customer) + protected function _buildCustomerData($customer, $magentoStoreId) { - $firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); $data = array(); $data["id"] = $customer->getId(); $data["email_address"] = $customer->getEmail() ? $customer->getEmail() : ''; $data["first_name"] = $customer->getFirstname() ? $customer->getFirstname() : ''; $data["last_name"] = $customer->getLastname() ? $customer->getLastname() : ''; - $data["opt_in_status"] = $this->getOptin(); + $data["opt_in_status"] = $this->getOptin($magentoStoreId); //customer orders data $orderCollection = Mage::getModel('sales/order')->getCollection() - ->addFieldToFilter('state', 'complete') + ->addFieldToFilter('state', + array( + array('neq' => Mage_Sales_Model_Order::STATE_CANCELED), + array('neq' => Mage_Sales_Model_Order::STATE_CLOSED) + )) ->addAttributeToFilter('customer_id', array('eq' => $customer->getId())); - if($firstDate) { - $orderCollection->addFieldToFilter('created_at', array('from' => $firstDate)); - } $totalOrders = 0; $totalAmountSpent = 0; - foreach ($orderCollection as $order) { + foreach ($orderCollection as $customerOrder) { $totalOrders++; - $totalAmountSpent += (int)$order->getGrandTotal(); + $totalAmountSpent += ($customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded() - $customerOrder->getTotalCanceled()); } $data["orders_count"] = $totalOrders; @@ -105,7 +102,7 @@ protected function _buildCustomerData($customer) $customerAddress["address1"] = $street[0]; } - if (count($street) > 1) { + if (count($street) > 1 && $street[1]) { $customerAddress["address2"] = $street[1]; } @@ -130,7 +127,7 @@ protected function _buildCustomerData($customer) $customerAddress["country_code"] = $address->getCountry(); } - if (count($address)) { + if (count($customerAddress)) { $data["address"] = $customerAddress; } @@ -142,7 +139,6 @@ protected function _buildCustomerData($customer) break; } } - $mergeFields = $this->getMergeVars($customer); if (is_array($mergeFields)) { $data = array_merge($mergeFields, $data); @@ -150,18 +146,26 @@ protected function _buildCustomerData($customer) return $data; } - public function update($customer) + + /** + * Update customer sync data after modification. + * + * @param $customerId + * @param $storeId + */ + public function update($customerId, $storeId) { - if (Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { - $customer->setData("mailchimp_sync_error", ""); - $customer->setData("mailchimp_sync_modified", 1); + if (Mage::helper('mailchimp')->isEcomSyncDataEnabled($storeId)) { + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId); + $this->_updateSyncData($customerId, $mailchimpStoreId, null, null, 1, true); } } public function getMergeVars($object) { $storeId = $object->getStoreId(); - $maps = unserialize(Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_MAP_FIELDS, $storeId)); + $value = Mage::helper('mailchimp')->getMapFields($storeId); + $maps = unserialize($value); $websiteId = Mage::getModel('core/store')->load($storeId)->getWebsiteId(); $attrSetId = Mage::getResourceModel('eav/entity_attribute_collection') ->setEntityTypeFilter(1) @@ -179,9 +183,9 @@ public function getMergeVars($object) $chimpTag = $map['mailchimp']; if ($chimpTag && $customAtt) { $key = strtoupper($chimpTag); + $attributeCode = $customAtt; foreach ($attrSetId as $attribute) { if ($attribute['attribute_id'] == $customAtt) { - $attributeCode = $attribute['attribute_code']; if ($customer->getId()) { // if ($customer->getData($attributeCode)) { switch ($attributeCode) { @@ -189,13 +193,12 @@ public function getMergeVars($object) break; case 'default_billing': case 'default_shipping': - $addr = explode('_', $attributeCode); - $address = $customer->{'getPrimary' . ucfirst($addr[1]) . 'Address'}(); - if (!$address) { - if ($customer->{'getDefault' . ucfirst($addr[1])}()) { - $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[1])}()); - } - } + $address = $customer->getPrimaryAddress($attributeCode); +// if (!$address) { +// if ($customer->{'getDefault' . ucfirst($addr[1])}()) { +// $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[1])}()); +// } +// } if ($address) { $street = $address->getStreet(); @@ -280,12 +283,7 @@ public function getMergeVars($object) case 'billing_company': case 'shipping_company': $addr = explode('_', $attributeCode); - $address = $customer->{'getPrimary' . ucfirst($addr[0]) . 'Address'}(); - if (!$address) { - if ($customer->{'getDefault' . ucfirst($addr[0])}()) { - $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); - } - } + $address = $customer->getPrimaryAddress('default_'.ucfirst($addr[0])); if ($address) { $company = $address->getCompany(); @@ -297,12 +295,7 @@ public function getMergeVars($object) case 'billing_telephone': case 'shipping_telephone': $addr = explode('_', $attributeCode); - $address = $customer->{'getPrimary' . ucfirst($addr[0]) . 'Address'}(); - if (!$address) { - if ($customer->{'getDefault' . ucfirst($addr[0])}()) { - $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); - } - } + $address = $customer->getPrimaryAddress('default_'.ucfirst($addr[0])); if ($address) { $telephone = $address->getTelephone(); @@ -314,12 +307,7 @@ public function getMergeVars($object) case 'billing_country': case 'shipping_country': $addr = explode('_', $attributeCode); - $address = $customer->{'getPrimary' . ucfirst($addr[0]) . 'Address'}(); - if (!$address) { - if ($customer->{'getDefault' . ucfirst($addr[0])}()) { - $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); - } - } + $address = $customer->getPrimaryAddress('default_'.ucfirst($addr[0])); if ($address) { $countryCode = $address->getCountry(); @@ -332,12 +320,7 @@ public function getMergeVars($object) case 'billing_zipcode': case 'shipping_zipcode': $addr = explode('_', $attributeCode); - $address = $customer->{'getPrimary' . ucfirst($addr[0]) . 'Address'}(); - if (!$address) { - if ($customer->{'getDefault' . ucfirst($addr[0])}()) { - $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); - } - } + $address = $customer->getPrimaryAddress('default_'.ucfirst($addr[0])); if ($address) { $zipCode = $address->getPostcode(); @@ -366,9 +349,9 @@ public function createGuestCustomer($guestId, $order) return $guestCustomer; } - public function getOptin() + public function getOptin($magentoStoreId) { - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMERS_OPTIN, 0)) { + if (Mage::helper('mailchimp')->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMERS_OPTIN, $magentoStoreId)) { $optin = true; } else { $optin = false; @@ -376,18 +359,19 @@ public function getOptin() return $optin; } - protected function _saveCustomer($customer) - { - if($customer->dataHasChangedFor('mailchimp_sync_delta')) { - $customer->getResource()->saveAttribute($customer, 'mailchimp_sync_delta'); - } - - if($customer->dataHasChangedFor('mailchimp_sync_error')) { - $customer->getResource()->saveAttribute($customer, 'mailchimp_sync_error'); - } - if($customer->dataHasChangedFor('mailchimp_sync_modified')) { - $customer->getResource()->saveAttribute($customer, 'mailchimp_sync_modified'); - } + /** + * update customer sync data + * + * @param $customerId + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param null $syncModified + * @param bool $saveOnlyIfexists + */ + protected function _updateSyncData($customerId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = null, $saveOnlyIfexists = false) + { + Mage::helper('mailchimp')->saveEcommerceSyncData($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, null, null, $saveOnlyIfexists); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 2da8c1ebb..146edcfc3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -31,41 +31,48 @@ class Ebizmarts_MailChimp_Model_Api_Orders * Set the request for orders to be created on MailChimp * * @param $mailchimpStoreId + * @param $magentoStoreId * @return array */ - public function createBatchJson($mailchimpStoreId) + public function createBatchJson($mailchimpStoreId, $magentoStoreId) { $batchArray = array(); - $this->_firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); + $this->_firstDate = Mage::helper('mailchimp')->getEcommerceFirstDate($magentoStoreId); $this->_counter = 0; - $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' . Mage::helper('mailchimp')->getDateMicrotime(); + $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' . Mage::helper('mailchimp')->getDateMicrotime(); - // get all the carts modified but not converted in orders - $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId)); - // get new carts - $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId)); + // get all the orders modified + $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId, $magentoStoreId)); + // get new orders + $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId, $magentoStoreId)); return $batchArray; } - protected function _getModifiedOrders($mailchimpStoreId) + protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) { $batchArray = array(); - //create missing products first - $collection = Mage::getModel('sales/order')->getCollection() - ->addAttributeToSelect('entity_id') - ->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())) - ->addFieldToFilter('mailchimp_sync_modified', array('eq' => 1)); - if ($this->_firstDate) { - $collection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); - } - - $collection->getSelect()->limit(self::BATCH_LIMIT); + $modifiedOrders = Mage::getModel('sales/order')->getCollection(); + // select orders for the current Magento store id + $modifiedOrders->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + //join with mailchimp_ecommerce_sync_data table to filter by sync data. + $modifiedOrders->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the order are already in mailchimp and not deleted + $modifiedOrders->getSelect()->where("m4m.mailchimp_sync_modified = 1"); + // limit the collection + $modifiedOrders->getSelect()->limit(self::BATCH_LIMIT); - foreach ($collection as $item) { + foreach ($modifiedOrders as $item) { try { - $order = Mage::getModel('sales/order')->load($item->getEntityId()); - $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId); + $orderId = $item->getEntityId(); + $order = Mage::getModel('sales/order')->load($orderId); + //create missing products first + $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId); if (count($productData)) { foreach ($productData as $p) { $batchArray[$this->_counter] = $p; @@ -73,137 +80,95 @@ protected function _getModifiedOrders($mailchimpStoreId) } } - $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); + $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, true); if (!empty($orderJson)) { $batchArray[$this->_counter]['method'] = "PATCH"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); - $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $orderId; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; $batchArray[$this->_counter]['body'] = $orderJson; } else { $error = Mage::helper('mailchimp')->__('Something went wrong when retreiving product information.'); - $order->setData("mailchimp_sync_error", $error); + $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now(), $error); + continue; } //update order delta - $order->setData("mailchimp_sync_delta", Varien_Date::now()); - $order->setMailchimpSyncModified(0); - $order->setMailchimpUpdateObserverRan(true); - $order->save(); + $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now()); $this->_counter++; } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $magentoStoreId); } } return $batchArray; } - protected function _getNewOrders($mailchimpStoreId) + protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) { $batchArray = array(); - //create missing products first - $collection = Mage::getModel('sales/order')->getCollection() - ->addAttributeToSelect('entity_id') - ->addFieldToFilter( - 'mailchimp_sync_delta', array( - array('null' => true), - array('eq' => ''), - array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) - ) - ); + $newOrders = Mage::getModel('sales/order')->getCollection(); + // select carts for the current Magento store id + $newOrders->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + // filter by first date if exists. if ($this->_firstDate) { - $collection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); + $newOrders->addFieldToFilter('created_at', array('gt' => $this->_firstDate)); } + $newOrders->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the orders are not in mailchimp + $newOrders->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); + // limit the collection + $newOrders->getSelect()->limit(self::BATCH_LIMIT); - $collection->getSelect()->limit(self::BATCH_LIMIT); - - foreach ($collection as $item) { + foreach ($newOrders as $item) { try { - $order = Mage::getModel('sales/order')->load($item->getEntityId()); - $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId); + $orderId = $item->getEntityId(); + $order = Mage::getModel('sales/order')->load($orderId); + //create missing products first + $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId); if (count($productData)) { foreach ($productData as $p) { $batchArray[$this->_counter] = $p; $this->_counter++; } } - - $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); + $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 . '_' . $order->getEntityId(); + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; $batchArray[$this->_counter]['body'] = $orderJson; } else { $error = Mage::helper('mailchimp')->__('Something went wrong when retreiving product information.'); - $order->setData("mailchimp_sync_error", $error); + $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now(), $error); } //update order delta - $order->setData("mailchimp_sync_delta", Varien_Date::now()); - $order->setMailchimpSyncModified(0); - $order->setMailchimpUpdateObserverRan(true); - $order->save(); + $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now()); $this->_counter++; } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $magentoStoreId); } } return $batchArray; } - /** - * Set the orders to be removed from MailChimp because they were canceled - * - * @param $mailchimpStoreId - * @return array - */ -// public function createCanceledBatchJson($mailchimpStoreId) -// { -// //create missing products first -// $collection = Mage::getModel('sales/order')->getCollection() -// ->addAttributeToSelect('status') -// ->addAttributeToSelect('mailchimp_sync_delta') -// ->addAttributeToSelect('entity_id') -// ->addFieldToFilter('state', 'canceled') -// ->addFieldToFilter( -// 'mailchimp_sync_delta', array( -// array('null' => true), -// array('eq' => ''), -// array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) -// ) -// ); -// $collection->getSelect()->limit(self::BATCH_LIMIT); -// -// $batchArray = array(); -// $counter = 0; -// foreach ($collection as $order) { -// if (!empty($orderJson)) { -// $batchArray[$counter]['method'] = "DELETE"; -// $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); -// -// //update order delta -// $order->setData("mailchimp_sync_delta", Varien_Date::now()); -// $order->save(); -// } -// $counter++; -// } -// -// return $batchArray; -// } - /** * Set all the data for each order to be sent * * @param $order * @param $mailchimpStoreId + * @param $magentoStoreId + * @param $isModifiedOrder * @return string */ - protected function GeneratePOSTPayload($order, $mailchimpStoreId) + protected function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, $isModifiedOrder = false) { -// $order = Mage::getModel('sales/order')->load($orderFromCollection->getEntityId()); - $data = array(); $data['id'] = $order->getEntityId(); if ($order->getMailchimpCampaignId()) { @@ -245,11 +210,12 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) } $data['lines'] = array(); - //order lines $items = $order->getAllVisibleItems(); $itemCount = 0; foreach ($items as $item) { + $productId = $item->getProductId(); + $productSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { $options = $item->getProductOptions(); $sku = $options['simple_sku']; @@ -258,51 +224,38 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) continue; } } else { - $variant = $item->getProductId(); + $variant = $productId; } - - // load the product and check if the product was already sent to mailchimp - $syncDelta = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), 'mailchimp_sync_delta', $order->getStoreId()); - $syncError = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), 'mailchimp_sync_error', $order->getStoreId()); - - if ($syncDelta && $syncError == 0) { + if ($productSyncData->getMailchimpSyncDelta() && $productSyncData->getMailchimpSyncError() == 0) { $itemCount++; $data["lines"][] = array( "id" => (string)$itemCount, - "product_id" => $item->getProductId(), + "product_id" => $productId, "product_variant_id" => $variant, "quantity" => (int)$item->getQtyOrdered(), "price" => $item->getPrice(), - "discount" => $item->getDiscountAmount() + "discount" => abs($item->getDiscountAmount()) ); } } - if (!$itemCount) { unset($data['lines']); return ""; } - //customer data - $api = $this->_getApi(); + $api = Mage::helper('mailchimp')->getApi($magentoStoreId); $customers = array(); try { $customers = $api->ecommerce->customers->getByEmail($mailchimpStoreId, $order->getCustomerEmail()); } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $magentoStoreId); } - - if (!$this->_isModifiedOrder($order)) { + if (!$isModifiedOrder) { if (isset($customers['total_items']) && $customers['total_items'] > 0) { $id = $customers['customers'][0]['id']; $data['customer'] = array( 'id' => $id ); -// $guestCustomer = Mage::getModel('mailchimp/api_customers')->createGuestCustomer($id, $order); -// $mergeFields = Mage::getModel('mailchimp/api_customers')->getMergeVars($guestCustomer); -// if (is_array($mergeFields)) { -// $data['customer'] = array_merge($mergeFields, $data['customer']); -// } } else { if ((bool)$order->getCustomerIsGuest()) { $guestId = "GUEST-" . Mage::helper('mailchimp')->getDateMicrotime(); @@ -311,11 +264,6 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) "email_address" => $order->getCustomerEmail(), "opt_in_status" => false ); -// $guestCustomer = Mage::getModel('mailchimp/api_customers')->createGuestCustomer($guestId, $order); -// $mergeFields = Mage::getModel('mailchimp/api_customers')->getMergeVars($guestCustomer); -// if (is_array($mergeFields)) { -// $data['customer'] = array_merge($mergeFields, $data['customer']); -// } } else { $custEmailAddr = null; try { @@ -329,7 +277,7 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) $data["customer"] = array( "id" => ($order->getCustomerId()) ? $order->getCustomerId() : $guestId = "CUSTOMER-" . Mage::helper('mailchimp')->getDateMicrotime(), "email_address" => ($custEmailAddr) ? $custEmailAddr : $order->getCustomerEmail(), - "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin() + "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin($magentoStoreId) ); } } @@ -342,12 +290,12 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) } } - $store = Mage::getModel('core/store')->load($order->getStoreId()); + $store = Mage::getModel('core/store')->load($magentoStoreId); $data['order_url'] = $store->getUrl( 'sales/order/view/', array( - 'order_id' => $order->getId(), - '_nosid' => true, - '_secure' => true + 'order_id' => $order->getId(), + '_nosid' => true, + '_secure' => true ) ); if ($order->getCustomerFirstname()) { @@ -357,48 +305,38 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) if ($order->getCustomerLastname()) { $data["customer"]["last_name"] = $order->getCustomerLastname(); } - $billingAddress = $order->getBillingAddress(); $street = $billingAddress->getStreet(); $address = array(); - if ($street[0]) { - $address["address1"] = $street[0]; - $data['billing_address']["address1"] = $street[0]; + $address["address1"] = $data['billing_address']["address1"] = $street[0]; } if (count($street) > 1) { - $address["address2"] = $street[1]; - $data['billing_address']["address2"] = $street[1]; + $address["address2"] = $data['billing_address']["address2"] = $street[1]; } if ($billingAddress->getCity()) { - $address["city"] = $billingAddress->getCity(); - $data['billing_address']["city"] = $billingAddress->getCity(); + $address["city"] = $data['billing_address']["city"] = $billingAddress->getCity(); } if ($billingAddress->getRegion()) { - $address["province"] = $billingAddress->getRegion(); - $data['billing_address']["province"] = $billingAddress->getRegion(); + $address["province"] = $data['billing_address']["province"] = $billingAddress->getRegion(); } if ($billingAddress->getRegionCode()) { - $address["province_code"] = $billingAddress->getRegionCode(); - $data['billing_address']["province_code"] = $billingAddress->getRegionCode(); + $address["province_code"] = $data['billing_address']["province_code"] = $billingAddress->getRegionCode(); } if ($billingAddress->getPostcode()) { - $address["postal_code"] = $billingAddress->getPostcode(); - $data['billing_address']["postal_code"] = $billingAddress->getPostcode(); + $address["postal_code"] = $data['billing_address']["postal_code"] = $billingAddress->getPostcode(); } if ($billingAddress->getCountry()) { - $address["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); - $address["country_code"] = $billingAddress->getCountry(); - $data['billing_address']["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); - $data['billing_address']["country_code"] = $billingAddress->getCountry(); + $countryName = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $address["country"] = $data['billing_address']["country"] = $countryName; + $address["country_code"] = $data['billing_address']["country_code"] = $billingAddress->getCountry(); } - if (count($address)) { $data["customer"]["address"] = $address; } @@ -409,10 +347,8 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) //company if ($billingAddress->getCompany()) { - $data["customer"]["company"] = $billingAddress->getCompany(); - $data["billing_address"]["company"] = $billingAddress->getCompany(); + $data["customer"]["company"] = $data["billing_address"]["company"] = $billingAddress->getCompany(); } - $shippingAddress = $order->getShippingAddress(); if ($shippingAddress) { $street = $shippingAddress->getStreet(); @@ -453,52 +389,34 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) $data["shipping_address"]["company"] = $shippingAddress->getCompany(); } } - //customer orders data $orderCollection = Mage::getModel('sales/order')->getCollection() - ->addFieldToFilter('state', array('eq' => 'complete')) - ->addAttributeToFilter('customer_email', array('eq' => $order->getCustomerEmail())) - ->addFieldToFilter('mailchimp_sync_delta', array('notnull' => true)) - ->addFieldToFilter('mailchimp_sync_delta', array('neq' => '')) - ->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())) - ->addFieldToFilter('mailchimp_sync_error', array('eq' => "")); - if ($this->_firstDate) { - $orderCollection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); - } - + ->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 = 1; $totalAmountSpent = (int)$order->getGrandTotal(); - foreach ($orderCollection as $orderAlreadySent) { + foreach ($orderCollection as $customerOrder) { $totalOrders++; - $totalAmountSpent += (int)$orderAlreadySent->getGrandTotal(); + $totalAmountSpent += ($customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded() - $customerOrder->getTotalCanceled()); } $data["customer"]["orders_count"] = $totalOrders; $data["customer"]["total_spent"] = $totalAmountSpent; $jsonData = ""; - //enconde to JSON try { $jsonData = json_encode($data); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Order " . $order->getEntityId() . " json encode failed"); + Mage::helper('mailchimp')->logError("Order " . $order->getEntityId() . " json encode failed", $magentoStoreId); } - return $jsonData; } - /** - * Return true if order has been already sent to MailChimp and has been modified afterwards. - * - * @param $order - * @return bool - */ - protected function _isModifiedOrder($order) - { - return ($order->getMailchimpSyncModified() && $order->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()); - } - protected function _getMailChimpStatus($order) { $mailChimpFinancialStatus = null; @@ -560,25 +478,30 @@ protected function _getMailChimpStatus($order) return $mailChimpStatus; } - public function update($order) + /** + * @param $orderId + * @param $magentoStoreId + */ + public function update($orderId, $magentoStoreId) { - if (Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { - $order->setData('mailchimp_sync_error', ''); - $order->setData('mailchimp_sync_modified', 1); + if (Mage::helper('mailchimp')->isEcomSyncDataEnabled($magentoStoreId)) { + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($magentoStoreId); + $this->_updateSyncData($orderId, $mailchimpStoreId, null, null, 1, true); } } /** - * Get Api Object + * update customer sync data * - * @return Ebizmarts_Mailchimp|null + * @param $orderId + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param null $syncModified + * @param bool $saveOnlyIfexists */ - protected function _getApi() + protected function _updateSyncData($orderId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = null, $saveOnlyIfexists = false) { - if (!$this->_api) { - $this->_api = Mage::helper('mailchimp')->getApi(); - } - - return $this->_api; + Mage::helper('mailchimp')->saveEcommerceSyncData($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, null, null, $saveOnlyIfexists); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 3f280af11..4e8860f73 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -14,39 +14,40 @@ class Ebizmarts_MailChimp_Model_Api_Products const BATCH_LIMIT = 100; - public function createBatchJson($mailchimpStoreId) + public function createBatchJson($mailchimpStoreId, $magentoStoreId) { - $store = Mage::app()->getDefaultStoreView(); + //if MailChimp store configured on website or default config send website, default config respectively + $magentoStoreId = Mage::helper('mailchimp')->getDefaultStoreIdForMailChimpScope($magentoStoreId); //create missing products first - $collection = Mage::getModel('catalog/product')->getCollection() - ->addAttributeToSelect('id') - ->addAttributeToFilter('status', Mage_Catalog_Model_Product_Status::STATUS_ENABLED) - ->addAttributeToFilter( - array( - array('attribute' => 'mailchimp_sync_delta', 'null' => true), - array('attribute' => 'mailchimp_sync_delta', 'eq' => ''), - array('attribute' => 'mailchimp_sync_delta', 'lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()), - array('attribute' => 'mailchimp_sync_modified', 'eq' => 1) - ), '', 'left' - ); + $collection = Mage::getModel('catalog/product')->getCollection(); + $collection->setStoreId($magentoStoreId); + $collection->getSelect()->joinLeft( + ['m4m' => 'mailchimp_ecommerce_sync_data'], + "m4m.related_id = e.entity_id and m4m.type = '".Ebizmarts_MailChimp_Model_Config::IS_PRODUCT."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null ". + "OR m4m.mailchimp_sync_modified = 1"); $collection->getSelect()->limit(self::BATCH_LIMIT); $batchArray = array(); - $batchId = Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . '_' . Mage::helper('mailchimp')->getDateMicrotime(); + $batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . '_' . Mage::helper('mailchimp')->getDateMicrotime(); $counter = 0; foreach ($collection as $item) { - $product = Mage::getModel('catalog/product')->setStoreId($store->getId())->load($item->getId()); - $product->getTierPrice(); + $product = Mage::getModel('catalog/product')->setStoreId($magentoStoreId)->load($item->getEntityId()); + if ($item->getMailchimpSyncDeleted()) { + $batchArray = array_merge($this->buildProductDataRemoval($product, $batchId, $mailchimpStoreId, $magentoStoreId), $batchArray); + } //define variants and root products - if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { - $batchArray = array_merge($this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId), $batchArray); + if ($item->getMailchimpSyncModified() && $item->getMailchimpSyncDelta() && $item->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId)) { + $batchArray = array_merge($this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId), $batchArray); $counter = (count($batchArray)); - $this->_setProductNoError($product); - $this->_saveProduct($product); + $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now()); continue; } else { - $data = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId); + $data = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); } if (!empty($data)) { @@ -54,20 +55,15 @@ public function createBatchJson($mailchimpStoreId) $counter++; //update product delta - $this->_setProductNoError($product); - $this->_saveProduct($product); + $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now()); } else { - $product->setData("mailchimp_sync_delta", Varien_Date::now()); - $product->setData("mailchimp_sync_error", "This product type is not supported on MailChimp."); - $product->setData('mailchimp_sync_modified', 0); - $this->_saveProduct($product); - continue; + $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now(), "This product type is not supported on MailChimp."); } } return $batchArray; } - protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId) + protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) { $variantProducts = array(); if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE) { @@ -75,12 +71,12 @@ protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId) } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { //get children $childProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($product->getId()); - + //add itself as variant $variantProducts[] = $product; if (count($childProducts[0])) { foreach ($childProducts[0] as $childId) { - $variantProducts[] = Mage::getModel('catalog/product')->load($childId); + $variantProducts[] = Mage::getModel('catalog/product')->setStoreId($magentoStoreId)->load($childId); } } } else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL || $product->getTypeId() == "downloadable") { @@ -97,7 +93,7 @@ protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId) $body = json_encode($bodyData); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed"); + Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId); return array(); } @@ -108,7 +104,7 @@ protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId) $data['body'] = $body; return $data; } - protected function _buildOldProductRequest($product,$batchId,$mailchimpStoreId) + protected function _buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) { $operations = array(); if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_SIMPLE || $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL || $product->getTypeId() == "downloadable") { @@ -140,7 +136,7 @@ protected function _buildOldProductRequest($product,$batchId,$mailchimpStoreId) $body = json_encode($variendata); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed"); + Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId); continue; } @@ -204,58 +200,90 @@ protected function _buildProductData($product, $isVarient = true, $variants = nu return $data; } - public function update($product) + + /** + * Update product sync data after modification. + * + * @param $productId + * @param $storeId + */ + public function update($productId, $storeId) { - if (Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { - $product->setData('mailchimp_sync_error', ''); - $product->setData('mailchimp_sync_modified', 1); + if (Mage::helper('mailchimp')->isEcomSyncDataEnabled($storeId)) { + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId); + $this->_updateSyncData($productId, $mailchimpStoreId, null, null, 1, null, true); } } - public function sendModifiedProduct($order, $mailchimpStoreId) + + /** + * Return products belonging to an order or a cart in a valid format to be sent to MailChimp. + * + * @param $order + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) { $data = array(); - $batchId = Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . '_' . Mage::helper('mailchimp')->getDateMicrotime(); + $batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . '_' . Mage::helper('mailchimp')->getDateMicrotime(); $items = $order->getAllVisibleItems(); +// $magentoStoreId = Mage::helper('mailchimp')->getDefaultStoreIdForMailChimpScope($magentoStoreId); foreach ($items as $item) { $product = Mage::getModel('catalog/product')->load($item->getProductId()); + $productSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($product->getId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); if ($product->getId()!=$item->getProductId()||$product->getTypeId()=='bundle'||$product->getTypeId()=='grouped') { + if ($product->getId()) { + $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now(), "This product type is not supported on MailChimp."); + } continue; } - if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { - $data[] = $this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId); - $this->_setProductNoError($product); - $this->_saveProduct($product); - } elseif (!$product->getMailchimpSyncDelta() || $product->getMailchimpSyncDelta() < Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { - $data[] = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId); - $this->_setProductNoError($product); - $this->_saveProduct($product); + if ($productSyncData->getMailchimpSyncModified() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId)) { + $data[] = $this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now()); + } elseif (!$productSyncData->getMailchimpSyncDelta() || $productSyncData->getMailchimpSyncDelta() < Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId)) { + $data[] = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now()); } } - return $data; } - protected function _setProductNoError($product) - { - $product->setData("mailchimp_sync_delta", Varien_Date::now()); - $product->setData("mailchimp_sync_error", ""); - $product->setData('mailchimp_sync_modified', 0); + /** + * update product sync data + * + * @param $productId + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param null $syncModified + * @param null $syncDeleted + * @param bool $saveOnlyIfexists + */ + protected function _updateSyncData($productId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = null, $syncDeleted = null, $saveOnlyIfexists = false) + { + Mage::helper('mailchimp')->saveEcommerceSyncData($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, null, $saveOnlyIfexists); } - protected function _saveProduct($product) + + public function buildProductDataRemoval($product, $batchId, $mailchimpStoreId) { - if($product->dataHasChangedFor('mailchimp_sync_delta')) { - $product->getResource()->saveAttribute($product, 'mailchimp_sync_delta'); - } + //@Todo handle product removal + $productdata = array(); - if($product->dataHasChangedFor('mailchimp_sync_error')) { - $product->getResource()->saveAttribute($product, 'mailchimp_sync_error'); - } + $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($product->getId()); - if($product->dataHasChangedFor('mailchimp_sync_modified')) { - $product->getResource()->saveAttribute($product, 'mailchimp_sync_modified'); + if (empty($parentIds)) { + $parentIds = array($product->getId()); } - } + //add or update variant +// foreach ($parentIds as $parentId) { +// $productdata['method'] = "DELETE"; +// $productdata['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/" . $parentId . '/variants/' . $data['id']; +// $productdata['operation_id'] = $batchId . '_' . $parentId; +// } + + } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index a63ef8771..0cbf11de2 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -13,65 +13,73 @@ class Ebizmarts_MailChimp_Model_Api_Stores { - /** - * @return bool|mixed - * @throws Exception - */ - public function getMailChimpStore() - { - $api = Mage::helper('mailchimp')->getApi(); - - if ($api) { - $storeExists = null; - $storeId = Mage::helper('mailchimp')->getMCStoreId(); - - if ($storeId == null || $storeId == "") { - return null; - } - - try { - $store = $api->ecommerce->stores->get($storeId); - if (is_array($store) && isset($store['id'])) { - $storeExists = $store; - } - } - catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); - } - catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); - } - - return $storeExists; - } else { - throw new Exception('You must provide a MailChimp API key'); - } - } +// /** +// * Return MailChimp store for given scope if exists, else return null. +// * +// * @param $scope +// * @param $scopeId +// * @return array|null +// * @throws Exception +// */ +// public function getMailChimpStore($scope, $scopeId) +// { +// $api = Mage::helper('mailchimp')->getApi($scopeId, $scope); +// +// if ($api) { +// $storeExists = null; +// $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($scopeId, $scope); +// +// if ($mailchimpStoreId == null || $mailchimpStoreId == "") { +// return null; +// } +// +// try { +// $store = $api->ecommerce->stores->get($mailchimpStoreId); +// if (is_array($store) && isset($store['id'])) { +// $storeExists = $store; +// } +// } +// catch (Mailchimp_Error $e) { +// Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); +// } +// catch (Exception $e) { +// Mage::helper('mailchimp')->logError($e->getMessage()); +// } +// +// return $storeExists; +// } else { +// throw new Exception('You must provide a MailChimp API key'); +// } +// } /** - * @param $storeId + * Create MailChimp store. + * + * @param $mailChimpStoreId * @param null $listId + * @param $scope + * @param $scopeId * @throws Exception */ - public function createMailChimpStore($storeId, $listId=null) + public function createMailChimpStore($mailChimpStoreId, $listId=null, $scopeId, $scope) { - $api = Mage::helper('mailchimp')->getApi(); + $api = Mage::helper('mailchimp')->getApi($scopeId, $scope); if ($api) { if (!$listId) { - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); + $listId = Mage::helper('mailchimp')->getGeneralList($scopeId, $scope); } if ($listId != null && $listId != "") { - $storeName = Mage::helper('mailchimp')->getMCStoreName(); - $storeEmail = Mage::helper('mailchimp')->getConfigValue('trans_email/ident_general/email'); + $storeName = Mage::helper('mailchimp')->getMCStoreName($scopeId, $scope); + $storeEmail = Mage::helper('mailchimp')->getConfigValueForScope('trans_email/ident_general/email', $scopeId, $scope); if (strpos($storeEmail, 'example.com') !== false) { $storeEmail = null; throw new Exception('Please, change the general email in Store Email Addresses/General Contact'); } - $currencyCode = Mage::helper('mailchimp')->getConfigValue(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_DEFAULT); + $currencyCode = Mage::helper('mailchimp')->getConfigValueForScope(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_DEFAULT, $scopeId, $scope); $isSyncing = true; - $api->ecommerce->stores->add($storeId, $listId, $storeName, $currencyCode, $isSyncing, 'Magento', null, $storeEmail); + $api->ecommerce->stores->add($mailChimpStoreId, $listId, $storeName, $currencyCode, $isSyncing, 'Magento', null, $storeEmail); } else { throw new Exception('You don\'t have any lists configured in MailChimp'); } @@ -81,20 +89,32 @@ public function createMailChimpStore($storeId, $listId=null) } /** - * @param $storeId + * Delete MailChimp store. + * + * @param $mailchimpStoreId + * @param $scopeId + * @param $scope */ - public function deleteStore($storeId) + public function deleteMailChimpStore($mailchimpStoreId, $scopeId, $scope) { - $api = Mage::helper('mailchimp')->getApi(); - $api->ecommerce->stores->delete($storeId); + $api = Mage::helper('mailchimp')->getApi($scopeId, $scope); + $api->ecommerce->stores->delete($mailchimpStoreId); $connection = Mage::getSingleton('core/resource')->getConnection('core_write'); $resource = Mage::getResourceModel('mailchimp/synchbatches'); $connection->update($resource->getMainTable(), array('status'=>'canceled'), "status = 'pending'"); } - public function modifyName($name) + + /** + * Edit MailChimp store name for given scope. + * + * @param $name + * @param $scopeId + * @param $scope + */ + public function modifyName($name, $scopeId, $scope) { - $api = Mage::helper('mailchimp')->getApi(); - $storeId = Mage::helper('mailchimp')->getMCStoreId(); + $api = Mage::helper('mailchimp')->getApi($scopeId, $scope); + $storeId = Mage::helper('mailchimp')->getMCStoreId($scopeId, $scope); $api->ecommerce->stores->edit($storeId, $name); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 82b37aa69..860c76dd4 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -24,13 +24,13 @@ public function createBatchJson($listId, $storeId, $limit) 'mailchimp_sync_delta', array( array('null' => true), array('eq' => ''), - array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) + array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag($storeId)) ) ); $collection->getSelect()->limit($limit); $subscriberArray = array(); $date = Mage::helper('mailchimp')->getDateMicrotime(); - $batchId = Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_' . $date; + $batchId = 'storeid-' . $storeId . '_' . Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_' . $date; $counter = 0; foreach ($collection as $subscriber) { @@ -44,7 +44,7 @@ public function createBatchJson($listId, $storeId, $limit) } catch (Exception $e) { //json encode failed $errorMessage = "Subscriber ".$subscriber->getSubscriberId()." json encode failed"; - Mage::helper('mailchimp')->logError($errorMessage); + Mage::helper('mailchimp')->logError($errorMessage, $storeId); } if (!empty($subscriberJson)) { @@ -67,6 +67,7 @@ public function createBatchJson($listId, $storeId, $limit) protected function _buildSubscriberData($subscriber) { + $storeId = $subscriber->getStoreId(); $data = array(); $data["email_address"] = $subscriber->getSubscriberEmail(); $mergeVars = Mage::getModel('mailchimp/api_customers')->getMergeVars($subscriber); @@ -74,7 +75,7 @@ protected function _buildSubscriberData($subscriber) $data["merge_fields"] = $mergeVars; } - $data["status_if_new"] = $this->_getMCStatus($subscriber->getStatus()); + $data["status_if_new"] = $this->_getMCStatus($subscriber->getStatus(), $storeId); return $data; } @@ -85,10 +86,11 @@ protected function _buildSubscriberData($subscriber) */ public function updateSubscriber($subscriber, $updateStatus = false) { - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); - $newStatus = $this->_getMCStatus($subscriber->getStatus()); + $storeId = $subscriber->getStoreId(); + $listId = Mage::helper('mailchimp')->getGeneralList($storeId); + $newStatus = $this->_getMCStatus($subscriber->getStatus(), $storeId); $forceStatus = ($updateStatus) ? $newStatus : null; - $api = Mage::helper('mailchimp')->getApi(); + $api = Mage::helper('mailchimp')->getApi($storeId); $mergeVars = Mage::getModel('mailchimp/api_customers')->getMergeVars($subscriber); try { @@ -100,25 +102,26 @@ public function updateSubscriber($subscriber, $updateStatus = false) $subscriber->setData("mailchimp_sync_delta", Varien_Date::now()); $subscriber->setData("mailchimp_sync_error", ""); } catch(Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId); Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $storeId); } } /** * Get status to send confirmation if Need to Confirm enabled on Magento * - * @param null $status + * @param $status + * @param $storeId * @return string */ - protected function _getMCStatus($status = null) + protected function _getMCStatus($status, $storeId) { $confirmationFlagPath = Mage_Newsletter_Model_Subscriber::XML_PATH_CONFIRMATION_FLAG; if ($status == Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { $status = 'unsubscribed'; - } elseif (Mage::helper('mailchimp')->getConfigValue($confirmationFlagPath) && + } elseif (Mage::helper('mailchimp')->getConfigValueForScope($confirmationFlagPath, $storeId) && ($status == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE || $status == Mage_Newsletter_Model_Subscriber::STATUS_UNCONFIRMED) ) { @@ -132,16 +135,17 @@ protected function _getMCStatus($status = null) public function removeSubscriber($subscriber) { - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); - $api = Mage::helper('mailchimp')->getApi(); + $storeId = $subscriber->getStoreId(); + $listId = Mage::helper('mailchimp')->getGeneralList($storeId); + $api = Mage::helper('mailchimp')->getApi($storeId); try { $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); $api->lists->members->update($listId, $md5HashEmail, null, 'unsubscribed'); } catch(Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId); Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $storeId); } } @@ -150,16 +154,17 @@ public function removeSubscriber($subscriber) */ public function deleteSubscriber($subscriber) { - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); - $api = Mage::helper('mailchimp')->getApi(); + $storeId = $subscriber->getStoreId(); + $listId = Mage::helper('mailchimp')->getGeneralList($storeId); + $api = Mage::helper('mailchimp')->getApi($storeId); try { $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); $api->lists->members->update($listId, $md5HashEmail, null, 'cleaned'); } catch(Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId); Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $storeId); } } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Cron.php b/app/code/community/Ebizmarts/MailChimp/Model/Cron.php index f2e3d6f43..0a4f3084b 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Cron.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Cron.php @@ -19,6 +19,6 @@ class Ebizmarts_MailChimp_Model_Cron public function syncBatchData($cron) { Mage::getModel('mailchimp/api_batches')->handleEcommerceBatches(); - Mage::getModel('mailchimp/api_batches')->handleSubscriberBatches(); +// Mage::getModel('mailchimp/api_batches')->handleSubscriberBatches(); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php b/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php new file mode 100755 index 000000000..a980e5978 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php @@ -0,0 +1,26 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 5/16/16 6:23 PM + * @file: MailchimpSychBatches.php + */ + +class Ebizmarts_Mailchimp_Model_Ecommercesyncdata extends Mage_Core_Model_Abstract +{ + /** + * Initialize model + * + * @return void + */ + public function _construct() + { + parent::_construct(); + $this->_init('mailchimp/ecommercesyncdata'); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php index 57f7e1607..d1f8008f9 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php @@ -159,7 +159,7 @@ public function getMail($storeId) return null; } - Mage::helper('mailchimp/mandrill')->log("store: $storeId API: " . Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)); + Mage::helper('mailchimp/mandrill')->log("store: $storeId API: " . Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId), $storeId); $mail = new Mandrill_Message(Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)); return $mail; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php index 88d9305dc..940306345 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php @@ -181,7 +181,7 @@ public function getMail() return $this->_mail; } else { $storeId = Mage::app()->getStore()->getId(); - Mage::helper('mailchimp/mandrill')->log("store: $storeId API: " . Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)); + Mage::helper('mailchimp/mandrill')->log("store: $storeId API: " . Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId), $storeId); $this->_mail = new Mandrill_Message(Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)); return $this->_mail; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php new file mode 100755 index 000000000..a303e6b4e --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php @@ -0,0 +1,25 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 5/16/16 6:37 PM + * @file: SychBatches.php + */ +class Ebizmarts_Mailchimp_Model_Mysql4_Ecommercesyncdata extends Mage_Core_Model_Mysql4_Abstract +{ + + /** + * Initialize + * + * @return void + */ + public function _construct() + { + $this->_init('mailchimp/ecommercesyncdata', 'id'); + } +} \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata/Collection.php new file mode 100755 index 000000000..d7a04bc3f --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata/Collection.php @@ -0,0 +1,27 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 5/16/16 6:53 PM + * @file: Collection.php + */ + +class Ebizmarts_Mailchimp_Model_Mysql4_Ecommercesyncdata_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + $this->_init('mailchimp/ecommercesyncdata'); + } +} \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index b30de65f7..13119eebd 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -12,7 +12,6 @@ */ class Ebizmarts_MailChimp_Model_Observer { - /** * Handle save of System -> Configuration, section * @@ -21,11 +20,12 @@ class Ebizmarts_MailChimp_Model_Observer */ public function saveConfig(Varien_Event_Observer $observer) { - $generalEnabled = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE); - $listId = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + $generalEnabled = Mage::helper('mailchimp')->isMailChimpEnabled($scopeArray[1], $scopeArray[0]); + $listId = Mage::helper('mailchimp')->getGeneralList($scopeArray[1], $scopeArray[0]); if ($generalEnabled && $listId) { - $this->_createWebhook($listId); + $this->_createWebhook($listId, $scopeArray[1], $scopeArray[0]); } return $observer; @@ -35,8 +35,10 @@ public function saveConfig(Varien_Event_Observer $observer) * Create MailChimp webhook based on the Two Way Sync field. If disabled the webhook is created only for subsciption confirmation when opt-in enabled. * * @param $listId + * @param $scopeId + * @param $scope */ - protected function _createWebhook($listId) + protected function _createWebhook($listId, $scopeId, $scope) { $store = Mage::app()->getDefaultStoreView(); $webhooksKey = Mage::helper('mailchimp')->getWebhooksKey(); @@ -53,9 +55,8 @@ protected function _createWebhook($listId) if (FALSE != strstr($hookUrl, '?', true)) { $hookUrl = strstr($hookUrl, '?', true); } - - $api = Mage::helper('mailchimp')->getApi(); - if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_TWO_WAY_SYNC)) { + $api = Mage::helper('mailchimp')->getApi($scopeId, $scope); + if (Mage::helper('mailchimp')->getTwoWaySyncEnabled($scopeId, $scope)) { $events = array( 'subscribe' => true, 'unsubscribe' => true, @@ -100,7 +101,7 @@ protected function _createWebhook($listId) $api->lists->webhooks->add($listId, $hookUrl, $events, $sources); } } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope); Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); $textToCompare = 'The resource submitted could not be validated. For field-specific details, see the \'errors\' array.'; if ($e->getMailchimpDetails() == $textToCompare) { @@ -108,7 +109,7 @@ protected function _createWebhook($listId) Mage::getSingleton('adminhtml/session')->addError($errorMessage); } } catch (Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $scopeId, $scope); } } @@ -119,17 +120,16 @@ protected function _createWebhook($listId) */ public function handleSubscriber(Varien_Event_Observer $observer) { - $isEnabled = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE); + $subscriber = $observer->getEvent()->getSubscriber(); + $isEnabled = Mage::helper('mailchimp')->isMailChimpEnabled($subscriber->getStoreId()); if ($isEnabled) { - $subscriber = $observer->getEvent()->getSubscriber(); $subscriber->setImportMode(true); if (!Mage::getSingleton('customer/session')->isLoggedIn() && !Mage::app()->getStore()->isAdmin()) { Mage::getModel('core/cookie')->set( 'email', $subscriber->getSubscriberEmail(), null, null, null, null, false ); } - - + if (TRUE === $subscriber->getIsStatusChanged()) { Mage::getModel('mailchimp/api_subscribers')->updateSubscriber($subscriber, true); } @@ -143,9 +143,9 @@ public function handleSubscriber(Varien_Event_Observer $observer) */ public function handleSubscriberDeletion(Varien_Event_Observer $observer) { - $isEnabled = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE); + $subscriber = $observer->getEvent()->getSubscriber(); + $isEnabled = Mage::helper('mailchimp')->isMailChimpEnabled($subscriber->getStoreId()); if ($isEnabled) { - $subscriber = $observer->getEvent()->getSubscriber(); if (TRUE === $subscriber->getIsStatusChanged()) { Mage::getModel('mailchimp/api_subscribers')->deleteSubscriber($subscriber); } @@ -196,9 +196,10 @@ public function alterNewsletterGrid(Varien_Event_Observer $observer) public function customerSaveBefore(Varien_Event_Observer $observer) { $customer = $observer->getEvent()->getCustomer(); + $storeId = Mage::app()->getStore()->getStoreId(); //update mailchimp ecommerce data for that customer - Mage::getModel('mailchimp/api_customers')->update($customer); + Mage::getModel('mailchimp/api_customers')->update($customer->getId(), $storeId); return $observer; } @@ -211,8 +212,9 @@ public function customerSaveBefore(Varien_Event_Observer $observer) public function productSaveBefore(Varien_Event_Observer $observer) { $product = $observer->getEvent()->getProduct(); + $storeId = Mage::app()->getStore()->getStoreId(); //update mailchimp ecommerce data for that product variant - Mage::getModel('mailchimp/api_products')->update($product); + Mage::getModel('mailchimp/api_products')->update($product->getId(), $storeId); return $observer; } @@ -230,20 +232,22 @@ public function saveCampaignData(Varien_Event_Observer $observer) } } + /** + * Catch order save before event, mark it as modified and associate the landing page to the order data. + * + * @param Varien_Event_Observer $observer + * @return Varien_Event_Observer + */ public function orderSaveBefore(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); - if ($order->getMailchimpUpdateObserverRan()) { - return $observer; - } else { - $order->setMailchimpUpdateObserverRan(true); - } + $storeId = Mage::app()->getStore()->getStoreId(); //update mailchimp ecommerce data for that product variant - Mage::getModel('mailchimp/api_orders')->update($order); + Mage::getModel('mailchimp/api_orders')->update($order->getId(), $storeId); $landingCookie = $this->_getLandingCookie(); - if ($landingCookie) { - $observer->getEvent()->getOrder()->setMailchimpLandingPage($landingCookie); + if ($landingCookie && !$order->getMailchimpLandingPage()) { + $order->setMailchimpLandingPage($landingCookie); } } @@ -286,6 +290,12 @@ protected function _getCampaignCookie() return null; } } + + /** + * Get landing_page cookie if exists. + * + * @return null + */ protected function _getLandingCookie() { $cookie = Mage::getModel('core/cookie')->get('mailchimp_landing_page'); @@ -304,8 +314,14 @@ protected function _getLandingCookie() */ public function addColumnToSalesOrderGrid($observer) { + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); $block = $observer->getEvent()->getBlock(); - if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Grid && Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::MONKEY_GRID) &&(Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_ACTIVE) || Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE))) { + if ($block instanceof Mage_Adminhtml_Block_Sales_Order_Grid + && Mage::helper('mailchimp')->getMonkeyInGrid($scopeArray[1], $scopeArray[0]) + && ( + Mage::helper('mailchimp')->isAbandonedCartEnabled($scopeArray[1], $scopeArray[0]) + || Mage::helper('mailchimp')->isMailChimpEnabled($scopeArray[1], $scopeArray[0]) + )) { $block->addColumnAfter( 'mailchimp_flag', array( 'header' => Mage::helper('mailchimp')->__('MailChimp'), @@ -322,30 +338,6 @@ public function addColumnToSalesOrderGrid($observer) return $observer; } - /** - * Create MailChimp store. - */ - protected function _createMailChimpStore() - { - try { - $mailchimpStore = Mage::getModel('mailchimp/api_stores')->getMailChimpStore(); - if (!$mailchimpStore) { - Mage::helper('mailchimp')->resetMCEcommerceData(); - } - - if (!Mage::helper('mailchimp')->getMCStoreId()) { - $warningMessage = 'The MailChimp store was not created properly, please save your configuration to create it.'; - Mage::getSingleton('adminhtml/session')->addWarning($warningMessage); - } - } catch (Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); - Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); - } catch (Exception $e) { - Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); - } - } - - /** * Add customer to the cart if it placed the email address in the popup or footer subscription form. * @@ -356,7 +348,7 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) { $quote = $observer->getEvent()->getQuote(); if (!Mage::getSingleton('customer/session')->isLoggedIn() && - Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ENABLE_POPUP, $quote->getStoreId()) + Mage::helper('mailchimp')->isEmailCatcherEnabled($quote->getStoreId()) ) { $action = Mage::app()->getRequest()->getActionName(); $onCheckout = ($action == 'saveOrder' || $action == 'savePayment' || @@ -412,10 +404,8 @@ public function newOrder(Varien_Event_Observer $observer) continue; } - $product = Mage::getModel('catalog/product')->load($item->getProductId()); - $product->setData('mailchimp_sync_modified', 1); - $resource = $product->getResource(); - $resource->saveAttribute($product, 'mailchimp_sync_modified'); + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($order->getStoreId()); + Mage::helper('mailchimp')->saveEcommerceSyncData($item->getProductId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, null, null, 1, null, null, true); } return $observer; @@ -431,6 +421,8 @@ public function newOrder(Varien_Event_Observer $observer) public function newCreditMemo(Varien_Event_Observer $observer) { $creditMemo = $observer->getEvent()->getCreditmemo(); + $order = $creditMemo->getOrder(); + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($order->getStoreId()); $items = $creditMemo->getAllItems(); foreach ($items as $item) { @@ -438,13 +430,10 @@ public function newCreditMemo(Varien_Event_Observer $observer) continue; } - $product = Mage::getModel('catalog/product')->load($item->getProductId()); - $product->setData('mailchimp_sync_modified', 1); - $resource = $product->getResource(); - $resource->saveAttribute($product, 'mailchimp_sync_modified'); + Mage::helper('mailchimp')->saveEcommerceSyncData($item->getProductId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, null, null, 1, null, null, true); } - $creditMemo->getOrder()->setMailchimpSyncModified(1); + Mage::helper('mailchimp')->saveEcommerceSyncData($order->getEntityId(), Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, null, null, 1, null, null, true); return $observer; } @@ -458,6 +447,8 @@ public function newCreditMemo(Varien_Event_Observer $observer) public function cancelCreditMemo(Varien_Event_Observer $observer) { $creditMemo = $observer->getEvent()->getCreditmemo(); + $order = $creditMemo->getOrder(); + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($order->getStoreId()); $items = $creditMemo->getAllItems(); foreach ($items as $item) { @@ -465,13 +456,10 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) continue; } - $product = Mage::getModel('catalog/product')->load($item->getProductId()); - $product->setData('mailchimp_sync_modified', 1); - $resource = $product->getResource(); - $resource->saveAttribute($product, 'mailchimp_sync_modified'); + Mage::helper('mailchimp')->saveEcommerceSyncData($item->getProductId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, null, null, 1, null, null, true); } - $creditMemo->getOrder()->setMailchimpSyncModified(1); + Mage::helper('mailchimp')->saveEcommerceSyncData($order->getEntityId(), Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, null, null, 1, null, null, true); return $observer; } @@ -485,16 +473,19 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) public function itemCancel(Varien_Event_Observer$observer) { $item = $observer->getEvent()->getItem(); + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($item->getStoreId()); if ($item->getProductType()!='bundle' && $item->getProductType()!='configurable') { - $product = Mage::getModel('catalog/product')->load($item->getProductId()); - $product->setData('mailchimp_sync_modified', 1); - $resource = $product->getResource(); - $resource->saveAttribute($product, 'mailchimp_sync_modified'); + Mage::helper('mailchimp')->saveEcommerceSyncData($item->getProductId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, null, null, 1, null, null, true); } return $observer; } + /** + * Add column to order grid to identify orders gained by MailChimp campaigns and automations. + * + * @param Varien_Event_Observer $observer + */ public function addOrderViewMonkey(Varien_Event_Observer $observer) { $block = $observer->getBlock(); @@ -508,12 +499,65 @@ public function addOrderViewMonkey(Varien_Event_Observer $observer) } } + + /** + * Catch Magento store name change event and call changeName function to check if MailChimp store name must be changed as well. + * + * @param Varien_Event_Observer $observer + */ public function changeStoreName(Varien_Event_Observer $observer) { + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); $group = $observer->getGroup(); $storeName = Mage::getStoreConfig('general/store_information/name'); if ($storeName == '') { - Mage::helper('mailchimp')->changeName($group->getName()); + Mage::helper('mailchimp')->changeName($group->getName(), $scopeArray[1], $scopeArray[0]); } } + + public function productAttributeUpdate(Varien_Event_Observer $observer) + { + Mage::log(__METHOD__, null, 'observer.log', true); + $productIds = $observer->getEvent()->getProductIds(); + $storeId = $observer->getEvent()->getStoreId(); + $scope = 'stores'; + if ($storeId === 0) { + $scope = 'default'; + } + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId, $scope); + Mage::log($storeId, null, 'observer.log', true); + foreach ($productIds as $productId) { + Mage::getModel('mailchimp/api_products')->update($productId, $mailchimpStoreId, null, null, 1, null, true); + } + } + public function productWebsiteUpdate(Varien_Event_Observer $observer) + { + Mage::log(__METHOD__, null, 'observer.log', true); + $productIds = $observer->getEvent()->getProductIds(); + $websiteIds = $observer->getEvent()->getWebsiteIds(); + $action = $observer->getEvent()->getAction(); + Mage::log($productIds, null, 'observer.log', true); + Mage::log($websiteIds, null, 'observer.log', true); + Mage::log($action, null, 'observer.log', true); +// foreach ($websiteIds as $websiteId) { +// $stores = Mage::app()->getWebsite($websiteId)->getStores(); +// foreach ($stores as $storeId => $store) { +// $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId); +// foreach ($productIds as $productId) { +// $productSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); +// if ($productSyncData->getMailchimpSyncDelta() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($storeId)) { +// if ($action == 'remove' && !$productSyncData->getMailchimpSyncDeleted()) { +// $productSyncData->setData("mailchimp_sync_modified", 0) +// ->setData("mailchimp_sync_deleted", 1) +// ->save(); +// } elseif (!$productSyncData->getMailchimpSyncModified()) { +// $productSyncData->setData("mailchimp_sync_modified", 1) +// ->setData("mailchimp_sync_deleted", 0) +// ->save(); +// } +// } +// } +// } +// } + } } 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 d0df87148..cc7a4fe0c 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 @@ -16,12 +16,16 @@ protected function _beforeSave() { $groups = $this->getData('groups'); $active = (isset($groups['ecommerce']['fields']['active']['value'])) ? $groups['ecommerce']['fields']['active']['value'] : false; + if ($active === null) { + $active = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); + } if ($this->isValueChanged() && $active) { if ($this->getScope() == 'default') { if ($this->getOldValue()) { - Mage::helper('mailchimp')->deleteStore(); - Mage::helper('mailchimp')->resetErrors(); - Mage::helper('mailchimp')->resetCampaign(); + Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); } } } 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 d77162cff..1a01de79f 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 @@ -16,11 +16,14 @@ class Ebizmarts_MailChimp_Model_System_Config_Backend_Ecommerce extends Mage_Cor protected function _afterSave() { $groups = $this->getData('groups'); - $active = $groups['general']['fields']['active']['value']; - $storeId = Mage::helper('mailchimp')->getMCStoreId(); + $active = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : null; + $storeId = Mage::helper('mailchimp')->getMCStoreId($this->getScopeId(), $this->getScope()); + if ($active === null) { + $active = Mage::helper('mailchimp')->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + } - if ($this->isValueChanged()&&$active&&!$storeId&&$this->getValue()) { - Mage::helper('mailchimp')->createStore($this->getValue()); + if ($this->isValueChanged() && $active && !$storeId && $this->getValue()) { + Mage::helper('mailchimp')->createStore($this->getValue(), $this->getScopeId(), $this->getScope()); } } } \ No newline at end of file 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 aebfe3827..3f923f635 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 @@ -15,25 +15,29 @@ class Ebizmarts_MailChimp_Model_System_Config_Backend_List extends Mage_Core_Mod protected function _beforeSave() { $groups = $this->getData('groups'); - $active = $groups['ecommerce']['fields']['active']['value']; - - if ($this->isValueChanged()&&$active) { - if ($this->getScope()=='default') { - if ($this->getOldValue()) { - Mage::helper('mailchimp')->deleteStore(); - Mage::helper('mailchimp')->resetErrors(); - Mage::helper('mailchimp')->resetCampaign(); - } + $active = (isset($groups['ecommerce']['fields']['active']['value'])) ? $groups['ecommerce']['fields']['active']['value'] : null; + if ($active === null) { + $active = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); + } + + if ($this->isValueChanged() && $active) { + if ($this->getOldValue()) { + Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); } } } protected function _afterSave() { $groups = $this->getData('groups'); - $active = $groups['ecommerce']['fields']['active']['value']; - + $active = (isset($groups['ecommerce']['fields']['active']['value'])) ? $groups['ecommerce']['fields']['active']['value'] : null; + if ($active === null) { + $active = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); + } if ($this->isValueChanged() && $active) { - Mage::helper('mailchimp')->createStore($this->getValue()); + Mage::helper('mailchimp')->createStore($this->getValue(), $this->getScopeId(), $this->getScope()); } } } \ No newline at end of file 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 new file mode 100644 index 000000000..59319397c --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Mapfield.php @@ -0,0 +1,36 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @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 +{ + protected function _afterLoad() + { + if (!is_array($this->getValue())) { + if (is_object($this->getValue())) { + $serializedValue = $this->getValue()->asArray(); + } else { + $serializedValue = $this->getValue(); + } + + $unserializedValue = false; + if (!empty($serializedValue)) { + try { + $unserializedValue = Mage::helper('core/unserializeArray') + ->unserialize($serializedValue); + } catch (Exception $e) { + Mage::logException($e); + } + } + $this->setValue($unserializedValue); + } + } +} \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php index b7b54ccce..a055b9e88 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php @@ -21,7 +21,7 @@ protected function _afterSave() $name = Mage::app()->getDefaultStoreView()->getWebsite()->getDefaultStore()->getFrontendName(); } - Mage::helper('mailchimp')->changeName($name); + Mage::helper('mailchimp')->changeName($name, $this->getScopeId(), $this->getScope()); } } } \ No newline at end of file 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 19ba9acba..3d0e2cbfb 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 @@ -25,12 +25,13 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Account */ public function __construct() { - $mcStoreId = (Mage::helper('mailchimp')->getMCStoreId()) ? Mage::helper('mailchimp')->getMCStoreId() : null; - $api = Mage::helper('mailchimp')->getApi(); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + $mcStoreId = (Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0])) ? Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0]) : null; + $api = Mage::helper('mailchimp')->getApi($scopeArray[1], $scopeArray[0]); if ($api) { try { $this->_accountDetails = $api->root->info('account_name,total_subscribers'); - if (Mage::helper('mailchimp')->getMCStoreId()) { + if (Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0])) { $this->_accountDetails['store_exists'] = true; $totalCustomers = $api->ecommerce->customers->getAll($mcStoreId, 'total_items'); $this->_accountDetails['total_customers'] = $totalCustomers['total_items']; @@ -45,7 +46,7 @@ public function __construct() } } catch (Exception $e) { $this->_accountDetails = "--- Invalid API Key ---"; - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $scopeArray[1]); } } } @@ -57,7 +58,7 @@ public function __construct() */ public function toOptionArray() { - $helper = Mage::helper('mailchimp'); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); if (is_array($this->_accountDetails)) { $totalSubscribersText = Mage::helper('mailchimp')->__('Total subscribers:'); $totalSubscribers = $totalSubscribersText . ' ' . $this->_accountDetails['total_subscribers']; @@ -86,7 +87,7 @@ public function toOptionArray() array('value' => 6, 'label' => $totalCarts) ) ); - } elseif (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ACTIVE)) { + } elseif (Mage::helper('mailchimp')->isEcommerceEnabled($scopeArray[1], $scopeArray[0])) { $text = 'Warning: The MailChimp store was not created properly, please Reset Ecommerce Data and reload the page.'; $label = Mage::helper('mailchimp')->__($text); $returnArray = array_merge($returnArray, array(array('value' => 7, 'label' => $label))); @@ -94,9 +95,9 @@ public function toOptionArray() return $returnArray; } elseif (!$this->_accountDetails) { - return array(array('value' => '', 'label' => $helper->__('--- Enter your API KEY first ---'))); + return array(array('value' => '', 'label' => Mage::helper('mailchimp')->__('--- Enter your API KEY first ---'))); } else { - return array(array('value' => '', 'label' => $helper->__($this->_accountDetails))); + return array(array('value' => '', 'label' => Mage::helper('mailchimp')->__($this->_accountDetails))); } } 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 ed292395c..071bee601 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/List.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/List.php @@ -25,11 +25,12 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_List */ public function __construct() { + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); if ($this->_lists == null) { - $apiKey = Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_APIKEY); + $apiKey = Mage::helper('mailchimp')->getApiKey($scopeArray[1], $scopeArray[0]); if ($apiKey) { try { - $api = Mage::helper('mailchimp')->getApi(); + $api = Mage::helper('mailchimp')->getApi($scopeArray[1], $scopeArray[0]); $this->_lists = $api->lists->getLists(null, 'lists', null, 100); if (isset($this->_lists['lists']) && count($this->_lists['lists']) == 0) { $apiKeyArray = explode('-', $apiKey); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php index 0771bd4dd..409644b0a 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php @@ -14,9 +14,11 @@ class Ebizmarts_MailChimp_Adminhtml_EcommerceController extends Mage_Adminhtml_C { public function resetLocalErrorsAction() { + $param = Mage::app()->getRequest()->getParam('scope'); + $scopeArray = explode('-', $param); $result = 1; try { - Mage::helper('mailchimp')->resetErrors(); + Mage::helper('mailchimp')->resetErrors($scopeArray[1], $scopeArray[0]); } catch(Exception $e) { $result = 0; @@ -26,17 +28,19 @@ public function resetLocalErrorsAction() } public function resetEcommerceDataAction() { + $param = Mage::app()->getRequest()->getParam('scope'); + $scopeArray = explode('-', $param); $result = 1; try { - Mage::helper('mailchimp')->resetMCEcommerceData(true); - Mage::helper('mailchimp')->resetErrors(); + Mage::helper('mailchimp')->resetMCEcommerceData($scopeArray[1], $scopeArray[0], true); + Mage::helper('mailchimp')->resetErrors($scopeArray[1], $scopeArray[0]); } catch(Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeArray[1], $scopeArray[0]); $result = 0; } catch(Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $scopeArray[1], $scopeArray[0]); } Mage::app()->getResponse()->setBody($result); @@ -44,16 +48,18 @@ public function resetEcommerceDataAction() public function createMergeFieldsAction() { + $param = Mage::app()->getRequest()->getParam('scope'); + $scopeArray = explode('-', $param); $result = 1; try { - Mage::helper('mailchimp')->createMergeFields(); + Mage::helper('mailchimp')->createMergeFields($scopeArray[1], $scopeArray[0]); } catch(Mailchimp_Error $e) { - Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeArray[1], $scopeArray[0]); $result = 0; } catch(Exception $e) { - Mage::helper('mailchimp')->logError($e->getMessage()); + Mage::helper('mailchimp')->logError($e->getMessage(), $scopeArray[1], $scopeArray[0]); } Mage::app()->getResponse()->setBody($result); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php index 610029ed1..e7f2c8b2e 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php @@ -21,17 +21,20 @@ public function indexAction() $this->_setActiveMenu('newsletter/mailchimp'); $this->renderLayout(); } + public function gridAction() { $this->loadLayout(false); $this->renderLayout(); } + public function downloadresponseAction() { $batch_id = $this->getRequest()->getParam('batch_id'); $this->getResponse()->setHeader('Content-disposition', 'attachment; filename='.$batch_id.'.json'); $this->getResponse()->setHeader('Content-type', 'application/json'); - $files = Mage::getModel('mailchimp/api_batches')->getBatchResponse($batch_id); +// $files = Mage::getModel('mailchimp/api_batches')->getBatchResponse($batch_id); + $files = array(); $fileContent = array(); foreach ($files as $file) { $items = json_decode(file_get_contents($file)); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php index c32239596..51999bd56 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php @@ -25,17 +25,16 @@ public function saveaddAction() $label = $postData['label']; $value = $postData['value']; $fieldType = $postData['fieldtype']; - $customFieldTypes = unserialize( - Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS) - ); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + $customFieldTypes = unserialize(Mage::helper('mailchimp')->getCustomMapFields($scopeArray[1], $scopeArray[0])); if(!$customFieldTypes){ $customFieldTypes = array(); } $customFieldTypes[] = array('label' => $label, 'value' => $value, 'field_type' => $fieldType); - Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, serialize($customFieldTypes)); - Mage::getConfig()->cleanCache(); + $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, serialize($customFieldTypes))); + Mage::helper('mailchimp')->saveMailchimpConfig($configValue, $scopeArray[1], $scopeArray[0]); Mage::getSingleton('core/session')->setMailChimpValue($value); Mage::getSingleton('core/session')->setMailChimpLabel($label); Mage::getSingleton('adminhtml/session')->addSuccess($this->__('The custom value was added successfully.')); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php index 12ceda92a..63d507666 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php @@ -21,12 +21,15 @@ public function loadquoteAction() if (isset($params['id'])) { //restore the quote $quote = Mage::getModel('sales/quote')->load($params['id']); - $url = Mage::getUrl(Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_PAGE, $quote->getStoreId())); + $storeId = $quote->getStoreId(); + $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId); + $quoteSyncData = Mage::helper('mailchimp')->getEcommerceSyncData($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']; } - if ((!isset($params['token']) || (isset($params['token']) && $params['token'] != $quote->getMailchimpToken()))) { + if ((!isset($params['token']) || (isset($params['token']) && $params['token'] != $quoteSyncData->getMailchimpToken()))) { Mage::getSingleton('customer/session')->addNotice("Your token cart is incorrect"); $this->_redirect($url); } else { diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index 7a574c5a0..c5522d9df 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -3,10 +3,10 @@ - 1.1.5 + 1.1.6 - 1.1.5 + 1.1.6 @@ -92,6 +92,22 @@ + + + + mailchimp/observer + productAttributeUpdate + + + + + + + mailchimp/observer + productWebsiteUpdate + + + @@ -107,6 +123,9 @@ mailchimp_errors
+ + mailchimp_ecommerce_sync_data
+
diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 030bd00df..1d1b654f5 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -61,9 +61,6 @@ 1 1 1 - - 1 - @@ -74,9 +71,6 @@ 1 1 1 - - 1 - @@ -86,9 +80,6 @@ 1 1 1 - - 1 - @@ -99,9 +90,6 @@ 1 1 1 - - 1 - 1 @@ -111,22 +99,22 @@ mailchimp/adminhtml_system_config_resetList 52 1 - 0 + 1 1 - - 1 - mailchimp/adminhtml_system_config_form_field_mapfields - adminhtml/system_config_backend_serialized_array + mailchimp/system_config_backend_mapfield 55 1 - 0 - 0 + 1 + 1 See recommended configuration here.]]> + + 1 + @@ -134,8 +122,8 @@ mailchimp/adminhtml_system_config_createMergeFields 57 1 - 0 - 0 + 1 + 1 1 @@ -149,11 +137,11 @@ 1 1 1 + 1 + 1 - 1 - @@ -163,10 +151,10 @@ 1 1 1 + 1 - @@ -174,12 +162,12 @@ adminhtml/system_config_source_yesno 80 1 - 1 - 1 + 0 + 0 + File is {{base_dir}}/var/log/MailChimp_ApiCall.log 1 - File is {{base_dir}}/var/log/MailChimp_ApiCall.log @@ -200,8 +188,8 @@ 200 text 1 - 0 - 0 + 1 + 1 @@ -209,8 +197,8 @@ adminhtml/system_config_source_yesno 205 1 - 0 - 0 + 1 + 1 @@ -219,8 +207,11 @@ adminhtml/system_config_source_yesno 208 1 - 0 - 0 + 1 + 1 + + 1 + @@ -236,13 +227,13 @@ - + button mailchimp/adminhtml_system_config_resetErrors 210 1 - 0 - 0 + 1 + 1 1 @@ -253,8 +244,8 @@ mailchimp/adminhtml_system_config_resetEcommerceData 220 1 - 0 - 0 + 1 + 1 1 @@ -416,8 +407,8 @@ 500 text 1 - 0 - 0 + 1 + 1 @@ -510,7 +501,7 @@ adminhtml/system_config_source_yesno 30 1 - 0 + 1 1 File is {{base_dir}}/var/log/Ebizmarts_Mandrill.log diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php index 0d36269d9..339acb371 100755 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php @@ -11,92 +11,6 @@ $installer->getConnection()->addColumn( $installer->getTable('newsletter_subscriber'), 'subscriber_lastname', 'varchar(50)' ); -$eav = new Mage_Eav_Model_Entity_Setup('core_setup'); - -$eav->addAttribute( - 'customer', 'mailchimp_sync_delta', array( - 'label' => 'MailChimp last sync timestamp', - 'type' => 'datetime', - 'input' => 'text', - 'visible' => true, - 'required' => false, - 'position' => 1, - ) -); -$eav->addAttribute( - 'customer', 'mailchimp_sync_error', array( - 'label' => 'MailChimp Error Description', - 'type' => 'varchar', - 'input' => 'text', - 'visible' => true, - 'required' => false, - 'position' => 1, - ) -); - - -$attribute = Mage::getSingleton("eav/config")->getAttribute("customer", "mailchimp_sync_delta"); -$usedInForms=array(); - -$usedInForms[]="adminhtml_customer"; -$attribute->setData("used_in_forms", $usedInForms) - ->setData("is_used_for_customer_segment", true) - ->setData("is_system", 0) - ->setData("is_user_defined", 1) - ->setData("is_visible", 1) - ->setData("sort_order", 100); -$attribute->save(); - -$attribute = Mage::getSingleton("eav/config")->getAttribute("customer", "mailchimp_sync_error"); -$usedInForms=array(); - -$usedInForms[]="adminhtml_customer"; -$attribute->setData("used_in_forms", $usedInForms) - ->setData("is_used_for_customer_segment", true) - ->setData("is_system", 0) - ->setData("is_user_defined", 1) - ->setData("is_visible", 1) - ->setData("sort_order", 100); -$attribute->save(); - - - -$eav->addAttribute( - 'catalog_product', 'mailchimp_sync_delta', array( - 'label' => 'MailChimp last sync timestamp', - 'type' => 'datetime', - 'input' => 'text', - 'visible' => true, - 'required' => false, - 'position' => 1, - ) -); - -$eav->addAttribute( - 'catalog_product', 'mailchimp_sync_error', array( - 'label' => 'MailChimp Error Description', - 'type' => 'varchar', - 'input' => 'text', - 'visible' => true, - 'required' => false, - 'position' => 1, - ) -); - -try { - $installer->run( - " - ALTER TABLE `{$this->getTable('sales_flat_quote')}` ADD column `mailchimp_sync_delta` datetime NOT NULL; - ALTER TABLE `{$this->getTable('sales_flat_quote')}` ADD column `mailchimp_sync_error` VARCHAR(255) NOT NULL; - ALTER TABLE `{$this->getTable('sales_flat_order')}` ADD column `mailchimp_sync_delta` datetime NOT NULL; - ALTER TABLE `{$this->getTable('sales_flat_order')}` ADD column `mailchimp_sync_error` VARCHAR(255) NOT NULL; -" - ); -} -catch (Exception $e) -{ - Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); -} $installer->run( " diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php index 888211019..f31f58d06 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php @@ -17,7 +17,6 @@ $installer->run( " - CREATE TABLE IF NOT EXISTS `{$this->getTable('mailchimp_errors')}` ( `id` INT(10) unsigned NOT NULL auto_increment, `type` VARCHAR(256) DEFAULT '', @@ -29,7 +28,6 @@ `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; - " ); diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php index 418b23074..b1be92782 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php @@ -15,33 +15,6 @@ $installer->startSetup(); - -$eav = new Mage_Eav_Model_Entity_Setup('core_setup'); - -$eav->addAttribute( - 'catalog_product', 'mailchimp_sync_modified', array( - 'label' => 'MailChimp Modified', - 'type' => 'int', - 'visible' => false, - 'required' => false, - 'position' => 1, - 'default' => 0 - ) -); - -// create mailchimp_sync_modified to the customer - -$eav->addAttribute( - 'customer', 'mailchimp_sync_modified', array( - 'label' => 'MailChimp Modified', - 'type' => 'int', - 'visible' => false, - 'required' => false, - 'position' => 1, - 'default' => 0 - ) -); - try { $installer->run( " diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php index 6f5a45d07..d906b870e 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php @@ -20,10 +20,6 @@ $installer->run( " ALTER TABLE `{$this->getTable('sales_flat_quote')}` - ADD column `mailchimp_deleted` INT(1) NOT NULL DEFAULT 0; - ALTER TABLE `{$this->getTable('sales_flat_quote')}` - ADD column `mailchimp_token` VARCHAR(255) NOT NULL DEFAULT ''; - ALTER TABLE `{$this->getTable('sales_flat_quote')}` ADD column `mailchimp_abandonedcart_flag` INT(1) NOT NULL DEFAULT 0; ALTER TABLE `{$this->getTable('sales_flat_order')}` ADD column `mailchimp_abandonedcart_flag` INT(1) NOT NULL DEFAULT 0; diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php deleted file mode 100644 index 8811e7b6a..000000000 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php +++ /dev/null @@ -1,42 +0,0 @@ - - * @copyright Ebizmarts (http://ebizmarts.com) - * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 6/9/16 4:05 PM - * @file: mysql4-upgrade-1.0.1-1.0.2.php - */ - -$installer = $this; - -$installer->startSetup(); - -$deltaAttributeCode = 'mailchimp_sync_delta'; -$errorAttributeCode = 'mailchimp_sync_error'; -$modifiedAttributeCode = 'mailchimp_sync_modified'; -$productEntityTypeId = $installer->getEntityTypeId('catalog_product'); -$customerEntityTypeId = $installer->getEntityTypeId('customer'); -$productDeltaAttributeId = $installer->getAttributeId($productEntityTypeId, $deltaAttributeCode); -$productErrorAttributeId = $installer->getAttributeId($productEntityTypeId, $errorAttributeCode); -$productModifiedAttributeId = $installer->getAttributeId($productEntityTypeId, $modifiedAttributeCode); -$customerDeltaAttributeId = $installer->getAttributeId($customerEntityTypeId, $deltaAttributeCode); -$customerErrorAttributeId = $installer->getAttributeId($customerEntityTypeId, $errorAttributeCode); -$customerModifiedAttributeId = $installer->getAttributeId($customerEntityTypeId, $modifiedAttributeCode); -try { - $installer->updateAttribute($productEntityTypeId, $productDeltaAttributeId, 'is_user_defined', 1); - $installer->updateAttribute($productEntityTypeId, $productErrorAttributeId, 'is_user_defined', 1); - $installer->updateAttribute($productEntityTypeId, $productModifiedAttributeId, 'is_user_defined', 1); - $installer->updateAttribute($productEntityTypeId, $productDeltaAttributeId, 'frontend_input', 'datetime'); - $installer->updateAttribute($customerEntityTypeId, $customerDeltaAttributeId, 'is_user_defined', 1); - $installer->updateAttribute($customerEntityTypeId, $customerErrorAttributeId, 'is_user_defined', 1); - $installer->updateAttribute($customerEntityTypeId, $customerModifiedAttributeId, 'is_user_defined', 1); - $installer->updateAttribute($customerEntityTypeId, $customerDeltaAttributeId, 'frontend_input', 'datetime'); -} catch(Exception $e) { - Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); -} - -$installer->endSetup(); \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php index 1fed48157..51eff0a81 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php @@ -25,8 +25,6 @@ ADD column `mailchimp_campaign_id` VARCHAR (16) NOT NULL DEFAULT ''; ALTER TABLE `{$this->getTable('sales_flat_order')}` ADD column `mailchimp_landing_page` VARCHAR (512) NOT NULL DEFAULT ''; - ALTER TABLE `{$this->getTable('sales_flat_order')}` - ADD COLUMN `mailchimp_sync_modified` INT(1) DEFAULT 0; " ); } diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.6.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.6.php new file mode 100755 index 000000000..ed6d4c775 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.5-1.1.6.php @@ -0,0 +1,151 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/9/16 4:05 PM + * @file: mysql4-upgrade-1.0.1-1.0.2.php + */ + +$installer = $this; + +$installer->startSetup(); + + +$installer->run( + " + CREATE TABLE IF NOT EXISTS `{$this->getTable('mailchimp_ecommerce_sync_data')}` ( + `id` INT(10) unsigned NOT NULL auto_increment, + `related_id` INT(10) DEFAULT 0, + `type` VARCHAR(3) NOT NULL, + `mailchimp_store_id` VARCHAR(50) NOT NULL DEFAULT '', + `mailchimp_sync_error` VARCHAR(255) NOT NULL DEFAULT '', + `mailchimp_sync_delta` DATETIME NOT NULL, + `mailchimp_sync_modified` INT(1) NOT NULL DEFAULT 0, + `mailchimp_sync_deleted` INT(1) NOT NULL DEFAULT 0, + `mailchimp_token` VARCHAR(32) NOT NULL DEFAULT '', + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +" +); + +try { + $installer->run( + " + ALTER TABLE `{$this->getTable('mailchimp_errors')}` + ADD column `store_id` INT(5) DEFAULT 0; + " + ); +} +catch (Exception $e) +{ + Mage::log($e->getMessage()); +} + +//migrate data from older version to the new schemma +$mailchimpSyncDataCollection = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection(); +if (!count($mailchimpSyncDataCollection)) { + $mailchimpStoreIdCollection = Mage::getModel('core/config_data')->getCollection() + ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID)) + ->addFieldToFilter('scope_id', array('eq' => 0)); + if (count($mailchimpStoreIdCollection)) { + $mailchimpStoreId = $mailchimpStoreIdCollection->getFirstItem()->getValue(); + //migrate customers + $customerCollection = Mage::getModel('customer/customer')->getCollection(); + foreach ($customerCollection as $customer) { + $syncDelta = null; + $syncError = null; + $syncModified = null; + if ($customer->getMailchimpSyncDelta() && $customer->getMailchimpSyncDelta() > '0000-00-00 00:00:00') { + $syncDelta = $customer->getMailchimpSyncDelta(); + if ($customer->getMailchimpSyncError()) { + $syncError = $customer->getMailchimpSyncError(); + } + if ($customer->getMailchimpSyncModified()) { + $syncModified = $customer->getMailchimpSyncModified(); + } + Mage::helper('mailchimp')->saveEcommerceSyncData($customer->getEntityId(), Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified); + } + } + //migrate products + $productCollection = Mage::getModel('catalog/product')->getCollection(); + foreach ($productCollection as $product) { + $syncDelta = null; + $syncError = null; + $syncModified = null; + if ($product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > '0000-00-00 00:00:00') { + $syncDelta = $product->getMailchimpSyncDelta(); + if ($product->getMailchimpSyncError()) { + $syncError = $product->getMailchimpSyncError(); + } + if ($product->getMailchimpSyncModified()) { + $syncModified = $product->getMailchimpSyncModified(); + } + Mage::helper('mailchimp')->saveEcommerceSyncData($product->getEntityId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, $syncDelta, $syncError, $syncModified); + } + } + //migrate orders + $orderCollection = Mage::getModel('sales/order')->getCollection(); + foreach ($orderCollection as $order) { + $syncDelta = null; + $syncError = null; + $syncModified = null; + if ($order->getMailchimpSyncDelta() && $order->getMailchimpSyncDelta() > '0000-00-00 00:00:00') { + $syncDelta = $order->getMailchimpSyncDelta(); + if ($order->getMailchimpSyncError()) { + $syncError = $order->getMailchimpSyncError(); + } + if ($order->getMailchimpSyncModified()) { + $syncModified = $order->getMailchimpSyncModified(); + } + Mage::helper('mailchimp')->saveEcommerceSyncData($order->getEntityId(), Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified); + } + } + //migrate carts + $quoteCollection = Mage::getModel('sales/quote')->getCollection(); + foreach ($quoteCollection as $quote) { + $syncDelta = null; + $syncError = null; + $syncDeleted = null; + $token = null; + if ($quote->getMailchimpSyncDelta() && $quote->getMailchimpSyncDelta() > '0000-00-00 00:00:00') { + $syncDelta = $quote->getMailchimpSyncDelta(); + if ($quote->getMailchimpSyncError()) { + $syncError = $quote->getMailchimpSyncError(); + } + if ($quote->getMailchimpSyncDeleted()) { + $syncDeleted = $quote->getMailchimpSyncDeleted(); + } + if ($quote->getMailchimpToken()) { + $token = $quote->getMailchimpToken(); + } + Mage::helper('mailchimp')->saveEcommerceSyncData($quote->getEntityId(), Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, null, $syncDeleted, $token); + } + } + } +} + +//Remove attributes no longer used +$installer->removeAttribute('catalog_product', 'mailchimp_sync_delta'); +$installer->removeAttribute('catalog_product', 'mailchimp_sync_error'); +$installer->removeAttribute('catalog_product', 'mailchimp_sync_modified'); +$installer->removeAttribute('customer', 'mailchimp_sync_delta'); +$installer->removeAttribute('customer', 'mailchimp_sync_error'); +$installer->removeAttribute('customer', 'mailchimp_sync_modified'); + +$quoteTable = $this->getTable('sales/quote'); +$installer->getConnection()->dropColumn($quoteTable, 'mailchimp_sync_delta'); +$installer->getConnection()->dropColumn($quoteTable, 'mailchimp_sync_error'); +$installer->getConnection()->dropColumn($quoteTable, 'mailchimp_deleted'); +$installer->getConnection()->dropColumn($quoteTable, 'mailchimp_token'); + +$orderTable = $this->getTable('sales/order'); +$installer->getConnection()->dropColumn($orderTable, 'mailchimp_sync_delta'); +$installer->getConnection()->dropColumn($orderTable, 'mailchimp_sync_error'); +$installer->getConnection()->dropColumn($orderTable, 'mailchimp_sync_modified'); + +$installer->endSetup(); \ No newline at end of file diff --git a/composer.json b/composer.json index a4c2fa4a8..4029865a6 100644 --- a/composer.json +++ b/composer.json @@ -12,5 +12,11 @@ ], "require": { "magento-hackathon/magento-composer-installer": "*" - } + }, + "repositories": [ + { + "type": "composer", + "url": "https://packages.firegento.com" + } + ] } From 45b378a5455aa310247dd41f40c96c7cb6154c6d Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 10 Mar 2017 17:09:05 -0300 Subject: [PATCH 10/43] Better handling on store creation and deletetion for multi-stores. --- .../System/Config/ResetEcommerceData.php | 33 ++++++--- .../Adminhtml/System/Config/ResetErrors.php | 22 +++--- .../Ebizmarts/MailChimp/Helper/Data.php | 38 +++++++--- .../MailChimp/Model/Api/Customers.php | 69 +++++++++---------- .../Ebizmarts/MailChimp/Model/Observer.php | 10 +++ .../Model/System/Config/Backend/Apikey.php | 23 +++---- .../Model/System/Config/Backend/Ecommerce.php | 20 ++++-- .../Model/System/Config/Backend/List.php | 36 ++++------ .../Model/System/Config/Source/Account.php | 63 +++++++++++------ .../Ebizmarts/MailChimp/etc/system.xml | 3 +- .../system/config/resetecommercedata.phtml | 28 ++++---- .../mailchimp/system/config/resetlist.phtml | 7 +- 12 files changed, 208 insertions(+), 144 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php index 7f709a038..eca8b99a7 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetEcommerceData.php @@ -26,17 +26,32 @@ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) public function getButtonHtml() { - $button = $this->getLayout()->createBlock('adminhtml/widget_button') - ->setData( - array( - 'id' => 'resetecommercedata_button', - 'label' => $this->helper('mailchimp')->__('Reset Ecommerce Data'), - 'onclick' => 'javascript:resetecommerce(); return false;' - ) - ); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + if (Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) { + $label = $this->helper('mailchimp')->__('Reset Ecommerce Data'); + $button = $this->getLayout()->createBlock('adminhtml/widget_button') + ->setData( + array( + 'id' => 'resetecommercedata_button', + 'label' => $label, + 'onclick' => 'javascript:resetecommerce(); return false;', + 'title' => $this->helper('mailchimp')->__('Re-create MailChimp store for current scope') + ) + ); - return $button->toHtml(); + return $button->toHtml(); + } } + + /** + * @return string + */ + public function getMessage() + { + return __(Mage::getStoreConfig(Mage::helper('mailchimp')->__('Are you sure you want to delete the current MailChimp store and create a new one? + \nAutomations created for this store will need to be re-created.'))); + } + public function getAjaxCheckUrl() { $scopeString = Mage::helper('mailchimp')->getScopeString(); 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 3a1c613cf..5b8c90b06 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 @@ -26,16 +26,20 @@ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) public function getButtonHtml() { - $button = $this->getLayout()->createBlock('adminhtml/widget_button') - ->setData( - array( - 'id' => 'reseterrors_button', - 'label' => $this->helper('mailchimp')->__('Reset Local Errors'), - 'onclick' => 'javascript:reseterrors(); return false;' - ) - ); + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + if (Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) { + $button = $this->getLayout()->createBlock('adminhtml/widget_button') + ->setData( + array( + 'id' => 'reseterrors_button', + 'label' => $this->helper('mailchimp')->__('Reset Local Errors'), + 'onclick' => 'javascript:reseterrors(); return false;', + 'title' => $this->helper('mailchimp')->__('Reset Local Errors only for current scope') + ) + ); - return $button->toHtml(); + return $button->toHtml(); + } } public function getAjaxCheckUrl() { diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index b2c9be9bc..bd9f4fc85 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -179,6 +179,20 @@ public function getMCStoreId($scopeId, $scope = null) return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeId, $scope); } + /** + * Remove local store_id value of the MC store for given scope. + * + * @param $scopeId + * @param null $scope + * @return mixed + */ + public function deleteLocalMCStoreData($scopeId, $scope = null) + { + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, $scope, $scopeId); + Mage::getConfig()->cleanCache(); + } + /** * Return if Ecommerce configuration is enabled for given scope. * @@ -436,6 +450,13 @@ public function logRequest($message, $scopeId, $batchId=null) Mage::log($message, null, 'MailChimp_Requests.log', true); } else { $logDir = Mage::getBaseDir('var') . DS . 'log'; + if (!file_exists($logDir)) { + mkdir($logDir, 0750); + } + $logDir .= DS . 'MailChimp_Requests'; + if (!file_exists($logDir)) { + mkdir($logDir, 0750); + } $fileName = $logDir.DS.$batchId.'.Request.log'; $oldPermission = umask(0046); file_put_contents($fileName, $message); @@ -533,7 +554,6 @@ public function resetCampaign($scopeId, $scope) * @param $listId * @param $scopeId * @param $scope - * @param bool $clearConfig */ public function createStore($listId, $scopeId, $scope) { @@ -575,8 +595,7 @@ public function deleteStore($scopeId, $scope) } //clear store config values - Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scope, $scopeId); - Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 1, $scope, $scopeId); + $this->deleteLocalMCStoreData($scopeId, $scope); } } @@ -820,21 +839,22 @@ public function getIfMCStoreIdExistsForScope($scopeId, $scope) /** * Get actual scope where the MailChimp store was created if exists. * - * @param $storeId + * @param $scopeId + * @param null $scope * @return array|null */ - public function getMailChimpScopeByStoreId($storeId) + public function getMailChimpScopeByStoreId($scopeId, $scope = null) { - $scope = null; - $mailChimpStoreId = $this->getMCStoreId($storeId); + $mailchimpScope = null; + $mailChimpStoreId = $this->getMCStoreId($scopeId, $scope); $collection = Mage::getModel('core/config_data')->getCollection() ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID)) ->addFieldToFilter('value', array('eq' => $mailChimpStoreId)); if (count($collection)) { $configEntry = $collection->getFirstItem(); - $scope = array('scope' => $configEntry->getScope(), 'scope_id' => $configEntry->getScopeId()); + $mailchimpScope = array('scope' => $configEntry->getScope(), 'scope_id' => $configEntry->getScopeId()); } - return $scope; + return $mailchimpScope; } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index a5653e428..64382f120 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -93,52 +93,49 @@ protected function _buildCustomerData($customer, $magentoStoreId) $data["total_spent"] = $totalAmountSpent; //addresses data - foreach ($customer->getAddresses() as $address) { - //send only first address - if (!array_key_exists("address", $data)) { - $customerAddress = array(); - $street = $address->getStreet(); - if ($street[0]) { - $customerAddress["address1"] = $street[0]; - } - - if (count($street) > 1 && $street[1]) { - $customerAddress["address2"] = $street[1]; - } + $address = $customer->getDefaultBillingAddresses(); + if ($address) { + $customerAddress = array(); + $street = $address->getStreet(); + if ($street[0]) { + $customerAddress["address1"] = $street[0]; + } - if ($address->getCity()) { - $customerAddress["city"] = $address->getCity(); - } + if (count($street) > 1 && $street[1]) { + $customerAddress["address2"] = $street[1]; + } - if ($address->getRegion()) { - $customerAddress["province"] = $address->getRegion(); - } + if ($address->getCity()) { + $customerAddress["city"] = $address->getCity(); + } - if ($address->getRegionCode()) { - $customerAddress["province_code"] = $address->getRegionCode(); - } + if ($address->getRegion()) { + $customerAddress["province"] = $address->getRegion(); + } - if ($address->getPostcode()) { - $customerAddress["postal_code"] = $address->getPostcode(); - } + if ($address->getRegionCode()) { + $customerAddress["province_code"] = $address->getRegionCode(); + } - if ($address->getCountry()) { - $customerAddress["country"] = Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName(); - $customerAddress["country_code"] = $address->getCountry(); - } + if ($address->getPostcode()) { + $customerAddress["postal_code"] = $address->getPostcode(); + } - if (count($customerAddress)) { - $data["address"] = $customerAddress; - } + if ($address->getCountry()) { + $customerAddress["country"] = Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName(); + $customerAddress["country_code"] = $address->getCountry(); + } - //company - if ($address->getCompany()) { - $data["company"] = $address->getCompany(); - } + if (count($customerAddress)) { + $data["address"] = $customerAddress; + } - break; + //company + if ($address->getCompany()) { + $data["company"] = $address->getCompany(); } } + $mergeFields = $this->getMergeVars($customer); if (is_array($mergeFields)) { $data = array_merge($mergeFields, $data); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 13119eebd..0f65f5f3d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -20,6 +20,7 @@ class Ebizmarts_MailChimp_Model_Observer */ public function saveConfig(Varien_Event_Observer $observer) { + $post = Mage::app()->getRequest()->getPost(); $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); $generalEnabled = Mage::helper('mailchimp')->isMailChimpEnabled($scopeArray[1], $scopeArray[0]); $listId = Mage::helper('mailchimp')->getGeneralList($scopeArray[1], $scopeArray[0]); @@ -27,6 +28,15 @@ public function saveConfig(Varien_Event_Observer $observer) if ($generalEnabled && $listId) { $this->_createWebhook($listId, $scopeArray[1], $scopeArray[0]); } + if (isset($post['groups']['general']['fields']['list']['inherit']) && Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) { + Mage::helper('mailchimp')->deleteStore($scopeArray[1], $scopeArray[0]); + Mage::helper('mailchimp')->removeEcommerceSyncData($scopeArray[1], $scopeArray[0]); + Mage::helper('mailchimp')->resetCampaign($scopeArray[1], $scopeArray[0]); + Mage::helper('mailchimp')->clearErrorGrid($scopeArray[1], $scopeArray[0], true); + } + if (isset($post['groups']['general']['fields']['list']['value']) && !Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0]) && Mage::helper('mailchimp')->isEcomSyncDataEnabled($scopeArray[1], $scopeArray[0], true)) { + Mage::helper('mailchimp')->createStore($post['groups']['general']['fields']['list']['value'], $scopeArray[1], $scopeArray[0]); + } return $observer; } 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 cc7a4fe0c..c989d127f 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 @@ -12,22 +12,15 @@ */ class Ebizmarts_MailChimp_Model_System_Config_Backend_Apikey extends Mage_Core_Model_Config_Data { - protected function _beforeSave() + protected function _afterSave() { - $groups = $this->getData('groups'); - $active = (isset($groups['ecommerce']['fields']['active']['value'])) ? $groups['ecommerce']['fields']['active']['value'] : false; - if ($active === null) { - $active = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); - } - if ($this->isValueChanged() && $active) { - if ($this->getScope() == 'default') { - if ($this->getOldValue()) { - Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); - Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); - Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); - Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); - } - } + $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : Mage::helper('mailchimp')->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($this->getScopeId(), $this->getScope()); + if ($this->isValueChanged() && $moduleIsActive && $thisScopeHasMCStoreId) { + Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); } } } \ No newline at end of file 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 1a01de79f..01955f641 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 @@ -12,17 +12,25 @@ */ class Ebizmarts_MailChimp_Model_System_Config_Backend_Ecommerce extends Mage_Core_Model_Config_Data { - protected function _afterSave() { $groups = $this->getData('groups'); - $active = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : null; - $storeId = Mage::helper('mailchimp')->getMCStoreId($this->getScopeId(), $this->getScope()); - if ($active === null) { - $active = Mage::helper('mailchimp')->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + //If settings are inherited get from config. + $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : Mage::helper('mailchimp')->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + if (isset($groups['general']['fields']['list']) && isset($groups['general']['fields']['list']['value'])) { + $listId = $groups['general']['fields']['list']['value']; + } else { + $listId = Mage::helper('mailchimp')->getGeneralList($this->getScopeId(), $this->getScope()); } + $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($this->getScopeId(), $this->getScope()); - if ($this->isValueChanged() && $active && !$storeId && $this->getValue()) { + if ($thisScopeHasMCStoreId && (!$this->getValue() || !$moduleIsActive || !$listId)) { + Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); + } + if ($moduleIsActive && $listId && $this->getValue() && !$thisScopeHasMCStoreId) { Mage::helper('mailchimp')->createStore($this->getValue(), $this->getScopeId(), $this->getScope()); } } 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 3f923f635..61303fd6a 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 @@ -12,31 +12,23 @@ */ class Ebizmarts_MailChimp_Model_System_Config_Backend_List extends Mage_Core_Model_Config_Data { - protected function _beforeSave() - { - $groups = $this->getData('groups'); - $active = (isset($groups['ecommerce']['fields']['active']['value'])) ? $groups['ecommerce']['fields']['active']['value'] : null; - if ($active === null) { - $active = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); - } - - if ($this->isValueChanged() && $active) { - if ($this->getOldValue()) { - Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); - Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); - Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); - Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); - } - } - } protected function _afterSave() { - $groups = $this->getData('groups'); - $active = (isset($groups['ecommerce']['fields']['active']['value'])) ? $groups['ecommerce']['fields']['active']['value'] : null; - if ($active === null) { - $active = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); + $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : Mage::helper('mailchimp')->isMailChimpEnabled($this->getScopeId(), $this->getScope()); + if (isset($groups['ecommerce']['fields']['active']) && isset($groups['ecommerce']['fields']['active']['value'])) { + $ecommerceActive = $groups['ecommerce']['fields']['active']['value']; + } else { + $ecommerceActive = Mage::helper('mailchimp')->isEcommerceEnabled($this->getScopeId(), $this->getScope()); + } + $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($this->getScopeId(), $this->getScope()); + + if ($thisScopeHasMCStoreId && (!$ecommerceActive || !$moduleIsActive || !$this->getValue())) { + Mage::helper('mailchimp')->deleteStore($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope()); + Mage::helper('mailchimp')->clearErrorGrid($this->getScopeId(), $this->getScope(), true); } - if ($this->isValueChanged() && $active) { + if ($moduleIsActive && $ecommerceActive && $this->getValue() && !$thisScopeHasMCStoreId) { Mage::helper('mailchimp')->createStore($this->getValue(), $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 3d0e2cbfb..cda7771f2 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 @@ -1,4 +1,5 @@ getScopeString()); + $mcStoreId = (Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0])) ? Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0]) : null; + $listId = Mage::helper('mailchimp')->getGeneralList($scopeArray[1], $scopeArray[0]); $api = Mage::helper('mailchimp')->getApi($scopeArray[1], $scopeArray[0]); if ($api) { try { $this->_accountDetails = $api->root->info('account_name,total_subscribers'); - if (Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0])) { - $this->_accountDetails['store_exists'] = true; - $totalCustomers = $api->ecommerce->customers->getAll($mcStoreId, 'total_items'); - $this->_accountDetails['total_customers'] = $totalCustomers['total_items']; - $totalProducts = $api->ecommerce->products->getAll($mcStoreId, 'total_items'); - $this->_accountDetails['total_products'] = $totalProducts['total_items']; - $totalOrders = $api->ecommerce->orders->getAll($mcStoreId, 'total_items'); - $this->_accountDetails['total_orders'] = $totalOrders['total_items']; - $totalCarts = $api->ecommerce->carts->getAll($mcStoreId, 'total_items'); - $this->_accountDetails['total_carts'] = $totalCarts['total_items']; + if ($mcStoreId && Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) { + try { + $storeName = $api->ecommerce->stores->get($mcStoreId, 'name'); + $this->_accountDetails['store_exists'] = true; + $this->_accountDetails['store_name'] = $storeName['name']; + $totalCustomers = $api->ecommerce->customers->getAll($mcStoreId, 'total_items'); + $this->_accountDetails['total_customers'] = $totalCustomers['total_items']; + $totalProducts = $api->ecommerce->products->getAll($mcStoreId, 'total_items'); + $this->_accountDetails['total_products'] = $totalProducts['total_items']; + $totalOrders = $api->ecommerce->orders->getAll($mcStoreId, 'total_items'); + $this->_accountDetails['total_orders'] = $totalOrders['total_items']; + $totalCarts = $api->ecommerce->carts->getAll($mcStoreId, 'total_items'); + $this->_accountDetails['total_carts'] = $totalCarts['total_items']; + } catch (Mailchimp_Error $e) { + Mage::helper('mailchimp')->deleteLocalMCStoreData($scopeArray[1], $scopeArray[0]); + if ($listId) { + Mage::helper('mailchimp')->createStore($listId, $scopeArray[1], $scopeArray[0]); + $message = Mage::helper('mailchimp')->__('Looks like your MailChimp store was deleted. A new one has been created.'); + Mage::getSingleton('adminhtml/session')->addWarning($message); + } + $this->_accountDetails['store_exists'] = false; + } } else { $this->_accountDetails['store_exists'] = false; } @@ -63,11 +78,9 @@ public function toOptionArray() $totalSubscribersText = Mage::helper('mailchimp')->__('Total subscribers:'); $totalSubscribers = $totalSubscribersText . ' ' . $this->_accountDetails['total_subscribers']; $username = Mage::helper('mailchimp')->__('Username:') . ' ' . $this->_accountDetails['account_name']; - $title = Mage::helper('mailchimp')->__('Ecommerce Data uploaded to MailChimp:'); $returnArray = array( array('value' => 0, 'label' => $username), - array('value' => 1, 'label' => $totalSubscribers), - array('value' => 2, 'label' => $title) + array('value' => 1, 'label' => $totalSubscribers) ); if ($this->_accountDetails['store_exists']) { $totalCustomersText = Mage::helper('mailchimp')->__(' Total Customers:'); @@ -78,22 +91,28 @@ public function toOptionArray() $totalOrders = $totalOrdersText . ' ' . $this->_accountDetails['total_orders']; $totalCartsText = Mage::helper('mailchimp')->__(' Total Carts:'); $totalCarts = $totalCartsText . ' ' . $this->_accountDetails['total_carts']; + $title = Mage::helper('mailchimp')->__('Ecommerce Data uploaded to MailChimp store ' . $this->_accountDetails['store_name'] . ':'); + $returnArray = array_merge( + $returnArray, + array( + array('value' => 2, 'label' => $title), + array('value' => 3, 'label' => $totalCustomers), + array('value' => 4, 'label' => $totalProducts), + array('value' => 5, 'label' => $totalOrders), + array('value' => 6, 'label' => $totalCarts) + ) + ); + } elseif (Mage::helper('mailchimp')->isEcomSyncDataEnabled($scopeArray[1], $scopeArray[0], true)) { + $title = Mage::helper('mailchimp')->__('No MailChimp store was created for this scope, parent scopes might be sending data for this store anyways.'); $returnArray = array_merge( $returnArray, array( - array('value' => 3, 'label' => $totalCustomers), - array('value' => 4, 'label' => $totalProducts), - array('value' => 5, 'label' => $totalOrders), - array('value' => 6, 'label' => $totalCarts) + array('value' => 7, 'label' => $title) ) ); - } elseif (Mage::helper('mailchimp')->isEcommerceEnabled($scopeArray[1], $scopeArray[0])) { - $text = 'Warning: The MailChimp store was not created properly, please Reset Ecommerce Data and reload the page.'; - $label = Mage::helper('mailchimp')->__($text); - $returnArray = array_merge($returnArray, array(array('value' => 7, 'label' => $label))); } - return $returnArray; + return $returnArray; } elseif (!$this->_accountDetails) { return array(array('value' => '', 'label' => Mage::helper('mailchimp')->__('--- Enter your API KEY first ---'))); } else { diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 1d1b654f5..54bc028c9 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -195,6 +195,7 @@ select adminhtml/system_config_source_yesno + mailchimp/system_config_backend_ecommerce 205 1 1 @@ -227,7 +228,6 @@ - button mailchimp/adminhtml_system_config_resetErrors 210 @@ -239,7 +239,6 @@ - button mailchimp/adminhtml_system_config_resetEcommerceData 220 diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetecommercedata.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetecommercedata.phtml index 8452cde2b..c2ad7d3a5 100644 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetecommercedata.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetecommercedata.phtml @@ -1,21 +1,23 @@ diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetlist.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetlist.phtml index ed511ae6b..da0cec12c 100644 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetlist.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resetlist.phtml @@ -1,9 +1,14 @@