From 9cbdbba14b745a2d14fc61f96151d0a6b70242c9 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 28 Jul 2017 17:09:28 -0300 Subject: [PATCH 01/42] Added button to send ecommerce data without loosing the store and maintainig Automations usage during the sending process. In progress(works) #413 --- .../System/Config/ResendEcommerceData.php | 61 +++ .../System/Config/ResetEcommerceData.php | 2 +- .../Ebizmarts/MailChimp/Helper/Data.php | 379 +++++++++++++++++- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 18 +- .../Ebizmarts/MailChimp/Model/Api/Carts.php | 48 ++- .../MailChimp/Model/Api/Customers.php | 44 +- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 52 ++- .../MailChimp/Model/Api/Products.php | 51 ++- .../Ebizmarts/MailChimp/Model/Config.php | 6 + .../Model/System/Config/Source/Account.php | 62 +-- .../Adminhtml/EcommerceController.php | 22 +- .../Ebizmarts/MailChimp/etc/system.xml | 16 +- .../system/config/resendecommercedata.phtml | 25 ++ 13 files changed, 670 insertions(+), 116 deletions(-) create mode 100644 app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php create mode 100644 app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resendecommercedata.phtml diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php new file mode 100644 index 000000000..43c7395b1 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php @@ -0,0 +1,61 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 5/27/16 1:16 PM + * @file: ResendEcommerceData.php + */ +class Ebizmarts_MailChimp_Block_Adminhtml_System_Config_ResendEcommerceData + extends Mage_Adminhtml_Block_System_Config_Form_Field +{ + protected function _construct() + { + parent::_construct(); + $this->setTemplate('ebizmarts/mailchimp/system/config/resendecommercedata.phtml'); + } + + protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) + { + return $this->_toHtml(); + } + + public function getButtonHtml() + { + $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + if (Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) { + $label = $this->helper('mailchimp')->__('Resend Ecommerce Data'); + $button = $this->getLayout()->createBlock('adminhtml/widget_button') + ->setData( + array( + 'id' => 'resendecommercedata_button', + 'label' => $label, + 'onclick' => 'javascript:resendecommerce(); return false;', + 'title' => $this->helper('mailchimp')->__('Re-create MailChimp store for current scope') + ) + ); + + return $button->toHtml(); + } + } + + /** + * @return string + */ + public function getMessage() + { + $message = 'Are you sure you want to delete the local data in order to send all items again?\nAutomations will work normally but the synchronization process for the old data will take longer than resetting the MailChimp store.'; + return $this->helper('mailchimp')->__($message); + } + + public function getAjaxCheckUrl() + { + $scopeString = Mage::helper('mailchimp')->getScopeString(); + return Mage::helper('adminhtml')->getUrl('adminhtml/ecommerce/resendEcommerceData', array('scope' => $scopeString)); + } + +} \ No newline at end of file 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 a62c681f2..6704ed57b 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 @@ -28,7 +28,7 @@ public function getButtonHtml() { $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); if (Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) { - $label = $this->helper('mailchimp')->__('Reset Ecommerce Data'); + $label = $this->helper('mailchimp')->__('Reset MailChimp Store'); $button = $this->getLayout()->createBlock('adminhtml/widget_button') ->setData( array( diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index ccc40da8b..ab441c4ae 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -402,15 +402,23 @@ public function resetMCEcommerceData($scopeId, $scope, $deleteDataInMailchimp = { $listId = $this->getGeneralList($scopeId, $scope); //delete store id and data from mailchimp - if ($deleteDataInMailchimp && $this->getMCStoreId($scopeId, $scope) && $this->getMCStoreId($scopeId, $scope) != "") { - $this->removeEcommerceSyncData($scopeId, $scope); - $this->resetCampaign($scopeId, $scope); - $this->clearErrorGrid($scopeId, $scope, true); - $this->deleteStore($scopeId, $scope); - } + if ($deleteDataInMailchimp) { + if ($this->getMCStoreId($scopeId, $scope) && $this->getMCStoreId($scopeId, $scope) != "") { + $this->removeEcommerceSyncData($scopeId, $scope); + $this->resetCampaign($scopeId, $scope); + $this->clearErrorGrid($scopeId, $scope, true); + $this->deleteStore($scopeId, $scope); + } - if ($this->isEcomSyncDataEnabled($scopeId, $scope, true)) { - $this->createStore($listId, $scopeId, $scope); + if ($this->isEcomSyncDataEnabled($scopeId, $scope, true)) { + $this->createStore($listId, $scopeId, $scope); + } + } else { + if ($this->getMCStoreId($scopeId, $scope) && $this->getMCStoreId($scopeId, $scope) != "") { + $this->saveLastItemsSent($scopeId, $scope); + $this->removeEcommerceSyncData($scopeId, $scope); + $this->clearErrorGrid($scopeId, $scope, true); + } } } @@ -661,6 +669,65 @@ public function deleteStore($scopeId, $scope) } } + protected function saveLastItemsSent($scopeId, $scope) + { + $isSyncing = $this->getMCIsSyncing($scopeId, $scope); + if (!$isSyncing) { + $customerLastId = $this->getLastCustomerSent($scopeId, $scope); + $productLastId = $this->getLastProductSent($scopeId, $scope); + $orderLastId = $this->getLastOrderSent($scopeId, $scope); + $cartLastId = $this->getLastCartSent($scopeId, $scope); + + $configValues = array(); + $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $customerLastId); + $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $productLastId); + $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $orderLastId); + $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $cartLastId); + $configValues[] = array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, 1); + $this->saveMailchimpConfig($configValues, $scopeId, $scope); + } + } + + protected function getLastCustomerSent($scopeId, $scope) + { + $mcStoreId = $this->getMCStoreId($scopeId, $scope); + $syncDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection') + ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) + ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER)); + $customerSyncData = $syncDataCollection->getLastItem(); + return $customerSyncData->getRelatedId(); + } + + protected function getLastProductSent($scopeId, $scope) + { + $mcStoreId = $this->getMCStoreId($scopeId, $scope); + $syncDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection') + ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) + ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_PRODUCT)); + $productSyncData = $syncDataCollection->getLastItem(); + return $productSyncData->getRelatedId(); + } + + protected function getLastOrderSent($scopeId, $scope) + { + $mcStoreId = $this->getMCStoreId($scopeId, $scope); + $syncDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection') + ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) + ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_ORDER)); + $orderSyncData = $syncDataCollection->getLastItem(); + return $orderSyncData->getRelatedId(); + } + + protected function getLastCartSent($scopeId, $scope) + { + $mcStoreId = $this->getMCStoreId($scopeId, $scope); + $syncDataCollection = Mage::getResourceModel('mailchimp/ecommercesyncdata_collection') + ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) + ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_QUOTE)); + $cartSyncData = $syncDataCollection->getLastItem(); + return $cartSyncData->getRelatedId(); + } + /** * Create MailChimp merge fields existing in the extension configuration page. * @@ -1446,11 +1513,7 @@ protected function _setIsSyncingInAllStores($syncValue) { $stores = Mage::app()->getStores(); foreach ($stores as $storeId => $store) { - $mailchimpApi = $this->getApi($storeId); - $mailchimpStoreId = $this->getMCStoreId($storeId); - if ($mailchimpStoreId) { - $this->getApiStores()->editIsSyncing($mailchimpApi, $syncValue, $mailchimpStoreId, $storeId); - } + $this->setIsSyncingPerStore($syncValue, $storeId); } } @@ -1848,7 +1911,7 @@ public function getIfConfigExistsForScope($configPath, $scopeId, $scope = 'store return $configAssociatedToScope; } - + /** * @param $batchArray * @param $productData @@ -1882,4 +1945,292 @@ public function isCheckoutSubscribeEnabled($scopeId, $scope = 'stores') { return ($this->isMailChimpEnabled($scopeId, $scope) && $this->getCheckoutSubscribeValue($scopeId, $scope) != Ebizmarts_MailChimp_Model_System_Config_Source_Checkoutsubscribe::DISABLED); } + + /** + * @param $syncValue + * @param $storeId + */ + public function setIsSyncingPerStore($syncValue, $storeId) + { + $mailchimpApi = $this->getApi($storeId); + $mailchimpStoreId = $this->getMCStoreId($storeId); + if ($mailchimpStoreId) { + $this->getApiStores()->editIsSyncing($mailchimpApi, $syncValue, $mailchimpStoreId, $storeId); + } + } + + public function setResendTurn($value, $scopeId, $scope = 'stores') + { + $configValue = array(array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, $value)); + $this->saveMailchimpConfig($configValue, $scopeId, $scope); + } + + public function getResendTurn($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, $scopeId, $scope); + } + + public function getResendEnabled($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $scopeId, $scope); + } + + public function getCustomerResendLastId($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $scopeId, $scope); + } + + public function getProductResendLastId($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $scopeId, $scope); + } + + public function getOrderResendLastId($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $scopeId, $scope); + } + + public function getCartResendLastId($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $scopeId, $scope); + } + + public function addResendFilter($collection, $magentoStoreId) + { + $resendEnabled = $this->getResendEnabled($magentoStoreId); + if ($resendEnabled) { + $resendTurn = $this->getResendTurn($magentoStoreId); + $lastOrderSent = $this->getOrderResendLastId($magentoStoreId); + if ($resendTurn) { + $collection->addFieldToFilter('entity_id', array('lteq' => $lastOrderSent)); + } else { + $collection->addFieldToFilter('entity_id', array('gt' => $lastOrderSent)); + } + } + } + + public function handleResendFinish($scopeId, $scope = 'stores') + { + $allItemsSent = $this->allResendItemsSent($scopeId, $scope); + if ($allItemsSent) { + $this->deleteResendConfigValues($scopeId, $scope); + } + } + + protected function deleteResendConfigValues($scopeId, $scope = 'stores') + { + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_LAST_ID, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_LAST_ID, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_LAST_ID, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CART_LAST_ID, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $scope, $scopeId); + Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, $scope, $scopeId); + Mage::getConfig()->cleanCache(); + } + + protected function allResendItemsSent($scopeId, $scope = 'stores') + { + if ($scope == 'stores') { + $allItemsSent = $this->allResendItemsSentPerStoreView($scopeId); + } else { + if ($scope == 'websites') { + $website = Mage::getModel('core/website')->load($scopeId); + $storeIds = $website->getStoreIds(); + $allItemsSent = $this->allResendItemsSentPerScope($storeIds); + } else { + $stores = Mage::app()->getStores(); + $allItemsSent = $this->allResendItemsSentPerScope($stores); + } + } + + return $allItemsSent; + } + + /** + * @param $storeId + * @return array + */ + public function handleResendDataBefore($storeId) + { + $resendEnabled = $this->getResendEnabled($storeId); + $resendTurn = $this->getResendTurn($storeId); + if ($resendEnabled && $resendTurn) { + $this->setIsSyncingPerStore(true, $storeId); + } + } + + /** + * @param $storeId + */ + public function handleResendDataAfter($storeId) + { + $resendEnabled = $this->getResendEnabled($storeId); + $resendTurn = $this->getResendTurn($storeId); + if ($resendEnabled) { + $configScope = $this->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $storeId); + if ($resendTurn) { + $this->setIsSyncingPerStore(false, $storeId); + $this->setResendTurn(0, $configScope['scope_id'], $configScope['scope']); + } else { + $this->setResendTurn(1, $configScope['scope_id'], $configScope['scope']); + } + $this->handleResendFinish($configScope['scope_id'], $configScope['scope']); + } + } + + /** + * @param $storeId + * @return bool + */ + protected function allResendItemsSentPerStoreView($storeId) + { + $customerId = $this->getCustomerResendLastId($storeId); + if ($customerId) { + $isMissingCustomer = $this->isMissingItemLowerThanId($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $storeId); + } + $productId = $this->getProductResendLastId($storeId); + if ($productId) { + $isMissingProduct = $this->isMissingItemLowerThanId($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $storeId); + } + $orderId = $this->getOrderResendLastId($storeId); + if ($orderId) { + $isMissingOrder = $this->isMissingItemLowerThanId($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $storeId); + } + $cartId = $this->getCartResendLastId($storeId); + if ($cartId) { + $isMissingCart = $this->isMissingItemLowerThanId($cartId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $storeId); + } else { + $isMissingCart = false; + } + + if (!$isMissingCustomer && !$isMissingProduct && !$isMissingOrder && !$isMissingCart) { + $allItemsSent = true; + } else { + $allItemsSent = false; + } + return $allItemsSent; + } + + /** + * @param $stores + * @return bool + */ + protected function allResendItemsSentPerScope($stores) + { + $allItemsSent = true; + foreach ($stores as $store) { + if ($store instanceof Mage_Core_Model_Store) { + $storeId = $store->getId(); + } else { + $storeId = $store; + } + $allItemsSentInCurrentStore = $this->allResendItemsSentPerStoreView($storeId); + if (!$allItemsSentInCurrentStore) { + $allItemsSent = false; + } + } + return $allItemsSent; + } + + protected function isMissingItemLowerThanId($itemId, $itemType, $mailchimpStoreId) + { + switch ($itemType) { + case Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER: + $isMissing = $this->isMissingCustomerLowerThanId($itemId, $mailchimpStoreId); + break; + case Ebizmarts_MailChimp_Model_Config::IS_PRODUCT: + $isMissing = $this->isMissingProductLowerThanId($itemId, $mailchimpStoreId); + break; + case Ebizmarts_MailChimp_Model_Config::IS_ORDER: + $isMissing = $this->isMissingOrderLowerThanId($itemId, $mailchimpStoreId); + break; + case Ebizmarts_MailChimp_Model_Config::IS_QUOTE: + $isMissing = $this->isMissingQuoteLowerThanId($itemId, $mailchimpStoreId); + break; + default: + $isMissing = false; + break; + } + return $isMissing; + } + + protected function isMissingCustomerLowerThanId($itemId, $storeId) + { + $mailchimpStoreId = $this->getMCStoreId($storeId); + $customerCollection = Mage::getResourceModel('customer/customer_collection') + ->addFieldToFilter('store_id', array('eq' => $storeId)) + ->addFieldToFilter('entity_id', array('lteq' => $itemId)); + Mage::getModel('mailchimp/api_customers')->joinMailchimpSyncDataWithoutWhere($customerCollection, $mailchimpStoreId); + $customerCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($customerCollection->getSize()) { + $isMissing = true; + } else { + $isMissing = false; + } + return $isMissing; + } + + protected function isMissingProductLowerThanId($itemId, $storeId) + { + $apiProducts = Mage::getModel('mailchimp/api_products'); + $mailchimpStoreId = $this->getMCStoreId($storeId); + $productCollection = Mage::getResourceModel('catalog/product_collection') + ->addStoreFilter($storeId) + ->addFieldToFilter('entity_id', array('lteq' => $itemId)); + $apiProducts->joinQtyAndBackorders($productCollection); + $apiProducts->joinCategoryId($productCollection); + $apiProducts->joinProductAttributes($productCollection); + $productCollection->getSelect()->group("e.entity_id"); + $apiProducts->joinMailchimpSyncDataWithoutWhere($productCollection, $mailchimpStoreId); + $productCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($productCollection->getSize()) { + $isMissing = true; + } else { + $isMissing = false; + } + return $isMissing; + } + + protected function isMissingOrderLowerThanId($itemId, $storeId) + { + $mailchimpStoreId = $this->getMCStoreId($storeId); + $orderCollection = Mage::getResourceModel('sales/order_collection') + ->addFieldToFilter('store_id', array('eq' => $storeId)) + ->addFieldToFilter('entity_id', array('lteq' => $itemId)); + $firstDate = $this->getEcommerceFirstDate($storeId); + if ($firstDate) { + $orderCollection->addFieldToFilter('created_at', array('gt' => $firstDate)); + } + Mage::getModel('mailchimp/api_orders')->joinMailchimpSyncDataWithoutWhere($orderCollection, $mailchimpStoreId); + $orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($orderCollection->getSize()) { + $isMissing = true; + } else { + $isMissing = false; + } + return $isMissing; + } + + protected function isMissingQuoteLowerThanId($itemId, $storeId) + { + $mailchimpStoreId = $this->getMCStoreId($storeId); + $quoteCollection = Mage::getResourceModel('sales/order_collection') + ->addFieldToFilter('store_id', array('eq' => $storeId)) + ->addFieldToFilter('entity_id', array('lteq' => $itemId)) + ->addFieldToFilter('is_active', array('eq'=>1)) + ->addFieldToFilter('customer_email', array('notnull'=>true)) + ->addFieldToFilter('items_count', array('gt'=>0)); + $firstDate = $this->getAbandonedCartFirstDate($storeId); + if ($firstDate) { + $quoteCollection->addFieldToFilter('updated_at', array('gt' => $firstDate)); + } + Mage::getModel('mailchimp/api_carts')->joinMailchimpSyncDataWithoutWhere($quoteCollection, $mailchimpStoreId); + $quoteCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($quoteCollection->getSize()) { + $isMissing = true; + } else { + $isMissing = false; + } + return $isMissing; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 3b725bf95..cec832b67 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -90,19 +90,23 @@ public function getApiOrders() */ public function handleEcommerceBatches() { + $helper = $this->getHelper(); $stores = Mage::app()->getStores(); foreach ($stores as $store) { - $this->_getResults($store->getId()); - $this->_sendEcommerceBatch($store->getId()); + $storeId = $store->getId(); + $this->_getResults($storeId); + $helper->handleResendDataBefore($storeId); + $this->_sendEcommerceBatch($storeId); + $helper->handleResendDataAfter($storeId); } foreach ($stores as $store) { - if ($this->getHelper()->getIsReseted($store->getId())) { - $scopeToReset = $this->getHelper()->getMailChimpScopeByStoreId($store->getId()); + if ($helper->getIsReseted($store->getId())) { + $scopeToReset = $helper->getMailChimpScopeByStoreId($store->getId()); if ($scopeToReset) { - $this->getHelper()->resetMCEcommerceData($scopeToReset['scope_id'], $scopeToReset['scope'], true); + $helper->resetMCEcommerceData($scopeToReset['scope_id'], $scopeToReset['scope'], true); $configValue = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 0)); - $this->getHelper()->saveMailchimpConfig($configValue, $scopeToReset['scope_id'], $scopeToReset['scope']); + $helper->saveMailchimpConfig($configValue, $scopeToReset['scope_id'], $scopeToReset['scope']); } } } @@ -556,7 +560,7 @@ protected function saveSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelt { $helper = $this->getHelper(); if ($itemType == 'SUB') { - $helper->updateSubscriberSyndData($itemId,$syncDelta, $syncError, 0, null); + $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 9546a492a..98bf2eb59 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -28,20 +28,24 @@ class Ebizmarts_MailChimp_Model_Api_Carts */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { + $helper = $this->getHelper(); $allCarts = array(); - if (!Mage::helper('mailchimp')->isAbandonedCartEnabled($magentoStoreId)) { + if (!$helper->isAbandonedCartEnabled($magentoStoreId)) { return $allCarts; } - $this->_firstDate = Mage::helper('mailchimp')->getAbandonedCartFirstDate($magentoStoreId); + $this->_firstDate = $helper->getAbandonedCartFirstDate($magentoStoreId); $this->_counter = 0; - $date = Mage::helper('mailchimp')->getDateMicrotime(); + $date = $helper->getDateMicrotime(); $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_QUOTE.'_'.$date; - // get all the carts converted in orders (must be deleted on mailchimp) - $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId)); - // get all the carts modified but not converted in orders - $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId)); + $resendTurn = $helper->getResendTurn($magentoStoreId); + if (!$resendTurn) { + // get all the carts converted in orders (must be deleted on mailchimp) + $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId)); + // get all the carts modified but not converted in orders + $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId)); + } // get new carts $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId)); return $allCarts; @@ -190,7 +194,7 @@ protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) */ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $helper = $this->getHelper(); $allCarts = array(); $newCarts = Mage::getResourceModel('sales/quote_collection'); $newCarts->addFieldToFilter('is_active', array('eq'=>1)); @@ -198,18 +202,14 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) $newCarts->addFieldToFilter('items_count', array('gt'=>0)); // select carts for the current Magento store id $newCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + $helper->addResendFilter($newCarts, $magentoStoreId); // filter by first date if exists. if ($this->_firstDate) { $newCarts->addFieldToFilter('updated_at', array('gt' => $this->_firstDate)); } //join with mailchimp_ecommerce_sync_data table to filter by sync data. - $newCarts->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + $this->joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId); // be sure that the quotes are already in mailchimp and not deleted $newCarts->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); // limit the collection @@ -507,4 +507,24 @@ public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $this->_counter = $productDataArray[1]; return $allCarts; } + + protected function getHelper() + { + return Mage::helper('mailchimp'); + } + + /** + * @param $newCarts + * @param $mailchimpStoreId + */ + public function joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId) + { + $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $newCarts->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + array('m4m.*') + ); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index 314a0505b..fdc68716f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -231,11 +231,15 @@ protected function makeBatchId() */ public function makeCustomersNotSentCollection() { + $helper = $this->mailchimpHelper; + $magentoStoreId = $this->getBatchMagentoStoreId(); /** * @var Mage_Customer_Model_Resource_Customer_Collection $collection */ $collection = $this->getCustomerResourceCollection(); - $collection->addFieldToFilter('store_id', array('eq' => $this->getBatchMagentoStoreId())); + $collection->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + + $helper->addResendFilter($collection, $magentoStoreId); $collection->addNameToSelect(); @@ -281,19 +285,7 @@ protected function joinSalesData($collection) */ protected function joinMailchimpSyncData($collection) { - $joinCondition = "m4m.related_id = e.entity_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; - $mailchimpTableName = $this->getSyncdataTableName(); - - $collection->getSelect()->joinLeft( - array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $this->mailchimpStoreId), array( - "m4m.related_id", - "m4m.type", - "m4m.mailchimp_store_id", - "m4m.mailchimp_sync_delta", - "m4m.mailchimp_sync_modified" - ) - ); + $this->joinMailchimpSyncDataWithoutWhere($collection); $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1"); } @@ -393,4 +385,28 @@ protected function getBatchMagentoStoreId() { return $this->magentoStoreId; } + + /** + * @param $collection + * @param null $mailchimpStoreId + */ + public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId = null) + { + if (!$mailchimpStoreId) { + $mailchimpStoreId = $this->mailchimpStoreId; + } + $joinCondition = "m4m.related_id = e.entity_id and m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + $mailchimpTableName = $this->getSyncdataTableName(); + + $collection->getSelect()->joinLeft( + array("m4m" => $mailchimpTableName), + sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId), array( + "m4m.related_id", + "m4m.type", + "m4m.mailchimp_store_id", + "m4m.mailchimp_sync_delta", + "m4m.mailchimp_sync_modified" + ) + ); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 191507ac6..c2d0499d3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -37,13 +37,16 @@ class Ebizmarts_MailChimp_Model_Api_Orders */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { + $helper = $this->getHelper(); $batchArray = array(); - $this->_firstDate = Mage::helper('mailchimp')->getEcommerceFirstDate($magentoStoreId); + $this->_firstDate = $helper->getEcommerceFirstDate($magentoStoreId); $this->_counter = 0; $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' . Mage::helper('mailchimp')->getDateMicrotime(); - - // get all the orders modified - $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId, $magentoStoreId)); + $resendTurn = $helper->getResendTurn($magentoStoreId); + if (!$resendTurn) { + // get all the orders modified + $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId, $magentoStoreId)); + } // get new orders $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId, $magentoStoreId)); @@ -52,6 +55,7 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) { + $helper = $this->getHelper(); $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); $batchArray = array(); $modifiedOrders = Mage::getResourceModel('sales/order_collection'); @@ -84,7 +88,7 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; $batchArray[$this->_counter]['body'] = $orderJson; } else { - $error = Mage::helper('mailchimp')->__('Something went wrong when retrieving product information.'); + $error = $helper->__('Something went wrong when retrieving product information.'); $this->_updateSyncData($orderId, $mailchimpStoreId, Varien_Date::now(), $error); continue; } @@ -102,22 +106,18 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $helper = $this->getHelper(); $batchArray = array(); $newOrders = Mage::getResourceModel('sales/order_collection'); // select carts for the current Magento store id $newOrders->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + $helper->addResendFilter($newOrders, $magentoStoreId); // filter by first date if exists. if ($this->_firstDate) { $newOrders->addFieldToFilter('created_at', array('gt' => $this->_firstDate)); } - $newOrders->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' - AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + $this->joinMailchimpSyncDataWithoutWhere($newOrders, $mailchimpStoreId); // be sure that the orders are not in mailchimp $newOrders->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); // limit the collection @@ -515,10 +515,10 @@ public function update($orderId, $magentoStoreId) * * @param $orderId * @param $mailchimpStoreId - * @param null $syncDelta - * @param null $syncError - * @param int $syncModified - * @param bool $saveOnlyIfexists + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param bool $saveOnlyIfexists */ protected function _updateSyncData($orderId, $mailchimpStoreId, $syncDelta = null, $syncError = null, $syncModified = 0, $saveOnlyIfexists = false) { @@ -611,4 +611,24 @@ public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order return $batchArray; } + + protected function getHelper() + { + return Mage::helper('mailchimp'); + } + + /** + * @param $newOrders + * @param $mailchimpStoreId + */ + public function joinMailchimpSyncDataWithoutWhere($newOrders, $mailchimpStoreId) + { + $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $newOrders->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_ORDER . "' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + array('m4m.*') + ); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index e1ca1b0b9..90f23bb83 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -37,13 +37,12 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) ->setConfig(Mage_Catalog_Helper_Product_Flat::XML_PATH_USE_PRODUCT_FLAT, 0); } $collection = $this->makeProductsNotSentCollection($magentoStoreId); - $this->joinMailchimpSyncData($mailchimpStoreId, $collection); + $this->joinMailchimpSyncData($collection, $mailchimpStoreId); $batchArray = array(); $batchId = $this->makeBatchId($magentoStoreId); $counter = 0; foreach ($collection as $product) { - if ($product->getMailchimpSyncDeleted()) { $batchArray = array_merge($this->buildProductDataRemoval($product, $batchId, $mailchimpStoreId, $magentoStoreId), $batchArray); } @@ -357,6 +356,7 @@ public function makeProductsNotSentCollection($magentoStoreId) $collection = $this->getProductResourceCollection(); $collection->addStoreFilter($magentoStoreId); + $this->mailchimpHelper->addResendFilter($collection, $magentoStoreId); $this->joinQtyAndBackorders($collection); @@ -387,7 +387,9 @@ public function getSyncdataTableName() */ protected function shouldSendProductUpdate($magentoStoreId, $product) { - return $product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId) && $product->getMailchimpSyncError() == ''; + $helper = $this->getMailChimpHelper(); + $resendTurn = $helper->getResendTurn($magentoStoreId); + return !$resendTurn && $product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId) && $product->getMailchimpSyncError() == ''; } /** @@ -447,7 +449,7 @@ protected function isConfigurableProduct($product) /** * @param $collection */ - protected function joinProductAttributes($collection) + public function joinProductAttributes($collection) { $attributeCodes = array("name", "visibility", "description", "price"); $config = Mage::getSingleton("eav/config"); @@ -470,7 +472,7 @@ protected function joinProductAttributes($collection) /** * @param $collection */ - protected function joinQtyAndBackorders($collection) + public function joinQtyAndBackorders($collection) { $collection->joinField( 'qty', 'cataloginventory/stock_item', 'qty', 'product_id=entity_id', @@ -484,30 +486,19 @@ protected function joinQtyAndBackorders($collection) } /** - * @param $mailchimpStoreId * @param $collection + * @param $mailchimpStoreId */ - protected function joinMailchimpSyncData($mailchimpStoreId, $collection) + protected function joinMailchimpSyncData($collection, $mailchimpStoreId) { - $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" - ) - ); + $this->joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId); $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1"); } /** * @param $collection */ - protected function joinCategoryId($collection) + public function joinCategoryId($collection) { $collection->joinField( 'category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, @@ -583,4 +574,24 @@ protected function getMailChimpHelper() { return $this->mailchimpHelper; } + + /** + * @param $collection + * @param $mailchimpStoreId + */ + public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId) + { + $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" + ) + ); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php index 350d40292..47831dfc3 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php @@ -39,6 +39,12 @@ class Ebizmarts_MailChimp_Model_Config const ECOMMERCE_CUSTOMERS_OPTIN = 'mailchimp/ecommerce/customers_optin'; const ECOMMERCE_FIRSTDATE = 'mailchimp/ecommerce/firstdate'; const ECOMMERCE_MC_JS_URL = 'mailchimp/ecommerce/mc_js_url'; + const ECOMMERCE_CUSTOMER_LAST_ID = 'mailchimp/ecommerce/customer_last_id'; + const ECOMMERCE_PRODUCT_LAST_ID = 'mailchimp/ecommerce/product_last_id'; + const ECOMMERCE_ORDER_LAST_ID = 'mailchimp/ecommerce/order_last_id'; + const ECOMMERCE_CART_LAST_ID = 'mailchimp/ecommerce/cart_last_id'; + const ECOMMERCE_RESEND_ENABLED = 'mailchimp/ecommerce/resend_enabled'; + const ECOMMERCE_RESEND_TURN = 'mailchimp/ecommerce/resend_turn'; const ENABLE_POPUP = 'mailchimp/emailcatcher/popup_general'; const POPUP_HEADING = 'mailchimp/emailcatcher/popup_heading'; 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 36679dc63..31cf63567 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 @@ -19,22 +19,24 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Account * @access protected * @var bool|array */ - protected $_accountDetails = false; + protected $accountDetails = false; + protected $helper; /** * Set AccountDetails on class property if not already set */ public function __construct() { - $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + $helper = $this->helper = $this->getHelper(); + $scopeArray = explode('-', $helper->getScopeString()); - $mcStoreId = (Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0])) ? Mage::helper('mailchimp')->getMCStoreId($scopeArray[1], $scopeArray[0]) : null; - $listId = Mage::helper('mailchimp')->getGeneralList($scopeArray[1], $scopeArray[0]); - $api = Mage::helper('mailchimp')->getApi($scopeArray[1], $scopeArray[0]); + $mcStoreId = ($helper->getMCStoreId($scopeArray[1], $scopeArray[0])) ? $helper->getMCStoreId($scopeArray[1], $scopeArray[0]) : null; + $listId = $helper->getGeneralList($scopeArray[1], $scopeArray[0]); + $api = $helper->getApi($scopeArray[1], $scopeArray[0]); if ($api) { try { $this->_accountDetails = $api->root->info('account_name,total_subscribers'); - if ($mcStoreId && Mage::helper('mailchimp')->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) { + if ($mcStoreId && $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $scopeArray[1], $scopeArray[0])) { try { $storeData = $api->ecommerce->stores->get($mcStoreId, 'name,is_syncing'); $this->_accountDetails['store_exists'] = true; @@ -49,10 +51,10 @@ public function __construct() $totalCarts = $api->ecommerce->carts->getAll($mcStoreId, 'total_items'); $this->_accountDetails['total_carts'] = $totalCarts['total_items']; } catch (MailChimp_Error $e) { - Mage::helper('mailchimp')->deleteLocalMCStoreData($scopeArray[1], $scopeArray[0]); + $helper->deleteLocalMCStoreData($scopeArray[1], $scopeArray[0]); if ($listId) { - Mage::helper('mailchimp')->createStore($listId, $scopeArray[1], $scopeArray[0]); - $message = Mage::helper('mailchimp')->__('Looks like your MailChimp store was deleted. A new one has been created.'); + $helper->createStore($listId, $scopeArray[1], $scopeArray[0]); + $message = $helper->__('Looks like your MailChimp store was deleted. A new one has been created.'); Mage::getSingleton('adminhtml/session')->addWarning($message); } @@ -63,7 +65,7 @@ public function __construct() } } catch (Exception $e) { $this->_accountDetails = "--- Invalid API Key ---"; - Mage::helper('mailchimp')->logError($e->getMessage(), $scopeArray[1]); + $helper->logError($e->getMessage(), $scopeArray[1]); } } } @@ -75,31 +77,32 @@ public function __construct() */ public function toOptionArray() { - $scopeArray = explode('-', Mage::helper('mailchimp')->getScopeString()); + $helper = $this->helper; + $scopeArray = explode('-', $helper->getScopeString()); if (is_array($this->_accountDetails)) { - $totalSubscribersText = Mage::helper('mailchimp')->__('Total subscribers:'); + $totalSubscribersText = $helper->__('Total subscribers:'); $totalSubscribers = $totalSubscribersText . ' ' . $this->_accountDetails['total_subscribers']; - $username = Mage::helper('mailchimp')->__('Username:') . ' ' . $this->_accountDetails['account_name']; + $username = $helper->__('Username:') . ' ' . $this->_accountDetails['account_name']; $returnArray = array( array('value' => 0, 'label' => $username), array('value' => 1, 'label' => $totalSubscribers) ); if ($this->_accountDetails['store_exists']) { - $totalCustomersText = Mage::helper('mailchimp')->__(' Total Customers:'); + $totalCustomersText = $helper->__(' Total Customers:'); $totalCustomers = $totalCustomersText . ' ' . $this->_accountDetails['total_customers']; - $totalProductsText = Mage::helper('mailchimp')->__(' Total Products:'); + $totalProductsText = $helper->__(' Total Products:'); $totalProducts = $totalProductsText . ' ' . $this->_accountDetails['total_products']; - $totalOrdersText = Mage::helper('mailchimp')->__(' Total Orders:'); + $totalOrdersText = $helper->__(' Total Orders:'); $totalOrders = $totalOrdersText . ' ' . $this->_accountDetails['total_orders']; - $totalCartsText = Mage::helper('mailchimp')->__(' Total Carts:'); + $totalCartsText = $helper->__(' 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']) { + $title = $helper->__('Ecommerce Data uploaded to MailChimp store ' . $this->_accountDetails['store_name'] . ':'); + if ($this->_accountDetails['store_sync_flag'] && !$helper->getResendEnabled($scopeArray[1], $scopeArray[0])) { $syncValue = 'In Progress'; } else { $syncValue = 'Finished'; } - $syncLabel = Mage::helper('mailchimp')->__('Initial sync: ' . $syncValue); + $syncLabel = $helper->__('Initial sync: ' . $syncValue); $returnArray = array_merge( $returnArray, array( @@ -111,9 +114,9 @@ public function toOptionArray() array('value' => 7, 'label' => $totalCarts) ) ); - } elseif (Mage::helper('mailchimp')->isEcomSyncDataEnabled($scopeArray[1], $scopeArray[0], true)) { - $noStoreText = Mage::helper('mailchimp')->__('No MailChimp store was created for this scope, parent scopes might be sending data for this store anyways.'); - $newStoreText = Mage::helper('mailchimp')->__('You can create a new MailChimp store for this scope by configuring a new list for this scope.'); + } elseif ($helper->isEcomSyncDataEnabled($scopeArray[1], $scopeArray[0], true)) { + $noStoreText = $helper->__('No MailChimp store was created for this scope, parent scopes might be sending data for this store anyways.'); + $newStoreText = $helper->__('You can create a new MailChimp store for this scope by configuring a new list for this scope.'); $returnArray = array_merge( $returnArray, array( @@ -123,8 +126,8 @@ public function toOptionArray() ); } - if (!Mage::helper('mailchimp')->migrationFinished() && Mage::helper('mailchimp')->isEcommerceEnabled($scopeArray[1], $scopeArray[0])) { - $storeMigrationText = Mage::helper('mailchimp')->__('The store data is currently being migrated to the new version. This process might take a while depending on the amount of data in Magento.'); + if (!$helper->migrationFinished() && $helper->isEcommerceEnabled($scopeArray[1], $scopeArray[0])) { + $storeMigrationText = $helper->__('The store data is currently being migrated to the new version. This process might take a while depending on the amount of data in Magento.'); $returnArray = array_merge( $returnArray, array( @@ -135,10 +138,15 @@ public function toOptionArray() return $returnArray; } elseif (!$this->_accountDetails) { - return array(array('value' => '', 'label' => Mage::helper('mailchimp')->__('--- Enter your API KEY first ---'))); + return array(array('value' => '', 'label' => $helper->__('--- Enter your API KEY first ---'))); } else { - return array(array('value' => '', 'label' => Mage::helper('mailchimp')->__($this->_accountDetails))); + return array(array('value' => '', 'label' => $helper->__($this->_accountDetails))); } } + protected function getHelper() + { + return Mage::helper('mailchimp'); + } + } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php index be1c1e936..a66565d1f 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php @@ -32,6 +32,7 @@ public function resetLocalErrorsAction() Mage::app()->getResponse()->setBody($result); } + public function resetEcommerceDataAction() { $param = Mage::app()->getRequest()->getParam('scope'); @@ -39,7 +40,25 @@ public function resetEcommerceDataAction() $result = 1; try { Mage::helper('mailchimp')->resetMCEcommerceData($scopeArray[1], $scopeArray[0], true); - Mage::helper('mailchimp')->resetErrors($scopeArray[1], $scopeArray[0]); + } + catch(MailChimp_Error $e) { + Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeArray[1], $scopeArray[0]); + $result = 0; + } + catch(Exception $e) { + Mage::helper('mailchimp')->logError($e->getMessage(), $scopeArray[1], $scopeArray[0]); + } + + Mage::app()->getResponse()->setBody($result); + } + + public function resendEcommerceDataAction() + { + $param = Mage::app()->getRequest()->getParam('scope'); + $scopeArray = explode('-', $param); + $result = 1; + try { + Mage::helper('mailchimp')->resetMCEcommerceData($scopeArray[1], $scopeArray[0], false); } catch(MailChimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage(), $scopeArray[1], $scopeArray[0]); @@ -76,6 +95,7 @@ protected function _isAllowed() switch ($this->getRequest()->getActionName()) { case 'resetLocalErrors': case 'resetEcommerceData': + case 'resendEcommerceData': case 'createMergeFields': $acl = 'system/config/mailchimp'; break; diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 3a92dc9cb..8d796d383 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -152,7 +152,7 @@ 1 1 1 - + @@ -223,7 +223,7 @@ 1 1 1 - + 1 @@ -239,6 +239,18 @@ 1 + + button + mailchimp/adminhtml_system_config_resendEcommerceData + 230 + 1 + 1 + 1 + + + 1 + + diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resendecommercedata.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resendecommercedata.phtml new file mode 100644 index 000000000..42ebcdbee --- /dev/null +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/resendecommercedata.phtml @@ -0,0 +1,25 @@ + + +getButtonHtml(); ?> \ No newline at end of file From a930493eaa3caabb4bb4b68dc173f482b79ab5fc Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 28 Jul 2017 17:12:35 -0300 Subject: [PATCH 02/42] Added else when no items in any of the tables. --- app/code/community/Ebizmarts/MailChimp/Helper/Data.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index ab441c4ae..97726e8f8 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -2087,14 +2087,20 @@ protected function allResendItemsSentPerStoreView($storeId) $customerId = $this->getCustomerResendLastId($storeId); if ($customerId) { $isMissingCustomer = $this->isMissingItemLowerThanId($customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $storeId); + } else { + $isMissingCustomer = false; } $productId = $this->getProductResendLastId($storeId); if ($productId) { $isMissingProduct = $this->isMissingItemLowerThanId($productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $storeId); + } else { + $isMissingProduct = false; } $orderId = $this->getOrderResendLastId($storeId); if ($orderId) { $isMissingOrder = $this->isMissingItemLowerThanId($orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $storeId); + } else { + $isMissingOrder = false; } $cartId = $this->getCartResendLastId($storeId); if ($cartId) { From 56f1292dee0d8ac0ede8154fadcc642496df4afe Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 31 Jul 2017 16:29:18 -0300 Subject: [PATCH 03/42] Fix added when resend is triggered before the initial sync finishes. --- .../Ebizmarts/MailChimp/Helper/Data.php | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 97726e8f8..e8e729ecb 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -1479,10 +1479,15 @@ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initi */ public function timePassed($initialTime) { + $storeCount = count(Mage::app()->getStores()); $timePassed = false; $finalTime = time(); $difference = $finalTime - $initialTime; - if ($difference > 270) { + //Set minimum of 30 seconds per store view. + $timeForAllStores = (30 * $storeCount); + //Set total time in 4:30 minutes if it is lower. + $timeAmount = ($timeForAllStores < 270) ? 270 : $timeForAllStores; + if ($difference > $timeAmount) { $timePassed = true; } return $timePassed; @@ -1495,28 +1500,28 @@ public function timePassed($initialTime) */ protected function _migrateFrom116($initialTime) { - //poner isSyncing en true y mostrar cartel en la configuracion que diga que la store esta sincronizando due to first time installation or migration of data due to module update. - $this->_setIsSyncingInAllStores(true); + $this->_setIsSyncingIfFinishedInAllStores(true); $finished = $this->_migrateOrdersFrom116($initialTime); if ($finished) { - $this->_setIsSyncingInAllStores(false); + $this->_setIsSyncingIfFinishedInAllStores(false); $this->delete116MigrationConfigData(); } } /** - * Modify is_syncing value for all stores. + * Modify is_syncing value if initial sync finished for all stores. * * @param $syncValue */ - protected function _setIsSyncingInAllStores($syncValue) + protected function _setIsSyncingIfFinishedInAllStores($syncValue) { $stores = Mage::app()->getStores(); foreach ($stores as $storeId => $store) { - $this->setIsSyncingPerStore($syncValue, $storeId); + $this->setIsSyncingIfFinishedPerStore($syncValue, $storeId); } } + /** * Update Order ids to the Increment id in MailChimp. * @@ -1947,14 +1952,17 @@ public function isCheckoutSubscribeEnabled($scopeId, $scope = 'stores') } /** + * Modify is_syncing value if initial sync finished in given store. + * * @param $syncValue * @param $storeId */ - public function setIsSyncingPerStore($syncValue, $storeId) + public function setIsSyncingIfFinishedPerStore($syncValue, $storeId) { + $isSyncing = $this->getMCIsSyncing($storeId); $mailchimpApi = $this->getApi($storeId); $mailchimpStoreId = $this->getMCStoreId($storeId); - if ($mailchimpStoreId) { + if ($mailchimpStoreId && !$isSyncing) { $this->getApiStores()->editIsSyncing($mailchimpApi, $syncValue, $mailchimpStoreId, $storeId); } } @@ -2055,7 +2063,7 @@ public function handleResendDataBefore($storeId) $resendEnabled = $this->getResendEnabled($storeId); $resendTurn = $this->getResendTurn($storeId); if ($resendEnabled && $resendTurn) { - $this->setIsSyncingPerStore(true, $storeId); + $this->setIsSyncingIfFinishedPerStore(true, $storeId); } } @@ -2069,7 +2077,7 @@ public function handleResendDataAfter($storeId) if ($resendEnabled) { $configScope = $this->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $storeId); if ($resendTurn) { - $this->setIsSyncingPerStore(false, $storeId); + $this->setIsSyncingIfFinishedPerStore(false, $storeId); $this->setResendTurn(0, $configScope['scope_id'], $configScope['scope']); } else { $this->setResendTurn(1, $configScope['scope_id'], $configScope['scope']); @@ -2223,9 +2231,9 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) $quoteCollection = Mage::getResourceModel('sales/order_collection') ->addFieldToFilter('store_id', array('eq' => $storeId)) ->addFieldToFilter('entity_id', array('lteq' => $itemId)) - ->addFieldToFilter('is_active', array('eq'=>1)) - ->addFieldToFilter('customer_email', array('notnull'=>true)) - ->addFieldToFilter('items_count', array('gt'=>0)); + ->addFieldToFilter('is_active', array('eq' => 1)) + ->addFieldToFilter('customer_email', array('notnull' => true)) + ->addFieldToFilter('items_count', array('gt' => 0)); $firstDate = $this->getAbandonedCartFirstDate($storeId); if ($firstDate) { $quoteCollection->addFieldToFilter('updated_at', array('gt' => $firstDate)); From 7487da6cb7d0e9bb2c42ef02a9fb5076dbc01c80 Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 31 Jul 2017 16:29:33 -0300 Subject: [PATCH 04/42] Added tests. --- .../Ebizmarts/MailChimp/Helper/DataTest.php | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) 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 33cfbd922..d4784043f 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php @@ -84,4 +84,85 @@ public function testDeleteStore() $helperMock->deleteStore($scopeId, $scope); } + + public function testaddResendFilter() + { + $storeId = 1; + /** + * @var \Ebizmarts_MailChimp_Helper_Data $helperMock + */ + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getResendEnabled', 'getResendTurn', 'getOrderResendLastId')) + ->getMock(); + + $helperMock->expects($this->once())->method('getResendEnabled')->with($storeId)->willReturn(1); + $helperMock->expects($this->once())->method('getResendTurn')->with($storeId)->willReturn(1); + $helperMock->expects($this->once())->method('getOrderResendLastId')->with($storeId); + + $collection = Mage::getResourceModel('sales/order_collection'); + $helperMock->addResendFilter($collection, $storeId); + } + + public function testHandleResendFinish() + { + $scopeId = 1; + $scope = 'stores'; + /** + * @var \Ebizmarts_MailChimp_Helper_Data $helperMock + */ + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('allResendItemsSent', 'deleteResendConfigValues')) + ->getMock(); + + $helperMock->expects($this->once())->method('allResendItemsSent')->with($scopeId, $scope)->willReturn(1); + $helperMock->expects($this->once())->method('deleteResendConfigValues')->with($scopeId, $scope); + + $helperMock->handleResendFinish($scopeId, $scope); + } + + public function testHandleResendDataBefore() + { + $storeId = 1; + + /** + * @var \Ebizmarts_MailChimp_Helper_Data $helperMock + */ + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getResendEnabled', 'getResendTurn', 'setIsSyncingIfFinishedPerStore')) + ->getMock(); + + $helperMock->expects($this->once())->method('getResendEnabled')->with($storeId)->willReturn(1); + $helperMock->expects($this->once())->method('getResendTurn')->with($storeId)->willReturn(1); + $helperMock->expects($this->once())->method('setIsSyncingIfFinishedPerStore')->with($storeId); + + $helperMock->handleResendDataBefore($storeId); + } + + public function testHandleResendDataAfter() + { + $storeId = 1; + $scopeArray = array('scope_id' => 1, 'scope' => 'stores'); + + /** + * @var \Ebizmarts_MailChimp_Helper_Data $helperMock + */ + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getResendEnabled', 'getResendTurn', 'getRealScopeForConfig', 'setIsSyncingIfFinishedPerStore', 'setResendTurn', 'handleResendFinish')) + ->getMock(); + + $helperMock->expects($this->once())->method('getResendEnabled')->with($storeId)->willReturn(1); + $helperMock->expects($this->once())->method('getResendTurn')->with($storeId)->willReturn(1); + $helperMock->expects($this->once())->method('getRealScopeForConfig')->with(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, $storeId)->willReturn($scopeArray); + $helperMock->expects($this->once())->method('setIsSyncingIfFinishedPerStore')->with(false, $storeId); + $helperMock->expects($this->once())->method('setResendTurn')->with(0, $scopeArray['scope_id'], $scopeArray['scope']); + $helperMock->expects($this->once())->method('handleResendFinish')->with($scopeArray['scope_id'], $scopeArray['scope']); + + $helperMock->handleResendDataAfter($storeId); + } + + } \ No newline at end of file From 16ad43c63c606c7581a0cb5f26844538f7eccc9f Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 1 Aug 2017 10:57:02 -0300 Subject: [PATCH 05/42] Using order collection mock in stead of regular order collection. --- .../tests/app/Ebizmarts/MailChimp/Helper/DataTest.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 d4784043f..3f6bb3f49 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php @@ -85,7 +85,7 @@ public function testDeleteStore() $helperMock->deleteStore($scopeId, $scope); } - public function testaddResendFilter() + public function testAddResendFilter() { $storeId = 1; /** @@ -96,12 +96,15 @@ public function testaddResendFilter() ->setMethods(array('getResendEnabled', 'getResendTurn', 'getOrderResendLastId')) ->getMock(); + $orderCollectionMock = $this->getMockBuilder(Mage_Sales_Model_Resource_Order_Collection::class) + ->disableOriginalConstructor() + ->getMock(); + $helperMock->expects($this->once())->method('getResendEnabled')->with($storeId)->willReturn(1); $helperMock->expects($this->once())->method('getResendTurn')->with($storeId)->willReturn(1); $helperMock->expects($this->once())->method('getOrderResendLastId')->with($storeId); - $collection = Mage::getResourceModel('sales/order_collection'); - $helperMock->addResendFilter($collection, $storeId); + $helperMock->addResendFilter($orderCollectionMock, $storeId); } public function testHandleResendFinish() From 3162df326c685af48079a2d9d67b86aef07c99f8 Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 1 Aug 2017 11:21:59 -0300 Subject: [PATCH 06/42] Rename MailChimp_Requests.log file to MailChimp_Failing_Requests.log --- app/code/community/Ebizmarts/MailChimp/Helper/Data.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 71b19dc30..57c7e4a4e 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -478,7 +478,7 @@ public function logRequest($message, $scopeId, $batchId = null) { if ($this->getLogsEnabled($scopeId)) { if (!$batchId) { - Mage::log($message, null, 'MailChimp_Requests.log', true); + Mage::log($message, null, 'MailChimp_Failing_Requests.log', true); } else { $logDir = Mage::getBaseDir('var') . DS . 'log'; if (!file_exists($logDir)) { From 26813c0fc2c90368dd9c1e9aebc1579a1037bdb0 Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 1 Aug 2017 11:23:16 -0300 Subject: [PATCH 07/42] Saving subscriber failing requests. --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 21 ++++++++++++------- .../MailChimp/Model/Api/Subscribers.php | 2 +- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 3b725bf95..2a431adb9 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -335,9 +335,10 @@ protected function _sendSubscriberBatches() public function sendStoreSubscriberBatch($storeId, $limit) { try { + $helper = $this->getHelper(); $subscribersArray = array(); - if ($this->getHelper()->isMailChimpEnabled($storeId)) { - $listId = $this->getHelper()->getGeneralList($storeId); + if ($helper->isMailChimpEnabled($storeId)) { + $listId = $helper->getGeneralList($storeId); $batchArray = array(); @@ -351,11 +352,15 @@ public function sendStoreSubscriberBatch($storeId, $limit) if (!empty($batchArray['operations'])) { $batchJson = json_encode($batchArray); if (!$batchJson || $batchJson == '') { - $this->getHelper()->logRequest('An empty operation was detected', $storeId); + $helper->logRequest('An empty operation was detected', $storeId); } else { - $mailchimpApi = $this->getHelper()->getApi($storeId); - $batchResponse = $mailchimpApi->batchOperation->add($batchJson); - $this->getHelper()->logRequest($batchJson, $storeId, $batchResponse['id']); + try { + $mailchimpApi = $helper->getApi($storeId); + $batchResponse = $mailchimpApi->batchOperation->add($batchJson); + $helper->logRequest($batchJson, $storeId, $batchResponse['id']); + } catch (MailChimp_Error $e) { + $helper->logRequest($batchJson, $storeId); + } //save batch id to db $batch = Mage::getModel('mailchimp/synchbatches'); @@ -367,9 +372,9 @@ public function sendStoreSubscriberBatch($storeId, $limit) } } } catch (MailChimp_Error $e) { - $this->getHelper()->logError($e->getFriendlyMessage(), $storeId); + $helper->logError($e->getFriendlyMessage(), $storeId); } catch (Exception $e) { - $this->getHelper()->logError($e->getMessage(), $storeId); + $helper->logError($e->getMessage(), $storeId); } return array(null, $limit); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 96c70a249..128e9f981 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -23,7 +23,7 @@ public function __construct() public function createBatchJson($listId, $storeId, $limit) { $helper = $this->mcHelper; - $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $storeId);; + $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $storeId); $moduleIsActive = $helper->isMailChimpEnabled($storeId); $subscriberArray = array(); From b90c549b8394223e298c7d2b99cc4ea565710fcc Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 2 Aug 2017 15:24:01 -0300 Subject: [PATCH 08/42] Send product data for the correct store view. resolves #421 --- .../Ebizmarts/MailChimp/Helper/Data.php | 2 +- .../MailChimp/Model/Api/Products.php | 40 ++++++++++--------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 71b19dc30..a832e9706 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -513,7 +513,7 @@ public function getWebhooksKey() * @param $scopeId * @param $scope */ - public function resetErrors($scopeId, $scope) + public function resetErrors($scopeId, $scope = 'stores') { // reset subscribers with errors $collection = Mage::getResourceModel('newsletter/subscriber_collection') diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index f17b61ce4..33a114329 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -126,8 +126,8 @@ 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')->getEcommMinSyncDateFlag($magentoStoreId) && $productSyncData->getMailchimpSyncError() == '') { + $parentSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($parentId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); + if ($parentSyncData->getMailchimpSyncDelta() && $parentSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId) && $parentSyncData->getMailchimpSyncError() == '') { $variendata = array(); $variendata["id"] = $data["id"]; $variendata["title"] = $data["title"]; @@ -172,7 +172,7 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar //data applied for both root and varient products $data["id"] = $product->getId(); - $data["title"] = $product->getName(); + $data["title"] = ($product->getName()) ? $product->getName() : $product->getDefaultName(); $data["url"] = $product->getProductUrl(); //image @@ -188,8 +188,8 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar $data += $this->getProductVariantData($product); } else { //this is for a root product - if ($product->getDescription()) { - $data["description"] = $product->getDescription(); + if ($product->getDescription() || $product->getDefaultDescription()) { + $data["description"] = ($product->getDescription()) ? $product->getDescription() : $product->getDefaultDescription(); } //mailchimp product type (magento category) @@ -355,14 +355,13 @@ public function makeProductsNotSentCollection($magentoStoreId) * @var Mage_Catalog_Model_Resource_Product_Collection $collection */ $collection = $this->getProductResourceCollection(); - $collection->addStoreFilter($magentoStoreId); $this->joinQtyAndBackorders($collection); $this->joinCategoryId($collection); - $this->joinProductAttributes($collection); + $this->joinProductAttributes($collection, $magentoStoreId); $collection->getSelect()->group("e.entity_id"); $collection->getSelect()->limit(self::BATCH_LIMIT); @@ -446,23 +445,25 @@ protected function isConfigurableProduct($product) /** * @param $collection + * @param $magentoStoreId */ - protected function joinProductAttributes($collection) + protected function joinProductAttributes($collection, $magentoStoreId) { $attributeCodes = array("name", "visibility", "description", "price"); $config = Mage::getSingleton("eav/config"); foreach ($attributeCodes as $_code) { $attributeName = $config->getAttribute("catalog_product", $_code); - $attribteTableName = "product_attribute_" . $_code; + if ($_code != 'price') { + $collection->joinField( + $_code, $attributeName->getBackendTable(), 'value', 'entity_id = entity_id', + '{{table}}.store_id = ' . $magentoStoreId . ' AND {{table}}.attribute_id = ' . $attributeName->getId(), 'left' + ); + } - $collection->getSelect()->join( - array($attribteTableName => $attributeName->getBackendTable()), - 'e.entity_id = ' . $attribteTableName . '.entity_id', - array('value AS ' . $_code) - )->where( - $attribteTableName . ".attribute_id = ?", - $attributeName->getId() + $collection->joinField( + 'default_' . $_code, $attributeName->getBackendTable(), 'value', 'entity_id = entity_id', + '{{table}}.store_id = 0 AND {{table}}.attribute_id = ' . $attributeName->getId(), 'left' ); } } @@ -522,15 +523,16 @@ protected function joinCategoryId($collection) protected function getProductVariantData($product) { $data = array(); - $data["sku"] = $product->getSku(); - $data["price"] = (float)$product->getPrice(); + $data["sku"] = $product->getSku(); + $data["price"] = $product->getDefaultPrice(); //stock $data["inventory_quantity"] = (int)$product->getQty(); $data["backorders"] = (string)$product->getBackorders(); - $data["visibility"] = $this->visibilityOptions[$product->getVisibility()]; + $visibility = ($product->getVisibility()) ? $product->getVisibility() : $product->getDefaultVisibility(); + $data["visibility"] = $this->visibilityOptions[$visibility]; return $data; } From ae8cefdcef7bc792bd7a66c91f975729b642ee61 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 2 Aug 2017 16:45:05 -0300 Subject: [PATCH 09/42] Do not send address values that does not exist. --- .../MailChimp/Model/Api/Subscribers.php | 51 +++++++++++++++---- 1 file changed, 40 insertions(+), 11 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 96c70a249..42f3971bb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -137,17 +137,9 @@ public function getMergeVars($subscriber) 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() : "" - ); + $addressData = $this->getAddressData($address); + if (count($addressData)) { + $eventValue = $mergeVars[$key] = $addressData; } break; case 'gender': @@ -473,4 +465,41 @@ public function update($emailAddress, $storeId) ->save(); } } + + /** + * @param $address + * @return array + */ + protected function getAddressData($address) + { + $addressData = array(); + if ($address) { + $street = $address->getStreet(); + if (count($street) > 1) { + $addressData["address1"] = $street[0]; + $addressData["address2"] = $street[1]; + } else { + if (!empty($street[0])) { + $addressData["address1"] = $street[0]; + } + } + + if ($address->getCity()) { + $addressData["city"] = $address->getCity(); + } + + if ($address->getRegion()) { + $addressData["state"] = $address->getRegion(); + } + + if ($address->getPostcode()) { + $addressData["zip"] = $address->getPostcode(); + } + + if ($address->getCountry()) { + $addressData["country"] = Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName(); + } + } + return $addressData; + } } From fa06cf31deb6741278a0563e73953f0b6833d9c1 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 2 Aug 2017 16:51:13 -0300 Subject: [PATCH 10/42] Fix test. --- .../app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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 7d727dff8..ba3a767c8 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 @@ -93,8 +93,10 @@ private function productCollection() "getId", "getTypeId", "getName", + "getDefaultName", "getProductUrl", "getDescription", + "getDefaultDescription", "getCategoryId", ) ) @@ -102,10 +104,12 @@ private function productCollection() $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(3))->method('getTypeId')->willReturn("configurable"); + $productMock->expects($this->exactly(2))->method('getName')->willReturn(null); + $productMock->expects($this->exactly(2))->method('getDefaultName')->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->exactly(2))->method('getDescription')->willReturn(null); + $productMock->expects($this->exactly(2))->method('getDefaultDescription')->willReturn("Lorem ipsum dolor sit amet. LONG"); $productMock->expects($this->once())->method('getCategoryId')->willReturn(null); $products []= $productMock; From bcc36fa2af0365cb1181f9b0407f62868ee070bf Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 3 Aug 2017 17:17:41 -0300 Subject: [PATCH 11/42] Fix price for configurable products (should show parent price). resolves #370 Fix update product to update parent as well. resolves #363 --- .../MailChimp/Model/Api/Products.php | 137 ++++++++++++------ 1 file changed, 89 insertions(+), 48 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 46675a42c..2b94245d0 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -13,6 +13,7 @@ class Ebizmarts_MailChimp_Model_Api_Products { const BATCH_LIMIT = 100; private $_parentImageUrl = null; + private $_parentPrice = null; /** @var Mage_Catalog_Model_Product_Type_Configurable */ private $productTypeConfigurable; @@ -45,6 +46,7 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) foreach ($collection as $product) { if ($product->getMailchimpSyncDeleted()) { $batchArray = array_merge($this->buildProductDataRemoval($product, $batchId, $mailchimpStoreId, $magentoStoreId), $batchArray); + $counter = count($batchArray); } if ($this->shouldSendProductUpdate($magentoStoreId, $product)) { @@ -87,7 +89,6 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId } } else if ($this->isVirtualProduct($product) || $this->isDownloadableProduct($product)) { - $variantProducts = array(); $variantProducts[] = $product; } else { //@TODO bundle @@ -113,58 +114,90 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) { - $operations = array(); + $variantProducts = array(); if ($this->isSimpleProduct($product) || $this->isVirtualProduct($product) || $this->isDownloadableProduct($product)) { - $data = $this->_buildProductData($product); - + $variantProducts[] = $product; $parentIds = $this->productTypeConfigurableResource->getParentIdsByChild($product->getId()); + foreach ($parentIds as $parentId) { + $parent = Mage::getModel('catalog/product')->load($parentId); + $variantProducts[] = $parent; - if (empty($parentIds)) { - $parentIds = array($product->getId()); - } + $collection = $this->makeProductChildrenCollection($magentoStoreId); - //add or update variant - foreach ($parentIds as $parentId) { - $parentSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($parentId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId); - if ($parentSyncData->getMailchimpSyncDelta() && $parentSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId) && $parentSyncData->getMailchimpSyncError() == '') { - $variendata = array(); - $variendata["id"] = $data["id"]; - $variendata["title"] = $data["title"]; - $variendata["url"] = $data["url"]; - $variendata["sku"] = $data["sku"]; - $variendata["price"] = $data["price"]; - $variendata["inventory_quantity"] = $data["inventory_quantity"]; - $this->_parentImageUrl = Mage::helper('mailchimp')->getImageUrlById($parentId); - $dataImageUrl = (isset($data["image_url"])) ? $data["image_url"] : null; - $imageUrl = Mage::helper('mailchimp')->getMailChimpProductImageUrl($this->_parentImageUrl, $dataImageUrl); - if ($imageUrl) { - $variendata["image_url"] = $imageUrl; - } + $childProducts = $this->getConfigurableChildrenIds($parent); + $collection->addAttributeToFilter("entity_id", array("in" => $childProducts)); - $this->_parentImageUrl = null; - $variendata["backorders"] = $data["backorders"]; - $variendata["visibility"] = $data["visibility"]; - $productdata = array(); - $productdata['method'] = "PUT"; - $productdata['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/" . $parentId . '/variants/' . $data['id']; - $productdata['operation_id'] = $batchId . '_' . $parentId; - try { - $body = json_encode($variendata); - } catch (Exception $e) { - //json encode failed - Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId); - continue; + foreach ($collection as $childProduct) { + if ($childProduct->getId() != $product->getId()) { + $variantProducts[] = $childProduct; } + } + $bodyData = $this->_buildProductData($parent, false, $variantProducts); + try { + $body = json_encode($bodyData); + } catch (Exception $e) { + //json encode failed + $this->getMailChimpHelper()->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId); + return array(); + } - $productdata['body'] = $body; - $operations[] = $productdata; + $data = array(); + $data['method'] = "PATCH"; + $data['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/" . $parent->getId(); + $data['operation_id'] = $batchId . '_' . $parent->getId(); + $data['body'] = $body; + $operations[] = $data; + } + + } else if ($this->isConfigurableProduct($product)) { + $variantProducts[] = $product; + + $collection = $this->makeProductChildrenCollection($magentoStoreId); + + $childProducts = $this->getConfigurableChildrenIds($product); + $collection->addAttributeToFilter("entity_id", array("in" => $childProducts)); + + foreach ($collection as $childProduct) { + if ($childProduct->getId() != $product->getId()) { + $variantProducts[] = $childProduct; } } + } else { + //@TODO bundle + return array(); + } + $bodyData = $this->_buildProductData($product, false, $variantProducts); + try { + $body = json_encode($bodyData); + } catch (Exception $e) { + //json encode failed + $this->getMailChimpHelper()->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId); + return array(); } + $data = array(); + $data['method'] = "PATCH"; + $data['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/" . $product->getId(); + $data['operation_id'] = $batchId . '_' . $product->getId(); + $data['body'] = $body; + $operations[] = $data; return $operations; } + protected function getParentData($productId, $magentoStoreId) + { + $product = Mage::getModel('catalog/product')->load($productId); + $data = $this->_buildProductData($product, false); + $data['variants'][] = array('id' => $productId); + try { + $body = json_encode($data); + } catch (Exception $e) { + //json encode failed + Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed", $magentoStoreId); + } + return $body; + } + protected function _buildProductData($product, $isVariant = true, $variants = array()) { $data = array(); @@ -203,16 +236,23 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar $data["handle"] = ""; //variants - $data["variants"] = array(); - if (isset($data["image_url"])) { - $this->_parentImageUrl = $data["image_url"]; - } + if (count($variants)) { + $data["variants"] = array(); + if (isset($data["image_url"])) { + $this->_parentImageUrl = $data["image_url"]; + } + $price = (float)$product->getDefaultPrice(); + if ($price) { + $this->_parentPrice = $price; + } - foreach ($variants as $variant) { - $data["variants"][] = $this->_buildProductData($variant); - } + foreach ($variants as $variant) { + $data["variants"][] = $this->_buildProductData($variant); + } - $this->_parentImageUrl = null; + $this->_parentImageUrl = null; + $this->_parentPrice = null; + } } return $data; } @@ -515,7 +555,8 @@ protected function getProductVariantData($product) { $data = array(); $data["sku"] = $product->getSku(); - $data["price"] = $product->getDefaultPrice(); + + $data["price"] = (float)$this->_parentPrice; //stock $data["inventory_quantity"] = (int)$product->getQty(); From 8b9d2e40b13e7447a37a2b27dc3df9188b898df3 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 10:08:31 -0300 Subject: [PATCH 12/42] Removed extra if in error handling. --- app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 8e055a2c8..dcbb0a27c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -475,9 +475,6 @@ 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); @@ -564,7 +561,7 @@ protected function saveSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelt $syncModified = 0, $syncDeleted = null, $token = null, $saveOnlyIfexists = false) { $helper = $this->getHelper(); - if ($itemType == 'SUB') { + if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER) { $helper->updateSubscriberSyndData($itemId, $syncDelta, $syncError, 0, null); } else { $helper->saveEcommerceSyncData($itemId, $itemType, $mailchimpStoreId, $syncDelta, $syncError, $syncModified, $syncDeleted, $token, $saveOnlyIfexists); From b44826d0d9c8c2ce189c2323eec5f1dae5c97005 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 10:54:42 -0300 Subject: [PATCH 13/42] Fix for Sync Batches table with no batch id. resolves #404 --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 8e055a2c8..0196ed0e4 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -362,17 +362,17 @@ public function sendStoreSubscriberBatch($storeId, $limit) $mailchimpApi = $helper->getApi($storeId); $batchResponse = $mailchimpApi->batchOperation->add($batchJson); $helper->logRequest($batchJson, $storeId, $batchResponse['id']); + + //save batch id to db + $batch = Mage::getModel('mailchimp/synchbatches'); + $batch->setStoreId($storeId) + ->setBatchId($batchResponse['id']) + ->setStatus($batchResponse['status']); + $batch->save(); + return array($batchResponse, $limit); } catch (MailChimp_Error $e) { $helper->logRequest($batchJson, $storeId); } - - //save batch id to db - $batch = Mage::getModel('mailchimp/synchbatches'); - $batch->setStoreId($storeId) - ->setBatchId($batchResponse['id']) - ->setStatus($batchResponse['status']); - $batch->save(); - return array($batchResponse, $limit); } } } catch (MailChimp_Error $e) { From a855323be4c8223838d15b7567617d125a021035 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 11:00:25 -0300 Subject: [PATCH 14/42] initialize helper correctly. --- app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 0196ed0e4..e810c3bca 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -338,8 +338,8 @@ protected function _sendSubscriberBatches() */ public function sendStoreSubscriberBatch($storeId, $limit) { + $helper = $this->getHelper(); try { - $helper = $this->getHelper(); $subscribersArray = array(); if ($helper->isMailChimpEnabled($storeId)) { $listId = $helper->getGeneralList($storeId); From 82e2bd5f7661b3f909c7eeeac27d074ab679c64f Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 13:38:42 -0300 Subject: [PATCH 15/42] Showing campaign names as well as id in order view. resolves #416 --- .../Sales/Order/View/Info/Monkey.php | 29 ++++++- .../Ebizmarts/MailChimp/Helper/Data.php | 20 +++++ .../mailchimp/sales/order/view/monkey.phtml | 2 +- lib/Ebizmarts/MailChimp/Automation.php | 32 ++++++++ lib/Ebizmarts/MailChimp/Campaigns.php | 55 +++++++++++++ lib/Ebizmarts/MailChimp/Lists.php | 80 ++++++++++--------- 6 files changed, 178 insertions(+), 40 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php index 691433d58..0d702b2b8 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/Monkey.php @@ -14,7 +14,7 @@ class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey extends M { public function isReferred() { - $order = Mage::registry('current_order'); + $order = $this->getCurrentOrder(); $ret = false; if ($order->getMailchimpAbandonedcartFlag() || $order->getMailchimpCampaignId()) { $ret = true; @@ -22,9 +22,32 @@ public function isReferred() return $ret; } - public function getCampaign() + + public function getCampaignId() { - $order = Mage::registry('current_order'); + $order = $this->getCurrentOrder(); return $order->getMailchimpCampaignId(); } + + public function addCampaignName() + { + $helper = $this->getMailChimpHelper(); + $campaignId = $this->getCampaignId(); + $order = $this->getCurrentOrder(); + $campaignName = $helper->getMailChimpCampaignNameById($campaignId, $order->getStoreId()); + return $campaignName; + } + + protected function getMailChimpHelper() + { + return Mage::helper('mailchimp'); + } + + /** + * @return mixed + */ + protected function getCurrentOrder() + { + return Mage::registry('current_order'); + } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index f8b2b41fd..4fca0098d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -2247,4 +2247,24 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) } return $isMissing; } + + public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'stores') + { + $campaignName = null; + try { + $api = $this->getApi($scopeId, $scope); + $campaignData = $api->campaigns->get($campaignId); + if (isset($campaignData['settings'])) { + if (isset($campaignData['settings']['title'])) { + $campaignName = $campaignData['settings']['title']; + } + if ($campaignName == '' && isset($campaignData['settings']['subject_line'])) { + $campaignName = $campaignData['settings']['subject_line']; + } + } + } catch (MailChimp_Error $e) { + $this->logError($e->getFriendlyMessage()); + } + return $campaignName; + } } diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/sales/order/view/monkey.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/sales/order/view/monkey.phtml index de1e8663c..86e7e1f7c 100644 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/sales/order/view/monkey.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/sales/order/view/monkey.phtml @@ -11,7 +11,7 @@ - Yaay! Recovered by MailChimp's e-commerce automation, Campaign Id: getCampaign() ?> + __("Yaay! Recovered by MailChimp's campaign.") . "
" . $this->__("Name") . ": " . $this->addCampaignName() . "
" . $this->__("Id") . ": " . $this->getCampaignId() ?>
diff --git a/lib/Ebizmarts/MailChimp/Automation.php b/lib/Ebizmarts/MailChimp/Automation.php index ec0789486..ff2dea833 100644 --- a/lib/Ebizmarts/MailChimp/Automation.php +++ b/lib/Ebizmarts/MailChimp/Automation.php @@ -16,4 +16,36 @@ class MailChimp_Automation extends MailChimp_Abstract * @var MailChimp_AutomationEmails */ public $emails; + + public function get($id = null, $fields = null, $excludeFields = null, $status = null, $beforeSendTime = null, + $sinceSendTime = null, $beforeCreateTime = null, $sinceCreateTime = null) + { + $_params = array(); + if ($fields) { + $_params['fields'] = $fields; + } + if ($excludeFields) { + $_params['exclude_fields'] = $excludeFields; + } + if ($status) { + $_params['status'] = $status; + } + if ($beforeSendTime) { + $_params['before_send_time'] = $beforeSendTime; + } + if ($sinceSendTime) { + $_params['since_send_time'] = $sinceSendTime; + } + if ($beforeCreateTime) { + $_params['before_create_time'] = $beforeCreateTime; + } + if ($sinceCreateTime) { + $_params['since_create_time'] = $sinceCreateTime; + } + if ($id) { + return $this->_master->call('automations/' . $id, $_params, Ebizmarts_MailChimp::GET); + } else { + return $this->_master->call('automations', $_params, Ebizmarts_MailChimp::GET); + } + } } \ No newline at end of file diff --git a/lib/Ebizmarts/MailChimp/Campaigns.php b/lib/Ebizmarts/MailChimp/Campaigns.php index 7ebff6606..bd402c985 100644 --- a/lib/Ebizmarts/MailChimp/Campaigns.php +++ b/lib/Ebizmarts/MailChimp/Campaigns.php @@ -1,4 +1,5 @@ _master->call('campaigns/' . $id, $_params, Ebizmarts_MailChimp::GET); + } else { + return $this->_master->call('campaigns', $_params, Ebizmarts_MailChimp::GET); + } + } } \ No newline at end of file diff --git a/lib/Ebizmarts/MailChimp/Lists.php b/lib/Ebizmarts/MailChimp/Lists.php index d3429d9fa..c0ad683d1 100644 --- a/lib/Ebizmarts/MailChimp/Lists.php +++ b/lib/Ebizmarts/MailChimp/Lists.php @@ -1,4 +1,5 @@ $name, 'contact'=>$contact, 'permission_remainder'=>$permissionRemanider, - 'use_archive_bar'=>$useArchiveBar, 'campaignDefaults'=>$campaingDefaults, - 'notify_on_subscribe'=>$notifyOnSubscribe, 'notify_on_unsubscribe'=>$notifyOnUnsubscribe, - 'email_type_option'=>$emailTypeOption, 'visibility'=>$visibility); + $emailTypeOption, $useArchiveBar = false, $notifyOnSubscribe = false, $visibility = 'pub' + ) + { + + $_params = array('name' => $name, 'contact' => $contact, 'permission_remainder' => $permissionRemanider, + 'use_archive_bar' => $useArchiveBar, 'campaignDefaults' => $campaingDefaults, + 'notify_on_subscribe' => $notifyOnSubscribe, 'notify_on_unsubscribe' => $notifyOnUnsubscribe, + 'email_type_option' => $emailTypeOption, 'visibility' => $visibility); return $this->_master->call('lists', $_params, Ebizmarts_MailChimp::POST); } - - public function getLists($id=null, $fields=null, $excludeFields=null, $count=null, $offset=null, - $beforeDateCreated=null, $sinceDateCreated=null, $beforeCampaignLastSent=null, - $sinceCampaignLastSent=null,$email=null - ) { - + + public function getLists($id = null, $fields = null, $excludeFields = null, $count = null, $offset = null, + $beforeDateCreated = null, $sinceDateCreated = null, $beforeCampaignLastSent = null, + $sinceCampaignLastSent = null, $email = null + ) + { + $_params = array(); if ($fields) { $_params['fields'] = $fields; @@ -120,7 +122,7 @@ public function getLists($id=null, $fields=null, $excludeFields=null, $count=nul $_params['email'] = $email; } if ($id) { - return $this->_master->call('lists/'.$id, $_params, Ebizmarts_MailChimp::GET); + return $this->_master->call('lists/' . $id, $_params, Ebizmarts_MailChimp::GET); } else { return $this->_master->call('lists', $_params, Ebizmarts_MailChimp::GET); } @@ -132,37 +134,43 @@ public function getLists($id=null, $fields=null, $excludeFields=null, $count=nul * @param $contact Contact information displayed in campaign footers to comply with international * spam laws. * @param $permissionRemainder The permission reminder for the list. - * @param null $useArchiveBar Whether campaigns for this list use the Archive Bar in archives by default. - * @param null $campaignDefaults Default values for campaigns created for this list. - * @param null $notifyOnSubscribe The email address to send subscribe notifications to. - * @param null $notifyOnUnsubscribe The email address to send unsubscribe notifications to. + * @param null $useArchiveBar Whether campaigns for this list use the Archive Bar in archives by default. + * @param null $campaignDefaults Default values for campaigns created for this list. + * @param null $notifyOnSubscribe The email address to send subscribe notifications to. + * @param null $notifyOnUnsubscribe The email address to send unsubscribe notifications to. * @param $emailTypeOption Whether the list supports multiple formats for emails. * When set to true, subscribers can choose whether they want to receive HTML or * plain-text emails. * When set to false, subscribers will receive HTML emails, with a plain-text * alternative backup. - * @param null $visibility Whether this list is public or private. (pub/prv) + * @param null $visibility Whether this list is public or private. (pub/prv) * @return mixed * @throws MailChimp_Error * @throws MailChimp_HttpError */ - public function edit($listId, $name, $contact, $permissionRemainder, $emailTypeOption, $useArchiveBar=null, - $campaignDefaults=null, $notifyOnSubscribe=null, $notifyOnUnsubscribe=null, $visibility=null - ) { - - $_params = array('name'=>$name, 'contact'=>$contact, 'permission_remainder'=>$permissionRemainder, - 'email_type_option'=>$emailTypeOption); - if($useArchiveBar) { $_params['use_archive_bar'] = $useArchiveBar; + public function edit($listId, $name, $contact, $permissionRemainder, $emailTypeOption, $useArchiveBar = null, + $campaignDefaults = null, $notifyOnSubscribe = null, $notifyOnUnsubscribe = null, $visibility = null + ) + { + + $_params = array('name' => $name, 'contact' => $contact, 'permission_remainder' => $permissionRemainder, + 'email_type_option' => $emailTypeOption); + if ($useArchiveBar) { + $_params['use_archive_bar'] = $useArchiveBar; } - if($campaignDefaults) { $_params['campaign_defaults'] = $campaignDefaults; + if ($campaignDefaults) { + $_params['campaign_defaults'] = $campaignDefaults; } - if($notifyOnSubscribe) { $_params['notify_on_subscribe'] = $notifyOnSubscribe; + if ($notifyOnSubscribe) { + $_params['notify_on_subscribe'] = $notifyOnSubscribe; } - if($notifyOnUnsubscribe) { $_params['notify_on_unsubscribe'] = $notifyOnUnsubscribe; + if ($notifyOnUnsubscribe) { + $_params['notify_on_unsubscribe'] = $notifyOnUnsubscribe; } - if($visibility) { $_params['visibility'] = $visibility; + if ($visibility) { + $_params['visibility'] = $visibility; } - return $this->_master->call('lists/'.$listId, $_params, Ebizmarts_MailChimp::PATCH); + return $this->_master->call('lists/' . $listId, $_params, Ebizmarts_MailChimp::PATCH); } /** @@ -173,6 +181,6 @@ public function edit($listId, $name, $contact, $permissionRemainder, $emailTypeO */ public function delete($listId) { - return $this->_master->call('lists/'.$listId, null, Ebizmarts_MailChimp::DELETE); + return $this->_master->call('lists/' . $listId, null, Ebizmarts_MailChimp::DELETE); } } \ No newline at end of file From d8110478da76c62ebdf0f1ccc2b8c70352c0056f Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 15:33:11 -0300 Subject: [PATCH 16/42] Added tests. --- .../Sales/Order/View/Info/MonkeyTest.php | 80 +++++++++++++++++++ .../MailChimp/Model/Api/BatchesTest.php | 2 - 2 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php new file mode 100644 index 000000000..f7972bb3f --- /dev/null +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php @@ -0,0 +1,80 @@ +getLayout(); + $this->_block = new Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey; + $this->_orderMock = $this->getMockBuilder(Mage_Sales_Model_Order::class) + ->disableOriginalConstructor() + ->setMethods(array('getStoreId', 'getMailchimpAbandonedcartFlag', 'getMailchimpCampaignId')) + ->getMock(); + if (!Mage::registry('current_order')) { + Mage::register('current_order', $this->_orderMock); + } + /* We are required to set layouts before we can do anything with blocks */ + $this->_block->setLayout($layout); + } + + public function testIsReferred() + { + /** + * @var \Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey $monkeyBlock + */ + $monkeyBlockMock = $this->getMockBuilder(Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey::class) + ->disableOriginalConstructor() + ->setMethods(array('getMailChimpHelper', 'getCampaignId', 'getCurrentOrder')) + ->getMock(); + $orderMock = $this->_orderMock; + + $monkeyBlockMock->expects($this->once())->method('getCurrentOrder')->willReturn($orderMock); + $orderMock->expects($this->exactly(2))->method('getMailchimpAbandonedcartFlag')->willReturn(false); + $orderMock->expects($this->exactly(2))->method('getMailchimpCampaignId')->willReturn(true); + + $this->assertEquals($this->_block->isReferred(), $monkeyBlockMock->isReferred()); + } + + + public function testAddCampaignName() + { + $campaignId = '1111111'; + $storeId = 1; + /** + * @var \Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey $monkeyBlock + */ + $monkeyBlockMock = $this->getMockBuilder(Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_View_Info_Monkey::class) + ->disableOriginalConstructor() + ->setMethods(array('getMailChimpHelper', 'getCampaignId', 'getCurrentOrder')) + ->getMock(); + /** + * @var \Ebizmarts_MailChimp_Helper_Data $helperMock + */ + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getMailChimpCampaignNameById')) + ->getMock(); + + $orderMock = $this->_orderMock; + + $monkeyBlockMock->expects($this->once())->method('getMailChimpHelper')->willReturn($helperMock); + $monkeyBlockMock->expects($this->once())->method('getCampaignId')->willReturn($campaignId); + $monkeyBlockMock->expects($this->once())->method('getCurrentOrder')->willReturn($orderMock); + $orderMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + $helperMock->expects($this->once())->method('getMailChimpCampaignNameById')->with($campaignId, $storeId); + + + $this->assertEquals($this->_block->addCampaignName(), $monkeyBlockMock->addCampaignName()); + } +} \ 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 b2ba14efe..017ff1d4e 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 @@ -64,8 +64,6 @@ public function testSendEcommerceBatch() $apiBatchesMock->expects($this->once())->method('getApiProducts')->willReturn($apiProductsMock); $apiBatchesMock->expects($this->once())->method('getApiCarts')->willReturn($apiCartsMock); $apiBatchesMock->expects($this->once())->method('getApiOrders')->willReturn($apiOrdersMock); -// $apiBatchesMock->expects($this->once())->method('deleteUnsentItems'); -// $apiBatchesMock->expects($this->once())->method('markItemsAsSent')->with('batchId', 'b81c3085c51fa593e1d6b0cf59884f3e'); $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); From 256db3a8227bab949842b1c241a3260a19f983e5 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 15:40:47 -0300 Subject: [PATCH 17/42] Add check for the cases where unserialize fails in webhook processing. resolves #415 --- .../MailChimp/Model/ProcessWebhook.php | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index d77e5f267..793465468 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -41,25 +41,26 @@ public function processWebhookData() $collection->getSelect()->limit(self::BATCH_LIMIT); foreach ($collection as $webhookRequest) { $data = unserialize($webhookRequest->getDataRequest()); - - switch ($webhookRequest->getType()) { - case 'subscribe': - $this->_subscribe($data); - break; - case 'unsubscribe': - $this->_unsubscribe($data); - break; - case 'cleaned': - $this->_clean($data); - break; - case 'upemail': - $this->_updateEmail($data); - break; - case 'profile': - $this->_profile($data); + if ($data) { + switch ($webhookRequest->getType()) { + case 'subscribe': + $this->_subscribe($data); + break; + case 'unsubscribe': + $this->_unsubscribe($data); + break; + case 'cleaned': + $this->_clean($data); + break; + case 'upemail': + $this->_updateEmail($data); + break; + case 'profile': + $this->_profile($data); + } + $webhookRequest->setProcessed(1) + ->save(); } - $webhookRequest->setProcessed(1) - ->save(); } } From 2a4ca56260ef98be7396b427be4a653ce44e6b12 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 15:50:38 -0300 Subject: [PATCH 18/42] Set batch as processed if data fails. --- .../MailChimp/Model/ProcessWebhook.php | 35 ++++++++++--------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index 793465468..e0ceb09bb 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -1,4 +1,5 @@ addFieldToFilter('processed',array('eq'=>0)); + $collection->addFieldToFilter('processed', array('eq' => 0)); $collection->getSelect()->limit(self::BATCH_LIMIT); foreach ($collection as $webhookRequest) { $data = unserialize($webhookRequest->getDataRequest()); @@ -58,9 +59,9 @@ public function processWebhookData() case 'profile': $this->_profile($data); } - $webhookRequest->setProcessed(1) - ->save(); } + $webhookRequest->setProcessed(1) + ->save(); } } @@ -180,19 +181,19 @@ protected function _unsubscribe(array $data) try { $action = isset($data['action']) ? $data['action'] : 'delete'; switch ($action) { - case 'delete' : - //if config setting "Webhooks Delete action" is set as "Delete customer account" - if (Mage::getStoreConfig("mailchimp/general/webhook_delete", $subscriber->getStoreId())) { - $subscriber->delete(); - } elseif ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { - $this->unsubscribeMember($subscriber); - } - break; - case 'unsub': - if ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { - $this->unsubscribeMember($subscriber); - } - break; + case 'delete' : + //if config setting "Webhooks Delete action" is set as "Delete customer account" + if (Mage::getStoreConfig("mailchimp/general/webhook_delete", $subscriber->getStoreId())) { + $subscriber->delete(); + } elseif ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { + $this->unsubscribeMember($subscriber); + } + break; + case 'unsub': + if ($subscriber->getSubscriberStatus() != Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { + $this->unsubscribeMember($subscriber); + } + break; } } catch (Exception $e) { Mage::logException($e); From c6271470f708e98ebef0d8c303eb399af7387eb6 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 16:00:04 -0300 Subject: [PATCH 19/42] Added catch for exception. --- app/code/community/Ebizmarts/MailChimp/Helper/Data.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 4fca0098d..d0319fbef 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -2264,6 +2264,8 @@ public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'st } } catch (MailChimp_Error $e) { $this->logError($e->getFriendlyMessage()); + } catch (Exception $e) { + $this->logError($e->getMessage()); } return $campaignName; } From f69c36f9f99da8003321a63366b55d9f8f63a190 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 4 Aug 2017 16:16:22 -0300 Subject: [PATCH 20/42] Fix for tests when run by travis. --- .../Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php index f7972bb3f..4e788541a 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/View/Info/MonkeyTest.php @@ -40,10 +40,10 @@ public function testIsReferred() $orderMock = $this->_orderMock; $monkeyBlockMock->expects($this->once())->method('getCurrentOrder')->willReturn($orderMock); - $orderMock->expects($this->exactly(2))->method('getMailchimpAbandonedcartFlag')->willReturn(false); - $orderMock->expects($this->exactly(2))->method('getMailchimpCampaignId')->willReturn(true); + $orderMock->expects($this->exactly(1))->method('getMailchimpAbandonedcartFlag')->willReturn(false); + $orderMock->expects($this->exactly(1))->method('getMailchimpCampaignId')->willReturn(true); - $this->assertEquals($this->_block->isReferred(), $monkeyBlockMock->isReferred()); + $monkeyBlockMock->isReferred(); } @@ -75,6 +75,6 @@ public function testAddCampaignName() $helperMock->expects($this->once())->method('getMailChimpCampaignNameById')->with($campaignId, $storeId); - $this->assertEquals($this->_block->addCampaignName(), $monkeyBlockMock->addCampaignName()); + $monkeyBlockMock->addCampaignName(); } } \ No newline at end of file From ad3dd76659188ccb736fafd3850032ed4410dbf1 Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 7 Aug 2017 11:16:48 -0300 Subject: [PATCH 21/42] Fix for quote re-send. --- app/code/community/Ebizmarts/MailChimp/Helper/Data.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index d0319fbef..460bdc232 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -1872,6 +1872,7 @@ public function updateSubscriberSyndData($itemId, $syncDelta = null, $syncError if ($syncDeleted) { $subscriber->setData("mailchimp_sync_deleted", $syncDeleted); } + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE); $subscriber->save(); } } @@ -2228,7 +2229,7 @@ protected function isMissingOrderLowerThanId($itemId, $storeId) protected function isMissingQuoteLowerThanId($itemId, $storeId) { $mailchimpStoreId = $this->getMCStoreId($storeId); - $quoteCollection = Mage::getResourceModel('sales/order_collection') + $quoteCollection = Mage::getResourceModel('sales/quote_collection') ->addFieldToFilter('store_id', array('eq' => $storeId)) ->addFieldToFilter('entity_id', array('lteq' => $itemId)) ->addFieldToFilter('is_active', array('eq' => 1)) From cf09cee6ce452b528e7742a98e3486b3c24acab1 Mon Sep 17 00:00:00 2001 From: ebizmarts-keller Date: Thu, 24 Aug 2017 11:21:06 -0300 Subject: [PATCH 22/42] closes #439 Different currencies causing revenue not to be showed properly --- .../community/Ebizmarts/MailChimp/Model/Api/Orders.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index c2d0499d3..0aeb7bae6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -174,11 +174,11 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreI $data['landing_site'] = $order->getMailchimpLandingPage(); } - $data['currency_code'] = $order->getOrderCurrencyCode(); - $data['order_total'] = $order->getGrandTotal(); - $data['tax_total'] = $this->returnZeroIfNull($order->getTaxAmount()); - $data['discount_total'] = abs($order->getDiscountAmount()); - $data['shipping_total'] = $this->returnZeroIfNull($order->getShippingAmount()); + $data['currency_code'] = $order->getStoreCurrencyCode(); + $data['order_total'] = $order->getBaseGrandTotal(); + $data['tax_total'] = $this->returnZeroIfNull($order->getBaseTaxAmount()); + $data['discount_total'] = abs($order->getBaseDiscountAmount()); + $data['shipping_total'] = $this->returnZeroIfNull($order->getBaseShippingAmount()); $statusArray = $this->_getMailChimpStatus($order); if (isset($statusArray['financial_status'])) { $data['financial_status'] = $statusArray['financial_status']; From 04e582150e2875f32a1b0da98ac79a430b5a1f70 Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 29 Aug 2017 17:09:33 -0300 Subject: [PATCH 23/42] Set deleted subscribers in Magento as unsubscribed in MailChimp. resolves #448 --- .../community/Ebizmarts/MailChimp/Model/Api/Subscribers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index d3a17b2e0..d47f4b25f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -447,7 +447,7 @@ public function deleteSubscriber($subscriber) $api = $helper->getApi($storeId); try { $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); - $api->lists->members->update($listId, $md5HashEmail, null, 'cleaned'); + $api->lists->members->update($listId, $md5HashEmail, null, 'unsubscribed'); } catch (MailChimp_Error $e) { $helper->logError($e->getFriendlyMessage(), $storeId); Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); From fb6d51e9e6e07ae9f79585a9bc29a303995ee1e2 Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 29 Aug 2017 17:30:30 -0300 Subject: [PATCH 24/42] Add filter for subscribers with errors. resolves #436 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index d3a17b2e0..f42969394 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -52,6 +52,7 @@ public function createBatchJson($listId, $storeId, $limit) array('eq' => 1) ) ); + $collection->addFieldToFilter('mailchimp_sync_error', array('eq' => '')); $collection->getSelect()->limit($limit); $date = $helper->getDateMicrotime(); $batchId = 'storeid-' . $storeId . '_' . Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_' . $date; From ab42f1726da4525b3c0f3c6fe7c644f2df524ba1 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 30 Aug 2017 17:47:13 -0300 Subject: [PATCH 25/42] Add configuration fields for batch limits on each object type. resolves #256 --- .../Ebizmarts/MailChimp/Helper/Data.php | 25 +++++++++ .../Ebizmarts/MailChimp/Model/Api/Batches.php | 3 +- .../Ebizmarts/MailChimp/Model/Api/Carts.php | 15 ++++-- .../MailChimp/Model/Api/Customers.php | 5 +- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 13 ++++- .../MailChimp/Model/Api/Products.php | 11 +++- .../Ebizmarts/MailChimp/Model/Config.php | 5 ++ .../Model/System/Config/Source/BatchLimit.php | 28 ++++++++++ .../Ebizmarts/MailChimp/etc/config.xml | 9 ++++ .../Ebizmarts/MailChimp/etc/system.xml | 52 ++++++++++++++++++- 10 files changed, 156 insertions(+), 10 deletions(-) create mode 100755 app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 460bdc232..eed1d301d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -2270,4 +2270,29 @@ public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'st } return $campaignName; } + + public function getCustomerAmountLimit() + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMER_AMOUNT, 0, 'default'); + } + + public function getProductAmountLimit() + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PRODUCT_AMOUNT, 0, 'default'); + } + + public function getOrderAmountLimit() + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_ORDER_AMOUNT, 0, 'default'); + } + + public function getCartAmountLimit() + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::CART_AMOUNT, 0, 'default'); + } + + public function getSubscriberAmountLimit() + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBSCRIBER_AMOUNT, 0, 'default'); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 34936e90b..1ffe66231 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -302,7 +302,8 @@ public function ecommerceSentCallback($args) */ protected function _sendSubscriberBatches() { - $subscriberLimit = Ebizmarts_MailChimp_Model_Api_Subscribers::BATCH_LIMIT; + $helper = $this->getHelper(); + $subscriberLimit = $helper->getSubscriberAmountLimit(); $stores = Mage::app()->getStores(); $batchResponses = array(); foreach ($stores as $store) { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 98bf2eb59..f04416cfa 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -74,7 +74,7 @@ protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) // be sure that the quotes are already in mailchimp and not deleted $convertedCarts->getSelect()->where("m4m.mailchimp_sync_deleted = 0"); // limit the collection - $convertedCarts->getSelect()->limit(self::BATCH_LIMIT); + $convertedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($convertedCarts as $cart) { $cartId = $cart->getEntityId(); // we need to delete all the carts associated with this email @@ -130,7 +130,7 @@ protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) AND m4m.mailchimp_sync_delta < updated_at" ); // limit the collection - $modifiedCarts->getSelect()->limit(self::BATCH_LIMIT); + $modifiedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($modifiedCarts as $cart) { $cartId = $cart->getEntityId(); $allCarts[$this->_counter]['method'] = 'DELETE'; @@ -213,7 +213,7 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) // be sure that the quotes are already in mailchimp and not deleted $newCarts->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); // limit the collection - $newCarts->getSelect()->limit(self::BATCH_LIMIT); + $newCarts->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($newCarts as $cart) { $cartId = $cart->getEntityId(); @@ -381,6 +381,15 @@ protected function _getCheckoutUrl($cart) return $url; } + /** + * @return mixed + */ + protected function getBatchLimitFromConfig() + { + $helper = $this->getHelper(); + return $helper->getCustomerAmountLimit(); + } + /** * Get Customer data for the cart. * diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index fdc68716f..699b89561 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -326,11 +326,12 @@ protected function checkEcommerceOptInConfigAndUpdateStorage($magentoStoreId) } /** - * @return int + * @return mixed */ protected function getBatchLimitFromConfig() { - return self::BATCH_LIMIT; + $helper = $this->mailchimpHelper; + return $helper->getCustomerAmountLimit(); } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 0aeb7bae6..5338b88be 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -71,7 +71,7 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) // be sure that the order are already in mailchimp and not deleted $modifiedOrders->getSelect()->where("m4m.mailchimp_sync_modified = 1"); // limit the collection - $modifiedOrders->getSelect()->limit(self::BATCH_LIMIT); + $modifiedOrders->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($modifiedOrders as $item) { try { @@ -121,7 +121,7 @@ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) // be sure that the orders are not in mailchimp $newOrders->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); // limit the collection - $newOrders->getSelect()->limit(self::BATCH_LIMIT); + $newOrders->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($newOrders as $item) { try { @@ -427,6 +427,15 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreI return $jsonData; } + /** + * @return mixed + */ + protected function getBatchLimitFromConfig() + { + $helper = $this->getHelper(); + return $helper->getOrderAmountLimit(); + } + protected function returnZeroIfNull($value) { $returnValue = $value; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 2b94245d0..710f188fc 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -404,11 +404,20 @@ public function makeProductsNotSentCollection($magentoStoreId) $this->joinProductAttributes($collection, $magentoStoreId); $collection->getSelect()->group("e.entity_id"); - $collection->getSelect()->limit(self::BATCH_LIMIT); + $collection->getSelect()->limit($this->getBatchLimitFromConfig()); return $collection; } + /** + * @return mixed + */ + protected function getBatchLimitFromConfig() + { + $helper = $this->mailchimpHelper; + return $helper->getProductAmountLimit(); + } + /** * @return string */ diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php index 47831dfc3..a55994c7d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php @@ -34,6 +34,7 @@ class Ebizmarts_MailChimp_Model_Config const GENERAL_MIGRATE_FROM_116 = 'mailchimp/general/migrate_from_116'; const GENERAL_MIGRATE_FROM_1164 = 'mailchimp/general/migrate_from_1164'; const GENERAL_MIGRATE_LAST_ORDER_ID = 'mailchimp/general/migrate_last_order_id'; + const GENERAL_SUBSCRIBER_AMOUNT = 'mailchimp/ecommerce/order_amount'; const ECOMMERCE_ACTIVE = 'mailchimp/ecommerce/active'; const ECOMMERCE_CUSTOMERS_OPTIN = 'mailchimp/ecommerce/customers_optin'; @@ -45,6 +46,9 @@ class Ebizmarts_MailChimp_Model_Config const ECOMMERCE_CART_LAST_ID = 'mailchimp/ecommerce/cart_last_id'; const ECOMMERCE_RESEND_ENABLED = 'mailchimp/ecommerce/resend_enabled'; const ECOMMERCE_RESEND_TURN = 'mailchimp/ecommerce/resend_turn'; + const ECOMMERCE_CUSTOMER_AMOUNT = 'mailchimp/ecommerce/customer_amount'; + const ECOMMERCE_PRODUCT_AMOUNT = 'mailchimp/ecommerce/product_amount'; + const ECOMMERCE_ORDER_AMOUNT = 'mailchimp/ecommerce/order_amount'; const ENABLE_POPUP = 'mailchimp/emailcatcher/popup_general'; const POPUP_HEADING = 'mailchimp/emailcatcher/popup_heading'; @@ -62,6 +66,7 @@ class Ebizmarts_MailChimp_Model_Config const ABANDONEDCART_FIRSTDATE = 'mailchimp/abandonedcart/firstdate'; const ABANDONEDCART_PAGE = 'mailchimp/abandonedcart/page'; const MONKEY_GRID = 'mailchimp/general/monkey_grid'; + const CART_AMOUNT = 'mailchimp/abandonedcart/cart_amount'; const WARNING_MESSAGE = 'mailchimp/warning_message'; const POPUP_MESSAGE = 'mailchimp/popup_message'; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php new file mode 100755 index 000000000..0955e7755 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php @@ -0,0 +1,28 @@ + + * @license http://opensource.org/licenses/osl-3.0.php + */ +class Ebizmarts_MailChimp_Model_System_Config_Source_BatchLimit +{ + /** + * Options getter + * + * @return array + */ + public function toOptionArray() + { + return array( + array('value' => 50, 'label' => Mage::helper('mailchimp')->__('50')), + array('value' => 100, 'label' => Mage::helper('mailchimp')->__('100')), + array('value' => 200, 'label' => Mage::helper('mailchimp')->__('200')), + array('value' => 500, 'label' => Mage::helper('mailchimp')->__('500')), + array('value' => 1000, 'label' => Mage::helper('mailchimp')->__('1000')), + array('value' => 5000, 'label' => Mage::helper('mailchimp')->__('5000')) + ); + } +} \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index aebfb9594..8590b76f1 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -314,7 +314,13 @@ 1 + 200 + + 100 + 100 + 50 + 1 1 @@ -329,6 +335,9 @@ + + 100 + diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 8d796d383..ece559afc 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -112,11 +112,21 @@ 1 + + + select + mailchimp/system_config_source_batchLimit + 53 + 1 + 0 + 0 + + select mailchimp/system_config_source_checkoutsubscribe - 53 + 54 1 1 1 @@ -251,6 +261,36 @@ 1 + + + select + mailchimp/system_config_source_batchLimit + 240 + 1 + 0 + 0 + + + + + select + mailchimp/system_config_source_batchLimit + 250 + 1 + 0 + 0 + + + + + select + mailchimp/system_config_source_batchLimit + 260 + 1 + 0 + 0 + + @@ -446,6 +486,16 @@ 1 + + + select + mailchimp/system_config_source_batchLimit + 30 + 1 + 0 + 0 + + From 5f3d405ba10848e54ac92f272b7fa65a2a20a19a Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 31 Aug 2017 11:46:19 -0300 Subject: [PATCH 26/42] Fix test. --- .../tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 ba3a767c8..e3c707e19 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 @@ -129,7 +129,8 @@ public function testMakeProductsNotSentCollection() 'joinQtyAndBackorders', 'joinCategoryId', 'joinProductAttributes', - 'getProductResourceCollection' + 'getProductResourceCollection', + 'getBatchLimitFromConfig' ) ) ->getMock(); @@ -152,6 +153,7 @@ 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('getBatchLimitFromConfig')->willReturn(100); $collection = $this->productsApiMock->makeProductsNotSentCollection(0); From f40583029f781ccaba496b26519120ba79395bbb Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 31 Aug 2017 15:11:57 -0300 Subject: [PATCH 27/42] Cart item price sent in the correct currency. resolves #441 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index f04416cfa..dac4d5d94 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -348,7 +348,7 @@ protected function _makeCart($cart, $mailchimpStoreId, $magentoStoreId) $line['product_id'] = $item->getProductId(); $line['product_variant_id'] = $variantId; $line['quantity'] = (int)$item->getQty(); - $line['price'] = $item->getPrice(); + $line['price'] = $item->getRowTotal(); $lines[] = $line; } From fc2f6c4ccd9c7001e6d58a44eb0d0c512c0f6194 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 31 Aug 2017 15:13:03 -0300 Subject: [PATCH 28/42] Cart item price sent in the correct currency. resolves #441 --- .../Ebizmarts/MailChimp/Model/System/Config/Source/Account.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 31cf63567..eb837b878 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 @@ -19,7 +19,7 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_Account * @access protected * @var bool|array */ - protected $accountDetails = false; + protected $_accountDetails = false; protected $helper; /** From 4dbbfd2ff152bb3ed00fbdb01652b97d5c0fcff2 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 31 Aug 2017 15:50:53 -0300 Subject: [PATCH 29/42] Add more store information. resolves #357 --- .../community/Ebizmarts/MailChimp/Helper/Data.php | 15 +++++++++++++++ .../Ebizmarts/MailChimp/Model/Api/Stores.php | 6 +++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index eed1d301d..e97e953f0 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -2295,4 +2295,19 @@ public function getSubscriberAmountLimit() { return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBSCRIBER_AMOUNT, 0, 'default'); } + + public function getStoreLanguageCode($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $scopeId, $scope); + } + + public function getStoreTimeZone($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Mage_Core_Model_Locale::XML_PATH_DEFAULT_TIMEZONE, $scopeId, $scope); + } + + public function getStorePhone($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope('general/store_information/phone', $scopeId, $scope); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index 6b07e4154..df3291f30 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -40,7 +40,11 @@ public function createMailChimpStore($mailChimpStoreId, $listId = null, $scopeId $currencyCode = Mage::helper('mailchimp')->getConfigValueForScope(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_DEFAULT, $scopeId, $scope); $isSyncing = true; - $response = $api->ecommerce->stores->add($mailChimpStoreId, $listId, $storeName, $currencyCode, $isSyncing, 'Magento', $storeDomain, $storeEmail); + $primaryLocale = Mage::helper('mailchimp')->getStoreLanguageCode($scopeId, $scope); + $timeZone = Mage::helper('mailchimp')->getStoreTimeZone($scopeId, $scope); + $storePhone = Mage::helper('mailchimp')->getStorePhone($scopeId, $scope); + $currencySymbol = Mage::app()->getLocale()->currency($currencyCode)->getSymbol(); + $response = $api->ecommerce->stores->add($mailChimpStoreId, $listId, $storeName, $currencyCode, $isSyncing, 'Magento', $storeDomain, $storeEmail, $currencySymbol, $primaryLocale, $timeZone, $storePhone); return $response; } else { throw new Exception('You don\'t have any lists configured in MailChimp'); From e8bf2d771f40cebe3bc9dab15cabd23184ae4ab5 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 1 Sep 2017 18:01:09 -0300 Subject: [PATCH 30/42] Set protected method to public. Fix subscriber language. --- app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php | 2 +- .../community/Ebizmarts/MailChimp/Model/Api/Subscribers.php | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 710f188fc..95416e94c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -498,7 +498,7 @@ protected function isConfigurableProduct($product) * @param $collection * @param $magentoStoreId */ - protected function joinProductAttributes($collection, $magentoStoreId) + public function joinProductAttributes($collection, $magentoStoreId) { $attributeCodes = array("name", "visibility", "description", "price"); $config = Mage::getSingleton("eav/config"); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index e2af7b4d4..ae8996adf 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -94,6 +94,7 @@ public function createBatchJson($listId, $storeId, $limit) protected function _buildSubscriberData($subscriber) { + $helper = $this->mcHelper; $storeId = $subscriber->getStoreId(); $data = array(); $data["email_address"] = $subscriber->getSubscriberEmail(); @@ -103,6 +104,7 @@ protected function _buildSubscriberData($subscriber) } $data["status_if_new"] = $this->translateMagentoStatusToMailchimpStatus($subscriber->getStatus(), $storeId); + $data["language"] = $helper->getStoreLanguageCode($storeId); return $data; } From 535b526f848d33ba4006ac2b5267a423875190af Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 1 Sep 2017 18:03:59 -0300 Subject: [PATCH 31/42] Fixed alt message for resend ecommerce data button. --- .../Block/Adminhtml/System/Config/ResendEcommerceData.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php index 43c7395b1..46e6c00cb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResendEcommerceData.php @@ -35,7 +35,7 @@ public function getButtonHtml() 'id' => 'resendecommercedata_button', 'label' => $label, 'onclick' => 'javascript:resendecommerce(); return false;', - 'title' => $this->helper('mailchimp')->__('Re-create MailChimp store for current scope') + 'title' => $this->helper('mailchimp')->__('Resend Ecommerce Data current scope') ) ); From ebb4b7265fcd5a7079aa8876b4f49733b929366c Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 4 Sep 2017 15:30:53 -0300 Subject: [PATCH 32/42] Add missing parameter. --- app/code/community/Ebizmarts/MailChimp/Helper/Data.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index e97e953f0..72eeaffd6 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -2194,7 +2194,7 @@ protected function isMissingProductLowerThanId($itemId, $storeId) ->addFieldToFilter('entity_id', array('lteq' => $itemId)); $apiProducts->joinQtyAndBackorders($productCollection); $apiProducts->joinCategoryId($productCollection); - $apiProducts->joinProductAttributes($productCollection); + $apiProducts->joinProductAttributes($productCollection, $storeId); $productCollection->getSelect()->group("e.entity_id"); $apiProducts->joinMailchimpSyncDataWithoutWhere($productCollection, $mailchimpStoreId); $productCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); From e379841a856a186d940a04336a2c432b76343796 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 7 Sep 2017 12:16:39 -0300 Subject: [PATCH 33/42] Fix for subscribers being sent multiple times. --- .../Ebizmarts/MailChimp/Model/Api/Subscribers.php | 6 ++++-- .../community/Ebizmarts/MailChimp/Model/Config.php | 10 +++++----- .../Ebizmarts/MailChimp/Model/ProcessWebhook.php | 6 ++++-- .../MailChimp/Model/System/Config/Backend/List.php | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index ae8996adf..288228b1a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -24,12 +24,13 @@ public function createBatchJson($listId, $storeId, $limit) { $helper = $this->mcHelper; $thisScopeHasSubMinSyncDateFlag = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, $storeId); + $thisScopeHasList = $helper->getIfConfigExistsForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $storeId); $moduleIsActive = $helper->isMailChimpEnabled($storeId); $subscriberArray = array(); if ($moduleIsActive) { - $realScope = $helper->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $storeId); - if ($helper->getGeneralList($realScope['scope_id'], $realScope['scope']) && !$thisScopeHasSubMinSyncDateFlag) { + if ($thisScopeHasList && !$thisScopeHasSubMinSyncDateFlag || !$helper->getSubMinSyncDateFlag($storeId)) { + $realScope = $helper->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $storeId); $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, Varien_Date::now())); $helper->saveMailchimpConfig($configValues, $realScope['scope_id'], $realScope['scope']); } @@ -82,6 +83,7 @@ public function createBatchJson($listId, $storeId, $limit) $subscriber->setData("mailchimp_sync_delta", Varien_Date::now()); $subscriber->setData("mailchimp_sync_error", ""); $subscriber->setData("mailchimp_sync_modified", 0); + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE); $subscriber->save(); } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php index a55994c7d..f2efa8d2d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php @@ -34,7 +34,7 @@ class Ebizmarts_MailChimp_Model_Config const GENERAL_MIGRATE_FROM_116 = 'mailchimp/general/migrate_from_116'; const GENERAL_MIGRATE_FROM_1164 = 'mailchimp/general/migrate_from_1164'; const GENERAL_MIGRATE_LAST_ORDER_ID = 'mailchimp/general/migrate_last_order_id'; - const GENERAL_SUBSCRIBER_AMOUNT = 'mailchimp/ecommerce/order_amount'; + const GENERAL_SUBSCRIBER_AMOUNT = 'mailchimp/general/subscriber_batch_amount'; const ECOMMERCE_ACTIVE = 'mailchimp/ecommerce/active'; const ECOMMERCE_CUSTOMERS_OPTIN = 'mailchimp/ecommerce/customers_optin'; @@ -46,9 +46,9 @@ class Ebizmarts_MailChimp_Model_Config const ECOMMERCE_CART_LAST_ID = 'mailchimp/ecommerce/cart_last_id'; const ECOMMERCE_RESEND_ENABLED = 'mailchimp/ecommerce/resend_enabled'; const ECOMMERCE_RESEND_TURN = 'mailchimp/ecommerce/resend_turn'; - const ECOMMERCE_CUSTOMER_AMOUNT = 'mailchimp/ecommerce/customer_amount'; - const ECOMMERCE_PRODUCT_AMOUNT = 'mailchimp/ecommerce/product_amount'; - const ECOMMERCE_ORDER_AMOUNT = 'mailchimp/ecommerce/order_amount'; + const ECOMMERCE_CUSTOMER_AMOUNT = 'mailchimp/ecommerce/customer_batch_amount'; + const ECOMMERCE_PRODUCT_AMOUNT = 'mailchimp/ecommerce/product_batch_amount'; + const ECOMMERCE_ORDER_AMOUNT = 'mailchimp/ecommerce/order_batch_amount'; const ENABLE_POPUP = 'mailchimp/emailcatcher/popup_general'; const POPUP_HEADING = 'mailchimp/emailcatcher/popup_heading'; @@ -66,7 +66,7 @@ class Ebizmarts_MailChimp_Model_Config const ABANDONEDCART_FIRSTDATE = 'mailchimp/abandonedcart/firstdate'; const ABANDONEDCART_PAGE = 'mailchimp/abandonedcart/page'; const MONKEY_GRID = 'mailchimp/general/monkey_grid'; - const CART_AMOUNT = 'mailchimp/abandonedcart/cart_amount'; + const CART_AMOUNT = 'mailchimp/abandonedcart/cart_batch_amount'; const WARNING_MESSAGE = 'mailchimp/warning_message'; const POPUP_MESSAGE = 'mailchimp/popup_message'; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index e0ceb09bb..98d9f8a56 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -83,8 +83,9 @@ protected function _updateEmail(array $data) if ($oldSubscriber) { if (!$newSubscriber->getId()) { if ($oldSubscriber->getId()) { - $oldSubscriber->setSubscriberEmail($new) - ->save(); + $oldSubscriber->setSubscriberEmail($new); + $oldSubscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE); + $oldSubscriber->save(); } else { $this->subscribeMember($newSubscriber); } @@ -234,6 +235,7 @@ protected function _profile(array $data) $saveRequired = true; } if ($saveRequired) { + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE); $subscriber->save(); } } else { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/List.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/List.php index 4cca79cc0..23355f7fc 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 @@ -17,7 +17,7 @@ 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) + if ($this->isValueChanged() && ($moduleIsActive || $thisScopeHasSubMinSyncDateFlag) && $this->getValue()) { $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_SUBMINSYNCDATEFLAG, Varien_Date::now())); Mage::helper('mailchimp')->saveMailchimpConfig($configValues, $this->getScopeId(), $this->getScope()); From 8837f9e23aebfb53a545453f60049264636cba57 Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 12 Sep 2017 14:22:53 -0300 Subject: [PATCH 34/42] Send correct product Url for not visible child products. resolves #341 --- .../Ebizmarts/MailChimp/Helper/Data.php | 2 +- .../MailChimp/Model/Api/Products.php | 87 +++++++++++++++++-- .../MailChimp/Model/ProcessWebhook.php | 2 +- .../controllers/WebhookController.php | 2 +- .../mailchimp/checkout/subscribe.phtml | 2 - 5 files changed, 81 insertions(+), 14 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 72eeaffd6..130b551c5 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -1941,7 +1941,7 @@ 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); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 95416e94c..0017c96f5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -13,6 +13,8 @@ class Ebizmarts_MailChimp_Model_Api_Products { const BATCH_LIMIT = 100; private $_parentImageUrl = null; + private $_parentId = null; + private $_parentUrl = null; private $_parentPrice = null; /** @var Mage_Catalog_Model_Product_Type_Configurable */ private $productTypeConfigurable; @@ -95,7 +97,7 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId return array(); } - $bodyData = $this->_buildProductData($product, false, $variantProducts); + $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts); try { $body = json_encode($bodyData); } catch (Exception $e) { @@ -132,7 +134,7 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor $variantProducts[] = $childProduct; } } - $bodyData = $this->_buildProductData($parent, false, $variantProducts); + $bodyData = $this->_buildProductData($parent, $magentoStoreId, false, $variantProducts); try { $body = json_encode($bodyData); } catch (Exception $e) { @@ -166,7 +168,7 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor //@TODO bundle return array(); } - $bodyData = $this->_buildProductData($product, false, $variantProducts); + $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts); try { $body = json_encode($bodyData); } catch (Exception $e) { @@ -187,7 +189,7 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor protected function getParentData($productId, $magentoStoreId) { $product = Mage::getModel('catalog/product')->load($productId); - $data = $this->_buildProductData($product, false); + $data = $this->_buildProductData($product, $magentoStoreId, false); $data['variants'][] = array('id' => $productId); try { $body = json_encode($data); @@ -198,14 +200,24 @@ protected function getParentData($productId, $magentoStoreId) return $body; } - protected function _buildProductData($product, $isVariant = true, $variants = array()) + protected function _buildProductData($product, $magentoStoreId, $isVariant = true, $variants = array()) { $data = array(); //data applied for both root and varient products $data["id"] = $product->getId(); $data["title"] = ($product->getName()) ? $product->getName() : $product->getDefaultName(); - $data["url"] = $product->getProductUrl(); + $visibility = ($product->getVisibility()) ? $product->getVisibility() : $product->getDefaultVisibility(); + if ($visibility == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE && $this->_parentId) { + $url = $this->getNotVisibleProductUrl($product->getId(), $magentoStoreId); + if (!$url) { + $url = $this->getProductUrl($product, $magentoStoreId); + } + $data["url"] = $url; + } else { + $url = $this->getProductUrl($product, $magentoStoreId); + $data["url"] = $url; + } //image $imageUrl = $this->getMailChimpHelper()->getMailChimpProductImageUrl($this->_parentImageUrl, $this->getMailChimpHelper()->getImageUrlById($product->getId())); @@ -241,17 +253,21 @@ protected function _buildProductData($product, $isVariant = true, $variants = ar if (isset($data["image_url"])) { $this->_parentImageUrl = $data["image_url"]; } + $this->_parentId = $product->getId(); + $this->_parentUrl = $data['url']; $price = (float)$product->getDefaultPrice(); if ($price) { $this->_parentPrice = $price; } foreach ($variants as $variant) { - $data["variants"][] = $this->_buildProductData($variant); + $data["variants"][] = $this->_buildProductData($variant, $magentoStoreId); } $this->_parentImageUrl = null; $this->_parentPrice = null; + $this->_parentId = null; + $this->_parentUrl = null; } } return $data; @@ -309,12 +325,11 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) if ($product->getId()) { $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now(), "This product type is not supported on MailChimp."); } - continue; } if ($productSyncData->getMailchimpSyncModified() && $productSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId)) { - $data[] = $this->_buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + $data = array_merge($this->_buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId), $data); $this->_updateSyncData($product->getId(), $mailchimpStoreId, Varien_Date::now()); } elseif (!$productSyncData->getMailchimpSyncDelta() || $productSyncData->getMailchimpSyncDelta() < Mage::helper('mailchimp')->getEcommMinSyncDateFlag($magentoStoreId)) { $data[] = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); @@ -646,4 +661,58 @@ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId ) ); } + + public function getNotVisibleProductUrl($childId, $magentoStoreId) + { + $tableName = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute'); + $eavTableName = Mage::getSingleton('core/resource')->getTableName('eav/attribute'); + + $collection = $this->getProductResourceCollection(); + $collection->addStoreFilter($magentoStoreId); + $collection->addFieldToFilter('entity_id', array('eq' => $this->_parentId)); + + $collection->getSelect()->joinLeft( + array("super_attribute" => $tableName), + 'entity_id=super_attribute.product_id' + ); + + $collection->getSelect()->joinLeft( + array("eav_attribute" => $eavTableName), + 'super_attribute.attribute_id=eav_attribute.attribute_id' + ); + $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns('eav_attribute.attribute_code'); + + $rc = Mage::getResourceModel('catalog/product'); + $url = $this->_parentUrl; + $tailUrl = '?'; + $count = 0; + foreach ($collection as $attribute) { + if ($attribute->getAttributeCode()) { + $attributeLabel = $attribute->getAttributeCode(); + $attributeValue = $rc->getAttributeRawValue($childId, $attribute->getAttributeCode(), $magentoStoreId); + if ($count > 0) { + $tailUrl .= '&'; + } + $tailUrl .= $attributeLabel . '=' . $attributeValue; + } + } + if ($tailUrl != '?') { + $url .= $tailUrl; + } + return $url; + } + + /** + * @param $product + * @param $magentoStoreId + * @return mixed + */ + protected function getProductUrl($product, $magentoStoreId) + { + $oldStoreId = Mage::app()->getStore()->getId(); + Mage::app()->setCurrentStore($magentoStoreId); + $url = $product->getProductUrl(); + Mage::app()->setCurrentStore($oldStoreId); + return $url; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index 98d9f8a56..eacf0b073 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -12,7 +12,7 @@ */ class Ebizmarts_MailChimp_Model_ProcessWebhook { - const BATCH_LIMIT = 50; + const BATCH_LIMIT = 200; /** * Webhooks request url path * diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php b/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php index bfa906e86..ad73be99b 100755 --- a/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php @@ -72,7 +72,7 @@ public function indexAction() Mage::getModel('mailchimp/processWebhook')->saveWebhookRequest($data); } else { $helper->logError($this->__('Something went wrong with the Webhook Data')); - $helper->logError($this->__($data)); + $helper->logError($data); } } else { $helper->logError($this->__('Webhook Key invalid! Key Request: %s - My Key: %s', $requestKey, $myKey)); 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 index 0e6d16c81..7a8d73b00 100644 --- a/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml @@ -46,10 +46,8 @@ $generalList = $this->getGeneralList(); // $("co-payment-form").insert(listValue); } } else { - alert(element.readAttribute('value')); var arrCheckedLists = checkedLists.split(','); var pos = arrCheckedLists.indexOf(element.readAttribute('value')); - alert(pos); if (pos != -1) { arrCheckedLists.splice(pos, 1); checkedLists = arrCheckedLists.join(','); From 3363de96c189de314496bfad03c4b6e50759603e Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 12 Sep 2017 16:23:51 -0300 Subject: [PATCH 35/42] Fix with attribute id in stead of code. --- .../Ebizmarts/MailChimp/Model/Api/Products.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 0017c96f5..fa016efbb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -680,23 +680,24 @@ public function getNotVisibleProductUrl($childId, $magentoStoreId) array("eav_attribute" => $eavTableName), 'super_attribute.attribute_id=eav_attribute.attribute_id' ); - $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns('eav_attribute.attribute_code'); + $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns('eav_attribute.attribute_id'); $rc = Mage::getResourceModel('catalog/product'); $url = $this->_parentUrl; - $tailUrl = '?'; + $tailUrl = '#'; $count = 0; foreach ($collection as $attribute) { - if ($attribute->getAttributeCode()) { - $attributeLabel = $attribute->getAttributeCode(); - $attributeValue = $rc->getAttributeRawValue($childId, $attribute->getAttributeCode(), $magentoStoreId); + if ($attribute->getAttributeId()) { + $attributeId = $attribute->getAttributeId(); + $attributeValue = $rc->getAttributeRawValue($childId, $attribute->getAttributeId(), $magentoStoreId); if ($count > 0) { $tailUrl .= '&'; } - $tailUrl .= $attributeLabel . '=' . $attributeValue; + $tailUrl .= $attributeId . '=' . $attributeValue; } + $count++; } - if ($tailUrl != '?') { + if ($tailUrl != '#') { $url .= $tailUrl; } return $url; From 9fa7f00b6fa6d956c8d4b2ade2a130c0c5f2477a Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 12 Sep 2017 17:43:32 -0300 Subject: [PATCH 36/42] Fix with attribute id in stead of code. resolves #273 --- app/code/community/Ebizmarts/MailChimp/Helper/Data.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 130b551c5..ee0120bbf 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -762,7 +762,7 @@ public function createMergeFields($scopeId, $scope) if (!$alreadyExists) { foreach ($customFieldTypes as $customFieldType) { - if ($customFieldType['value'] == $chimpTag) { + if ($customFieldType['value'] == $customAtt) { try { $api->lists->mergeFields->add($listId, $customFieldType['label'], $customFieldType['field_type'], null, $chimpTag); } catch (MailChimp_Error $e) { From ef317d70acee7d5f52019688694bc031608007b4 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 13 Sep 2017 14:30:17 -0300 Subject: [PATCH 37/42] Avoid setting url for not visible products to avoid 404 error page. --- .../Ebizmarts/MailChimp/Model/Api/Products.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index fa016efbb..6432536f6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -208,14 +208,15 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $data["id"] = $product->getId(); $data["title"] = ($product->getName()) ? $product->getName() : $product->getDefaultName(); $visibility = ($product->getVisibility()) ? $product->getVisibility() : $product->getDefaultVisibility(); - if ($visibility == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE && $this->_parentId) { - $url = $this->getNotVisibleProductUrl($product->getId(), $magentoStoreId); - if (!$url) { - $url = $this->getProductUrl($product, $magentoStoreId); + $url = null; + if ($visibility == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) { + if ($this->_parentUrl) { + $url = $this->getNotVisibleProductUrl($product->getId(), $magentoStoreId); } - $data["url"] = $url; } else { $url = $this->getProductUrl($product, $magentoStoreId); + } + if ($url) { $data["url"] = $url; } @@ -254,7 +255,9 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $this->_parentImageUrl = $data["image_url"]; } $this->_parentId = $product->getId(); - $this->_parentUrl = $data['url']; + if ($visibility != Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) { + $this->_parentUrl = $data['url']; + } $price = (float)$product->getDefaultPrice(); if ($price) { $this->_parentPrice = $price; From e6d20fdaed95b4221985fbae447fa71bd34a76b1 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 14 Sep 2017 16:35:19 -0300 Subject: [PATCH 38/42] Send correct path for simple products not visible. --- .../MailChimp/Model/Api/Products.php | 82 +++++++++++-------- 1 file changed, 49 insertions(+), 33 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 6432536f6..74bfe4a50 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -210,9 +210,7 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $visibility = ($product->getVisibility()) ? $product->getVisibility() : $product->getDefaultVisibility(); $url = null; if ($visibility == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) { - if ($this->_parentUrl) { - $url = $this->getNotVisibleProductUrl($product->getId(), $magentoStoreId); - } + $url = $this->getNotVisibleProductUrl($product->getId(), $magentoStoreId); } else { $url = $this->getProductUrl($product, $magentoStoreId); } @@ -667,41 +665,59 @@ public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId public function getNotVisibleProductUrl($childId, $magentoStoreId) { - $tableName = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute'); - $eavTableName = Mage::getSingleton('core/resource')->getTableName('eav/attribute'); + $parentId = null; + if (!$this->_parentId) { + $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($childId); + if (count($parentIds)) { + $parentId = $parentIds[0]; + } + } else { + $parentId = $this->_parentId; + } + if ($parentId) { + $tableName = Mage::getSingleton('core/resource')->getTableName('catalog/product_super_attribute'); + $eavTableName = Mage::getSingleton('core/resource')->getTableName('eav/attribute'); - $collection = $this->getProductResourceCollection(); - $collection->addStoreFilter($magentoStoreId); - $collection->addFieldToFilter('entity_id', array('eq' => $this->_parentId)); + $collection = $this->getProductResourceCollection(); + $collection->addStoreFilter($magentoStoreId); + $collection->addFieldToFilter('entity_id', array('eq' => $parentId)); - $collection->getSelect()->joinLeft( - array("super_attribute" => $tableName), - 'entity_id=super_attribute.product_id' - ); + $collection->getSelect()->joinLeft( + array("super_attribute" => $tableName), + 'entity_id=super_attribute.product_id' + ); - $collection->getSelect()->joinLeft( - array("eav_attribute" => $eavTableName), - 'super_attribute.attribute_id=eav_attribute.attribute_id' - ); - $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns('eav_attribute.attribute_id'); - - $rc = Mage::getResourceModel('catalog/product'); - $url = $this->_parentUrl; - $tailUrl = '#'; - $count = 0; - foreach ($collection as $attribute) { - if ($attribute->getAttributeId()) { - $attributeId = $attribute->getAttributeId(); - $attributeValue = $rc->getAttributeRawValue($childId, $attribute->getAttributeId(), $magentoStoreId); - if ($count > 0) { - $tailUrl .= '&'; + $collection->getSelect()->joinLeft( + array("eav_attribute" => $eavTableName), + 'super_attribute.attribute_id=eav_attribute.attribute_id' + ); + $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns('eav_attribute.attribute_id'); + + $rc = Mage::getResourceModel('catalog/product'); + if ($this->_parentUrl) { + $url = $this->_parentUrl; + } else { + $path = $rc->getAttributeRawValue($parentId, 'url_path', $magentoStoreId); + $url = Mage::getUrl($path, array('_store' => $magentoStoreId)); + } + $tailUrl = '#'; + $count = 0; + foreach ($collection as $attribute) { + if ($attribute->getAttributeId()) { + $attributeId = $attribute->getAttributeId(); + $attributeValue = $rc->getAttributeRawValue($childId, $attribute->getAttributeId(), $magentoStoreId); + if ($count > 0) { + $tailUrl .= '&'; + } + $tailUrl .= $attributeId . '=' . $attributeValue; } - $tailUrl .= $attributeId . '=' . $attributeValue; + $count++; } - $count++; - } - if ($tailUrl != '#') { - $url .= $tailUrl; + if ($tailUrl != '#') { + $url .= $tailUrl; + } + } else { + $url = null; } return $url; } From 48ba8ab6e4f314d3d0fc60029d7ea232dd4bfc60 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 14 Sep 2017 16:43:43 -0300 Subject: [PATCH 39/42] Do not leave product without url to avoid MailChimp error. --- .../community/Ebizmarts/MailChimp/Model/Api/Products.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 74bfe4a50..8f3c1e6ab 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -214,9 +214,10 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru } else { $url = $this->getProductUrl($product, $magentoStoreId); } - if ($url) { - $data["url"] = $url; + if (!$url) { + $url = Mage::app()->getStore($magentoStoreId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); } + $data["url"] = $url; //image $imageUrl = $this->getMailChimpHelper()->getMailChimpProductImageUrl($this->_parentImageUrl, $this->getMailChimpHelper()->getImageUrlById($product->getId())); From 9ef04bb9e6500856e93f404a2fa80aabd51c6999 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 15 Sep 2017 15:46:14 -0300 Subject: [PATCH 40/42] Send subscriber address as addr. --- .../community/Ebizmarts/MailChimp/Model/Api/Subscribers.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 288228b1a..42e2f97a5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -481,8 +481,8 @@ protected function getAddressData($address) if ($address) { $street = $address->getStreet(); if (count($street) > 1) { - $addressData["address1"] = $street[0]; - $addressData["address2"] = $street[1]; + $addressData["addr1"] = $street[0]; + $addressData["addr2"] = $street[1]; } else { if (!empty($street[0])) { $addressData["address1"] = $street[0]; From 9550b0b4aef2eb6f6c60b98a9ca70caad7c982c7 Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 18 Sep 2017 11:03:31 -0300 Subject: [PATCH 41/42] Fix address when there is only address 1 set. --- .../community/Ebizmarts/MailChimp/Model/Api/Subscribers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 42e2f97a5..ee2a12c17 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -485,7 +485,7 @@ protected function getAddressData($address) $addressData["addr2"] = $street[1]; } else { if (!empty($street[0])) { - $addressData["address1"] = $street[0]; + $addressData["addr1"] = $street[0]; } } From e0e41fc9bccc1dd0e846345875e6b0673c5a35a2 Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 18 Sep 2017 15:38:32 -0300 Subject: [PATCH 42/42] Update module version. --- app/code/community/Ebizmarts/MailChimp/etc/config.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index 8590b76f1..81fbd4c07 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.8 + 1.1.9 - 1.1.8 + 1.1.9