diff --git a/.travis.yml b/.travis.yml
index f85ef1b6c..95fb5ae09 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,8 +1,7 @@
dist: trusty
language: php
php:
- #- 5.4
- #- 5.5
+ - 5.5
- 5.6
- 7.0
@@ -57,7 +56,4 @@ script:
- |
if [ "$TEST_SUITE" = "phpunit" ]; then
cd magento/dev/tests/mailchimp && phpunit && cd $TRAVIS_BUILD_DIR
- fi
-
-#notifications:
-# slack: ebizmarts:DqCqxnqWzW55zoFU069hxs1T
+ fi
\ No newline at end of file
diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Account.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Account.php
index 87bde7568..dd76eea7a 100755
--- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Account.php
+++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Account.php
@@ -18,8 +18,17 @@ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
$html = '
';
foreach ($values as $dat) {
- if ($dat['value'] >= 7) {
+ if ($dat['value'] > 7 && $dat['value'] < 10) {
$html .= "- {$dat['label']}
";
+ } elseif ($dat['value'] == 10) {
+ $html .= "- {$dat['label']}
";
+ } elseif($dat['value'] == 3) {
+ $textArray = explode(':', $dat['label']);
+ if (strstr($textArray[1], $this->__('Finished'))) {
+ $html .= "- {$textArray[0]} : {$textArray[1]}
";
+ } else {
+ $html .= "- {$textArray[0]} : {$textArray[1]}
";
+ }
} else {
$html .= "- {$dat['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 e114160c4..a62c681f2 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
@@ -27,7 +27,7 @@ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
public function getButtonHtml()
{
$scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString());
- if (Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) {
+ if (Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) {
$label = $this->helper('mailchimp')->__('Reset Ecommerce Data');
$button = $this->getLayout()->createBlock('adminhtml/widget_button')
->setData(
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 c690eeb71..a74c5bbbc 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
@@ -27,7 +27,7 @@ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
public function getButtonHtml()
{
$scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString());
- if (Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) {
+ if (Mage::helper('mailchimp')->isMailChimpEnabled($scopeArray[1], $scopeArray[0]) || $scopeArray[1] == 0) {
$button = $this->getLayout()->createBlock('adminhtml/widget_button')
->setData(
array(
diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php
new file mode 100644
index 000000000..96e519d1f
--- /dev/null
+++ b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php
@@ -0,0 +1,123 @@
+
+ * @license http://opensource.org/licenses/osl-3.0.php
+ */
+class Ebizmarts_MailChimp_Block_Checkout_Subscribe extends Mage_Core_Block_Template
+{
+
+ protected $_lists = array();
+ protected $_info = array();
+ protected $_myLists = array();
+ protected $_generalList = array();
+ protected $_form;
+ protected $_api;
+ protected $helper;
+ protected $storeId;
+
+ public function __construct()
+ {
+ parent::__construct();
+ $this->helper = Mage::helper('mailchimp');
+ $this->storeId = Mage::app()->getStore()->getId();
+ }
+
+ /**
+ * Render block HTML
+ *
+ * @return string
+ */
+ protected function _toHtml()
+ {
+ $helper = $this->helper;
+ $storeId = $this->storeId;
+
+ $alreadySubscribed = Mage::getModel('newsletter/subscriber')
+ ->loadByEmail($this->getQuote()->getCustomerEmail())
+ ->isSubscribed();
+
+ if ($helper->isCheckoutSubscribeEnabled($storeId) && !$alreadySubscribed) {
+ return parent::_toHtml();
+ } else {
+ return '';
+ }
+ }
+
+ /**
+ * Retrieve current quote object from session
+ *
+ * @return Mage_Sales_Model_Quote
+ */
+ protected function getQuote()
+ {
+ return Mage::getSingleton('checkout/session')
+ ->getQuote();
+ }
+
+ protected function getCurrentCheckoutSubscribeValue()
+ {
+ return $this->helper->getCheckoutSubscribeValue($this->storeId);
+ }
+
+ protected function isForceHidden($currentValue = null)
+ {
+ if (!$currentValue) {
+ $currentValue = $this->getCurrentCheckoutSubscribeValue();
+ }
+ return ($currentValue == Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::FORCE_HIDDEN);
+ }
+
+ protected function isForceVisible($currentValue)
+ {
+ return ($currentValue == Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::FORCE_VISIBLE);
+ }
+
+ protected function isCheckedByDefault($currentValue)
+ {
+ return ($currentValue == Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::CHECKED_BY_DEFAULT);
+ }
+
+ public function isForceEnabled()
+ {
+ $currentValue = $this->getCurrentCheckoutSubscribeValue();
+ if ($this->isForceHidden($currentValue) || $this->isForceVisible($currentValue)) {
+ return true;
+ }
+ return false;
+ }
+
+ public function isChecked()
+ {
+ $currentValue = $this->getCurrentCheckoutSubscribeValue();
+ if ($this->isCheckedByDefault($currentValue) || $this->isForceVisible($currentValue)) {
+ return true;
+ }
+ return false;
+ }
+
+ public function addToPostOnLoad()
+ {
+ return ($this->isChecked() || $this->isForceHidden());
+ }
+
+ /**
+ * Get list data from MC
+ *
+ * @return array
+ */
+ public function getGeneralList()
+ {
+ $storeId = $this->storeId;
+ $helper = $this->helper;
+ $listId = $helper->getGeneralList($storeId);
+
+ //@Todo add support for intetest groups
+
+ return $listId;
+ }
+}
diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php
index 2bc81ed87..71b19dc30 100755
--- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php
+++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php
@@ -15,10 +15,10 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract
/**
* Get Config value for certain scope.
- *
+ *
* @param $path
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
* @throws Mage_Core_Exception
*/
@@ -85,18 +85,18 @@ public function getMCStoreName($scopeId, $scope)
{
$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;
+ 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;
}
@@ -161,7 +161,7 @@ public function getMagentoStoresForMCStoreIdByScope($scopeId, $scope)
* Return if module is enabled for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function isMailChimpEnabled($scopeId, $scope = null)
@@ -185,7 +185,7 @@ public function getApiKey($scopeId, $scope = null)
* Get local store_id value of the MC store for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getMCStoreId($scopeId, $scope = null)
@@ -197,7 +197,7 @@ public function getMCStoreId($scopeId, $scope = null)
* Remove local store_id value of the MC store for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function deleteLocalMCStoreData($scopeId, $scope = null)
@@ -205,7 +205,7 @@ 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()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, $scope, $scopeId);
- Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG, $scope, $scopeId);
+ Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, $scope, $scopeId);
Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $scope, $scopeId);
Mage::getConfig()->cleanCache();
}
@@ -214,7 +214,7 @@ public function deleteLocalMCStoreData($scopeId, $scope = null)
* Return if Ecommerce configuration is enabled for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function isEcommerceEnabled($scopeId, $scope = null)
@@ -226,7 +226,7 @@ public function isEcommerceEnabled($scopeId, $scope = null)
* Get general list configured for the given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getGeneralList($scopeId, $scope = null)
@@ -238,7 +238,7 @@ public function getGeneralList($scopeId, $scope = null)
* Get map fields configured for the given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getMapFields($scopeId, $scope = null)
@@ -250,7 +250,7 @@ public function getMapFields($scopeId, $scope = null)
* Get custom merge fields configured for the given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getCustomMergeFieldsSerialized($scopeId, $scope = null)
@@ -262,7 +262,7 @@ public function getCustomMergeFieldsSerialized($scopeId, $scope = null)
* Get if store has been reseted for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getIsReseted($scopeId, $scope = null)
@@ -274,7 +274,7 @@ public function getIsReseted($scopeId, $scope = null)
* Get if Abandoned Cart module is enabled.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function isAbandonedCartEnabled($scopeId, $scope = null)
@@ -286,7 +286,7 @@ public function isAbandonedCartEnabled($scopeId, $scope = null)
* Get date configured for carts to be sent for the given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getAbandonedCartFirstDate($scopeId, $scope = null)
@@ -298,7 +298,7 @@ public function getAbandonedCartFirstDate($scopeId, $scope = null)
* Get date configured for ecommerce data to be sent for the given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getEcommerceFirstDate($scopeId, $scope = null)
@@ -310,7 +310,7 @@ public function getEcommerceFirstDate($scopeId, $scope = null)
* Get local is_syncing value of the MC store for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
public function getMCIsSyncing($scopeId, $scope = null)
@@ -322,18 +322,18 @@ public function getMCIsSyncing($scopeId, $scope = null)
* Minimum date for which ecommerce data needs to be re-uploaded for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return mixed
*/
- public function getMCMinSyncDateFlag($scopeId, $scope = null)
+ public function getEcommMinSyncDateFlag($scopeId, $scope = null)
{
- return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG, $scopeId, $scope);
+ return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, $scopeId, $scope);
}
/**
* Get if logs are enabled for given scope.
*
- * @param int $scopeId
+ * @param int $scopeId
* @param null $scope
* @return mixed
*/
@@ -345,7 +345,7 @@ public function getLogsEnabled($scopeId = 0, $scope = null)
/**
* Get if two way sync is enabled for given scope.
*
- * @param int $scopeId
+ * @param int $scopeId
* @param null $scope
* @return mixed
*/
@@ -354,10 +354,22 @@ public function getTwoWaySyncEnabled($scopeId = 0, $scope = null)
return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_TWO_WAY_SYNC, $scopeId, $scope);
}
+ /**
+ * Get webhook Id.
+ *
+ * @param int $scopeId
+ * @param null $scope
+ * @return mixed
+ */
+ public function getWebhookId($scopeId = 0, $scope = null)
+ {
+ return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $scopeId, $scope);
+ }
+
/**
* Get if monkey should be displayed in order grid.
*
- * @param int $scopeId
+ * @param int $scopeId
* @param null $scope
* @return mixed
*/
@@ -369,7 +381,7 @@ public function getMonkeyInGrid($scopeId = 0, $scope = null)
/**
* Get if Email Catcher popup is enabled for given scope.
*
- * @param int $scopeId
+ * @param int $scopeId
* @param null $scope
* @return mixed
*/
@@ -382,7 +394,7 @@ public function isEmailCatcherEnabled($scopeId = 0, $scope = null)
* Call deleteStore and CreateStore functions.
* Update config values.
*
- * @param bool $deleteDataInMailchimp
+ * @param bool $deleteDataInMailchimp
* @param $scopeId
* @param $scope
*/
@@ -407,13 +419,14 @@ public function resetMCEcommerceData($scopeId, $scope, $deleteDataInMailchimp =
*
* @param $scopeId
* @param $scope
- * @param bool $deleteErrorsOnly
+ * @param bool $deleteErrorsOnly
*/
public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = false)
{
- $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection')
- ->addFieldToFilter('mailchimp_store_id', array('eq' => $this->getMCStoreId($scopeId, $scope)));
- if ($deleteErrorsOnly) {
+ $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection');
+ if (!$deleteErrorsOnly || $scopeId != 0) {
+ $collection->addFieldToFilter('mailchimp_store_id', array('eq' => $this->getMCStoreId($scopeId, $scope)));
+ } else {
$collection->addFieldToFilter('mailchimp_sync_error', array('neq' => ''));
}
foreach ($collection as $item) {
@@ -425,8 +438,8 @@ public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = fa
* Check if Ecommerce data is configured to be sent.
*
* @param $scopeId
- * @param null $scope
- * @param bool $isStoreCreation
+ * @param null $scope
+ * @param bool $isStoreCreation
* @return bool
*/
public function isEcomSyncDataEnabled($scopeId, $scope = null, $isStoreCreation = false)
@@ -444,8 +457,8 @@ public function isEcomSyncDataEnabled($scopeId, $scope = null, $isStoreCreation
* Save error response from MailChimp's API in "MailChimp_Error.log" file.
*
* @param $message
- * @param int $scopeId
- * @param string $scope
+ * @param int $scopeId
+ * @param string $scope
*/
public function logError($message, $scopeId = 0, $scope = 'default')
{
@@ -459,7 +472,7 @@ public function logError($message, $scopeId = 0, $scope = 'default')
*
* @param $message
* @param $scopeId
- * @param null $batchId
+ * @param null $batchId
*/
public function logRequest($message, $scopeId, $batchId = null)
{
@@ -505,7 +518,9 @@ public function resetErrors($scopeId, $scope)
// reset subscribers with errors
$collection = Mage::getResourceModel('newsletter/subscriber_collection')
->addFieldToFilter('mailchimp_sync_error', array('neq' => ''));
- $collection = $this->addStoresToFilter($collection, $scopeId, $scope);
+ if ($scopeId != 0) {
+ $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", '');
@@ -522,22 +537,22 @@ public function resetErrors($scopeId, $scope)
*
* @param $scopeId
* @param $scope
- * @param bool $excludeSubscribers
+ * @param bool $excludeSubscribers
*/
public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false)
{
- //Make sure there are no errors without MailChimp store id due to older versions.
+ //Make sure there are no errors without no MailChimp store id due to older versions.
$this->handleOldErrors();
- $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($scopeId, $scope);
- $storesForScope = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope);
- if ($scopeId == 0) {
- $storesForScope[] = 0;
- }
- $errorCollection = Mage::getResourceModel('mailchimp/mailchimperrors_collection')
- ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId));
+ $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope);
+ $errorCollection = Mage::getResourceModel('mailchimp/mailchimperrors_collection');
if ($excludeSubscribers) {
- $errorCollection->addFieldToFilter('regtype', array('neq' => Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER));
+// $errorCollection->addFieldToFilter('regtype', array('neq' => Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER));
+ $errorCollection->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId));
+ } else {
+ if ($scopeId != 0) {
+ $errorCollection->addFieldToFilter('store_id', array('eq' => $scopeId));
+ }
}
foreach ($errorCollection as $item) {
@@ -551,6 +566,7 @@ public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false)
public function handleOldErrors()
{
$errorCollection = Mage::getResourceModel('mailchimp/mailchimperrors_collection')
+ ->addFieldToFilter('type', array('neq' => 'SUB'))
->addFieldToFilter('mailchimp_store_id', array('eq' => ''));
foreach ($errorCollection as $error) {
$storeId = $error->getStoreId();
@@ -602,12 +618,12 @@ public function createStore($listId, $scopeId, $scope)
$mailchimpStoreId = md5($this->getMCStoreName($scopeId, $scope) . '_' . $date);
//create store in mailchimp
try {
- $response = Mage::getModel('mailchimp/api_stores')->createMailChimpStore($mailchimpStoreId, $listId, $scopeId, $scope);
+ $response = $this->getApiStores()->createMailChimpStore($mailchimpStoreId, $listId, $scopeId, $scope);
//save in config
$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_ECOMMMINSYNCDATEFLAG, Varien_Date::now()),
array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 1)
);
if (isset($response['connected_site']['site_script']['url'])) {
@@ -632,11 +648,14 @@ public function deleteStore($scopeId, $scope)
$mailchimpStoreId = $this->getMCStoreId($scopeId, $scope);
if (!empty($mailchimpStoreId)) {
try {
- Mage::getModel('mailchimp/api_stores')->deleteMailChimpStore($mailchimpStoreId, $scopeId, $scope);
+ $this->getApiStores()->deleteMailChimpStore($mailchimpStoreId, $scopeId, $scope);
} catch (MailChimp_Error $e) {
- Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope);
+ $this->logError($e->getFriendlyMessage(), $scopeId, $scope);
}
+ //delete configured webhook
+ $listId = $this->getGeneralList($scopeId, $scope);
+ $this->deleteCurrentWebhook($scopeId, $scope, $listId);
//clear store config values
$this->deleteLocalMCStoreData($scopeId, $scope);
}
@@ -738,7 +757,7 @@ public function getDateMicrotime()
* Get Api object for given scope.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return Ebizmarts_MailChimp|null
*/
public function getApi($scopeId, $scope = null)
@@ -761,9 +780,9 @@ public function getApi($scopeId, $scope = null)
*/
public function changeName($name, $scopeId, $scope)
{
- if ($this->getMCStoreId($scopeId, $scope) && $this->getIfMCStoreIdExistsForScope($scopeId, $scope)) {
+ if ($this->getMCStoreId($scopeId, $scope) && $this->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeId, $scope)) {
try {
- Mage::getModel('mailchimp/api_stores')->modifyName($name, $scopeId, $scope);
+ $this->getApiStores()->modifyName($name, $scopeId, $scope);
} catch (MailChimp_Error $e) {
Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeId, $scope);
}
@@ -776,17 +795,18 @@ public function changeName($name, $scopeId, $scope)
* @param $itemId
* @param $itemType
* @param $mailchimpStoreId
- * @param null $syncDelta
- * @param null $syncError
- * @param int $syncModified
- * @param null $syncDeleted
- * @param null $token
- * @param bool $saveOnlyIfexists
+ * @param null $syncDelta
+ * @param null $syncError
+ * @param int $syncModified
+ * @param null $syncDeleted
+ * @param null $token
+ * @param bool $saveOnlyIfexists
*/
public function saveEcommerceSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelta = null, $syncError = null,
- $syncModified = 0, $syncDeleted = null, $token = null, $saveOnlyIfexists = false
- ) {
-
+ $syncModified = 0, $syncDeleted = null, $token = null, $saveOnlyIfexists = false
+ )
+ {
+
$ecommerceSyncDataItem = $this->getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId);
if (!$saveOnlyIfexists || $ecommerceSyncDataItem->getMailchimpSyncDelta()) {
if ($syncDelta) {
@@ -820,7 +840,10 @@ public function getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId)
$collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection')
->addFieldToFilter('related_id', array('eq' => $itemId))
->addFieldToFilter('type', array('eq' => $itemType))
- ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId));
+ ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId))
+ ->setCurPage(1)
+ ->setPageSize(1);
+
if ($collection->getSize()) {
$ecommerceSyndDataItem = $collection->getFirstItem();
} else {
@@ -858,37 +881,11 @@ public function addStoresToFilter($collection, $scopeId, $scope)
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 = Mage::registry('mailchimp_store_exists_for_scope_' . $scope . '_' . $scopeId);
- if ($mcStoreAssociatedToScope === null) {
- $mcStoreAssociatedToScope = false;
- $numEntries = Mage::getResourceModel('core/config_data_collection')
- ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID))
- ->addFieldToFilter('scope', array('eq' => $scope))
- ->addFieldToFilter('scope_id', array('eq' => $scopeId))
- ->getSize();
- if ($numEntries) {
- $mcStoreAssociatedToScope = true;
- }
- Mage::register('mailchimp_store_exists_for_scope_' . $scope . '_' . $scopeId, $mcStoreAssociatedToScope);
- }
-
- return $mcStoreAssociatedToScope;
- }
-
/**
* Get actual scope where the MailChimp store was created if exists.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return array|null
*/
public function getMailChimpScopeByStoreId($scopeId, $scope = null)
@@ -969,16 +966,27 @@ public function getMailChimpProductImageUrl($parentImageUrl, $productImageUrl)
*/
public function getImageUrlById($productId)
{
- $productMediaConfig = Mage::getModel('catalog/product_media_config');
- $product = Mage::getModel('catalog/product')->load($productId);
- if ($product->getImage() == 'no_selection') {
+ $productMediaConfig = $this->getProductMediaConfig();
+ $product = $this->loadProductById($productId);
+ $productImage = $product->getImage();
+ if ($productImage == 'no_selection' || $productImage == null) {
$imageUrl = null;
} else {
- $imageUrl = $productMediaConfig->getMediaUrl($product->getImage());
+ $imageUrl = $productMediaConfig->getMediaUrl($productImage);
}
return $imageUrl;
}
+ private function getProductMediaConfig()
+ {
+ return Mage::getModel('catalog/product_media_config');
+ }
+
+ private function loadProductById($productId)
+ {
+ return Mage::getModel('catalog/product')->load($productId);
+ }
+
/**
* If orders with the given email exists, returns the date of the last order made.
*
@@ -1021,7 +1029,7 @@ public function customMergeFieldAlreadyExists($value, $scopeId, $scope)
* Get custom merge fields for given scope as an array.
*
* @param $scopeId
- * @param null $scope
+ * @param null $scope
* @return array|mixed
*/
public function getCustomMergeFields($scopeId, $scope = null)
@@ -1052,10 +1060,10 @@ public function getMCJs()
{
$script = '';
$storeId = Mage::app()->getStore()->getId();
- if ($this->isEcommerceEnabled($storeId)) {
+ if ($this->isEcomSyncDataEnabled($storeId)) {
$url = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $storeId);
if (!$url) {
- $url = Mage::getModel('mailchimp/api_stores')->getMCJsUrl($storeId, 'stores');
+ $url = $this->getApiStores()->getMCJsUrl($storeId, 'stores');
}
$script = '';
}
@@ -1173,21 +1181,21 @@ protected function _migrateCustomersFrom115($mailchimpStoreId, $initialTime)
);
$this->_makeForCollectionItem(
$customerCollection, $mailchimpStoreId, $initialTime, function ($customer, $mailchimpStoreId) {
- $customerId = $customer->getEntityId();
- $customerObject = Mage::getModel('customer/customer')->load($customerId);
- $syncError = null;
- $syncModified = null;
- $syncDelta = $customerObject->getMailchimpSyncDelta();
- if ($customer->getMailchimpSyncError()) {
- $syncError = $customer->getMailchimpSyncError();
- }
-
- if ($customer->getMailchimpSyncModified()) {
- $syncModified = $customer->getMailchimpSyncModified();
- }
+ $customerId = $customer->getEntityId();
+ $customerObject = Mage::getModel('customer/customer')->load($customerId);
+ $syncError = null;
+ $syncModified = null;
+ $syncDelta = $customerObject->getMailchimpSyncDelta();
+ if ($customer->getMailchimpSyncError()) {
+ $syncError = $customer->getMailchimpSyncError();
+ }
- Mage::helper('mailchimp')->saveEcommerceSyncData($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified);
+ if ($customer->getMailchimpSyncModified()) {
+ $syncModified = $customer->getMailchimpSyncModified();
}
+
+ Mage::helper('mailchimp')->saveEcommerceSyncData($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified);
+ }
);
}
} catch (Exception $e) {
@@ -1223,21 +1231,21 @@ protected function _migrateProductsFrom115($mailchimpStoreId, $initialTime)
);
$this->_makeForCollectionItem(
$productCollection, $mailchimpStoreId, $initialTime, function ($product, $mailchimpStoreId) {
- $productId = $product->getEntityId();
- $_resource = Mage::getResourceSingleton('catalog/product');
- $syncDelta = $_resource->getAttributeRawValue($productId, 'mailchimp_sync_delta', Mage::app()->getStore());
- $syncError = null;
- $syncModified = null;
- if ($product->getMailchimpSyncError()) {
- $syncError = $product->getMailchimpSyncError();
- }
-
- if ($product->getMailchimpSyncModified()) {
- $syncModified = $product->getMailchimpSyncModified();
- }
+ $productId = $product->getEntityId();
+ $_resource = Mage::getResourceSingleton('catalog/product');
+ $syncDelta = $_resource->getAttributeRawValue($productId, 'mailchimp_sync_delta', Mage::app()->getStore());
+ $syncError = null;
+ $syncModified = null;
+ if ($product->getMailchimpSyncError()) {
+ $syncError = $product->getMailchimpSyncError();
+ }
- Mage::helper('mailchimp')->saveEcommerceSyncData($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, $syncDelta, $syncError, $syncModified);
+ if ($product->getMailchimpSyncModified()) {
+ $syncModified = $product->getMailchimpSyncModified();
}
+
+ Mage::helper('mailchimp')->saveEcommerceSyncData($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, $syncDelta, $syncError, $syncModified);
+ }
);
}
} catch (Exception $e) {
@@ -1271,21 +1279,21 @@ protected function _migrateOrdersFrom115($mailchimpStoreId, $initialTime)
$orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS NULL AND main_table.mailchimp_sync_delta > '0000-00-00 00:00:00'");
$this->_makeForCollectionItem(
$orderCollection, $mailchimpStoreId, $initialTime, function ($order, $mailchimpStoreId) {
- $orderId = $order->getEntityId();
- $syncError = null;
- $syncModified = null;
- $orderObject = Mage::getModel('sales/order')->load($orderId);
- $syncDelta = $orderObject->getMailchimpSyncDelta();
- if ($order->getMailchimpSyncError()) {
- $syncError = $order->getMailchimpSyncError();
- }
-
- if ($order->getMailchimpSyncModified()) {
- $syncModified = $order->getMailchimpSyncModified();
- }
+ $orderId = $order->getEntityId();
+ $syncError = null;
+ $syncModified = null;
+ $orderObject = Mage::getModel('sales/order')->load($orderId);
+ $syncDelta = $orderObject->getMailchimpSyncDelta();
+ if ($order->getMailchimpSyncError()) {
+ $syncError = $order->getMailchimpSyncError();
+ }
- Mage::helper('mailchimp')->saveEcommerceSyncData($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified);
+ if ($order->getMailchimpSyncModified()) {
+ $syncModified = $order->getMailchimpSyncModified();
}
+
+ Mage::helper('mailchimp')->saveEcommerceSyncData($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, $syncDelta, $syncError, $syncModified);
+ }
);
}
} catch (Exception $e) {
@@ -1320,26 +1328,26 @@ protected function _migrateCartsFrom115($mailchimpStoreId, $initialTime)
$quoteCollection->getSelect()->where("m4m.mailchimp_sync_delta IS NULL AND main_table.mailchimp_sync_delta > '0000-00-00 00:00:00'");
$finished = $this->_makeForCollectionItem(
$quoteCollection, $mailchimpStoreId, $initialTime, function ($quote, $mailchimpStoreId) {
- $quoteId = $quote->getEntityId();
- $syncError = null;
- $syncDeleted = null;
- $token = null;
- $quoteObject = Mage::getModel('sales/order')->load($quoteId);
- $syncDelta = $quoteObject->getMailchimpSyncDelta();
- if ($quote->getMailchimpSyncError()) {
- $syncError = $quote->getMailchimpSyncError();
- }
-
- if ($quote->getMailchimpSyncDeleted()) {
- $syncDeleted = $quote->getMailchimpSyncDeleted();
- }
+ $quoteId = $quote->getEntityId();
+ $syncError = null;
+ $syncDeleted = null;
+ $token = null;
+ $quoteObject = Mage::getModel('sales/order')->load($quoteId);
+ $syncDelta = $quoteObject->getMailchimpSyncDelta();
+ if ($quote->getMailchimpSyncError()) {
+ $syncError = $quote->getMailchimpSyncError();
+ }
- if ($quote->getMailchimpToken()) {
- $token = $quote->getMailchimpToken();
- }
+ if ($quote->getMailchimpSyncDeleted()) {
+ $syncDeleted = $quote->getMailchimpSyncDeleted();
+ }
- Mage::helper('mailchimp')->saveEcommerceSyncData($quoteId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, null, $syncDeleted, $token);
+ if ($quote->getMailchimpToken()) {
+ $token = $quote->getMailchimpToken();
}
+
+ Mage::helper('mailchimp')->saveEcommerceSyncData($quoteId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, null, $syncDeleted, $token);
+ }
);
} else {
$finished = true;
@@ -1359,7 +1367,7 @@ protected function _migrateCartsFrom115($mailchimpStoreId, $initialTime)
* @param $collection
* @param $mailchimpStoreId
* @param $initialTime
- * @param Closure $callback
+ * @param Closure $callback
* @return bool
*/
protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initialTime, Closure $callback)
@@ -1441,7 +1449,7 @@ protected function _setIsSyncingInAllStores($syncValue)
$mailchimpApi = $this->getApi($storeId);
$mailchimpStoreId = $this->getMCStoreId($storeId);
if ($mailchimpStoreId) {
- Mage::getModel('mailchimp/api_stores')->editIsSyncing($mailchimpApi, $syncValue, $mailchimpStoreId, $storeId);
+ $this->getApiStores()->editIsSyncing($mailchimpApi, $syncValue, $mailchimpStoreId, $storeId);
}
}
}
@@ -1526,7 +1534,7 @@ protected function _migrateFrom1164($initialTime)
*/
public function getMagentoStoreIdsByListId($listId)
{
- $storeIds = Mage::registry('mailchimp_store_ids_for_list_'.$listId);
+ $storeIds = Mage::registry('mailchimp_store_ids_for_list_' . $listId);
if ($storeIds === null) {
$stores = Mage::app()->getStores();
$storeIds = array();
@@ -1538,7 +1546,7 @@ public function getMagentoStoreIdsByListId($listId)
}
}
}
- Mage::register('mailchimp_store_ids_for_list_'.$listId, $storeIds);
+ Mage::register('mailchimp_store_ids_for_list_' . $listId, $storeIds);
}
return $storeIds;
@@ -1549,7 +1557,7 @@ public function getMagentoStoreIdsByListId($listId)
* address for magento stores subscribed to the given Mailchimp List ID.
*
* @param string $listId Mailchimp list ID
- * @param string $email Subscriber email address.
+ * @param string $email Subscriber email address.
* @returns Mage_Newsletter_Model_Subscriber $subscriber
*/
public function loadListSubscriber($listId, $email)
@@ -1557,6 +1565,8 @@ public function loadListSubscriber($listId, $email)
$subscriber = null;
$storeIds = $this->getMagentoStoreIdsByListId($listId);
+ //add store id 0 for those created from the back end.
+ $storeIds[] = 0;
if (count($storeIds) > 0) {
$subscriber = Mage::getModel('newsletter/subscriber')->getCollection()
->addFieldToFilter('store_id', array('in' => $storeIds))
@@ -1578,8 +1588,8 @@ public function loadListSubscriber($listId, $email)
* No customer with that address. Just assume the first
* store ID is the correct one as there is no other way
* to tell which store this mailchimp list guest subscriber
- * belongs to.
-*/
+ * belongs to.
+ */
$subscriber->setStoreId($storeIds[0]);
}
}
@@ -1592,7 +1602,7 @@ public function loadListSubscriber($listId, $email)
* address for magento stores subscribed to the given Mailchimp List ID.
*
* @param string $listId Mailchimp list ID
- * @param string $email Subscriber email address.
+ * @param string $email Subscriber email address.
* @returns Mage_Customer_Model_Customer|null $customer
*/
public function loadListCustomer($listId, $email)
@@ -1614,4 +1624,262 @@ public function loadListCustomer($listId, $email)
return $customer;
}
+
+ public function handleWebhookChange($scopeId, $scope = 'stores')
+ {
+ $webhookScope = $this->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $scopeId, $scope);
+ $listId = $this->getGeneralList($scopeId, $scope);
+ $this->deleteCurrentWebhook($webhookScope['scope_id'], $webhookScope['scope'], $listId);
+ if ($this->isMailChimpEnabled($scopeId, $scope)) {
+ $this->createNewWebhook($webhookScope['scope_id'], $webhookScope['scope'], $listId);
+ }
+ }
+
+ protected function deleteCurrentWebhook($scopeId, $scope, $listId)
+ {
+ $api = $this->getApi($scopeId, $scope);
+ $webhookId = $this->getWebhookId($scopeId, $scope);
+ if ($webhookId) {
+ $api->lists->webhooks->delete($listId, $webhookId);
+ Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $scope, $scopeId);
+ } else {
+ $webhookUrl = $this->getWebhookUrl($scopeId, $scope);
+ $webhooks = $api->lists->webhooks->getAll($listId);
+ foreach ($webhooks['webhooks'] as $webhook) {
+ if (strpos($webhook['url'], $webhookUrl) !== false) {
+ $api->lists->webhooks->delete($listId, $webhook['id']);
+ }
+ }
+ }
+ }
+
+ protected function createNewWebhook($scopeId, $scope, $listId)
+ {
+ $hookUrl = $this->getWebhookUrl();
+
+ $api = $this->getApi($scopeId, $scope);
+ if ($this->getTwoWaySyncEnabled($scopeId, $scope)) {
+ $events = array(
+ 'subscribe' => true,
+ 'unsubscribe' => true,
+ 'profile' => false,
+ 'cleaned' => true,
+ 'upemail' => true,
+ 'campaign' => false
+ );
+ $sources = array(
+ 'user' => true,
+ 'admin' => true,
+ 'api' => true
+ );
+ } else {
+ $events = array(
+ 'subscribe' => true,
+ 'unsubscribe' => true,
+ 'profile' => false,
+ 'cleaned' => false,
+ 'upemail' => false,
+ 'campaign' => false
+ );
+ $sources = array(
+ 'user' => true,
+ 'admin' => true,
+ 'api' => false
+ );
+ }
+ try {
+ $response = $api->lists->webhooks->getAll($listId);
+ $createWebhook = true;
+ if (isset($response['total_items']) && $response['total_items'] > 0) {
+ foreach ($response['webhooks'] as $webhook) {
+ if ($webhook['url'] == $hookUrl) {
+ $createWebhook = false;
+ }
+ }
+ }
+ if ($createWebhook) {
+ $newWebhook = $api->lists->webhooks->add($listId, $hookUrl, $events, $sources);
+ $newWebhookId = $newWebhook['id'];
+ $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $newWebhookId));
+ $this->saveMailchimpConfig($configValues, $scopeId, $scope);
+
+ }
+ } catch (MailChimp_Error $e) {
+ $this->logError($e->getFriendlyMessage(), $scopeId, $scope);
+ $textToCompare = 'The resource submitted could not be validated. For field-specific details, see the \'errors\' array.';
+ if ($e->getMailchimpDetails() == $textToCompare) {
+ $errorMessage = 'Your store could not be accessed by MailChimp\'s Api. Please confirm the URL: ' . $hookUrl . ' is accessible externally to allow the webhook creation.';
+ $this->logError($errorMessage, $scopeId, $scope);
+ }
+ } catch (Exception $e) {
+ $this->logError($e->getMessage(), $scopeId, $scope);
+ }
+
+ }
+
+
+ protected function getWebhookUrl()
+ {
+ $store = Mage::app()->getDefaultStoreView();
+ $webhooksKey = $this->getWebhooksKey();
+ //Generating Webhooks URL
+ $url = Ebizmarts_MailChimp_Model_ProcessWebhook::WEBHOOKS_PATH;
+ $hookUrl = $store->getUrl(
+ $url, array(
+ 'wkey' => $webhooksKey,
+ '_nosid' => true,
+ '_secure' => true,
+ )
+ );
+
+ if (false != strstr($hookUrl, '?', true)) {
+ $hookUrl = strstr($hookUrl, '?', true);
+ }
+ return $hookUrl;
+ }
+
+ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores')
+ {
+ $websiteId = null;
+ if ($scope == 'stores') {
+ $websiteId = Mage::getModel('core/store')->load($scopeId)->getWebsiteId();
+ $scopeIdsArray = array($scopeId, $websiteId, 0);
+ } else {
+ $scopeIdsArray = array($scopeId, 0);
+ }
+ $configCollection = Mage::getResourceModel('core/config_data_collection')
+ ->addFieldToFilter('path', array('eq' => $path))
+ ->addFieldToFilter('scope_id', array('in' => $scopeIdsArray));
+
+ $scopeSoFar = null;
+ foreach ($configCollection as $config) {
+ //Discard possible extra website or store
+ if ($this->isExtraEntry($config, $scope, $websiteId)) {
+ continue;
+ }
+ switch ($config->getScope()) {
+ case 'stores':
+ $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope());
+ break;
+ case 'websites':
+ if (!$scopeSoFar || $scopeSoFar['scope'] == 'default') {
+ $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope());
+ }
+ break;
+ case 'default':
+ if ($scopeSoFar['scope'] != 'stores') {
+ $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope());
+ }
+ break;
+ }
+
+ }
+ return $scopeSoFar;
+ }
+
+ /**
+ * Return true if the config entry does not belong to the store required or website that contains that store.
+ *
+ * @param $config
+ * @param $scope
+ * @param $websiteId
+ * @return bool
+ */
+ protected function isExtraEntry($config, $scope, $websiteId)
+ {
+ return $config->getScopeId() != 0 && (($config->getScope() == 'stores' && $scope != 'stores') || ($config->getScope() == 'websites' && $scope == 'stores' && $config->getScopeId() != $websiteId));
+ }
+
+ public function updateSubscriberSyndData($itemId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncDeleted = null)
+ {
+ $subscriber = Mage::getModel('newsletter/subscriber')->load($itemId);
+ if ($subscriber->getId()) {
+ if ($syncDelta) {
+ $subscriber->setData("mailchimp_sync_delta", $syncDelta);
+ }
+ if ($syncError) {
+ $subscriber->setData("mailchimp_sync_error", $syncError);
+ }
+ $subscriber->setData("mailchimp_sync_modified", $syncModified);
+ if ($syncDeleted) {
+ $subscriber->setData("mailchimp_sync_deleted", $syncDeleted);
+ }
+ $subscriber->save();
+ }
+ }
+
+ /**
+ * Get date configured for subscriber data to be sent for the given scope.
+ *
+ * @param $scopeId
+ * @param string $scope
+ * @return mixed
+ */
+ public function getSubMinSyncDateFlag($scopeId, $scope = 'stores')
+ {
+ return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $scopeId, $scope);
+ }
+
+ /**
+ * Return true if the configPath has been saved specifically for the given scope.
+ *
+ * @param $configPath
+ * @param $scopeId
+ * @param string $scope
+ * @return bool|mixed
+ */
+ public function getIfConfigExistsForScope($configPath, $scopeId, $scope = 'stores')
+ {
+ $configPathArray = explode('/', $configPath);
+ $configName = $configPathArray[2];
+ $configAssociatedToScope = Mage::registry('mailchimp_' . $configName . '_exists_for_scope_' . $scope . '_' . $scopeId);
+ if ($configAssociatedToScope === null) {
+ $configAssociatedToScope = false;
+ $numEntries = Mage::getResourceModel('core/config_data_collection')
+ ->addFieldToFilter('path', array('eq' => $configPath))
+ ->addFieldToFilter('scope', array('eq' => $scope))
+ ->addFieldToFilter('scope_id', array('eq' => $scopeId))
+ ->getSize();
+ if ($numEntries) {
+ $configAssociatedToScope = true;
+ }
+ Mage::register('mailchimp_' . $configName . '_exists_for_scope_' . $scope . '_' . $scopeId, $configAssociatedToScope);
+ }
+
+ return $configAssociatedToScope;
+ }
+
+ /**
+ * @param $batchArray
+ * @param $productData
+ * @param $counter
+ * @return mixed
+ */
+ public function addEntriesToArray($batchArray, $productData, $counter)
+ {
+ if (count($productData)) {
+ foreach ($productData as $p) {
+ if (!empty($p)) {
+ $batchArray[$counter] = $p;
+ $counter++;
+ }
+ }
+ }
+ return array($batchArray, $counter);
+ }
+
+ protected function getApiStores()
+ {
+ return Mage::getModel('mailchimp/api_stores');
+ }
+
+ public function getCheckoutSubscribeValue($scopeId, $scope = 'stores')
+ {
+ return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_CHECKOUT_SUBSCRIBE, $scopeId, $scope);
+ }
+
+ public function isCheckoutSubscribeEnabled($scopeId, $scope = 'stores')
+ {
+ return ($this->isMailChimpEnabled($scopeId, $scope) && $this->getCheckoutSubscribeValue($scopeId, $scope) != Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::DISABLED);
+ }
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php
index 0d96f7e43..3b725bf95 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php
@@ -120,7 +120,7 @@ public function handleSubscriberBatches()
* Get results of batch operations sent to MailChimp.
*
* @param $magentoStoreId
- * @param bool $isEcommerceData
+ * @param bool $isEcommerceData
*/
protected function _getResults($magentoStoreId, $isEcommerceData = true)
{
@@ -220,6 +220,7 @@ public function _sendEcommerceBatch($magentoStoreId)
$itemAmount = ($customerAmount + $productAmount + $orderAmount);
if ($helper->getMCIsSyncing($magentoStoreId) && $itemAmount == 0) {
Mage::getModel('mailchimp/api_stores')->editIsSyncing($mailchimpApi, false, $mailchimpStoreId, $magentoStoreId);
+ $helper->handleWebhookChange($magentoStoreId);
}
} catch (MailChimp_Error $e) {
$helper->logError($e->getFriendlyMessage(), $magentoStoreId);
@@ -241,16 +242,53 @@ public function _sendEcommerceBatch($magentoStoreId)
protected function deleteUnsentItems()
{
- $write_connection = Mage::getSingleton('core/resource')->getConnection('core_write');
- $resource = Mage::getResourceModel('mailchimp/ecommercesyncdata');
- $write_connection->delete($resource->getMainTable(), "batch_id IS NULL");
+ $ecommerceDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection')
+ ->addFieldToFilter('batch_id', array('null' => true));
+ Mage::getSingleton('core/resource_iterator')->walk($ecommerceDataCollection->getSelect(), array(array($this, 'ecommerceDeleteCallback')));
+ }
+
+ public function ecommerceDeleteCallback($args)
+ {
+ $ecommerceData = Mage::getModel('mailchimp/ecommercesyncdata');
+ $ecommerceData->setData($args['row']);
+ $ecommerceData->delete();
}
protected function markItemsAsSent($batchResponseId, $mailchimpStoreId)
{
- $write_connection = Mage::getSingleton('core/resource')->getConnection('core_write');
+ $ecommerceDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection')
+ ->addFieldToFilter('batch_id', array('null' => true))
+ ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId));
+ Mage::getSingleton('core/resource_iterator')->walk($ecommerceDataCollection->getSelect(), array(array($this, 'ecommerceSentCallback')));
+ foreach ($ecommerceDataCollection as $ecommerceData) {
+ $ecommerceData->setBatchId($batchResponseId)
+ ->save();
+ }
+ }
+
+ public function ecommerceSentCallback($args)
+ {
+ $ecommerceData = Mage::getModel('mailchimp/ecommercesyncdata');
+ $ecommerceData->setData($args['row']); // map data to customer model
+ $writeAdapter = Mage::getSingleton('core/resource')->getConnection('core_write');
+ $insertData = array(
+ 'id' => $ecommerceData->getId(),
+ 'related_id' => $ecommerceData->getRelatedId(),
+ 'type' => $ecommerceData->getType(),
+ 'mailchimp_store_id' => $ecommerceData->getMailchimpStoreId(),
+ 'mailchimp_sync_error' => $ecommerceData->getMailchimpSyncError(),
+ 'mailchimp_sync_delta' => $ecommerceData->getMailchimpSyncDelta(),
+ 'mailchimp_sync_modified' => $ecommerceData->getMailchimpSyncModified(),
+ 'mailchimp_sync_deleted' => $ecommerceData->getMailchimpSyncDeleted(),
+ 'mailchimp_token' => $ecommerceData->getMailchimpToken(),
+ 'batch_id' => $ecommerceData->getBatchId()
+ );
$resource = Mage::getResourceModel('mailchimp/ecommercesyncdata');
- $write_connection->update($resource->getMainTable(), array('batch_id' => $batchResponseId), "batch_id IS NULL AND mailchimp_store_id = '" . $mailchimpStoreId . "'");
+ $writeAdapter->insertOnDuplicate(
+ $resource->getMainTable(),
+ $insertData,
+ array('id', 'related_id', 'type', 'mailchimp_store_id', 'mailchimp_sync_error', 'mailchimp_sync_delta', 'mailchimp_sync_modified', 'mailchimp_sync_deleted', 'mailchimp_token', 'batch_id')
+ );
}
/**
@@ -260,7 +298,7 @@ protected function markItemsAsSent($batchResponseId, $mailchimpStoreId)
*/
protected function _sendSubscriberBatches()
{
- $subscriberLimit = Ebizmarts_MailChimp_Model_Api_subscribers::BATCH_LIMIT;
+ $subscriberLimit = Ebizmarts_MailChimp_Model_Api_Subscribers::BATCH_LIMIT;
$stores = Mage::app()->getStores();
$batchResponses = array();
foreach ($stores as $store) {
@@ -348,35 +386,37 @@ public function getBatchResponse($batchId, $magentoStoreId)
try {
$baseDir = Mage::getBaseDir();
$api = $this->getHelper()->getApi($magentoStoreId);
- // check the status of the job
- $response = $api->batchOperation->status($batchId);
- if (isset($response['status']) && $response['status'] == 'finished') {
- // get the tar.gz file with the results
- $fileUrl = urldecode($response['response_body_url']);
- $fileName = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '.tar.gz';
- $fd = fopen($fileName, 'w');
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $fileUrl);
- curl_setopt($ch, CURLOPT_FILE, $fd);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects
- $r = curl_exec($ch);
- curl_close($ch);
- fclose($fd);
- mkdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, 0750, true);
- $archive = new Mage_Archive();
- if (file_exists($fileName)) {
- $archive->unpack($fileName, $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId);
- $archive->unpack($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar', $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId);
- $dir = scandir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId);
- foreach ($dir as $d) {
- $name = pathinfo($d);
- if ($name['extension'] == 'json') {
- $files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d;
+ if ($api) {
+ // check the status of the job
+ $response = $api->batchOperation->status($batchId);
+ if (isset($response['status']) && $response['status'] == 'finished') {
+ // get the tar.gz file with the results
+ $fileUrl = urldecode($response['response_body_url']);
+ $fileName = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '.tar.gz';
+ $fd = fopen($fileName, 'w');
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, $fileUrl);
+ curl_setopt($ch, CURLOPT_FILE, $fd);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects
+ $r = curl_exec($ch);
+ curl_close($ch);
+ fclose($fd);
+ mkdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, 0750, true);
+ $archive = new Mage_Archive();
+ if (file_exists($fileName)) {
+ $archive->unpack($fileName, $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId);
+ $archive->unpack($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar', $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId);
+ $dir = scandir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId);
+ foreach ($dir as $d) {
+ $name = pathinfo($d);
+ if ($name['extension'] == 'json') {
+ $files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d;
+ }
}
- }
- unlink($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar');
- unlink($fileName);
+ unlink($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar');
+ unlink($fileName);
+ }
}
}
} catch (MailChimp_Error $e) {
@@ -426,10 +466,17 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId)
if ($errorDetails == "") {
$errorDetails = $response->detail;
}
+ if (strstr($errorDetails, 'already exists in the account')) {
+ continue;
+ }
+ if (strstr($errorDetails, 'already exists in the account')) {
+ $this->saveSyncData($id, $type, $mailchimpStoreId, null, null, 1, null, null, true);
+ continue;
+ }
$error = $response->title . " : " . $response->detail;
- $this->getHelper()->saveEcommerceSyncData($id, $type, $mailchimpStoreId, null, $error, 0, null, null, true);
+ $this->saveSyncData($id, $type, $mailchimpStoreId, null, $error, 0, null, null, true);
$mailchimpErrors->setType($response->type);
$mailchimpErrors->setTitle($response->title);
@@ -503,4 +550,15 @@ public function replaceAllOrders($initialTime, $magentoStoreId)
$this->getHelper()->logError($e->getMessage(), $magentoStoreId);
}
}
+
+ protected function saveSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelta = null, $syncError = null,
+ $syncModified = 0, $syncDeleted = null, $token = null, $saveOnlyIfexists = false)
+ {
+ $helper = $this->getHelper();
+ if ($itemType == 'SUB') {
+ $helper->updateSubscriberSyndData($itemId,$syncDelta, $syncError, 0, null);
+ } else {
+ $helper->saveEcommerceSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, $token, $saveOnlyIfexists);
+ }
+ }
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php
index 9ad4ff9ea..9546a492a 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php
@@ -164,13 +164,7 @@ protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId)
}
// send the products that not already sent
- $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);
- if (count($productData)) {
- foreach($productData as $p) {
- $allCarts[$this->_counter] = $p;
- $this->_counter += 1;
- }
- }
+ $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts);
$cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId);
if ($cartJson!="") {
@@ -257,13 +251,7 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId)
}
// send the products that not already sent
- $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);
- if (count($productData)) {
- foreach($productData as $p) {
- $allCarts[$this->_counter] = $p;
- $this->_counter += 1;
- }
- }
+ $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts);
$cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId);
if ($cartJson!="") {
@@ -503,4 +491,20 @@ protected function _updateSyncData($cartId, $mailchimpStoreId, $syncDelta = null
{
Mage::helper('mailchimp')->saveEcommerceSyncData($cartId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, $token);
}
+
+ /**
+ * @param $mailchimpStoreId
+ * @param $magentoStoreId
+ * @param $cart
+ * @param $allCarts
+ * @return mixed
+ */
+ public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts)
+ {
+ $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId);
+ $productDataArray = Mage::helper('mailchimp')->addEntriesToArray($allCarts, $productData, $this->_counter);
+ $allCarts = $productDataArray[0];
+ $this->_counter = $productDataArray[1];
+ return $allCarts;
+ }
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php
index fa874c8d9..314a0505b 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php
@@ -15,8 +15,8 @@ class Ebizmarts_MailChimp_Model_Api_Customers
const BATCH_LIMIT = 100;
/**
- * @var Ebizmarts_MailChimp_Helper_Data
-*/
+ * @var Ebizmarts_MailChimp_Helper_Data
+ */
private $mailchimpHelper;
private $optInConfiguration;
private $optInStatusForStore;
@@ -132,6 +132,9 @@ protected function getCustomerAddressData($customer)
if ($customer->getRegionId()) {
$customerAddress["province_code"] = $this->directoryRegionModel->load($customer->getRegionId())->getCode();
+ if (!$customerAddress["province_code"]) {
+ unset($customerAddress["province_code"]);
+ }
}
if ($customer->getPostcode()) {
@@ -224,17 +227,15 @@ protected function makeBatchId()
}
/**
- * @param $mailchimpStoreId
- * @param $magentoStoreId
* @return Mage_Customer_Model_Resource_Customer_Collection
*/
public function makeCustomersNotSentCollection()
{
/**
- * @var Mage_Customer_Model_Resource_Customer_Collection $collection
-*/
+ * @var Mage_Customer_Model_Resource_Customer_Collection $collection
+ */
$collection = $this->getCustomerResourceCollection();
- $collection->addFieldToFilter('website_id', array('eq' => $this->getWebsiteIdForStoreId($this->getBatchMagentoStoreId())));
+ $collection->addFieldToFilter('store_id', array('eq' => $this->getBatchMagentoStoreId()));
$collection->addNameToSelect();
@@ -276,7 +277,6 @@ protected function joinSalesData($collection)
}
/**
- * @param $mailchimpStoreId
* @param $collection
*/
protected function joinMailchimpSyncData($collection)
@@ -298,15 +298,6 @@ protected function joinMailchimpSyncData($collection)
$collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1");
}
- /**
- * @param $magentoStoreId
- * @return int|null|string
- */
- protected function getWebsiteIdForStoreId($magentoStoreId)
- {
- return Mage::app()->getStore($magentoStoreId)->getWebsiteId();
- }
-
/**
* @return string
*/
@@ -378,7 +369,6 @@ protected function getCustomerLastname($customer)
}
/**
- * @param $magentoStoreId
* @param $customer
*/
protected function logCouldNotEncodeCustomerError($customer)
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php
index 69e5aa819..191507ac6 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php
@@ -13,6 +13,7 @@ class Ebizmarts_MailChimp_Model_Api_Orders
{
const BATCH_LIMIT = 50;
+ const BATCH_LIMIT_ONLY_ORDERS = 500;
const PAID = 'paid';
const PARTIALLY_PAID = 'parially_paid';
const SHIPPED = 'shipped';
@@ -72,19 +73,14 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId)
try {
$orderId = $item->getEntityId();
$order = Mage::getModel('sales/order')->load($orderId);
+ $incrementId = $order->getIncrementId();
//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++;
- }
- }
+ $batchArray = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray);
$orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, true);
if (!empty($orderJson)) {
$batchArray[$this->_counter]['method'] = "PATCH";
- $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $orderId;
+ $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $incrementId;
$batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId;
$batchArray[$this->_counter]['body'] = $orderJson;
} else {
@@ -132,13 +128,7 @@ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId)
$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++;
- }
- }
+ $batchArray = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray);
$orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId);
if (!empty($orderJson)) {
@@ -446,7 +436,7 @@ protected function returnZeroIfNull($value)
return $returnValue;
}
-
+
protected function _getMailChimpStatus($order)
{
$mailChimpFinancialStatus = null;
@@ -566,6 +556,7 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS
);
// be sure that the orders are not in mailchimp
$orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS NOT NULL AND m4m.mailchimp_sync_error = ''");
+ $orderCollection->getSelect()->limit(self::BATCH_LIMIT_ONLY_ORDERS);
foreach ($orderCollection as $order) {
//Delete order
$orderId = $order->getEntityId();
@@ -603,4 +594,21 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS
Mage::helper('mailchimp')->saveMailchimpConfig($config, $magentoStoreId, 'stores');
return $batchArray;
}
+
+ /**
+ * @param $mailchimpStoreId
+ * @param $magentoStoreId
+ * @param $order
+ * @param $batchArray
+ * @return mixed
+ */
+ public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray)
+ {
+ $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId);
+ $productDataArray = Mage::helper('mailchimp')->addEntriesToArray($batchArray, $productData, $this->_counter);
+ $batchArray = $productDataArray[0];
+ $this->_counter = $productDataArray[1];
+
+ return $batchArray;
+ }
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php
index dc6ef8d3e..f17b61ce4 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php
@@ -13,10 +13,13 @@ class Ebizmarts_MailChimp_Model_Api_Products
{
const BATCH_LIMIT = 100;
private $_parentImageUrl = null;
+ /** @var Mage_Catalog_Model_Product_Type_Configurable */
private $productTypeConfigurable;
+
private $mailchimpHelper;
private $visibilityOptions;
private $productTypeConfigurableResource;
+ public static $noChildrenIds = array(0 => array());
public function __construct()
{
@@ -28,7 +31,12 @@ public function __construct()
public function createBatchJson($mailchimpStoreId, $magentoStoreId)
{
- $collection = $this->makeProductsNotSentCollection($mailchimpStoreId, $magentoStoreId);
+ if (Mage::helper('catalog/category_flat')->isEnabled()) {
+ Mage::app()->getStore($magentoStoreId)
+ ->setConfig(Mage_Catalog_Helper_Category_Flat::XML_PATH_IS_ENABLED_FLAT_CATALOG_CATEGORY, 0)
+ ->setConfig(Mage_Catalog_Helper_Product_Flat::XML_PATH_USE_PRODUCT_FLAT, 0);
+ }
+ $collection = $this->makeProductsNotSentCollection($magentoStoreId);
$this->joinMailchimpSyncData($mailchimpStoreId, $collection);
$batchArray = array();
@@ -59,7 +67,6 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId)
$this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now(), "This product type is not supported on MailChimp.");
}
}
-
return $batchArray;
}
@@ -71,13 +78,12 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId
} else if ($this->isConfigurableProduct($product)) {
$variantProducts[] = $product;
- $childProducts = $this->productTypeConfigurable->getChildrenIds($product->getId());
+ $collection = $this->makeProductChildrenCollection($magentoStoreId);
- //@TODO: No manda los children que no tienen stock.
- $collection = $this->makeProductsNotSentCollection($mailchimpStoreId, $magentoStoreId);
+ $childProducts = $this->getConfigurableChildrenIds($product);
$collection->addAttributeToFilter("entity_id", array("in" => $childProducts));
- foreach($collection as $childProduct) {
+ foreach ($collection as $childProduct) {
$variantProducts[] = $childProduct;
}
@@ -94,7 +100,7 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId
$body = json_encode($bodyData);
} catch (Exception $e) {
//json encode failed
- $this->mailchimpHelper->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId);
+ $this->getMailChimpHelper()->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId);
return array();
}
@@ -121,7 +127,7 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor
//add or update variant
foreach ($parentIds as $parentId) {
$productSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($parentId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId);
- if ($productSyncData->getMailchimpSyncDelta() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId) && $productSyncData->getMailchimpSyncError() == '') {
+ if ($productSyncData->getMailchimpSyncDelta() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId) && $productSyncData->getMailchimpSyncError() == '') {
$variendata = array();
$variendata["id"] = $data["id"];
$variendata["title"] = $data["title"];
@@ -170,7 +176,7 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar
$data["url"] = $product->getProductUrl();
//image
- $imageUrl = $this->mailchimpHelper->getMailChimpProductImageUrl($this->_parentImageUrl, $this->mailchimpHelper->getImageUrlById($product->getId()));
+ $imageUrl = $this->getMailChimpHelper()->getMailChimpProductImageUrl($this->_parentImageUrl, $this->getMailChimpHelper()->getImageUrlById($product->getId()));
if ($imageUrl) {
$data["image_url"] = $imageUrl;
}
@@ -191,10 +197,10 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar
if ($categoryId) {
$category = Mage::getResourceModel('catalog/category')->checkId($categoryId);
$data["type"] = $category->getName();
+ $data["vendor"] = $data["type"];
}
//missing data
- $data["vendor"] = "";
$data["handle"] = "";
//variants
@@ -209,7 +215,6 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar
$this->_parentImageUrl = null;
}
-
return $data;
}
@@ -239,8 +244,8 @@ public function update($productId, $storeId)
*/
protected function _updateIfEnabled($productId, $storeId)
{
- if ($this->mailchimpHelper->isEcomSyncDataEnabled($storeId)) {
- $mailchimpStoreId = $this->mailchimpHelper->getMCStoreId($storeId);
+ if ($this->getMailChimpHelper()->isEcomSyncDataEnabled($storeId)) {
+ $mailchimpStoreId = $this->getMailChimpHelper()->getMCStoreId($storeId);
$this->_updateSyncData($productId, $mailchimpStoreId, null, null, 1, null, true);
}
}
@@ -260,7 +265,7 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId)
$items = $order->getAllVisibleItems();
foreach ($items as $item) {
$product = Mage::getModel('catalog/product')->load($item->getProductId());
- $productSyncData = $this->mailchimpHelper->getEcommerceSyncDataItem($product->getId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId);
+ $productSyncData = $this->getMailChimpHelper()->getEcommerceSyncDataItem($product->getId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId);
if ($product->getId() != $item->getProductId() || $this->isBundleProduct($product) || $this->isGroupedProduct($product)) {
if ($product->getId()) {
$this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now(), "This product type is not supported on MailChimp.");
@@ -269,15 +274,14 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId)
continue;
}
- if ($productSyncData->getMailchimpSyncModified() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId)) {
+ if ($productSyncData->getMailchimpSyncModified() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId)) {
$data[] = $this->_buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId);
$this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now());
- } elseif (!$productSyncData->getMailchimpSyncDelta() || $productSyncData->getMailchimpSyncDelta() < Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId)) {
+ } elseif (!$productSyncData->getMailchimpSyncDelta() || $productSyncData->getMailchimpSyncDelta() < Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId)) {
$data[] = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId);
$this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now());
}
}
-
return $data;
}
@@ -286,15 +290,15 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId)
*
* @param $productId
* @param $mailchimpStoreId
- * @param null $syncDelta
- * @param null $syncError
- * @param int $syncModified
- * @param null $syncDeleted
- * @param bool $saveOnlyIfexists
+ * @param null $syncDelta
+ * @param null $syncError
+ * @param int $syncModified
+ * @param null $syncDeleted
+ * @param bool $saveOnlyIfexists
*/
protected function _updateSyncData($productId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $syncDeleted = null, $saveOnlyIfexists = false)
{
- $this->mailchimpHelper->saveEcommerceSyncData(
+ $this->getMailChimpHelper()->saveEcommerceSyncData(
$productId,
Ebizmarts_MailChimp_Model_Config::IS_PRODUCT,
$mailchimpStoreId,
@@ -342,21 +346,18 @@ public function makeBatchId($magentoStoreId)
}
/**
- * @param $mailchimpStoreId
* @param $magentoStoreId
* @return Mage_Catalog_Model_Resource_Product_Collection
*/
- public function makeProductsNotSentCollection($mailchimpStoreId, $magentoStoreId)
+ public function makeProductsNotSentCollection($magentoStoreId)
{
/**
- * @var Mage_Catalog_Model_Resource_Product_Collection $collection
-*/
+ * @var Mage_Catalog_Model_Resource_Product_Collection $collection
+ */
$collection = $this->getProductResourceCollection();
$collection->addStoreFilter($magentoStoreId);
- $collection->addPriceData(null, $this->getWebsiteIdForStoreId($magentoStoreId));
-
$this->joinQtyAndBackorders($collection);
$this->joinCategoryId($collection);
@@ -386,7 +387,7 @@ public function getSyncdataTableName()
*/
protected function shouldSendProductUpdate($magentoStoreId, $product)
{
- return $product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($magentoStoreId) && $product->getMailchimpSyncError() == '';
+ return $product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId) && $product->getMailchimpSyncError() == '';
}
/**
@@ -448,8 +449,8 @@ protected function isConfigurableProduct($product)
*/
protected function joinProductAttributes($collection)
{
- $attributeCodes = array("name", "visibility", "description");
- $config = Mage::getSingleton("eav/config");
+ $attributeCodes = array("name", "visibility", "description", "price");
+ $config = Mage::getSingleton("eav/config");
foreach ($attributeCodes as $_code) {
$attributeName = $config->getAttribute("catalog_product", $_code);
@@ -488,16 +489,16 @@ protected function joinQtyAndBackorders($collection)
*/
protected function joinMailchimpSyncData($mailchimpStoreId, $collection)
{
- $joinCondition = "m4m.related_id = e.entity_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'";
+ $joinCondition = "m4m.related_id = e.entity_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'";
$mailchimpTableName = $this->getSyncdataTableName();
$collection->getSelect()->joinLeft(
array("m4m" => $mailchimpTableName),
sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId), array(
- "m4m.related_id",
- "m4m.type",
- "m4m.mailchimp_store_id",
- "m4m.mailchimp_sync_delta",
- "m4m.mailchimp_sync_modified"
+ "m4m.related_id",
+ "m4m.type",
+ "m4m.mailchimp_store_id",
+ "m4m.mailchimp_sync_delta",
+ "m4m.mailchimp_sync_modified"
)
);
$collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1");
@@ -516,18 +517,17 @@ protected function joinCategoryId($collection)
/**
* @param $product
- * @param $data
* @return mixed
*/
protected function getProductVariantData($product)
{
$data = array();
$data["sku"] = $product->getSku();
- $data["price"] = (int)$product->getPrice();
+ $data["price"] = (float)$product->getPrice();
//stock
$data["inventory_quantity"] = (int)$product->getQty();
- $data["backorders"] = (string)$product->getBackorders();
+ $data["backorders"] = (string)$product->getBackorders();
$data["visibility"] = $this->visibilityOptions[$product->getVisibility()];
@@ -543,12 +543,44 @@ protected function getProductResourceCollection()
return Mage::getResourceModel('catalog/product_collection');
}
+ /**
+ * @param $product
+ * @return array
+ */
+ protected function getConfigurableChildrenIds($product)
+ {
+ $childrenIds = $this->getChildrenIdsForConfigurable($product);
+
+ if ($childrenIds === self::$noChildrenIds) {
+ return array();
+ }
+
+ return $childrenIds;
+ }
+
/**
* @param $magentoStoreId
- * @return int|null|string
+ * @return Mage_Catalog_Model_Resource_Product_Collection
+ */
+ protected function makeProductChildrenCollection($magentoStoreId)
+ {
+ return $this->makeProductsNotSentCollection($magentoStoreId);
+ }
+
+ /**
+ * @param $product
+ * @return array
+ */
+ protected function getChildrenIdsForConfigurable($product)
+ {
+ return $this->productTypeConfigurable->getChildrenIds($product->getId());
+ }
+
+ /**
+ * @return Ebizmarts_MailChimp_Helper_Data
*/
- protected function getWebsiteIdForStoreId($magentoStoreId)
+ protected function getMailChimpHelper()
{
- return Mage::app()->getStore($magentoStoreId)->getWebsiteId();
+ return $this->mailchimpHelper;
}
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php
index ace0bc39e..6b07e4154 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php
@@ -16,7 +16,7 @@ class Ebizmarts_MailChimp_Model_Api_Stores
* Create MailChimp store.
*
* @param $mailChimpStoreId
- * @param null $listId
+ * @param null $listId
* @param $scope
* @param $scopeId
* @throws Exception
@@ -109,7 +109,8 @@ public function getMCJsUrl($scopeId, $scope)
if (isset($response['connected_site']['site_script']['url'])) {
$url = $response['connected_site']['site_script']['url'];
$configValues = array(array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $url));
- Mage::helper('mailchimp')->saveMailchimpConfig($configValues, $scopeId, $scope);
+ $realScope = Mage::helper('mailchimp')->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $scopeId, $scope);
+ Mage::helper('mailchimp')->saveMailchimpConfig($configValues, $realScope['scope_id'], $realScope['scope']);
return $url;
}
} catch (MailChimp_Error $e) {
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php
index d3941f803..96c70a249 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php
@@ -9,65 +9,83 @@
* @copyright Ebizmarts (http://ebizmarts.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
-
class Ebizmarts_MailChimp_Model_Api_Subscribers
{
const BATCH_LIMIT = 100;
+ private $mcHelper;
+
+ public function __construct()
+ {
+ $this->mcHelper = Mage::helper('mailchimp');
+ }
+
public function createBatchJson($listId, $storeId, $limit)
{
- //get subscribers
- $collection = Mage::getResourceModel('newsletter/subscriber_collection')
- ->addFieldToFilter('subscriber_status', array('eq' => 1))
- ->addFieldToFilter('store_id', array('eq' => $storeId))
- ->addFieldToFilter(
- array(
- 'mailchimp_sync_delta',
- 'mailchimp_sync_delta',
- 'mailchimp_sync_delta',
- 'mailchimp_sync_modified'
- ),
- array(
- array('null' => true),
- array('eq' => ''),
- array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag($storeId)),
- array('eq' => 1)
- )
- );
- $collection->getSelect()->limit($limit);
+ $helper = $this->mcHelper;
+ $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $storeId);;
+ $moduleIsActive = $helper->isMailChimpEnabled($storeId);
$subscriberArray = array();
- $date = Mage::helper('mailchimp')->getDateMicrotime();
- $batchId = 'storeid-' . $storeId . '_' . Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_' . $date;
- $counter = 0;
- foreach ($collection as $subscriber) {
- $data = $this->_buildSubscriberData($subscriber);
- $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail()));
- $subscriberJson = "";
-
- //enconde to JSON
- try {
- $subscriberJson = json_encode($data);
- } catch (Exception $e) {
- //json encode failed
- $errorMessage = "Subscriber ".$subscriber->getSubscriberId()." json encode failed";
- Mage::helper('mailchimp')->logError($errorMessage, $storeId);
+ if ($moduleIsActive) {
+ $realScope = $helper->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $storeId);
+ if ($helper->getGeneralList($realScope['scope_id'], $realScope['scope']) && !$thisScopeHasSubMinSyncDateFlag) {
+ $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, Varien_Date::now()));
+ $helper->saveMailchimpConfig($configValues, $realScope['scope_id'], $realScope['scope']);
}
- if (!empty($subscriberJson)) {
- $subscriberArray[$counter]['method'] = "PUT";
- $subscriberArray[$counter]['path'] = "/lists/" . $listId . "/members/" . $md5HashEmail;
- $subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId();
- $subscriberArray[$counter]['body'] = $subscriberJson;
-
- //update subscribers delta
- $subscriber->setData("mailchimp_sync_delta", Varien_Date::now());
- $subscriber->setData("mailchimp_sync_error", "");
- $subscriber->setData("mailchimp_sync_modified", 0);
- $subscriber->save();
- }
+ //get subscribers
+ $collection = Mage::getResourceModel('newsletter/subscriber_collection')
+ ->addFieldToFilter('subscriber_status', array('eq' => 1))
+ ->addFieldToFilter('store_id', array('eq' => $storeId))
+ ->addFieldToFilter(
+ array(
+ 'mailchimp_sync_delta',
+ 'mailchimp_sync_delta',
+ 'mailchimp_sync_delta',
+ 'mailchimp_sync_modified'
+ ),
+ array(
+ array('null' => true),
+ array('eq' => ''),
+ array('lt' => $helper->getSubMinSyncDateFlag($storeId)),
+ array('eq' => 1)
+ )
+ );
+ $collection->getSelect()->limit($limit);
+ $date = $helper->getDateMicrotime();
+ $batchId = 'storeid-' . $storeId . '_' . Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_' . $date;
+
+ $counter = 0;
+ foreach ($collection as $subscriber) {
+ $data = $this->_buildSubscriberData($subscriber);
+ $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail()));
+ $subscriberJson = "";
+
+ //enconde to JSON
+ try {
+ $subscriberJson = json_encode($data);
+ } catch (Exception $e) {
+ //json encode failed
+ $errorMessage = "Subscriber " . $subscriber->getSubscriberId() . " json encode failed";
+ $helper->logError($errorMessage, $storeId);
+ }
- $counter++;
+ if (!empty($subscriberJson)) {
+ $subscriberArray[$counter]['method'] = "PUT";
+ $subscriberArray[$counter]['path'] = "/lists/" . $listId . "/members/" . $md5HashEmail;
+ $subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId();
+ $subscriberArray[$counter]['body'] = $subscriberJson;
+
+ //update subscribers delta
+ $subscriber->setData("mailchimp_sync_delta", Varien_Date::now());
+ $subscriber->setData("mailchimp_sync_error", "");
+ $subscriber->setData("mailchimp_sync_modified", 0);
+ $subscriber->save();
+ }
+
+ $counter++;
+ }
}
return $subscriberArray;
@@ -90,8 +108,9 @@ protected function _buildSubscriberData($subscriber)
public function getMergeVars($subscriber)
{
+ $helper = $this->mcHelper;
$storeId = $subscriber->getStoreId();
- $mapFields = Mage::helper('mailchimp')->getMapFields($storeId);
+ $mapFields = $helper->getMapFields($storeId);
$maps = unserialize($mapFields);
$websiteId = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
$attrSetId = Mage::getResourceModel('eav/entity_attribute_collection')
@@ -113,167 +132,167 @@ public function getMergeVars($subscriber)
if ($attribute['attribute_id'] == $customAtt) {
$attributeCode = $attribute['attribute_code'];
switch ($attributeCode) {
- case 'email':
- break;
- case 'default_billing':
- case 'default_shipping':
- $address = $customer->getPrimaryAddress($attributeCode);
-
- if ($address) {
- $street = $address->getStreet();
- $eventValue = $mergeVars[$key] = array(
- "addr1" => $street[0] ? $street[0] : "",
- "addr2" => count($street) > 1 ? $street[1] : "",
- "city" => $address->getCity() ? $address->getCity() : "",
- "state" => $address->getRegion() ? $address->getRegion() : "",
- "zip" => $address->getPostcode() ? $address->getPostcode() : "",
- "country" => $address->getCountry() ? Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName() : ""
- );
- }
- break;
- case 'gender':
- if ($customer->getData($attributeCode)) {
- $genderValue = $customer->getData($attributeCode);
- if ($genderValue == 1) {
- $eventValue = $mergeVars[$key] = 'Male';
- } elseif ($genderValue == 2) {
- $eventValue = $mergeVars[$key] = 'Female';
+ case 'email':
+ break;
+ case 'default_billing':
+ case 'default_shipping':
+ $address = $customer->getPrimaryAddress($attributeCode);
+
+ if ($address) {
+ $street = $address->getStreet();
+ $eventValue = $mergeVars[$key] = array(
+ "addr1" => $street[0] ? $street[0] : "",
+ "addr2" => count($street) > 1 ? $street[1] : "",
+ "city" => $address->getCity() ? $address->getCity() : "",
+ "state" => $address->getRegion() ? $address->getRegion() : "",
+ "zip" => $address->getPostcode() ? $address->getPostcode() : "",
+ "country" => $address->getCountry() ? Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName() : ""
+ );
}
- }
- break;
- case 'group_id':
- if ($customer->getData($attributeCode)) {
- $group_id = (int)$customer->getData($attributeCode);
- $customerGroup = Mage::helper('customer')->getGroups()->toOptionHash();
- $eventValue = $mergeVars[$key] = $customerGroup[$group_id];
- } else {
- $eventValue = $mergeVars[$key] = Mage::helper('mailchimp')->__('NOT LOGGED IN');
- }
- break;
- case 'firstname':
- $firstName = $customer->getFirstname();
+ break;
+ case 'gender':
+ if ($customer->getData($attributeCode)) {
+ $genderValue = $customer->getData($attributeCode);
+ if ($genderValue == 1) {
+ $eventValue = $mergeVars[$key] = 'Male';
+ } elseif ($genderValue == 2) {
+ $eventValue = $mergeVars[$key] = 'Female';
+ }
+ }
+ break;
+ case 'group_id':
+ if ($customer->getData($attributeCode)) {
+ $group_id = (int)$customer->getData($attributeCode);
+ $customerGroup = Mage::helper('customer')->getGroups()->toOptionHash();
+ $eventValue = $mergeVars[$key] = $customerGroup[$group_id];
+ } else {
+ $eventValue = $mergeVars[$key] = 'NOT LOGGED IN';
+ }
+ break;
+ case 'firstname':
+ $firstName = $customer->getFirstname();
- if (!$firstName) {
- $firstName = $subscriber->getSubscriberFirstname();
- }
+ if (!$firstName) {
+ $firstName = $subscriber->getSubscriberFirstname();
+ }
- if ($firstName) {
- $eventValue = $mergeVars[$key] = $firstName;
- }
- break;
- case 'lastname':
- $lastName = $customer->getLastname();
+ if ($firstName) {
+ $eventValue = $mergeVars[$key] = $firstName;
+ }
+ break;
+ case 'lastname':
+ $lastName = $customer->getLastname();
- if (!$lastName) {
- $lastName = $subscriber->getSubscriberLastname();
- }
+ if (!$lastName) {
+ $lastName = $subscriber->getSubscriberLastname();
+ }
- if ($lastName) {
- $eventValue = $mergeVars[$key] = $lastName;
- }
- break;
- case 'store_id':
- $eventValue = $mergeVars[$key] = $storeId;
- break;
- case 'website_id':
- $websiteId = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
- $eventValue = $mergeVars[$key] = $websiteId;
- break;
- case 'created_in':
- if ($customer->getData($attributeCode)) {
- $eventValue = $mergeVars[$key] = $customer->getData($attributeCode);
- } else {
- $storeCode = Mage::getModel('core/store')->load($storeId)->getCode();
- $eventValue = $mergeVars[$key] = $storeCode;
- }
- break;
- case 'dob':
- if ($customer->getData($attributeCode)) {
- $eventValue = $mergeVars[$key] = date("m/d", strtotime($customer->getData($attributeCode)));
- }
- break;
- default:
- if ($customer->getData($attributeCode)) {
- $eventValue = $mergeVars[$key] = $customer->getData($attributeCode);
- }
- break;
+ if ($lastName) {
+ $eventValue = $mergeVars[$key] = $lastName;
+ }
+ break;
+ case 'store_id':
+ $eventValue = $mergeVars[$key] = $storeId;
+ break;
+ case 'website_id':
+ $websiteId = Mage::getModel('core/store')->load($storeId)->getWebsiteId();
+ $eventValue = $mergeVars[$key] = $websiteId;
+ break;
+ case 'created_in':
+ if ($customer->getData($attributeCode)) {
+ $eventValue = $mergeVars[$key] = $customer->getData($attributeCode);
+ } else {
+ $storeCode = Mage::getModel('core/store')->load($storeId)->getCode();
+ $eventValue = $mergeVars[$key] = $storeCode;
+ }
+ break;
+ case 'dob':
+ if ($customer->getData($attributeCode)) {
+ $eventValue = $mergeVars[$key] = date("m/d", strtotime($customer->getData($attributeCode)));
+ }
+ break;
+ default:
+ if ($customer->getData($attributeCode)) {
+ $eventValue = $mergeVars[$key] = $customer->getData($attributeCode);
+ }
+ break;
}
Mage::dispatchEvent(
'mailchimp_merge_field_send_before', array(
- 'customer_id' => $customer->getId(),
- 'subscriber_email' => $subscriberEmail,
- 'merge_field_tag' => $attributeCode,
- 'merge_field_value' => &$eventValue
+ 'customer_id' => $customer->getId(),
+ 'subscriber_email' => $subscriberEmail,
+ 'merge_field_tag' => $attributeCode,
+ 'merge_field_value' => &$eventValue
)
);
}
}
} else {
switch ($customAtt) {
- case 'billing_company':
- case 'shipping_company':
- $addr = explode('_', $customAtt);
- $address = $customer->getPrimaryAddress('default_' . $addr[0]);
-
- if ($address) {
- $company = $address->getCompany();
- if ($company) {
- $eventValue = $mergeVars[$key] = $company;
+ case 'billing_company':
+ case 'shipping_company':
+ $addr = explode('_', $customAtt);
+ $address = $customer->getPrimaryAddress('default_' . $addr[0]);
+
+ if ($address) {
+ $company = $address->getCompany();
+ if ($company) {
+ $eventValue = $mergeVars[$key] = $company;
+ }
}
- }
- break;
- case 'billing_telephone':
- case 'shipping_telephone':
- $addr = explode('_', $customAtt);
- $address = $customer->getPrimaryAddress('default_' . $addr[0]);
-
- if ($address) {
- $telephone = $address->getTelephone();
- if ($telephone) {
- $eventValue = $mergeVars[$key] = $telephone;
+ break;
+ case 'billing_telephone':
+ case 'shipping_telephone':
+ $addr = explode('_', $customAtt);
+ $address = $customer->getPrimaryAddress('default_' . $addr[0]);
+
+ if ($address) {
+ $telephone = $address->getTelephone();
+ if ($telephone) {
+ $eventValue = $mergeVars[$key] = $telephone;
+ }
}
- }
- break;
- case 'billing_country':
- case 'shipping_country':
- $addr = explode('_', $customAtt);
- $address = $customer->getPrimaryAddress('default_' . $addr[0]);
-
- if ($address) {
- $countryCode = $address->getCountry();
- if ($countryCode) {
- $countryName = Mage::getModel('directory/country')->loadByCode($countryCode)->getName();
- $eventValue = $mergeVars[$key] = $countryName;
+ break;
+ case 'billing_country':
+ case 'shipping_country':
+ $addr = explode('_', $customAtt);
+ $address = $customer->getPrimaryAddress('default_' . $addr[0]);
+
+ if ($address) {
+ $countryCode = $address->getCountry();
+ if ($countryCode) {
+ $countryName = Mage::getModel('directory/country')->loadByCode($countryCode)->getName();
+ $eventValue = $mergeVars[$key] = $countryName;
+ }
}
- }
- break;
- case 'billing_zipcode':
- case 'shipping_zipcode':
- $addr = explode('_', $customAtt);
- $address = $customer->getPrimaryAddress('default_' . $addr[0]);
-
- if ($address) {
- $zipCode = $address->getPostcode();
- if ($zipCode) {
- $eventValue = $mergeVars[$key] = $zipCode;
+ break;
+ case 'billing_zipcode':
+ case 'shipping_zipcode':
+ $addr = explode('_', $customAtt);
+ $address = $customer->getPrimaryAddress('default_' . $addr[0]);
+
+ if ($address) {
+ $zipCode = $address->getPostcode();
+ if ($zipCode) {
+ $eventValue = $mergeVars[$key] = $zipCode;
+ }
}
- }
- break;
- case 'dop':
- $dop = Mage::helper('mailchimp')->getLastDateOfPurchase($subscriberEmail);
- if ($dop) {
- $eventValue = $mergeVars[$key] = $dop;
- }
- break;
+ break;
+ case 'dop':
+ $dop = $helper->getLastDateOfPurchase($subscriberEmail);
+ if ($dop) {
+ $eventValue = $mergeVars[$key] = $dop;
+ }
+ break;
}
Mage::dispatchEvent(
'mailchimp_merge_field_send_before', array(
- 'customer_id' => $customer->getId(),
- 'subscriber_email' => $subscriberEmail,
- 'merge_field_tag' => $customAtt,
- 'merge_field_value' => &$eventValue
+ 'customer_id' => $customer->getId(),
+ 'subscriber_email' => $subscriberEmail,
+ 'merge_field_tag' => $customAtt,
+ 'merge_field_value' => &$eventValue
)
);
}
@@ -289,15 +308,16 @@ public function getMergeVars($subscriber)
/**
* @param $subscriber
- * @param bool $updateStatus If set to true, it will force the status update even for those already subscribed.
+ * @param bool $updateStatus If set to true, it will force the status update even for those already subscribed.
*/
public function updateSubscriber($subscriber, $updateStatus = false)
{
+ $helper = $this->mcHelper;
$storeId = $subscriber->getStoreId();
- $listId = Mage::helper('mailchimp')->getGeneralList($storeId);
+ $listId = $helper->getGeneralList($storeId);
$newStatus = $this->translateMagentoStatusToMailchimpStatus($subscriber->getStatus(), $storeId);
$forceStatus = ($updateStatus) ? $newStatus : null;
- $api = Mage::helper('mailchimp')->getApi($storeId);
+ $api = $helper->getApi($storeId);
$mergeVars = $this->getMergeVars($subscriber);
$md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail()));
try {
@@ -308,33 +328,49 @@ public function updateSubscriber($subscriber, $updateStatus = false)
$subscriber->setData("mailchimp_sync_delta", Varien_Date::now());
$subscriber->setData("mailchimp_sync_error", "");
$subscriber->setData("mailchimp_sync_modified", 0);
- } catch(MailChimp_Error $e) {
+ } catch (MailChimp_Error $e) {
if ($newStatus === 'subscribed' && $subscriber->getIsStatusChanged()) {
if (strstr($e->getMailchimpDetails(), 'is in a compliance state')) {
try {
$api->lists->members->update($listId, $md5HashEmail, null, 'pending', $mergeVars);
$subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNCONFIRMED);
- $message = Mage::helper('mailchimp')->__('To begin receiving the newsletter, you must first confirm your subscription');
+ $message = $helper->__('To begin receiving the newsletter, you must first confirm your subscription');
Mage::getSingleton('core/session')->addWarning($message);
} catch (MailChimp_Error $e) {
- Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId);
+ $helper->logError($e->getFriendlyMessage(), $storeId);
Mage::getSingleton('core/session')->addError($e->getFriendlyMessage());
$subscriber->unsubscribe();
+ $this->_processUpdateSubscriberError($e, $storeId);
} catch (Exception $e) {
- Mage::helper('mailchimp')->logError($e->getMessage(), $storeId);
+ $helper->logError($e->getMessage(), $storeId);
}
} else {
- Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId);
+ $helper->logError($e->getFriendlyMessage(), $storeId);
Mage::getSingleton('core/session')->addError($e->getFriendlyMessage());
$subscriber->unsubscribe();
+ $this->_processUpdateSubscriberError($e, $storeId);
}
} else {
- Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $storeId);
+ $helper->logError($e->getFriendlyMessage(), $storeId);
Mage::getSingleton('core/session')->addError($e->getFriendlyMessage());
}
} catch (Exception $e) {
- Mage::helper('mailchimp')->logError($e->getMessage(), $storeId);
+ $helper->logError($e->getMessage(), $storeId);
+ }
+ }
+
+ /**
+ * @param $e
+ * @param $storeId
+ */
+ protected function _processUpdateSubscriberError($e, $storeId)
+ {
+ $message = $e->getFriendlyMessage();
+ Mage::helper('mailchimp')->logError($message, $storeId);
+ if (Mage::getDesign()->getArea() === 'frontend') {
+ $message = Mage::helper('mailchimp')->__('Please, try again later');
}
+ Mage::getSingleton('core/session')->addError($message);
}
/**
@@ -393,17 +429,18 @@ protected function statusEqualsUnconfirmed($status)
public function removeSubscriber($subscriber)
{
+ $helper = $this->mcHelper;
$storeId = $subscriber->getStoreId();
- $listId = Mage::helper('mailchimp')->getGeneralList($storeId);
- $api = Mage::helper('mailchimp')->getApi($storeId);
+ $listId = $helper->getGeneralList($storeId);
+ $api = $helper->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(), $storeId);
+ } catch (MailChimp_Error $e) {
+ $helper->logError($e->getFriendlyMessage(), $storeId);
Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage());
} catch (Exception $e) {
- Mage::helper('mailchimp')->logError($e->getMessage(), $storeId);
+ $helper->logError($e->getMessage(), $storeId);
}
}
@@ -412,24 +449,26 @@ public function removeSubscriber($subscriber)
*/
public function deleteSubscriber($subscriber)
{
+ $helper = $this->mcHelper;
$storeId = $subscriber->getStoreId();
- $listId = Mage::helper('mailchimp')->getGeneralList($storeId);
- $api = Mage::helper('mailchimp')->getApi($storeId);
+ $listId = $helper->getGeneralList($storeId);
+ $api = $helper->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(), $storeId);
+ } catch (MailChimp_Error $e) {
+ $helper->logError($e->getFriendlyMessage(), $storeId);
Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage());
} catch (Exception $e) {
- Mage::helper('mailchimp')->logError($e->getMessage(), $storeId);
+ $helper->logError($e->getMessage(), $storeId);
}
}
public function update($emailAddress, $storeId)
{
+ $helper = $this->mcHelper;
$subscriber = Mage::getSingleton('newsletter/subscriber')->loadByEmail($emailAddress);
- if ($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED && $subscriber->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag($storeId)) {
+ if ($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED && $subscriber->getMailchimpSyncDelta() != $helper->getSubMinSyncDateFlag($storeId)) {
$subscriber->setMailchimpSyncModified(1)
->save();
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php
index 6b4295855..350d40292 100755
--- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php
@@ -18,13 +18,15 @@ class Ebizmarts_MailChimp_Model_Config
const GENERAL_LIST = 'mailchimp/general/list';
const GENERAL_OLD_LIST = 'mailchimp/general/old_list';
const GENERAL_LIST_CHANGED_SCOPES = 'mailchimp/general/list_changed_scopes';
+ const GENERAL_CHECKOUT_SUBSCRIBE = 'mailchimp/general/checkout_subscribe';
const GENERAL_MCSTOREID = 'mailchimp/general/storeid';
const GENERAL_MCISSYNCING = 'mailchimp/general/is_syicing';
- const GENERAL_MCMINSYNCDATEFLAG = 'mailchimp/general/mcminsyncdateflag';
+ const GENERAL_ECOMMMINSYNCDATEFLAG = 'mailchimp/general/mcminsyncdateflag';
+ const GENERAL_SUBMINSYNCDATEFLAG = 'mailchimp/general/subminsyncdateflag';
const GENERAL_MCSTORE_RESETED = 'mailchimp/general/mcstore_reset';
- const GENERAL_SUB_MCMINSYNCDATEFLAG = 'mailchimp/general/sub_mcminsyncdateflag';
const GENERAL_TWO_WAY_SYNC = 'mailchimp/general/webhook_active';
const GENERAL_UNSUBSCRIBE = 'mailchimp/general/webhook_delete';
+ const GENERAL_WEBHOOK_ID = 'mailchimp/general/webhook_id';
const GENERAL_LOG = 'mailchimp/general/enable_log';
const GENERAL_MAP_FIELDS = 'mailchimp/general/map_fields';
const GENERAL_CUSTOM_MAP_FIELDS = 'mailchimp/general/customer_map_fields';
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php
index 46ed58e4c..e48759063 100755
--- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php
@@ -22,14 +22,8 @@ public function saveConfig(Varien_Event_Observer $observer)
{
$post = Mage::app()->getRequest()->getPost();
$scopeArray = explode('-', $this->makeHelper()->getScopeString());
- $generalEnabled = $this->makeHelper()->isMailChimpEnabled($scopeArray[1], $scopeArray[0]);
- $listId = $this->makeHelper()->getGeneralList($scopeArray[1], $scopeArray[0]);
- if ($generalEnabled && $listId) {
- $this->_createWebhook($listId, $scopeArray[1], $scopeArray[0]);
- }
-
- if (isset($post['groups']['general']['fields']['list']['inherit']) && $this->makeHelper()->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) {
+ if (isset($post['groups']['general']['fields']['list']['inherit']) && $this->makeHelper()->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) {
$this->makeHelper()->removeEcommerceSyncData($scopeArray[1], $scopeArray[0]);
$this->makeHelper()->resetCampaign($scopeArray[1], $scopeArray[0]);
$this->makeHelper()->clearErrorGrid($scopeArray[1], $scopeArray[0], true);
@@ -39,89 +33,6 @@ public function saveConfig(Varien_Event_Observer $observer)
return $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, $scopeId, $scope)
- {
- $store = Mage::app()->getDefaultStoreView();
- $webhooksKey = $this->makeHelper()->getWebhooksKey();
- //Generating Webhooks URL
- $url = Ebizmarts_MailChimp_Model_ProcessWebhook::WEBHOOKS_PATH;
- $hookUrl = $store->getUrl(
- $url, array(
- 'wkey' => $webhooksKey,
- '_nosid' => true,
- '_secure' => true,
- )
- );
-
- if (false != strstr($hookUrl, '?', true)) {
- $hookUrl = strstr($hookUrl, '?', true);
- }
-
- $api = $this->makeHelper()->getApi($scopeId, $scope);
- if ($this->makeHelper()->getTwoWaySyncEnabled($scopeId, $scope)) {
- $events = array(
- 'subscribe' => true,
- 'unsubscribe' => true,
- 'profile' => true,
- 'cleaned' => true,
- 'upemail' => true,
- 'campaign' => false
- );
- $sources = array(
- 'user' => true,
- 'admin' => true,
- 'api' => true
- );
- } else {
- $events = array(
- 'subscribe' => true,
- 'unsubscribe' => false,
- 'profile' => false,
- 'cleaned' => false,
- 'upemail' => false,
- 'campaign' => false
- );
- $sources = array(
- 'user' => false,
- 'admin' => false,
- 'api' => true
- );
- }
-
- try {
- $response = $api->lists->webhooks->getAll($listId);
- $createWebhook = true;
- if (isset($response['total_items']) && $response['total_items'] > 0) {
- foreach ($response['webhooks'] as $webhook) {
- if ($webhook['url'] == $hookUrl) {
- $createWebhook = false;
- }
- }
- }
-
- if ($createWebhook) {
- $api->lists->webhooks->add($listId, $hookUrl, $events, $sources);
- }
- } catch (MailChimp_Error $e) {
- $this->makeHelper()->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) {
- $errorMessage = 'Your store could not be accessed by MailChimp\'s Api. Please confirm the URL: '. $hookUrl .' is accessible externally to allow the webhook creation.';
- Mage::getSingleton('adminhtml/session')->addError($errorMessage);
- }
- } catch (Exception $e) {
- $this->makeHelper()->logError($e->getMessage(), $scopeId, $scope);
- }
- }
-
/**
* Handle subscription change (subscribe/unsubscribe)
*
@@ -405,6 +316,16 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer)
*/
public function newOrder(Varien_Event_Observer $observer)
{
+ $post = Mage::app()->getRequest()->getPost('mailchimp_subscribe');
+ $helper = $this->makeHelper();
+ if (isset($post)) {
+ $order = $observer->getEvent()->getOrder();
+ $email = $order->getCustomerEmail();
+ $subscriber = $helper->loadListSubscriber($post, $email);
+ if ($subscriber) {
+ Mage::getModel('mailchimp/processWebhook')->subscribeMember($subscriber);
+ }
+ }
if(($this->_getLandingCookie())) {
Mage::getModel('core/cookie')->delete('mailchimp_landing_page');
}
@@ -552,7 +473,7 @@ public function productWebsiteUpdate(Varien_Event_Observer $observer)
// $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 ($productSyncData->getMailchimpSyncDelta() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($storeId)) {
// if ($action == 'remove' && !$productSyncData->getMailchimpSyncDeleted()) {
// $productSyncData->setData("mailchimp_sync_modified", 0)
// ->setData("mailchimp_sync_deleted", 1)
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php
index a2ea609e8..d77e5f267 100755
--- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php
@@ -11,6 +11,7 @@
*/
class Ebizmarts_MailChimp_Model_ProcessWebhook
{
+ const BATCH_LIMIT = 50;
/**
* Webhooks request url path
*
@@ -36,6 +37,8 @@ public function saveWebhookRequest(array $data)
public function processWebhookData()
{
$collection = Mage::getResourceModel('mailchimp/webhookrequest_collection');
+ $collection->addFieldToFilter('processed',array('eq'=>0));
+ $collection->getSelect()->limit(self::BATCH_LIMIT);
foreach ($collection as $webhookRequest) {
$data = unserialize($webhookRequest->getDataRequest());
@@ -75,12 +78,14 @@ protected function _updateEmail(array $data)
$oldSubscriber = Mage::helper('mailchimp')->loadListSubscriber($listId, $old);
$newSubscriber = Mage::helper('mailchimp')->loadListSubscriber($listId, $new);
- if (!$newSubscriber->getId()) {
- if ($oldSubscriber->getId()) {
- $oldSubscriber->setSubscriberEmail($new)
- ->save();
- } else {
- $this->subscribeMember($newSubscriber);
+ if ($oldSubscriber) {
+ if (!$newSubscriber->getId()) {
+ if ($oldSubscriber->getId()) {
+ $oldSubscriber->setSubscriberEmail($new)
+ ->save();
+ } else {
+ $this->subscribeMember($newSubscriber);
+ }
}
}
}
@@ -96,7 +101,7 @@ protected function _clean(array $data)
//Delete subscriber from Magento
$s = Mage::helper('mailchimp')->loadListSubscriber($data['list_id'], $data['email']);
- if ($s->getId()) {
+ if ($s && $s->getId()) {
try {
$s->delete();
} catch (Exception $e) {
@@ -117,28 +122,30 @@ protected function _subscribe(array $data)
$listId = $data['list_id'];
$email = $data['email'];
$subscriber = Mage::helper('mailchimp')->loadListSubscriber($listId, $email);
- if ($subscriber->getId()) {
- if ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED) {
- $this->subscribeMember($subscriber);
- }
- } else {
- if (isset($data['merges']['FNAME'])) {
- $subscriberFname = filter_var($data['merges']['FNAME'], FILTER_SANITIZE_STRING);
- $subscriber->setSubscriberFirstname($subscriberFname);
- }
+ if ($subscriber) {
+ if ($subscriber->getId()) {
+ if ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED) {
+ $this->subscribeMember($subscriber);
+ }
+ } else {
+ if (isset($data['merges']['FNAME'])) {
+ $subscriberFname = filter_var($data['merges']['FNAME'], FILTER_SANITIZE_STRING);
+ $subscriber->setSubscriberFirstname($subscriberFname);
+ }
- if (isset($data['merges']['LNAME'])) {
- $subscriberLname = filter_var($data['merges']['LNAME'], FILTER_SANITIZE_STRING);
- $subscriber->setSubscriberLastname($subscriberLname);
+ if (isset($data['merges']['LNAME'])) {
+ $subscriberLname = filter_var($data['merges']['LNAME'], FILTER_SANITIZE_STRING);
+ $subscriber->setSubscriberLastname($subscriberLname);
+ }
+ $this->subscribeMember($subscriber);
}
- $this->subscribeMember($subscriber);
}
} catch (Exception $e) {
Mage::logException($e);
}
}
- protected function subscribeMember($subscriber)
+ public function subscribeMember($subscriber)
{
$subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->setSubscriberConfirmCode($subscriber->randomSequence());
@@ -168,7 +175,7 @@ protected function setMemberGeneralData($subscriber)
protected function _unsubscribe(array $data)
{
$subscriber = Mage::helper('mailchimp')->loadListSubscriber($data['list_id'], $data['email']);
- if ($subscriber->getId()) {
+ if ($subscriber && $subscriber->getId()) {
try {
$action = isset($data['action']) ? $data['action'] : 'delete';
switch ($action) {
@@ -199,17 +206,32 @@ protected function _profile(array $data)
$fname = isset($data['merges']['FNAME']) ? $data['merges']['FNAME'] : null;
$lname = isset($data['merges']['LNAME']) ? $data['merges']['LNAME'] : null;
$customer = Mage::helper('mailchimp')->loadListCustomer($listId, $email);
+ $saveRequired = false;
if ($customer) {
- $customer->setFirstname($fname);
- $customer->setLastname($lname);
- $customer->save();
+ if ($fname && $fname !== $customer->getFirstname()) {
+ $customer->setFirstname($fname);
+ $saveRequired = true;
+ }
+ if ($lname && $lname !== $customer->getLastname()) {
+ $customer->setLastname($lname);
+ $saveRequired = true;
+ }
+ if ($saveRequired) {
+ $customer->save();
+ }
} else {
$subscriber = Mage::helper('mailchimp')->loadListSubscriber($listId, $email);
if ($subscriber) {
if ($subscriber->getId()) {
- if ($fname !== $subscriber->getSubscriberFirstname() || $lname !== $subscriber->getSubscriberLastname()) {
+ if ($fname && $fname !== $subscriber->getSubscriberFirstname()) {
$subscriber->setSubscriberFirstname($fname);
+ $saveRequired = true;
+ }
+ if ($lname && $lname !== $subscriber->getSubscriberLastname()) {
$subscriber->setSubscriberLastname($lname);
+ $saveRequired = true;
+ }
+ if ($saveRequired) {
$subscriber->save();
}
} else {
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php
index af6eaff2e..a96171ef0 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Active.php
@@ -27,7 +27,7 @@ protected function _afterSave()
$listId = Mage::helper('mailchimp')->getGeneralList($this->getScopeId(), $this->getScope());
}
- $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($this->getScopeId(), $this->getScope());
+ $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $this->getScopeId(), $this->getScope());
if ($this->isValueChanged() && $this->getValue() && $listId && $ecommerceActive && !$thisScopeHasMCStoreId) {
Mage::helper('mailchimp')->createStore($listId, $this->getScopeId(), $this->getScope());
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 98f8c5394..2530aa53b 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
@@ -15,7 +15,7 @@ class Ebizmarts_MailChimp_Model_System_Config_Backend_Apikey extends Mage_Core_M
protected function _afterSave()
{
$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());
+ $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $this->getScopeId(), $this->getScope());
if ($this->isValueChanged() && $moduleIsActive && $thisScopeHasMCStoreId) {
Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope());
Mage::helper('mailchimp')->resetCampaign($this->getScopeId(), $this->getScope());
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 b5be53203..1ae3cc841 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
@@ -23,7 +23,7 @@ protected function _afterSave()
$listId = Mage::helper('mailchimp')->getGeneralList($this->getScopeId(), $this->getScope());
}
- $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($this->getScopeId(), $this->getScope());
+ $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $this->getScopeId(), $this->getScope());
if ($this->isValueChanged() && $moduleIsActive && $listId && $this->getValue() && !$thisScopeHasMCStoreId) {
Mage::helper('mailchimp')->createStore($listId, $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 c36bf46a1..4cca79cc0 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,13 +15,20 @@ class Ebizmarts_MailChimp_Model_System_Config_Backend_List extends Mage_Core_Mod
protected function _afterSave()
{
$moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : Mage::helper('mailchimp')->isMailChimpEnabled($this->getScopeId(), $this->getScope());
+ $thisScopeHasSubMinSyncDateFlag = Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $this->getScopeId(), $this->getScope());
+
+ if ($this->isValueChanged() && $moduleIsActive && $this->getValue() && !$thisScopeHasSubMinSyncDateFlag)
+ {
+ $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, Varien_Date::now()));
+ Mage::helper('mailchimp')->saveMailchimpConfig($configValues, $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());
+ $thisScopeHasMCStoreId = Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $this->getScopeId(), $this->getScope());
if ($this->isValueChanged() && $thisScopeHasMCStoreId) {
Mage::helper('mailchimp')->removeEcommerceSyncData($this->getScopeId(), $this->getScope());
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php
new file mode 100644
index 000000000..b412d6950
--- /dev/null
+++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Twowaysync.php
@@ -0,0 +1,32 @@
+
+ * @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_Twowaysync extends Mage_Core_Model_Config_Data
+{
+ protected function _afterSave()
+ {
+ $helper = $this->getHelper();
+ $moduleIsActive = (isset($groups['general']['fields']['active']['value'])) ? $groups['general']['fields']['active']['value'] : $helper->isMailChimpEnabled($this->getScopeId(), $this->getScope());
+ $syncingFlag = $helper->getMCIsSyncing($this->getScopeId(), $this->getScope());
+ $ecommerceEnabled = $helper->isEcommerceEnabled($this->getScopeId(), $this->getScope());
+ $listId = $helper->getGeneralList($this->getScopeId(), $this->getScope());
+ if ($moduleIsActive && (!$ecommerceEnabled && $listId || $syncingFlag === 0)) {
+ $helper->handleWebhookChange($this->getScopeId(), $this->getScope());
+ }
+ }
+
+ protected function getHelper()
+ {
+ return Mage::helper('mailchimp');
+ }
+}
\ 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 7eba4bf70..36679dc63 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
@@ -34,11 +34,12 @@ public function __construct()
if ($api) {
try {
$this->_accountDetails = $api->root->info('account_name,total_subscribers');
- if ($mcStoreId && Mage::helper('mailchimp')->getIfMCStoreIdExistsForScope($scopeArray[1], $scopeArray[0])) {
+ if ($mcStoreId && Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) {
try {
- $storeName = $api->ecommerce->stores->get($mcStoreId, 'name');
+ $storeData = $api->ecommerce->stores->get($mcStoreId, 'name,is_syncing');
$this->_accountDetails['store_exists'] = true;
- $this->_accountDetails['store_name'] = $storeName['name'];
+ $this->_accountDetails['store_name'] = $storeData['name'];
+ $this->_accountDetails['store_sync_flag'] = $storeData['is_syncing'];
$totalCustomers = $api->ecommerce->customers->getAll($mcStoreId, 'total_items');
$this->_accountDetails['total_customers'] = $totalCustomers['total_items'];
$totalProducts = $api->ecommerce->products->getAll($mcStoreId, 'total_items');
@@ -93,14 +94,21 @@ public function toOptionArray()
$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'] . ':');
+ if ($this->_accountDetails['store_sync_flag']) {
+ $syncValue = 'In Progress';
+ } else {
+ $syncValue = 'Finished';
+ }
+ $syncLabel = Mage::helper('mailchimp')->__('Initial sync: ' . $syncValue);
$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)
+ array('value' => 3, 'label' => $syncLabel),
+ array('value' => 4, 'label' => $totalCustomers),
+ array('value' => 5, 'label' => $totalProducts),
+ array('value' => 6, 'label' => $totalOrders),
+ array('value' => 7, 'label' => $totalCarts)
)
);
} elseif (Mage::helper('mailchimp')->isEcomSyncDataEnabled($scopeArray[1], $scopeArray[0], true)) {
@@ -109,8 +117,8 @@ public function toOptionArray()
$returnArray = array_merge(
$returnArray,
array(
- array('value' => 7, 'label' => $noStoreText),
- array('value' => 8, 'label' => $newStoreText)
+ array('value' => 8, 'label' => $noStoreText),
+ array('value' => 9, 'label' => $newStoreText)
)
);
}
@@ -120,7 +128,7 @@ public function toOptionArray()
$returnArray = array_merge(
$returnArray,
array(
- array('value' => 9, 'label' => $storeMigrationText)
+ array('value' => 10, 'label' => $storeMigrationText)
)
);
}
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php
new file mode 100644
index 000000000..c075a0081
--- /dev/null
+++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Checkoutsubscribe.php
@@ -0,0 +1,35 @@
+
+ * @license http://opensource.org/licenses/osl-3.0.php
+ */
+class Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe
+{
+ const DISABLED = 0;
+ const CHECKED_BY_DEFAULT = 1;
+ const NOT_CHECKED_BY_DEFAULT = 2;
+ const FORCE_HIDDEN = 3;
+ const FORCE_VISIBLE = 4;
+
+ /**
+ * Options getter
+ *
+ * @return array
+ */
+ public function toOptionArray()
+ {
+ $helper = Mage::helper('mailchimp');
+ return array(
+ array('value' => self::CHECKED_BY_DEFAULT, 'label' => $helper->__('Enabled - Checked by default')),
+ array('value' => self::NOT_CHECKED_BY_DEFAULT, 'label' => $helper->__('Enabled - Not Checked by default')),
+ array('value' => self::FORCE_HIDDEN, 'label' => $helper->__('Enabled - Force subscription hidden')),
+ array('value' => self::FORCE_VISIBLE, 'label' => $helper->__('Enabled - Force subscription')),
+ array('value' => self::DISABLED, 'label' => $helper->__('-- Disabled --'))
+ );
+ }
+}
\ No newline at end of file
diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php
index 210f7d9f2..be1c1e936 100644
--- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php
+++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php
@@ -18,6 +18,12 @@ public function resetLocalErrorsAction()
$scopeArray = explode('-', $param);
$result = 1;
try {
+ $stores = Mage::app()->getStores();
+ if ($scopeArray[1] == 0) {
+ foreach ($stores as $store) {
+ Mage::helper('mailchimp')->resetErrors($store->getId());
+ }
+ }
Mage::helper('mailchimp')->resetErrors($scopeArray[1], $scopeArray[0]);
} catch(Exception $e)
{
diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml
index 45254c21c..aebfb9594 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.7
+ 1.1.8
- 1.1.7
+ 1.1.8
diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml
index 6fb3f5c5f..3a92dc9cb 100755
--- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml
+++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml
@@ -82,6 +82,14 @@
1
1
+
+ button
+ mailchimp/adminhtml_system_config_resetErrors
+ 45
+ 1
+ 1
+ 1
+
select
@@ -104,6 +112,16 @@
1
+
+
+ select
+ mailchimp/system_config_source_checkoutsubscribe
+ 53
+ 1
+ 1
+ 1
+
+
mailchimp/adminhtml_system_config_form_field_mapfields
@@ -113,9 +131,6 @@
1
1
See recommended configuration here.]]>
-
- 1
-
@@ -126,23 +141,18 @@
1
1
-
- 1
-
select
adminhtml/system_config_source_yesno
+ mailchimp/system_config_backend_twowaysync
60
1
1
1
1
-
- 1
-
@@ -153,9 +163,6 @@
1
1
-
- 1
-
@@ -166,9 +173,6 @@
0
0
-
- 1
-
@@ -178,9 +182,6 @@
1
1
1
-
- 1
-
@@ -227,17 +228,6 @@
1
-
- button
- mailchimp/adminhtml_system_config_resetErrors
- 210
- 1
- 1
- 1
-
- 1
-
-
button
mailchimp/adminhtml_system_config_resetEcommerceData
diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.6-1.1.6.7.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.6-1.1.6.7.php
deleted file mode 100755
index 89cd5a82f..000000000
--- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.6.6-1.1.6.7.php
+++ /dev/null
@@ -1,16 +0,0 @@
-run(
- "
-ALTER TABLE `{$this->getTable('sales_flat_order')}`
-ADD INDEX `customer_email` (`IDX_M4M_SALES_FLAT_ORDER_CUSTOMER_EMAIL`);
-"
- );
-} 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.7-1.1.8.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.7-1.1.8.php
new file mode 100755
index 000000000..94f6dd3b5
--- /dev/null
+++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.7-1.1.8.php
@@ -0,0 +1,27 @@
+run(
+ "
+ALTER TABLE `{$this->getTable('sales_flat_order')}`
+ADD INDEX `IDX_M4M_SALES_FLAT_ORDER_CUSTOMER_EMAIL` (`customer_email`);
+"
+ );
+} catch (Exception $e) {
+ Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true);
+}
+
+try {
+ $installer->run(
+ "
+ALTER TABLE `{$this->getTable('mailchimp_ecommerce_sync_data')}`
+ADD INDEX `batch_id` (`batch_id`);
+"
+ );
+} catch (Exception $e) {
+ Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true);
+}
+
+$installer->endSetup();
\ No newline at end of file
diff --git a/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml b/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml
index 0a37e2ba7..8ea478abc 100755
--- a/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml
+++ b/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml
@@ -1,6 +1,7 @@
+
@@ -21,7 +22,9 @@
-
+
+
+
@@ -29,4 +32,13 @@
template="ebizmarts/mailchimp/popup/emailcatcher.phtml">
+
+
+
+
+
+
+
+
+
diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml
new file mode 100644
index 000000000..0e6d16c81
--- /dev/null
+++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml
@@ -0,0 +1,102 @@
+isForceEnabled();
+$check = $this->isChecked();
+$hidden = $this->isForceHidden();
+$addToPostOnLoad = $this->addToPostOnLoad();
+$generalList = $this->getGeneralList();
+?>
+
+
+
+
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php
index eccf146df..33cfbd922 100644
--- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php
+++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php
@@ -11,8 +11,8 @@ public function setUp()
public function testGetLastDateOfPurchase()
{
/**
- * @var \Ebizmarts_MailChimp_Helper_Data $helperMock
-*/
+ * @var \Ebizmarts_MailChimp_Helper_Data $helperMock
+ */
$helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class)
->disableOriginalConstructor()
->setMethods(array('getOrderCollectionByCustomerEmail'))
@@ -27,22 +27,61 @@ public function testGetLastDateOfPurchase()
public function testCustomMergeFieldAlreadyExists()
{
/**
- * @var \Ebizmarts_MailChimp_Helper_Data $helperMock
-*/
+ * @var \Ebizmarts_MailChimp_Helper_Data $helperMock
+ */
$helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class)
->disableOriginalConstructor()
->setMethods(array('getCustomMergeFields'))
->getMock();
- $helperMock->expects($this->once())->method('getCustomMergeFields')->with(0, "store")
+ $helperMock->expects($this->once())->method('getCustomMergeFields')->with(0, "default")
->willReturn(
array(
- array(
- "value" => "FNAME"
- )
+ array(
+ "value" => "FNAME"
+ )
)
);
- $this->assertTrue($helperMock->customMergeFieldAlreadyExists("FNAME", 0, "store"));
+ $this->assertTrue($helperMock->customMergeFieldAlreadyExists("FNAME", 0, "default"));
+ }
+
+ public function testIsCheckoutSubscribeEnabled()
+ {
+ /**
+ * @var \Ebizmarts_MailChimp_Helper_Data $helperMock
+ */
+ $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class)
+ ->disableOriginalConstructor()
+ ->setMethods(array('isMailChimpEnabled', 'getCheckoutSubscribeValue'))
+ ->getMock();
+ $helperMock->expects($this->once())->method('isMailChimpEnabled')->with(1, 'stores')
+ ->willReturn(true);
+
+ $helperMock->expects($this->once())->method('getCheckoutSubscribeValue')->with(1, 'stores')
+ ->willReturn(Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::NOT_CHECKED_BY_DEFAULT);
+
+ $this->assertTrue($helperMock->isCheckoutSubscribeEnabled(1, "stores"));
+ }
+
+ public function testDeleteStore()
+ {
+ $scopeId = 1;
+ $scope = 'stores';
+ $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class)
+ ->disableOriginalConstructor()
+ ->setMethods(array('getMCStoreId', 'getApiStores', 'getGeneralList', 'deleteCurrentWebhook', 'deleteLocalMCStoreData'))
+ ->getMock();
+ $apiStoresMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Stores::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $helperMock->expects($this->once())->method('getMCStoreId')->with($scopeId, $scope)->willReturn('a18a1a8a1aa7aja1a');
+ $helperMock->expects($this->once())->method('getApiStores')->willReturn($apiStoresMock);
+ $helperMock->expects($this->once())->method('getGeneralList')->with($scopeId, $scope)->willReturn('listId');
+ $helperMock->expects($this->once())->method('deleteCurrentWebhook')->with($scopeId, $scope, 'listId');
+ $helperMock->expects($this->once())->method('deleteLocalMCStoreData')->with($scopeId, $scope);
+
+ $helperMock->deleteStore($scopeId, $scope);
}
}
\ No newline at end of file
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php
index 4cbfcbcfb..b2ba14efe 100644
--- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php
+++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php
@@ -28,7 +28,7 @@ public function testSendEcommerceBatch()
$helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class)
->disableOriginalConstructor()
- ->setMethods(array('getMCStoreId', 'isMailChimpEnabled', 'isEcomSyncDataEnabled', 'getApi', 'getIsReseted'))
+ ->setMethods(array('getMCStoreId', 'isMailChimpEnabled', 'isEcomSyncDataEnabled', 'getApi', 'getIsReseted', 'getMCIsSyncing'))
->getMock();
$apiCustomersMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Customers::class)
@@ -56,7 +56,7 @@ public function testSendEcommerceBatch()
$apiMock = $this->getMockBuilder(Ebizmarts_MailChimp::class)
->disableOriginalConstructor()
- // ->setMethods(array(''))
+// ->setMethods(array('edit'))
->getMock();
$apiBatchesMock->expects($this->once())->method('getHelper')->willReturn($helperMock);
@@ -69,6 +69,7 @@ public function testSendEcommerceBatch()
$helperMock->expects($this->once())->method('getMCStoreId')->with(1)->willReturn('b81c3085c51fa593e1d6b0cf59884f3e');
$helperMock->expects($this->once())->method('isMailChimpEnabled')->with(1)->willReturn(1);
$helperMock->expects($this->once())->method('isEcomSyncDataEnabled')->with(1)->willReturn(1);
+ $helperMock->expects($this->once())->method('getMCIsSyncing')->with(1)->willReturn(0);
$apiCustomersMock->expects($this->once())->method('createBatchJson')->with('b81c3085c51fa593e1d6b0cf59884f3e', 1);
$apiProductsMock->expects($this->once())->method('createBatchJson')->with('b81c3085c51fa593e1d6b0cf59884f3e', 1);
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php
index c9e8927b1..169192832 100644
--- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php
+++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php
@@ -83,7 +83,6 @@ public function testMakeCustomersNotSentCollection()
'joinDefaultBillingAddress',
'joinSalesData',
'getBatchLimitFromConfig',
- 'getWebsiteIdForStoreId',
'getBatchMagentoStoreId',
'getCustomerResourceCollection'
)
@@ -108,7 +107,6 @@ public function testMakeCustomersNotSentCollection()
$this->customersApiMock->expects($this->once())->method('joinDefaultBillingAddress');
$this->customersApiMock->expects($this->once())->method('joinSalesData');
$this->customersApiMock->expects($this->once())->method('getBatchLimitFromConfig')->willReturn(100);
- $this->customersApiMock->expects($this->once())->method('getWebsiteIdForStoreId')->with(1)->willReturn(1);
$collection = $this->customersApiMock->makeCustomersNotSentCollection();
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php
index f6fed927a..7d727dff8 100644
--- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php
+++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php
@@ -4,13 +4,15 @@ class Ebizmarts_MailChimp_Model_Api_ProductsTest extends PHPUnit_Framework_TestC
{
private $productsApiMock;
+ const BATCH_ID = 'storeid-0_PRO_2017-05-18-14-45-54-38849500';
+
+ const PRODUCT_ID = 603;
+
public function setUp()
{
Mage::app('default');
- /**
- * @var Ebizmarts_MailChimp_Model_Api_Products $apiProductsMock
-*/
+ /** @var Ebizmarts_MailChimp_Model_Api_Products $apiProductsMock productsApiMock */
$this->productsApiMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Products::class);
}
@@ -21,19 +23,99 @@ public function tearDown()
public function testCreateBatchJson()
{
- $this->productsApiMock = $this->productsApiMock->setMethods(array('makeBatchId', 'makeProductsNotSentCollection', 'joinMailchimpSyncData'))
- ->getMock();
+ $this->productsApiMock = $this->productsApiMock->setMethods(
+ array(
+ 'makeBatchId',
+ 'makeProductsNotSentCollection',
+ 'joinMailchimpSyncData',
+ 'shouldSendProductUpdate',
+ 'getChildrenIdsForConfigurable',
+ 'makeProductChildrenCollection',
+ "getMailChimpHelper"
+ )
+ )
+ ->getMock();
+ $mailChimpHelperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $mailChimpHelperMock->method("getMailChimpProductImageUrl")->willReturn("product_image_url");
+ $this->productsApiMock->expects($this->any())->method("getMailChimpHelper")
+ ->willReturn($mailChimpHelperMock);
$this->productsApiMock->expects($this->once())->method('makeBatchId')->with(0)
- ->willReturn('storeid-0_PRO_2017-05-18-14-45-54-38849500');
+ ->willReturn(self::BATCH_ID);
$this->productsApiMock->expects($this->never())->method('buildProductDataRemoval');
- $this->productsApiMock->expects($this->once())->method('makeProductsNotSentCollection');
+
$this->productsApiMock->expects($this->once())->method('joinMailchimpSyncData');
+ $this->productsApiMock->expects($this->once())->method('shouldSendProductUpdate')->willReturn(false);
+
+ $this->productsApiMock->expects($this->once())->method('makeProductsNotSentCollection')->with(0)
+ ->willReturn($this->productCollection());
- $this->productsApiMock->expects($this->once())->method('makeProductsNotSentCollection')->with('dasds231231312', 0)
- ->willReturn(new Varien_Object());
+ $this->productsApiMock->expects($this->once())->method("makeProductChildrenCollection")
+ ->willReturn($this->configurableChildrenCollection());
+ $this->productsApiMock->expects($this->once())->method("getChildrenIdsForConfigurable")
+ ->willReturn($this->configurableNoChildren());
- $this->productsApiMock->createBatchJson('dasds231231312', 0);
+ $return = $this->productsApiMock->createBatchJson('dasds231231312', 0);
+
+ $this->assertEquals(1, count($return));
+ $this->assertArrayHasKey("method", $return[0]);
+ $this->assertArrayHasKey("path", $return[0]);
+ $this->assertArrayHasKey("operation_id", $return[0]);
+ $this->assertArrayHasKey("body", $return[0]);
+ $this->assertEquals("POST", $return[0]["method"]);
+ $this->assertRegExp("/\/ecommerce\/stores\/(.*)\/products/", $return[0]["path"]);
+ $this->assertEquals(self::BATCH_ID . "_" . self::PRODUCT_ID, $return[0]["operation_id"]);
+ }
+
+ private function configurableChildrenCollection()
+ {
+ $collectionMock = $this->getMockBuilder(Mage_Catalog_Model_Resource_Product_Collection::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $collectionMock->expects($this->once())->method('addAttributeToFilter')->with("entity_id", array("in" => array()));
+ $collectionMock->expects($this->once())->method("getIterator")->willReturn(new ArrayIterator(array()));
+
+ return $collectionMock;
+ }
+
+ private function productCollection()
+ {
+ $products = array();
+
+ $productMock = $this->getMockBuilder(Mage_Catalog_Model_Product::class)
+ ->disableOriginalConstructor()
+ ->setMethods(
+ array(
+ "getMailchimpSyncDeleted",
+ "_getResource",
+ "getId",
+ "getTypeId",
+ "getName",
+ "getProductUrl",
+ "getDescription",
+ "getCategoryId",
+ )
+ )
+ ->getMock();
+ $productMock->method('_getResource')->willReturn(new Varien_Object());
+ $productMock->expects($this->once())->method('getMailchimpSyncDeleted')->willReturn(null);
+ $productMock->expects($this->any())->method('getId')->willReturn(self::PRODUCT_ID);
+ $productMock->expects($this->exactly(4))->method('getTypeId')->willReturn("configurable");
+ $productMock->expects($this->exactly(2))->method('getName')->willReturn("Lorem ipsum dolor sit amet 445452340");
+ $productMock->expects($this->exactly(2))->method('getProductUrl')->willReturn("http://a.example");
+ $productMock->expects($this->exactly(2))->method('getDescription')->willReturn("Lorem ipsum dolor sit amet. LONG");
+ $productMock->expects($this->once())->method('getCategoryId')->willReturn(null);
+
+ $products []= $productMock;
+
+ $collectionMock = $this->getMockBuilder(Mage_Catalog_Model_Resource_Product_Collection::class)
+ ->disableOriginalConstructor()
+ ->getMock();
+ $collectionMock->expects($this->once())->method("getIterator")->willReturn(new ArrayIterator($products));
+
+ return $collectionMock;
}
public function testMakeProductsNotSentCollection()
@@ -43,8 +125,7 @@ public function testMakeProductsNotSentCollection()
'joinQtyAndBackorders',
'joinCategoryId',
'joinProductAttributes',
- 'getProductResourceCollection',
- 'getWebsiteIdForStoreId'
+ 'getProductResourceCollection'
)
)
->getMock();
@@ -60,7 +141,6 @@ public function testMakeProductsNotSentCollection()
->getMock();
$productResourceCollectionMock->expects($this->exactly(2))->method('getSelect')->willReturn($dbSelectMock);
$productResourceCollectionMock->expects($this->once())->method('addStoreFilter');
- $productResourceCollectionMock->expects($this->once())->method('addPriceData')->with(null, 1);
$this->productsApiMock->expects($this->once())->method('getProductResourceCollection')
->willReturn($productResourceCollectionMock);
@@ -68,10 +148,18 @@ public function testMakeProductsNotSentCollection()
$this->productsApiMock->expects($this->once())->method('joinCategoryId');
$this->productsApiMock->expects($this->once())->method('joinProductAttributes');
$this->productsApiMock->expects($this->once())->method('getProductResourceCollection');
- $this->productsApiMock->expects($this->once())->method('getWebsiteIdForStoreId')->with(0)->willReturn(1);
- $collection = $this->productsApiMock->makeProductsNotSentCollection('dasds123321', 0);
+ $collection = $this->productsApiMock->makeProductsNotSentCollection(0);
$this->assertInstanceOf("Mage_Catalog_Model_Resource_Product_Collection", $collection);
}
+
+ /**
+ * @see \Mage_Catalog_Model_Resource_Product_Type_Configurable::getChildrenIds
+ * @return array
+ */
+ private function configurableNoChildren()
+ {
+ return \Ebizmarts_MailChimp_Model_Api_Products::$noChildrenIds;
+ }
}
\ No newline at end of file
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/SubscribersTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/SubscribersTest.php
index 164fefa31..ab9b46e1e 100644
--- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/SubscribersTest.php
+++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/SubscribersTest.php
@@ -13,7 +13,6 @@ public function setUp()
* @param $magentoStatus
* @param $storeId
* @param $expected
- * @param $configConfirmation
* @dataProvider magentoSubscriberStatus
*/
public function testMailchimpStatus($magentoStatus, $storeId, $expected)
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php
index 97e7de9a3..be3c809cb 100644
--- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php
+++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php
@@ -10,8 +10,8 @@ public function setUp()
public function testProductAttributeUpdateIsUsingCorrectStoreId()
{
/**
- * @var \Ebizmarts_MailChimp_Model_Observer $modelMock
-*/
+ * @var \Ebizmarts_MailChimp_Model_Observer $modelMock
+ */
$modelMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class)
->disableOriginalConstructor()
->setMethods(array('changeStoreName', 'makeHelper', 'makeApiProducts'))
@@ -30,7 +30,7 @@ public function testProductAttributeUpdateIsUsingCorrectStoreId()
->disableOriginalConstructor()
->setMethods(array('getProductIds', 'getStoreId'))
->getMock();
- $eventMock->expects($this->once())->method('getProductIds')->willReturn(array(12,34));
+ $eventMock->expects($this->once())->method('getProductIds')->willReturn(array(12, 34));
$eventMock->expects($this->once())->method('getStoreId')->willReturn(0);
$eventObserverMock = $this->makeEventObserverMock($eventMock, 2);
@@ -45,8 +45,8 @@ public function testProductAttributeUpdateIsUsingCorrectStoreId()
public function testSaveCampaignDataCallsCorrectFunctions()
{
/**
- * @var \Ebizmarts_MailChimp_Model_Observer $modelMock
-*/
+ * @var \Ebizmarts_MailChimp_Model_Observer $modelMock
+ */
$modelMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class)
->disableOriginalConstructor()
->setMethods(array("_getCampaignCookie", "_getLandingCookie"))
diff --git a/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css b/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css
old mode 100755
new mode 100644
index 6def4451a..235d74f99
--- a/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css
+++ b/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css
@@ -17,11 +17,11 @@ ul.tabs a.mailchimp-section:hover {
ul.tabs a.mailchimp-section span,
ul.tabs a.mailchimp-section:hover span {
- background: url(../images/mailchimp-tab.png) no-repeat 18px 3px;
+ background: url(../images/mailchimp-tab.png) no-repeat 18px;
overflow: hidden;
padding-left: 20px;
- width: 120px;
- height: 18px;
+ background-size: contain;
+
}
ul.tabs a.mailchimp-section.active, ul.tabs a.mailchimp-section.active:hover {
@@ -36,6 +36,7 @@ h3.mailchimp-header {
padding-left: 20px;;
width: 120px;
text-indent: -9999px;
+ background-size: contain;
}
fieldset#mailchimp_general p.note a {
diff --git a/skin/adminhtml/default/default/ebizmarts/mailchimp/images/mailchimp-tab.png b/skin/adminhtml/default/default/ebizmarts/mailchimp/images/mailchimp-tab.png
old mode 100755
new mode 100644
index f4138f0dc..f3047239e
Binary files a/skin/adminhtml/default/default/ebizmarts/mailchimp/images/mailchimp-tab.png and b/skin/adminhtml/default/default/ebizmarts/mailchimp/images/mailchimp-tab.png differ