From ded9b79a7566ffcc44896f863ce2169a1796c1f1 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 16 Dec 2016 14:40:17 -0300 Subject: [PATCH 01/53] Country data sent properly on carts. --- app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index b0e4218bf..1e743e6d5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -383,8 +383,8 @@ protected function _getCustomer($cart,$mailchimpStoreId) $address['postal_code'] = $billingAddress->getPostcode(); } if ($billingAddress->getCountry()) { - $address['country'] = $billingAddress->getCountry(); - $address['country_code'] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $address['country'] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $address['country_code'] = $billingAddress->getCountry(); } if (count($address)) { $customer['address'] = $address; From 19f391a63e92d752b3569783a5f725afaa138ef0 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 16 Dec 2016 14:41:26 -0300 Subject: [PATCH 02/53] closes #108 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 1e743e6d5..bf152c38a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -383,6 +383,7 @@ protected function _getCustomer($cart,$mailchimpStoreId) $address['postal_code'] = $billingAddress->getPostcode(); } if ($billingAddress->getCountry()) { + $address['country'] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); $address['country_code'] = $billingAddress->getCountry(); } From fc1ab19e5328c321c431a6c409e47c03c0d1114f Mon Sep 17 00:00:00 2001 From: gonzalo Date: Thu, 22 Dec 2016 16:12:39 -0300 Subject: [PATCH 03/53] closes #88 Only products and customer are affected with this --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 6 +-- .../Ebizmarts/MailChimp/Model/Api/Carts.php | 30 +++++++++----- .../MailChimp/Model/Api/Customers.php | 15 ++++++- .../MailChimp/Model/Api/Products.php | 40 +++++++++++-------- 4 files changed, 59 insertions(+), 32 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 27f358d9f..db6ef1cec 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -297,8 +297,7 @@ protected function processEachResponseFile($files, $batchId) $p = Mage::getModel('catalog/product')->load($id); if ($p->getId() == $id) { $p->setData("mailchimp_sync_error", $error); - $p->setMailchimpUpdateObserverRan(true); - $p->save(); + $p->getResource()->saveAttribute($p,'mailchimp_sync_error'); } else { Mage::helper('mailchimp')->logError("Error: product " . $id . " not found"); } @@ -307,8 +306,7 @@ protected function processEachResponseFile($files, $batchId) $c = Mage::getModel('customer/customer')->load($id); if ($c->getId() == $id) { $c->setData("mailchimp_sync_error", $error); - $c->setMailchimpUpdateObserverRan(true); - $c->save(); + $c->getResource()->saveAttribute($c,'mailchimp_sync_error'); } else { Mage::helper('mailchimp')->logError("Error: customer " . $id . " not found"); } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index b0e4218bf..195bf0b6c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -76,7 +76,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['body'] = ''; $cartForEmail->setData("mailchimp_sync_delta", Varien_Date::now()); $cartForEmail->setMailchimpDeleted(1); - $cartForEmail->save(); + $this->_saveCart($cartForEmail); $this->_counter += 1; } } @@ -87,7 +87,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['body'] = ''; $cart->setData("mailchimp_sync_delta", Varien_Date::now()); $cart->setMailchimpDeleted(1); - $cart->save(); + $this->_saveCart($cart); $this->_counter += 1; } return $allCarts; @@ -117,6 +117,9 @@ protected function _getModifiedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; $allCarts[$this->_counter]['body'] = ''; $this->_counter += 1; + /** + * @var $customer Mage_Customer_Model_Customer + */ $customer = Mage::getModel("customer/customer"); $customer->setWebsiteId(Mage::getModel('core/store')->load($cart->getStoreId())->getWebsiteId()); $customer->loadByEmail($cart->getCustomerEmail()); @@ -131,7 +134,7 @@ protected function _getModifiedQuotes($mailchimpStoreId) $allCarts[$this->_counter]['body'] = ''; $cartForEmail->setData("mailchimp_sync_delta", Varien_Date::now()); $cartForEmail->setMailchimpDeleted(1); - $cartForEmail->save(); + $this->_saveCart($cartForEmail); $this->_counter += 1; } } @@ -139,7 +142,7 @@ protected function _getModifiedQuotes($mailchimpStoreId) } if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $cart->save(); + $this->_saveCart($cart); continue; } // send the products that not already sent @@ -161,7 +164,7 @@ protected function _getModifiedQuotes($mailchimpStoreId) } } $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $cart->save(); + $this->_saveCart($cart); } return $allCarts; } @@ -186,7 +189,7 @@ protected function _getNewQuotes($mailchimpStoreId) foreach ($newCarts as $cart) { if (!count($cart->getAllVisibleItems())) { $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $cart->save(); + $this->_saveCart($cart); continue; } $customer = Mage::getModel("customer/customer"); @@ -201,7 +204,7 @@ protected function _getNewQuotes($mailchimpStoreId) $allCarts[$this->_counter]['body'] = ''; $cartForEmail->setData("mailchimp_sync_delta", Varien_Date::now()); $cartForEmail->setMailchimpDeleted(1); - $cartForEmail->save(); + $this->_saveCart($cartForEmail); $this->_counter += 1; } $allCartsForEmail->clear(); @@ -209,7 +212,7 @@ protected function _getNewQuotes($mailchimpStoreId) // don't send the carts for guest customers who are registered if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $cart->save(); + $this->_saveCart($cart); continue; } // send the products that not already sent @@ -227,7 +230,7 @@ protected function _getNewQuotes($mailchimpStoreId) $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cart->getEntityId(); $allCarts[$this->_counter]['body'] = $cartJson; $cart->setData("mailchimp_sync_delta", Varien_Date::now()); - $cart->save(); + $this->_saveCart($cart); $this->_counter += 1; } } @@ -403,4 +406,13 @@ protected function _getApi() } return $this->_api; } + + /** + * @param $cart Mage_Sales_Model_Quote + */ + protected function _saveCart($cart) + { + + $cart->save(); + } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index a05ec909d..163538d6c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -59,7 +59,7 @@ public function createBatchJson($mailchimpStoreId) $customer->setData("mailchimp_sync_error", ""); $customer->setData("mailchimp_sync_modified", 0); $customer->setMailchimpUpdateObserverRan(true); - $customer->save(); + $this->_saveCustomer($customer); } $counter++; } @@ -121,7 +121,6 @@ protected function _buildCustomerData($customer) public function update($customer) { if (Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { -// $customer->setData("mailchimp_sync_delta", Varien_Date::now()); $customer->setData("mailchimp_sync_error", ""); $customer->setData("mailchimp_sync_modified", 1); } @@ -330,4 +329,16 @@ public function getOptin() { } return $optin; } + protected function _saveCustomer($customer) + { + if($customer->dataHasChangedFor('mailchimp_sync_delta')) { + $customer->getResource()->saveAttribute($customer,'mailchimp_sync_delta'); + } + if($customer->dataHasChangedFor('mailchimp_sync_error')) { + $customer->getResource()->saveAttribute($customer,'mailchimp_sync_error'); + } + if($customer->dataHasChangedFor('mailchimp_sync_modified')) { + $customer->getResource()->saveAttribute($customer,'mailchimp_sync_modified'); + } + } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index e2b7cfb55..d32dbc8ec 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -41,11 +41,8 @@ public function createBatchJson($mailchimpStoreId) if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { $batchArray = array_merge($this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId), $batchArray); $counter = (count($batchArray)); - $product->setData("mailchimp_sync_delta", Varien_Date::now()); - $product->setData("mailchimp_sync_error", ""); - $product->setData('mailchimp_sync_modified', 0); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $this->_setProductNoError($product); + $this->_saveProduct($product); continue; } else { $data = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId); @@ -56,17 +53,13 @@ public function createBatchJson($mailchimpStoreId) $counter++; //update product delta - $product->setData("mailchimp_sync_delta", Varien_Date::now()); - $product->setData("mailchimp_sync_error", ""); - $product->setData('mailchimp_sync_modified', 0); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $this->_setProductNoError($product); + $this->_saveProduct($product); } else { $product->setData("mailchimp_sync_delta", Varien_Date::now()); $product->setData("mailchimp_sync_error", "This product type is not supported on MailChimp."); $product->setData('mailchimp_sync_modified', 0); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $this->_saveProduct($product); continue; } } @@ -230,21 +223,34 @@ public function sendModifiedProduct($order, $mailchimpStoreId) } if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { $data[] = $this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId); - $this->_updateProduct($product); + $this->_setProductNoError($product); + $this->_saveProduct($product); } elseif (!$product->getMailchimpSyncDelta() || $product->getMailchimpSyncDelta() < Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { $data[] = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId); - $this->_updateProduct($product); + $this->_setProductNoError($product); + $this->_saveProduct($product); } } return $data; } - protected function _updateProduct($product) + protected function _setProductNoError($product) { $product->setData("mailchimp_sync_delta", Varien_Date::now()); $product->setData("mailchimp_sync_error", ""); $product->setData('mailchimp_sync_modified', 0); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + + } + protected function _saveProduct($product) + { + if($product->dataHasChangedFor('mailchimp_sync_delta')) { + $product->getResource()->saveAttribute($product,'mailchimp_sync_delta'); + } + if($product->dataHasChangedFor('mailchimp_sync_error')) { + $product->getResource()->saveAttribute($product,'mailchimp_sync_error'); + } + if($product->dataHasChangedFor('mailchimp_sync_modified')) { + $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); + } } } \ No newline at end of file From c7b315fc363eb0c66714d262075e885c96e29f8c Mon Sep 17 00:00:00 2001 From: gonzalo Date: Mon, 26 Dec 2016 11:02:04 -0300 Subject: [PATCH 04/53] closes #113 --- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 4 ++++ .../community/Ebizmarts/MailChimp/Model/Config.php | 1 + .../community/Ebizmarts/MailChimp/etc/system.xml | 13 +++++++++++++ 3 files changed, 18 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 1df249f4b..df45842ba 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -23,6 +23,7 @@ class Ebizmarts_MailChimp_Model_Api_Orders */ public function createBatchJson($mailchimpStoreId) { + $firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); //create missing products first $collection = Mage::getModel('sales/order')->getCollection() ->addAttributeToSelect('entity_id') @@ -32,6 +33,9 @@ public function createBatchJson($mailchimpStoreId) array('eq' => ''), array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) )); + if($firstDate) { + $collection->addFieldToFilter('created_at',array('from' => $firstDate)); + } $collection->getSelect()->limit(self::BATCH_LIMIT); $batchArray = array(); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php index 5131c7bdc..43c1399a4 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php @@ -31,6 +31,7 @@ class Ebizmarts_MailChimp_Model_Config const ECOMMERCE_ACTIVE = 'mailchimp/ecommerce/active'; const ECOMMERCE_CUSTOMERS_OPTIN = 'mailchimp/ecommerce/customers_optin'; + const ECOMMERCE_FIRSTDATE = 'mailchimp/ecommerce/firstdate'; const ENABLE_POPUP = 'mailchimp/emailcatcher/popup_general'; const POPUP_HEADING = 'mailchimp/emailcatcher/popup_heading'; diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 46dd422ff..23b1ce55c 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -211,6 +211,19 @@ 0 0 + + + date + mailchimp/adminhtml_system_config_date + 209 + 1 + 1 + 1 + + + 1 + + button From b9b5ef9fd545c6ae2ef20bc129eb0eaab9edb665 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 4 Jan 2017 11:16:39 -0300 Subject: [PATCH 05/53] Corrected typo. --- .../MailChimp/controllers/Adminhtml/EcommerceController.php | 2 +- .../controllers/Adminhtml/MailchimperrorsController.php | 2 +- .../MailChimp/controllers/Adminhtml/MergevarsController.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php index 61091c07f..8bff9b810 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php @@ -10,7 +10,7 @@ * @date: 5/27/16 1:50 PM * @file: EcommerceController.php */ -class Ebizmarts_Mailchimp_Adminhtml_EcommerceController extends Mage_Adminhtml_Controller_Action +class Ebizmarts_MailChimp_Adminhtml_EcommerceController extends Mage_Adminhtml_Controller_Action { public function resetLocalErrorsAction() { diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php index 3d28515c3..9bc3613d7 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php @@ -10,7 +10,7 @@ * @date: 6/10/16 12:35 PM * @file: MailchimperrorsController.php */ -class Ebizmarts_Mailchimp_Adminhtml_MailchimperrorsController extends Mage_Adminhtml_Controller_Action +class Ebizmarts_MailChimp_Adminhtml_MailchimperrorsController extends Mage_Adminhtml_Controller_Action { public function indexAction() { diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php index 60224e38a..bd4ade79f 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php @@ -9,7 +9,7 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * @file: MergevarsController.php */ -class Ebizmarts_Mailchimp_Adminhtml_MergevarsController extends Mage_Adminhtml_Controller_Action +class Ebizmarts_MailChimp_Adminhtml_MergevarsController extends Mage_Adminhtml_Controller_Action { public function addmergevarAction(){ From a3a1083504b45fa5b3a9510266a6ccc1b0c33f2f Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 4 Jan 2017 11:18:08 -0300 Subject: [PATCH 06/53] If not recipient available continue with next email in queue. --- .../Ebizmarts/MailChimp/Model/Email/Queue.php | 64 ++++++++++--------- lib/Ebizmarts/Mailchimp/ListsMembers.php | 2 +- 2 files changed, 35 insertions(+), 31 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php index 6d0c7ac19..c01028d62 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php @@ -41,41 +41,45 @@ public function send() } else { $mailer->setBodyHtml($message->getMessageBody()); } - foreach ($message->getRecipients() as $recipient) { - list($email, $name, $type) = $recipient; - switch ($type) { - case self::EMAIL_TYPE_TO: - case self::EMAIL_TYPE_CC: - $mailer->addTo($email,$name); - break; - case self::EMAIL_TYPE_BCC: - $mailer->addBcc($email); - break; - } - } - if ($parameters->getReplyTo() !== null) { - $mailer->setReplyTo($parameters->getReplyTo()); - } - if ($parameters->getReturnTo() !== null) { - $mailer->setReturnPath($parameters->getReturnTo()); - } try { - Mage::dispatchEvent( - 'fooman_emailattachments_before_send_queue', - array( - 'mailer' => $mailer, - 'message' => $message, - 'mail_transport' => false + foreach ($message->getRecipients() as $recipient) { + list($email, $name, $type) = $recipient; + switch ($type) { + case self::EMAIL_TYPE_TO: + case self::EMAIL_TYPE_CC: + $mailer->addTo($email, $name); + break; + case self::EMAIL_TYPE_BCC: + $mailer->addBcc($email); + break; + } + } + if ($parameters->getReplyTo() !== null) { + $mailer->setReplyTo($parameters->getReplyTo()); + } + if ($parameters->getReturnTo() !== null) { + $mailer->setReturnPath($parameters->getReturnTo()); + } + try { + Mage::dispatchEvent( + 'fooman_emailattachments_before_send_queue', + array( + 'mailer' => $mailer, + 'message' => $message, + 'mail_transport' => false - ) - ); - $mailer->send(); + ) + ); + $mailer->send(); + } catch (Exception $e) { + Mage::logException($e); + } + unset($mailer); + $message->setProcessedAt(Varien_Date::formatDate(true)); + $message->save(); } catch (Exception $e) { Mage::logException($e); } - unset($mailer); - $message->setProcessedAt(Varien_Date::formatDate(true)); - $message->save(); }else{ $parameters = new Varien_Object($message->getMessageParameters()); if ($parameters->getReturnPathEmail() !== null) { diff --git a/lib/Ebizmarts/Mailchimp/ListsMembers.php b/lib/Ebizmarts/Mailchimp/ListsMembers.php index d74e5ba72..d57c03154 100644 --- a/lib/Ebizmarts/Mailchimp/ListsMembers.php +++ b/lib/Ebizmarts/Mailchimp/ListsMembers.php @@ -165,7 +165,7 @@ public function update($listId, $subscriberHash, $emailType=null, $status=null, public function addOrUpdate($listId, $subscriberHash, $emailAddress, $statusIfNew, $emailType=null, $status=null, $mergeFields=null, $interests=null, $language=null, $vip=null, $location=null) { - $_params = array('status'=>$statusIfNew,'email_address'=>$emailAddress); + $_params = array('status_if_new'=>$statusIfNew,'email_address'=>$emailAddress); if($emailType) $_params['email_type'] = $emailType; if($status) $_params['status'] = $status; if($mergeFields) $_params['merge_fields'] = $mergeFields; From c57f758c70c95727d87b632a39411124a073c2be Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 4 Jan 2017 11:31:31 -0300 Subject: [PATCH 07/53] Updated version number. --- 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 9eff0014a..c1630490f 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.3 + 1.1.3.1 - 1.1.3 + 1.1.3.1 From df7e5cf935def08969036a65edccdbf225157cd7 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 4 Jan 2017 17:36:51 -0300 Subject: [PATCH 08/53] Updated version number. --- .../MailChimp/Model/Api/Customers.php | 37 ++++++++++----- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 45 ++++++++++++++----- 2 files changed, 61 insertions(+), 21 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index 163538d6c..696d12a84 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -92,18 +92,33 @@ protected function _buildCustomerData($customer) foreach ($customer->getAddresses() as $address) { //send only first address if (!array_key_exists("address", $data)) { + $customerAddress = array(); $street = $address->getStreet(); - $data["address"] = array( - "address1" => $street[0] ? $street[0] : "", - "address2" => count($street)>1 ? $street[1] : "", - "city" => $address->getCity() ? $address->getCity() : "", - "province" => $address->getRegion() ? $address->getRegion() : "", - "province_code" => $address->getRegionCode() ? $address->getRegionCode() : "", - "postal_code" => $address->getPostcode(), - "country" => $address->getCountry() ? Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName(): "", - "country_code" => $address->getCountry() ? $address->getCountry() : "" - ); - + if ($street[0]) { + $customerAddress["address1"] = $street[0]; + } + if (count($street) > 1) { + $customerAddress["address2"] = $street[1]; + } + if ($address->getCity()) { + $customerAddress["city"] = $address->getCity(); + } + if ($address->getRegion()) { + $customerAddress["province"] = $address->getRegion(); + } + if ($address->getRegionCode()) { + $customerAddress["province_code"] = $address->getRegionCode(); + } + if ($address->getPostcode()) { + $customerAddress["postal_code"] = $address->getPostcode(); + } + if ($address->getCountry()) { + $customerAddress["country"] = Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName(); + $customerAddress["country_code"] = $address->getCountry(); + } + if (count($address)) { + $data["address"] = $customerAddress; + } //company if ($address->getCompany()) { $data["company"] = $address->getCompany(); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index df45842ba..e44ea8caa 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -215,16 +215,41 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } $billingAddress = $order->getBillingAddress(); $street = $billingAddress->getStreet(); - $data["customer"]["address"] = array( - "address1" => $street[0], - "address2" => count($street) > 1 ? $street[1] : "", - "city" => $billingAddress->getCity(), - "province" => $billingAddress->getRegion() ? $billingAddress->getRegion() : "", - "province_code" => $billingAddress->getRegionCode() ? $billingAddress->getRegionCode() : "", - "postal_code" => $billingAddress->getPostcode(), - "country" => $billingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName() : "", - "country_code" => $billingAddress->getCountry() - ); + $address = array(); + + if ($street[0]) { + $address["address1"] = $street[0]; + } + + if (count($street) > 1) { + $address["address2"] = $street[1]; + } + + if ($billingAddress->getCity()) { + $address["city"] = $billingAddress->getCity(); + } + + if ($billingAddress->getRegion()) { + $address["province"] = $billingAddress->getRegion(); + } + + if ($billingAddress->getRegionCode()) { + $address["province_code"] = $billingAddress->getRegionCode(); + } + + if ($billingAddress->getPostcode()) { + $address["postal_code"] = $billingAddress->getPostcode(); + } + + if ($billingAddress->getCountry()) { + $address["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $address["country_code"] = $billingAddress->getCountry(); + } + + if (count($address)) { + $data["customer"]["address"] = $address; + } + //company if ($billingAddress->getCompany()) { $data["customer"]["company"] = $billingAddress->getCompany(); From f938debcf6fdfd1c67f98148f17cc81c8be4af38 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 5 Jan 2017 11:06:07 -0300 Subject: [PATCH 09/53] Get Store name from unsecure url config in stead of directly from the browser. --- 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 dbf7c6ec7..c50cdcb98 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -83,7 +83,7 @@ public function getConfigValue($path, $storeId = null, $returnParentValueIfNull */ public function getMCStoreName() { - return parse_url(Mage::getBaseUrl(), PHP_URL_HOST); + return Mage::getStoreConfig('web/unsecure/base_url'); } /** From 269c1ca80d27a619e0a8f5c2dea07f8d71f1e52d Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 5 Jan 2017 16:08:50 -0300 Subject: [PATCH 10/53] Update frontend_input of customer and product mailchimp_sync_delta attribute to datetime. closes #111 --- .../Ebizmarts/MailChimp/etc/config.xml | 4 +-- .../mysql4-upgrade-1.1.3-1.1.4.php | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index c1630490f..bc079602b 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.3.1 + 1.1.4 - 1.1.3.1 + 1.1.4 diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php new file mode 100644 index 000000000..797f562e0 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php @@ -0,0 +1,35 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/9/16 4:05 PM + * @file: mysql4-upgrade-1.0.1-1.0.2.php + */ + +$installer = $this; + +$installer->startSetup(); + +$attributeCode = 'mailchimp_sync_delta'; +$productEntityTypeId = $installer->getEntityTypeId('catalog_product'); +$customerEntityTypeId = $installer->getEntityTypeId('customer'); +$productAttributeId = $installer->getAttributeId($productEntityTypeId, $attributeCode); +$customerAttributeId = $installer->getAttributeId($customerEntityTypeId, $attributeCode); + +try { + $installer->updateAttribute($productEntityTypeId, $productAttributeId, 'frontend_input', 'datetime'); +} catch(Exception $e) { + Mage::log($e->getMessage()); +} +try { + $installer->updateAttribute($customerEntityTypeId, $customerAttributeId, 'frontend_input', 'datetime'); +} catch(Exception $e) { + Mage::log($e->getMessage()); +} + +$installer->endSetup(); \ No newline at end of file From 9675ced6dea4a2d428fb5d5c219e3d65edb31740 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 5 Jan 2017 16:37:57 -0300 Subject: [PATCH 11/53] Allow custom attributes to be deleted from back end. closes #119 --- .../mailchimp_setup/mysql4-install-0.0.1.php | 4 +- .../mysql4-upgrade-1.0.1-1.0.2.php | 2 +- .../mysql4-upgrade-1.0.3-1.0.4.php | 2 +- .../mysql4-upgrade-1.0.5-1.0.6.php | 2 +- .../mysql4-upgrade-1.1.1-1.1.2.php | 2 +- .../mysql4-upgrade-1.1.3-1.1.4.php | 35 ---------------- .../mysql4-upgrade-1.1.3.1-1.1.4.php | 42 +++++++++++++++++++ 7 files changed, 48 insertions(+), 41 deletions(-) delete mode 100644 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php create mode 100644 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php index 86836e12e..0d36269d9 100755 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-install-0.0.1.php @@ -95,7 +95,7 @@ } catch (Exception $e) { - Mage::log($e->getMessage()); + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } $installer->run( @@ -116,7 +116,7 @@ mkdir($baseDir . DS . 'var' . DS . 'mailchimp'); } catch (Exception $e){ - Mage::log($e->getMessage()); + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } $installer->endSetup(); diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php index abd21b0b4..888211019 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.1-1.0.2.php @@ -41,7 +41,7 @@ ); } catch(Exception $e){ - Mage::log($e->getMessage()); + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } $installer->endSetup(); \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php index 21fd8a8bc..418b23074 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.3-1.0.4.php @@ -53,7 +53,7 @@ } catch (Exception $e) { - Mage::log($e->getMessage()); + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } $installer->endSetup(); \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php index 515ff2771..6f5a45d07 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.0.5-1.0.6.php @@ -32,7 +32,7 @@ } catch (Exception $e) { - Mage::log($e->getMessage()); + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } $installer->endSetup(); \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.1-1.1.2.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.1-1.1.2.php index 9e673309e..c663698d0 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.1-1.1.2.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.1-1.1.2.php @@ -26,7 +26,7 @@ } catch (Exception $e) { - Mage::log($e->getMessage()); + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } $installer->endSetup(); \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php deleted file mode 100644 index 797f562e0..000000000 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3-1.1.4.php +++ /dev/null @@ -1,35 +0,0 @@ - - * @copyright Ebizmarts (http://ebizmarts.com) - * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 6/9/16 4:05 PM - * @file: mysql4-upgrade-1.0.1-1.0.2.php - */ - -$installer = $this; - -$installer->startSetup(); - -$attributeCode = 'mailchimp_sync_delta'; -$productEntityTypeId = $installer->getEntityTypeId('catalog_product'); -$customerEntityTypeId = $installer->getEntityTypeId('customer'); -$productAttributeId = $installer->getAttributeId($productEntityTypeId, $attributeCode); -$customerAttributeId = $installer->getAttributeId($customerEntityTypeId, $attributeCode); - -try { - $installer->updateAttribute($productEntityTypeId, $productAttributeId, 'frontend_input', 'datetime'); -} catch(Exception $e) { - Mage::log($e->getMessage()); -} -try { - $installer->updateAttribute($customerEntityTypeId, $customerAttributeId, 'frontend_input', 'datetime'); -} catch(Exception $e) { - Mage::log($e->getMessage()); -} - -$installer->endSetup(); \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php new file mode 100644 index 000000000..8811e7b6a --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.3.1-1.1.4.php @@ -0,0 +1,42 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/9/16 4:05 PM + * @file: mysql4-upgrade-1.0.1-1.0.2.php + */ + +$installer = $this; + +$installer->startSetup(); + +$deltaAttributeCode = 'mailchimp_sync_delta'; +$errorAttributeCode = 'mailchimp_sync_error'; +$modifiedAttributeCode = 'mailchimp_sync_modified'; +$productEntityTypeId = $installer->getEntityTypeId('catalog_product'); +$customerEntityTypeId = $installer->getEntityTypeId('customer'); +$productDeltaAttributeId = $installer->getAttributeId($productEntityTypeId, $deltaAttributeCode); +$productErrorAttributeId = $installer->getAttributeId($productEntityTypeId, $errorAttributeCode); +$productModifiedAttributeId = $installer->getAttributeId($productEntityTypeId, $modifiedAttributeCode); +$customerDeltaAttributeId = $installer->getAttributeId($customerEntityTypeId, $deltaAttributeCode); +$customerErrorAttributeId = $installer->getAttributeId($customerEntityTypeId, $errorAttributeCode); +$customerModifiedAttributeId = $installer->getAttributeId($customerEntityTypeId, $modifiedAttributeCode); +try { + $installer->updateAttribute($productEntityTypeId, $productDeltaAttributeId, 'is_user_defined', 1); + $installer->updateAttribute($productEntityTypeId, $productErrorAttributeId, 'is_user_defined', 1); + $installer->updateAttribute($productEntityTypeId, $productModifiedAttributeId, 'is_user_defined', 1); + $installer->updateAttribute($productEntityTypeId, $productDeltaAttributeId, 'frontend_input', 'datetime'); + $installer->updateAttribute($customerEntityTypeId, $customerDeltaAttributeId, 'is_user_defined', 1); + $installer->updateAttribute($customerEntityTypeId, $customerErrorAttributeId, 'is_user_defined', 1); + $installer->updateAttribute($customerEntityTypeId, $customerModifiedAttributeId, 'is_user_defined', 1); + $installer->updateAttribute($customerEntityTypeId, $customerDeltaAttributeId, 'frontend_input', 'datetime'); +} catch(Exception $e) { + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); +} + +$installer->endSetup(); \ No newline at end of file From a86eb497b4eaea18ee55001e2f5959e3edb8e868 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 5 Jan 2017 16:46:13 -0300 Subject: [PATCH 12/53] If the batch id doesn't exists when retrieving batch responses mark status as error and continue with the next one. closes #116 --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index db6ef1cec..86e4db45c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -45,9 +45,14 @@ protected function _getResults($storeId, $isMailChimpStoreId = false) $storeId = ($isMailChimpStoreId) ? 0 : $storeId; $files = $this->getBatchResponse($item->getBatchId(), $storeId); if (count($files)) { - $this->processEachResponseFile($files, $item->getBatchId()); - $item->setStatus('completed'); - $item->save(); + if (isset($files['error'])) { + $item->setStatus('error'); + $item->save(); + } else { + $this->processEachResponseFile($files, $item->getBatchId()); + $item->setStatus('completed'); + $item->save(); + } } $baseDir = Mage::getBaseDir(); if (is_dir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $item->getBatchId())) { @@ -214,10 +219,9 @@ public function sendStoreSubscriberBatch($storeId, $limit) /** * @param $batchId - * @param $storeId * @return array */ - protected function getBatchResponse($batchId, $storeId = 0) + protected function getBatchResponse($batchId) { $files = array(); try { @@ -252,6 +256,7 @@ protected function getBatchResponse($batchId, $storeId = 0) unlink($fileName . '.tar.gz'); } } catch (Mailchimp_Error $e) { + $files['error'] = $e->getFriendlyMessage(); Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); From 70d62930a925a00eacf0a769e0cff3c33ee694b5 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 11 Jan 2017 11:29:21 -0300 Subject: [PATCH 13/53] Typo in configuration header fixed. closes #121 --- .../ebizmarts/mailchimp/system/config/fieldset/hint.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/fieldset/hint.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/fieldset/hint.phtml index 9157fa7d1..d0f66d5ba 100644 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/fieldset/hint.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/fieldset/hint.phtml @@ -8,7 +8,7 @@

__('MailChimp For Magento v%s by ebizmarts', $this->getMailChimpVersion()) ?>
- __('Need help? Read howto Configure and Connect or browse our support forums'); ?> + __('Need help? Read how to Configure and Connect or browse our support forums'); ?>

Subscribe for a free MailChimp Account!

\ No newline at end of file From 21f5e096f7e6a9405432dc0fdfe78b56b79f48b4 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 11 Jan 2017 16:54:38 -0300 Subject: [PATCH 14/53] First date filter added to order data saved in customer. --- .../community/Ebizmarts/MailChimp/Model/Api/Customers.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index 696d12a84..e03e419f9 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -68,6 +68,7 @@ public function createBatchJson($mailchimpStoreId) protected function _buildCustomerData($customer) { + $firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); $data = array(); $data["id"] = $customer->getId(); $data["email_address"] = $customer->getEmail() ? $customer->getEmail() : ''; @@ -79,6 +80,9 @@ protected function _buildCustomerData($customer) $orderCollection = Mage::getModel('sales/order')->getCollection() ->addFieldToFilter('state', 'complete') ->addAttributeToFilter('customer_id', array('eq' => $customer->getId())); + if($firstDate) { + $orderCollection->addFieldToFilter('created_at',array('from' => $firstDate)); + } $totalOrders = 0; $totalAmountSpent = 0; foreach ($orderCollection as $order) { From 7092415c642c441c8fdfc45b70068820f45b7ee2 Mon Sep 17 00:00:00 2001 From: Santiago Date: Sat, 14 Jan 2017 01:09:04 -0300 Subject: [PATCH 15/53] Send all orders and update the status to fit MailChimp API (In progress) --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 8 +- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 323 +++++++++++++----- .../Ebizmarts/MailChimp/Model/Observer.php | 11 +- .../Ebizmarts/MailChimp/etc/config.xml | 12 +- .../mysql4-upgrade-1.1.4-1.1.5.php | 31 ++ 5 files changed, 300 insertions(+), 85 deletions(-) create mode 100644 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 86e4db45c..c414ea9e8 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -88,10 +88,10 @@ public function _sendEcommerceBatch($mailchimpStoreId) $batchArray['operations'] = array_merge($batchArray['operations'], $cartsArray); $ordersArray = Mage::getModel('mailchimp/api_orders')->createBatchJson($mailchimpStoreId); $batchArray['operations'] = array_merge($batchArray['operations'], $ordersArray); - if (empty($ordersArray)) { - $ordersCanceledArray = Mage::getModel('mailchimp/api_orders')->createCanceledBatchJson($mailchimpStoreId); - $batchArray['operations'] = array_merge($batchArray['operations'], $ordersCanceledArray); - } +// if (empty($ordersArray)) { +// $ordersCanceledArray = Mage::getModel('mailchimp/api_orders')->createCanceledBatchJson($mailchimpStoreId); +// $batchArray['operations'] = array_merge($batchArray['operations'], $ordersCanceledArray); +// } try { /** * @var $mailchimpApi \Ebizmarts_Mailchimp diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index e44ea8caa..c15b1e9e5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -13,6 +13,18 @@ class Ebizmarts_MailChimp_Model_Api_Orders { const BATCH_LIMIT = 50; + const PAID = 'paid'; + const PARTIALLY_PAID = 'parially_paid'; + const SHIPPED = 'shipped'; + const PARTIALLY_SHIPPED = 'parially_shipped'; + const PENDING = 'pending'; + const REFUNDED = 'refunded'; + const PARTIALLY_REFUNDED = 'partially_refunded'; + const CANCELED = 'canceled'; + const COMPLETE = 'complete'; + protected $_firstDate; + protected $_counter; + protected $_batchId; protected $_api = null; /** @@ -23,41 +35,52 @@ class Ebizmarts_MailChimp_Model_Api_Orders */ public function createBatchJson($mailchimpStoreId) { - $firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); + Mage::log(__METHOD__, null, 'ebizmarts.log', true); + $batchArray = array(); + $this->_firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); + $this->_counter = 0; + $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_ORDER.'_'. Mage::helper('mailchimp')->getDateMicrotime(); + + Mage::log('before modified', null, 'ebizmarts.log', true); + // get all the carts modified but not converted in orders + $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId)); + Mage::log('before new', null, 'ebizmarts.log', true); + // get new carts + $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId)); + + return $batchArray; + } + + protected function _getModifiedOrders($mailchimpStoreId) + { + Mage::log(__METHOD__, null, 'ebizmarts.log', true); + $batchArray = array(); //create missing products first $collection = Mage::getModel('sales/order')->getCollection() ->addAttributeToSelect('entity_id') - ->addFieldToFilter('state', 'complete') - ->addFieldToFilter('mailchimp_sync_delta', array( - array('null' => true), - array('eq' => ''), - array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) - )); - if($firstDate) { - $collection->addFieldToFilter('created_at',array('from' => $firstDate)); + ->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())) + ->addFieldToFilter('mailchimp_sync_modified', array('eq' => 1)); + if($this->_firstDate) { + $collection->addFieldToFilter('created_at',array('from' => $this->_firstDate)); } $collection->getSelect()->limit(self::BATCH_LIMIT); - $batchArray = array(); - - $batchId = Ebizmarts_MailChimp_Model_Config::IS_ORDER.'_'. Mage::helper('mailchimp')->getDateMicrotime(); - $counter = 0; foreach ($collection as $item) { try { $order = Mage::getModel('sales/order')->load($item->getEntityId()); $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId); if (count($productData)) { foreach ($productData as $p) { - $batchArray[$counter] = $p; - $counter++; + $batchArray[$this->_counter] = $p; + $this->_counter++; } } $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); if (!empty($orderJson)) { - $batchArray[$counter]['method'] = "POST"; - $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; - $batchArray[$counter]['operation_id'] = $batchId . '_' . $order->getEntityId(); - $batchArray[$counter]['body'] = $orderJson; + $batchArray[$this->_counter]['method'] = "PATCH"; + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); + $batchArray[$this->_counter]['body'] = $orderJson; } else { $error = Mage::helper('mailchimp')->__('Something went wrong when retreiving product information.'); @@ -65,56 +88,111 @@ public function createBatchJson($mailchimpStoreId) } //update order delta $order->setData("mailchimp_sync_delta", Varien_Date::now()); + $order->setMailchimpSyncModified(0); + $order->setNotUpdateModified(1); $order->save(); - $counter++; + $this->_counter++; } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } } + Mage::log('modified orders: '.count($batchArray), null, 'ebizmarts.log', true); return $batchArray; } - /** - * Set the orders to be removed from MailChimp because they were canceled - * - * @param $mailchimpStoreId - * @return array - */ - public function createCanceledBatchJson($mailchimpStoreId) + protected function _getNewOrders($mailchimpStoreId) { + Mage::log(__METHOD__, null, 'ebizmarts.log', true); + $batchArray = array(); //create missing products first $collection = Mage::getModel('sales/order')->getCollection() - ->addAttributeToSelect('status') - ->addAttributeToSelect('mailchimp_sync_delta') ->addAttributeToSelect('entity_id') - ->addFieldToFilter('state', 'canceled') - ->addFieldToFilter( - 'mailchimp_sync_delta', array( + ->addFieldToFilter('mailchimp_sync_delta', array( array('null' => true), array('eq' => ''), array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) - ) - ); + )); + if($this->_firstDate) { + $collection->addFieldToFilter('created_at',array('from' => $this->_firstDate)); + } $collection->getSelect()->limit(self::BATCH_LIMIT); - $batchArray = array(); - $counter = 0; - foreach ($collection as $order) { - if (!empty($orderJson)) { - $batchArray[$counter]['method'] = "DELETE"; - $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); + foreach ($collection as $item) { + try { + $order = Mage::getModel('sales/order')->load($item->getEntityId()); + $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($order, $mailchimpStoreId); + if (count($productData)) { + foreach ($productData as $p) { + $batchArray[$this->_counter] = $p; + $this->_counter++; + } + } + $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); + if (!empty($orderJson)) { + $batchArray[$this->_counter]['method'] = "POST"; + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); + $batchArray[$this->_counter]['body'] = $orderJson; + } else { + $error = Mage::helper('mailchimp')->__('Something went wrong when retreiving product information.'); + $order->setData("mailchimp_sync_error", $error); + } //update order delta $order->setData("mailchimp_sync_delta", Varien_Date::now()); + $order->setMailchimpSyncModified(0); + $order->setNotUpdateModified(1); $order->save(); + $this->_counter++; + } catch (Exception $e) { + Mage::helper('mailchimp')->logError($e->getMessage()); } - $counter++; } - + Mage::log('new orders: '.count($batchArray), null, 'ebizmarts.log', true); return $batchArray; } + /** + * Set the orders to be removed from MailChimp because they were canceled + * + * @param $mailchimpStoreId + * @return array + */ +// public function createCanceledBatchJson($mailchimpStoreId) +// { +// //create missing products first +// $collection = Mage::getModel('sales/order')->getCollection() +// ->addAttributeToSelect('status') +// ->addAttributeToSelect('mailchimp_sync_delta') +// ->addAttributeToSelect('entity_id') +// ->addFieldToFilter('state', 'canceled') +// ->addFieldToFilter( +// 'mailchimp_sync_delta', array( +// array('null' => true), +// array('eq' => ''), +// array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) +// ) +// ); +// $collection->getSelect()->limit(self::BATCH_LIMIT); +// +// $batchArray = array(); +// $counter = 0; +// foreach ($collection as $order) { +// if (!empty($orderJson)) { +// $batchArray[$counter]['method'] = "DELETE"; +// $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); +// +// //update order delta +// $order->setData("mailchimp_sync_delta", Varien_Date::now()); +// $order->save(); +// } +// $counter++; +// } +// +// return $batchArray; +// } + /** * Set all the data for each order to be sent * @@ -135,6 +213,22 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $data['order_total'] = $order->getGrandTotal(); $data['tax_total'] = $order->getTaxAmount(); $data['shipping_total'] = $order->getShippingAmount(); + $data['financial_status'] = $this->_getMailChimpStatus($order); + $data['processed_at_foreign'] = $order->getCreatedAt(); + $data['updated_at_foreign'] = $order->getUpdatedAt(); + if ($order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { + $orderCancelDate = null; + $commentCollection = $order->getStatusHistoryCollection(); + foreach ($commentCollection as $comment) { + Mage::log($comment->getStatus(), null, 'canceled_status.log', true); + if ($comment->getStatus() === Mage_Sales_Model_Order::STATE_CANCELED) { + $orderCancelDate = $comment->getCreatedAt(); + } + } + if ($orderCancelDate) { + $data['cancelled_at_foreign'] = $orderCancelDate; + } + } $data['processed_at_foreign'] = $order->getCreatedAt(); $data['lines'] = array(); @@ -165,8 +259,8 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } } if (!$itemCount) { - return ""; unset($data['lines']); + return ""; } //customer data $api = $this->_getApi(); @@ -176,43 +270,45 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } - if (isset($customers['total_items']) && $customers['total_items'] > 0) { - $id = $customers['customers'][0]['id']; - $data['customer'] = array( - 'id' => $id - ); - $guestCustomer = Mage::getModel('mailchimp/api_customers')->createGuestCustomer($id, $order); - $mergeFields = Mage::getModel('mailchimp/api_customers')->getMergeVars($guestCustomer); - if (is_array($mergeFields)) { - $data['customer'] = array_merge($mergeFields, $data['customer']); - } - } else { - if ((bool)$order->getCustomerIsGuest()) { - $guestId = "GUEST-" . Mage::helper('mailchimp')->getDateMicrotime(); - $data["customer"] = array( - "id" => $guestId, - "email_address" => $order->getCustomerEmail(), - "opt_in_status" => false + if (!$this->_isModifiedOrder($order)) { + if (isset($customers['total_items']) && $customers['total_items'] > 0) { + $id = $customers['customers'][0]['id']; + $data['customer'] = array( + 'id' => $id ); - $guestCustomer = Mage::getModel('mailchimp/api_customers')->createGuestCustomer($guestId, $order); - $mergeFields = Mage::getModel('mailchimp/api_customers')->getMergeVars($guestCustomer); - if (is_array($mergeFields)) { - $data['customer'] = array_merge($mergeFields, $data['customer']); - } +// $guestCustomer = Mage::getModel('mailchimp/api_customers')->createGuestCustomer($id, $order); +// $mergeFields = Mage::getModel('mailchimp/api_customers')->getMergeVars($guestCustomer); +// if (is_array($mergeFields)) { +// $data['customer'] = array_merge($mergeFields, $data['customer']); +// } } else { - $data["customer"] = array( - "id" => $order->getCustomerId(), - "email_address" => $order->getCustomerEmail(), - "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin() - ); - } - if($order->getCustomerFirstname()) { - $data["customer"]["first_name"] = $order->getCustomerFirstname(); - } - if($order->getCustomerLastname()) { - $data["customer"]["last_name"] = $order->getCustomerLastname(); + if ((bool)$order->getCustomerIsGuest()) { + $guestId = "GUEST-" . Mage::helper('mailchimp')->getDateMicrotime(); + $data["customer"] = array( + "id" => $guestId, + "email_address" => $order->getCustomerEmail(), + "opt_in_status" => false + ); +// $guestCustomer = Mage::getModel('mailchimp/api_customers')->createGuestCustomer($guestId, $order); +// $mergeFields = Mage::getModel('mailchimp/api_customers')->getMergeVars($guestCustomer); +// if (is_array($mergeFields)) { +// $data['customer'] = array_merge($mergeFields, $data['customer']); +// } + } else { + $data["customer"] = array( + "id" => $order->getCustomerId(), + "email_address" => $order->getCustomerEmail(), + "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin() + ); + } } } + if($order->getCustomerFirstname()) { + $data["customer"]["first_name"] = $order->getCustomerFirstname(); + } + if($order->getCustomerLastname()) { + $data["customer"]["last_name"] = $order->getCustomerLastname(); + } $billingAddress = $order->getBillingAddress(); $street = $billingAddress->getStreet(); $address = array(); @@ -262,6 +358,9 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) ->addFieldToFilter('mailchimp_sync_delta', array('neq' => '')) ->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())) ->addFieldToFilter('mailchimp_sync_error', array('eq' => "")); + if($this->_firstDate) { + $orderCollection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); + } $totalOrders = 1; $totalAmountSpent = (int)$order->getGrandTotal(); foreach ($orderCollection as $orderAlreadySent) { @@ -274,9 +373,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) //enconde to JSON try { - $jsonData = json_encode($data); - } catch (Exception $e) { //json encode failed Mage::helper('mailchimp')->logError("Order ".$order->getId()." json encode failed"); @@ -285,6 +382,76 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) return $jsonData; } + /** + * Return all orders already sent to MailChimp that have been modified. + * + * @param $order + * @return bool + */ + protected function _isModifiedOrder($order) + { + return ($order->getMailchimpSyncModified() && $order->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()); + } + + protected function _getMailChimpStatus($order) + { + switch ($order->getState()) { + case 'complete': + $status = self::COMPLETE; + break; + case 'pending': + $status = $this->_getMailChimpPendingStatus($order); + break; + case 'canceled': + $status = self::CANCELED; + break; + default: + $status = self::PENDING; + break; + } + return $status; + } + + protected function _getMailChimpPendingStatus($order) + { +// if ($order->getBaseTotalDue() === 0) { +// $mailChimpStatus = self::PAID; +// } else { +// if ($order->getBaseTotalDue() < $order->getBaseGrandTotal()) { +// $mailChimpStatus = self::PARTIALLY_PAID; +// } +// } + $mailChimpStatus = null; + $totalItemsOrdered = $order->getData('total_qty_ordered'); + $shippedItemAmount = 0; + $invoicedItemAmount = 0; + + foreach ($order->getAllVisibleItems() as $item){ + $shippedItemAmount += $item->getQtyShipped(); + $invoicedItemAmount += $item->getQtyInvoiced(); + } + if ($invoicedItemAmount > 0) { + if ($totalItemsOrdered > $invoicedItemAmount) { + $mailChimpStatus = self::PARTIALLY_PAID; + } else { + $mailChimpStatus = self::PAID; + } + } + if ($shippedItemAmount > 0) { + if ($totalItemsOrdered > $shippedItemAmount) { + $mailChimpStatus = (!$mailChimpStatus) ? self::PARTIALLY_SHIPPED : $mailChimpStatus.','.self::PARTIALLY_SHIPPED; + } else { + $mailChimpStatus = (!$mailChimpStatus) ? self::SHIPPED : $mailChimpStatus.','.self::SHIPPED; + } + } + if (!$mailChimpStatus) { + $mailChimpStatus = self::PENDING; + } + + return $mailChimpStatus; + + } + /** * Get Api Object * diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index cd607a080..461b04822 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -227,9 +227,18 @@ public function productSaveBefore(Varien_Event_Observer $observer) */ public function saveCampaignData(Varien_Event_Observer $observer) { + $order = $observer->getEvent()->getOrder(); $campaignCookie = $this->_getCampaignCookie(); if ($campaignCookie) { - $observer->getEvent()->getOrder()->setMailchimpCampaignId($campaignCookie); + $order->setMailchimpCampaignId($campaignCookie); + } + } + + public function orderSaveBefore(Varien_Event_Observer $observer) + { + $order = $observer->getEvent()->getOrder(); + if ($order->getNotUpdateModified()) { + $order->setMailchimpSyncModified(1); } } diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index bc079602b..8070c324e 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.4 + 1.1.5 - 1.1.4 + 1.1.5 @@ -52,6 +52,14 @@ + + + + mailchimp/observer + orderSaveBefore + + + diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php new file mode 100644 index 000000000..2f7602559 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php @@ -0,0 +1,31 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/9/16 4:05 PM + * @file: mysql4-upgrade-1.0.1-1.0.2.php + */ + +$installer = $this; + +$installer->startSetup(); + +try { + $installer->run( + " + ALTER TABLE `{$this->getTable('sales_flat_order')}` ADD COLUMN `mailchimp_sync_modified` INT(1) DEFAULT 0; +" + ); +} +catch (Exception $e) +{ + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); +} + + +$installer->endSetup(); \ No newline at end of file From 5bcb825c2e8fa115428ac026be48655ad1553d1a Mon Sep 17 00:00:00 2001 From: gonzalo Date: Thu, 26 Jan 2017 15:24:54 -0300 Subject: [PATCH 16/53] closes #123 --- .../Ebizmarts/MailChimp/Model/Api/Carts.php | 2 +- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 3 ++ .../Ebizmarts/MailChimp/Model/Observer.php | 20 +++++++++++- .../Ebizmarts/MailChimp/etc/config.xml | 7 ++-- .../mysql4-upgrade-1.1.4-1.1.5.php | 32 +++++++++++++++++++ js/ebizmarts/mailchimp/campaignCatcher.js | 1 + 6 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 195bf0b6c..7accc0ad5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -321,7 +321,7 @@ protected function _makeCart($cart,$mailchimpStoreId) protected function _getCheckoutUrl($cart) { $token = md5(rand(0, 9999999)); - $url = Mage::getModel('core/url')->setStore($cart->getStoreId())->getUrl('', array('_nosid' => true)) . 'mailchimp/cart/loadquote?id=' . $cart->getEntityId() . '&token=' . $token; + $url = Mage::getModel('core/url')->setStore($cart->getStoreId())->getUrl('', array('_nosid' => true,'_secure' => true)) . 'mailchimp/cart/loadquote?id=' . $cart->getEntityId() . '&token=' . $token; $cart->setMailchimpToken($token); return $url; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index df45842ba..a71179a65 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -131,6 +131,9 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if ($order->getMailchimpCampaignId()) { $data['campaign_id'] = $order->getMailchimpCampaignId(); } + if ($order->getMailchimpLAndingPage()) { + $data['landing_site'] = $order->getMailchimpLandingPage(); + } $data['currency_code'] = $order->getOrderCurrencyCode(); $data['order_total'] = $order->getGrandTotal(); $data['tax_total'] = $order->getTaxAmount(); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index cd607a080..6ac59e4ee 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -43,7 +43,9 @@ protected function _createWebhook($listId) $url = Ebizmarts_MailChimp_Model_ProcessWebhook::WEBHOOKS_PATH; $hookUrl = Mage::getModel('core/url')->getUrl( $url, array( - 'wkey' => $webhooksKey + 'wkey' => $webhooksKey, + '_nosid' => true, + '_secure' => true )); if (FALSE != strstr($hookUrl, '?', true)) { @@ -231,6 +233,10 @@ public function saveCampaignData(Varien_Event_Observer $observer) if ($campaignCookie) { $observer->getEvent()->getOrder()->setMailchimpCampaignId($campaignCookie); } + $landingCookie = $this->_getLandingCookie(); + if ($landingCookie) { + $observer->getEvent()->getOrder()->setMailchimpLandingPage($landingCookie); + } } /** @@ -245,6 +251,9 @@ public function removeCampaignData(Varien_Event_Observer $observer) if ($this->_getCampaignCookie()) { Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); } + if( ($this->_getLandingCookie())) { + Mage::getModel('core/cookie')->delete('maichimp_landing_page'); + } return $observer; } @@ -262,6 +271,15 @@ protected function _getCampaignCookie() return null; } } + protected function _getLandingCookie() + { + $cookie = Mage::getModel('core/cookie')->get('maichimp_landing_page'); + if ($cookie && Mage::getModel('core/cookie')->getLifetime('maichimp_landing_page') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { + return $cookie; + } else { + return null; + } + } /** * Add column to associate orders gained from MailChimp campaigns and automations. diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index 9eff0014a..bc2726e5d 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.3 + 1.1.5 - 1.1.3 + 1.1.5 @@ -120,6 +120,9 @@ * + + * + diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php new file mode 100644 index 000000000..a4c8e8db7 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php @@ -0,0 +1,32 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/9/16 4:05 PM + * @file: mysql4-upgrade-1.0.1-1.0.2.php + */ + +$installer = $this; + +$installer->startSetup(); + + +try { + $installer->run( + " + ALTER TABLE `{$this->getTable('sales_flat_quote')}` + ADD column `mailchimp_landing_page` VARCHAR (512) NOT NULL DEFAULT ''; + ALTER TABLE `{$this->getTable('sales_flat_order')}` + ADD column `mailchimp_landing_page` VARCHAR (512) NOT NULL DEFAULT ''; +" + ); +} +catch (Exception $e) +{ + Mage::log($e->getMessage()); +} \ No newline at end of file diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index 9dab2e976..07f374bd0 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -12,6 +12,7 @@ if (params['mc_cid']) { createCookie('mailchimp_campaign_id' , params['mc_cid'], 3600*3); + createCookie('maichimp_landing_page', location, 3600*3); } } From 09fdad9d5cb525c810b31abe70e701edd70b4f36 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Fri, 27 Jan 2017 11:31:39 -0300 Subject: [PATCH 17/53] closes #123 --- js/ebizmarts/mailchimp/campaignCatcher.js | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index 07f374bd0..f40953a70 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -1,6 +1,7 @@ function getCampaign() { var urlparams = location.search.substr(1).split('&'); var params = new Array(); + var mc_cid = null; for (var i = 0; i < urlparams.length; i++) { var param = urlparams[i].split('='); var key = param[0]; @@ -8,10 +9,22 @@ if (key && val) { params[key] = val; } + if(key=='utm_source') { + var reg = /^mailchimp-/; + if(reg.exec(val)) { + var aux =val.split('-'); + mc_cid = aux[1]; + } + } + else { + if (key=='mc_cid') { + mc_cid = val; + } + } } - if (params['mc_cid']) { - createCookie('mailchimp_campaign_id' , params['mc_cid'], 3600*3); + if (mc_cid) { + createCookie('mailchimp_campaign_id' , mc_cid, 3600*3); createCookie('maichimp_landing_page', location, 3600*3); } } From 9e4292019ec32b8ec77549a869f973772af07ecd Mon Sep 17 00:00:00 2001 From: gonzalo Date: Mon, 30 Jan 2017 14:52:36 -0300 Subject: [PATCH 18/53] Fix the issue when enable "Add Store Code to Urls" --- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 6ac59e4ee..ec0757097 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -38,14 +38,15 @@ public function saveConfig(Varien_Event_Observer $observer) */ protected function _createWebhook($listId) { + $store = Mage::app()->getDefaultStoreView(); $webhooksKey = Mage::helper('mailchimp')->getWebhooksKey(); //Generating Webhooks URL $url = Ebizmarts_MailChimp_Model_ProcessWebhook::WEBHOOKS_PATH; - $hookUrl = Mage::getModel('core/url')->getUrl( + $hookUrl = $store->getUrl( $url, array( 'wkey' => $webhooksKey, '_nosid' => true, - '_secure' => true + '_secure' => true, )); if (FALSE != strstr($hookUrl, '?', true)) { From f0d2f39a317e62a0087460cb67d9edd0f3c0caca Mon Sep 17 00:00:00 2001 From: gonzalo Date: Mon, 30 Jan 2017 15:17:14 -0300 Subject: [PATCH 19/53] closes #125 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php | 2 +- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 6 +++++- .../sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 7accc0ad5..3439d3aaa 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -260,7 +260,7 @@ protected function _getAllCartsByEmail($email) */ protected function _makeCart($cart,$mailchimpStoreId) { - $campaignId = $cart->getMailChimpCampaignId(); + $campaignId = $cart->getMailchimpCampaignId(); $oneCart = array(); $oneCart['id'] = $cart->getEntityId(); $oneCart['customer'] = $this->_getCustomer($cart, $mailchimpStoreId); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index ec0757097..e255fbf75 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -361,7 +361,11 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) } $campaignId = $this->_getCampaignCookie(); if ($campaignId) { - $quote->setMailChimpCampaignId($campaignId); + $quote->setMailchimpCampaignId($campaignId); + } + $landingCookie = $this->_getLandingCookie(); + if ($landingCookie) { + $quote->setMailchimpLandingPage($landingCookie); } return $observer; } diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php index a4c8e8db7..3df7d86e2 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php @@ -21,6 +21,8 @@ " ALTER TABLE `{$this->getTable('sales_flat_quote')}` ADD column `mailchimp_landing_page` VARCHAR (512) NOT NULL DEFAULT ''; + ALTER TABLE `{$this->getTable('sales_flat_quote')}` + ADD column `mailchimp_campaign_id` VARCHAR (16) NOT NULL DEFAULT ''; ALTER TABLE `{$this->getTable('sales_flat_order')}` ADD column `mailchimp_landing_page` VARCHAR (512) NOT NULL DEFAULT ''; " From 1c5bd942460230f2a7bd1df235981ddb6963207b Mon Sep 17 00:00:00 2001 From: gonzalo Date: Mon, 30 Jan 2017 16:43:46 -0300 Subject: [PATCH 20/53] closes #113 --- .../MailChimp/controllers/Adminhtml/EcommerceController.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php index 61091c07f..9293c3a35 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php @@ -28,6 +28,7 @@ public function resetEcommerceDataAction() $result = 1; try { Mage::helper('mailchimp')->resetMCEcommerceData(true); + Mage::helper('mailchimp')->resetErrors(); } catch(Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); From 6c0e42be37cbc2a9a53042179ece051b5a5e5b8f Mon Sep 17 00:00:00 2001 From: gonzalo Date: Tue, 31 Jan 2017 12:22:38 -0300 Subject: [PATCH 21/53] closes #126 --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 2 +- .../Adminhtml/MailchimperrorsController.php | 24 ++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index db6ef1cec..88e35ebe6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -217,7 +217,7 @@ public function sendStoreSubscriberBatch($storeId, $limit) * @param $storeId * @return array */ - protected function getBatchResponse($batchId, $storeId = 0) + public function getBatchResponse($batchId, $storeId = 0) { $files = array(); try { diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php index 3d28515c3..d1e7aee63 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php @@ -26,12 +26,34 @@ public function gridAction() $this->loadLayout(false); $this->renderLayout(); } - + public function downloadresponseAction() + { + $batch_id = $this->getRequest()->getParam('batch_id'); + $this->getResponse()->setHeader('Content-disposition','attachment; filename='.$batch_id.'.json'); + $this->getResponse()->setHeader('Content-type','application/json'); + $files = Mage::getModel('mailchimp/api_batches')->getBatchResponse($batch_id); + $fileContent = array(); + foreach ($files as $file) { + $items = json_decode(file_get_contents($file)); + foreach ($items as $item) { +// $fileContent [] = $item; + $fileContent [] = array('status_code'=>$item->status_code,'operation_id'=>$item->operation_id,'response'=>json_decode($item->response)); + } + unlink($file); + } + $baseDir = Mage::getBaseDir(); + if (is_dir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batch_id)) { + rmdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batch_id); + } + $this->getResponse()->setBody(json_encode($fileContent,JSON_PRETTY_PRINT)); + return; + } protected function _isAllowed() { switch ($this->getRequest()->getActionName()) { case 'index': case 'grid': + case 'downloadresponse': $acl = 'newsletter/mailchimp/mailchimperrors'; break; } From c49e791b920d3ccf94e959aefb0e66e447bd2b7c Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 31 Jan 2017 16:56:29 -0300 Subject: [PATCH 22/53] Added support for refunded products. closes #114 MailChimp order statuses sent within orders, all orders are sent to MailChimp. closes #120 --- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 2 + .../Ebizmarts/MailChimp/Model/Api/Orders.php | 52 ++++++++++++------- .../Ebizmarts/MailChimp/Model/Observer.php | 14 ++++- .../Ebizmarts/MailChimp/etc/config.xml | 40 +++++++++++--- 4 files changed, 78 insertions(+), 30 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index c414ea9e8..eebf5f3bf 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -320,6 +320,8 @@ protected function processEachResponseFile($files, $batchId) $o = Mage::getModel('sales/order')->load($id); if ($o->getId() == $id) { $o->setData("mailchimp_sync_error", $error); + $o->setMailchimpSyncModified(0); + $o->setMailchimpUpdateObserverRan(true); $o->save(); } else { Mage::helper('mailchimp')->logError("Error: order " . $id . " not found"); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 7d56c72af..955af7d94 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -35,16 +35,13 @@ class Ebizmarts_MailChimp_Model_Api_Orders */ public function createBatchJson($mailchimpStoreId) { - Mage::log(__METHOD__, null, 'ebizmarts.log', true); $batchArray = array(); $this->_firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); $this->_counter = 0; $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_ORDER.'_'. Mage::helper('mailchimp')->getDateMicrotime(); - Mage::log('before modified', null, 'ebizmarts.log', true); // get all the carts modified but not converted in orders $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId)); - Mage::log('before new', null, 'ebizmarts.log', true); // get new carts $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId)); @@ -53,7 +50,6 @@ public function createBatchJson($mailchimpStoreId) protected function _getModifiedOrders($mailchimpStoreId) { - Mage::log(__METHOD__, null, 'ebizmarts.log', true); $batchArray = array(); //create missing products first $collection = Mage::getModel('sales/order')->getCollection() @@ -89,21 +85,19 @@ protected function _getModifiedOrders($mailchimpStoreId) //update order delta $order->setData("mailchimp_sync_delta", Varien_Date::now()); $order->setMailchimpSyncModified(0); - $order->setNotUpdateModified(1); + $order->setMailchimpUpdateObserverRan(true); $order->save(); $this->_counter++; } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } } - Mage::log('modified orders: '.count($batchArray), null, 'ebizmarts.log', true); return $batchArray; } protected function _getNewOrders($mailchimpStoreId) { - Mage::log(__METHOD__, null, 'ebizmarts.log', true); $batchArray = array(); //create missing products first $collection = Mage::getModel('sales/order')->getCollection() @@ -142,14 +136,13 @@ protected function _getNewOrders($mailchimpStoreId) //update order delta $order->setData("mailchimp_sync_delta", Varien_Date::now()); $order->setMailchimpSyncModified(0); - $order->setNotUpdateModified(1); + $order->setMailchimpUpdateObserverRan(true); $order->save(); $this->_counter++; } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } } - Mage::log('new orders: '.count($batchArray), null, 'ebizmarts.log', true); return $batchArray; } @@ -223,7 +216,6 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $orderCancelDate = null; $commentCollection = $order->getStatusHistoryCollection(); foreach ($commentCollection as $comment) { - Mage::log($comment->getStatus(), null, 'canceled_status.log', true); if ($comment->getStatus() === Mage_Sales_Model_Order::STATE_CANCELED) { $orderCancelDate = $comment->getCreatedAt(); } @@ -243,6 +235,9 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $options = $item->getProductOptions(); $sku = $options['simple_sku']; $variant = Mage::getModel('catalog/product')->getIdBySku($sku); + if (!$variant) { + continue; + } } else { $variant = $item->getProductId(); } @@ -298,13 +293,26 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) // $data['customer'] = array_merge($mergeFields, $data['customer']); // } } else { + $custEmailAddr = null; + try { + $customer = $api->ecommerce->customers->get($mailchimpStoreId, $order->getCustomerId(), 'email_address'); + if (isset($customer['email_address'])) { + $custEmailAddr = $customer['email_address']; + } + } catch (Mailchimp_Error $e) { + } $data["customer"] = array( - "id" => $order->getCustomerId(), - "email_address" => $order->getCustomerEmail(), + "id" => ($order->getCustomerId()) ? $order->getCustomerId() : $guestId = "CUSTOMER-" . Mage::helper('mailchimp')->getDateMicrotime(), + "email_address" => ($custEmailAddr) ? $custEmailAddr : $order->getCustomerEmail(), "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin() ); } } + } else { + $id = $customers['customers'][0]['id']; + $data['customer'] = array( + 'id' => $id + ); } if($order->getCustomerFirstname()) { $data["customer"]["first_name"] = $order->getCustomerFirstname(); @@ -386,7 +394,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } /** - * Return all orders already sent to MailChimp that have been modified. + * Return true if order has been already sent to MailChimp and has been modified afterwards. * * @param $order * @return bool @@ -403,6 +411,9 @@ protected function _getMailChimpStatus($order) $status = self::COMPLETE; break; case 'pending': + $status = self::PENDING; + break; + case 'processing': $status = $this->_getMailChimpPendingStatus($order); break; case 'canceled': @@ -417,13 +428,6 @@ protected function _getMailChimpStatus($order) protected function _getMailChimpPendingStatus($order) { -// if ($order->getBaseTotalDue() === 0) { -// $mailChimpStatus = self::PAID; -// } else { -// if ($order->getBaseTotalDue() < $order->getBaseGrandTotal()) { -// $mailChimpStatus = self::PARTIALLY_PAID; -// } -// } $mailChimpStatus = null; $totalItemsOrdered = $order->getData('total_qty_ordered'); $shippedItemAmount = 0; @@ -455,6 +459,14 @@ protected function _getMailChimpPendingStatus($order) } + public function update($order) + { + if (Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { + $order->setData('mailchimp_sync_error', ''); + $order->setData('mailchimp_sync_modified', 1); + } + } + /** * Get Api Object * diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index fa74dd59f..3d22f627e 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -240,9 +240,13 @@ public function saveCampaignData(Varien_Event_Observer $observer) public function orderSaveBefore(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); - if ($order->getNotUpdateModified()) { - $order->setMailchimpSyncModified(1); + if ($order->getMailchimpUpdateObserverRan()) { + return $observer; + } else { + $order->setMailchimpUpdateObserverRan(true); } + //update mailchimp ecommerce data for that product variant + Mage::getModel('mailchimp/api_orders')->update($order); $landingCookie = $this->_getLandingCookie(); if ($landingCookie) { $observer->getEvent()->getOrder()->setMailchimpLandingPage($landingCookie); @@ -388,6 +392,9 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) */ public function newOrder(Varien_Event_Observer $observer) { + if( ($this->_getLandingCookie())) { + Mage::getModel('core/cookie')->delete('maichimp_landing_page'); + } if ($this->_getCampaignCookie()) { Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); } @@ -427,6 +434,7 @@ public function newCreditMemo(Varien_Event_Observer $observer) $product->setMailchimpUpdateObserverRan(true); $product->save(); } + $creditMemo->getOrder()->setMailchimpSyncModified(1); return $observer; } @@ -451,6 +459,7 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) $product->setMailchimpUpdateObserverRan(true); $product->save(); } + $creditMemo->getOrder()->setMailchimpSyncModified(1); return $observer; } @@ -472,6 +481,7 @@ public function itemCancel(Varien_Event_Observer$observer) } return $observer; } + public function addOrderViewMonkey(Varien_Event_Observer $observer){ $block = $observer->getBlock(); if(($block->getNameInLayout() == 'order_info') && ($child = $block->getChild('mailchimp.order.info.monkey.block'))){ diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index 9cb1bbd0e..cf9faa5e5 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -35,14 +35,6 @@ - - - - mailchimp/observer - removeCampaignData - - - @@ -60,6 +52,38 @@ + + + + mailchimp/observer + newOrder + + + + + + + mailchimp/observer + newCreditmemo + + + + + + + mailchimp/observer + cancelCreditmemo + + + + + + + mailchimp/observer + itemCancel + + + From e75e353e30598631cfc836d0ad61ac4feb15133a Mon Sep 17 00:00:00 2001 From: gonzalo Date: Wed, 1 Feb 2017 13:24:09 -0300 Subject: [PATCH 23/53] closes #95 --- js/ebizmarts/mailchimp/campaignCatcher.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index f40953a70..5e8f6b902 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -24,8 +24,8 @@ } if (mc_cid) { - createCookie('mailchimp_campaign_id' , mc_cid, 3600*3); - createCookie('maichimp_landing_page', location, 3600*3); + createCookie('mailchimp_campaign_id' , mc_cid); + createCookie('maichimp_landing_page', location); } } From f13c52d1c5c85754a94f24131e3f880980f3f823 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Wed, 1 Feb 2017 14:01:40 -0300 Subject: [PATCH 24/53] closes #127 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php | 3 ++- 1 file changed, 2 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 d32dbc8ec..70ef4c4e8 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -16,6 +16,7 @@ class Ebizmarts_MailChimp_Model_Api_Products public function createBatchJson($mailchimpStoreId) { + $store = Mage::app()->getDefaultStoreView(); //create missing products first $collection = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('id') @@ -35,7 +36,7 @@ public function createBatchJson($mailchimpStoreId) $batchId = Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . '_' . Mage::helper('mailchimp')->getDateMicrotime(); $counter = 0; foreach ($collection as $item) { - $product = Mage::getModel('catalog/product')->load($item->getId()); + $product = Mage::getModel('catalog/product')->setStoreId($store->getId())->load($item->getId()); $product->getTierPrice(); //define variants and root products if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { From 03bc175d019bb877aac2bb060db4c8d40952aa82 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Wed, 1 Feb 2017 20:40:03 -0300 Subject: [PATCH 25/53] closes #128 --- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index a71179a65..5f0e5d91a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -228,9 +228,39 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) "country" => $billingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName() : "", "country_code" => $billingAddress->getCountry() ); + $data["billing_address"] = array( + "name" => $billingAddress->getName(), + "address1" => $street[0], + "address2" => count($street) > 1 ? $street[1] : "", + "city" => $billingAddress->getCity(), + "province" => $billingAddress->getRegion() ? $billingAddress->getRegion() : "", + "province_code" => $billingAddress->getRegionCode() ? $billingAddress->getRegionCode() : "", + "postal_code" => $billingAddress->getPostcode(), + "country" => $billingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName() : "", + "country_code" => $billingAddress->getCountry() + ); + $shippingAddress = $order->getShippingAddress(); + $street = $shippingAddress->getStreet(); + $data["shipping_address"] = array( + "name" => $shippingAddress->getName(), + "address1" => $street[0], + "address2" => count($street) > 1 ? $street[1] : "", + "city" => $shippingAddress->getCity(), + "province" => $shippingAddress->getRegion() ? $shippingAddress->getRegion() : "", + "province_code" => $shippingAddress->getRegionCode() ? $shippingAddress->getRegionCode() : "", + "postal_code" => $shippingAddress->getPostcode(), + "country" => $shippingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName() : "", + "country_code" => $shippingAddress->getCountry() + ); + + //company if ($billingAddress->getCompany()) { $data["customer"]["company"] = $billingAddress->getCompany(); + $data["billing_address"]["company"] = $billingAddress->getCompany(); + } + if ($shippingAddress->getCompamy()) { + $data["shipping_address"]["company"] = $billingAddress->getCompany(); } //customer orders data $orderCollection = Mage::getModel('sales/order')->getCollection() From 574cf177e61405237cda806433c7510f32b417ab Mon Sep 17 00:00:00 2001 From: gonzalo Date: Thu, 2 Feb 2017 12:09:52 -0300 Subject: [PATCH 26/53] closes #128 --- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 69 ++++++++++--------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 37fd56e49..d0c3d439e 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -326,72 +326,75 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if ($street[0]) { $address["address1"] = $street[0]; + $data['billing_address']["address1"] = $street[0]; } if (count($street) > 1) { $address["address2"] = $street[1]; + $data['billing_address']["address2"] = $street[1]; } if ($billingAddress->getCity()) { $address["city"] = $billingAddress->getCity(); + $data['billing_address']["city"] = $billingAddress->getCity(); } if ($billingAddress->getRegion()) { $address["province"] = $billingAddress->getRegion(); + $data['billing_address']["province"] = $billingAddress->getRegion(); } if ($billingAddress->getRegionCode()) { $address["province_code"] = $billingAddress->getRegionCode(); + $data['billing_address']["province_code"] = $billingAddress->getRegionCode(); } if ($billingAddress->getPostcode()) { $address["postal_code"] = $billingAddress->getPostcode(); + $data['billing_address']["postal_code"] = $billingAddress->getPostcode(); } if ($billingAddress->getCountry()) { $address["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); $address["country_code"] = $billingAddress->getCountry(); + $data['billing_address']["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $data['billing_address']["country_code"] = $billingAddress->getCountry(); } if (count($address)) { $data["customer"]["address"] = $address; } + if ($billingAddress->getName()) { + $data['billing_address']['name'] = $billingAddress->getName(); + } - $data["customer"]["address"] = array( - "address1" => $street[0], - "address2" => count($street) > 1 ? $street[1] : "", - "city" => $billingAddress->getCity(), - "province" => $billingAddress->getRegion() ? $billingAddress->getRegion() : "", - "province_code" => $billingAddress->getRegionCode() ? $billingAddress->getRegionCode() : "", - "postal_code" => $billingAddress->getPostcode(), - "country" => $billingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName() : "", - "country_code" => $billingAddress->getCountry() - ); - $data["billing_address"] = array( - "name" => $billingAddress->getName(), - "address1" => $street[0], - "address2" => count($street) > 1 ? $street[1] : "", - "city" => $billingAddress->getCity(), - "province" => $billingAddress->getRegion() ? $billingAddress->getRegion() : "", - "province_code" => $billingAddress->getRegionCode() ? $billingAddress->getRegionCode() : "", - "postal_code" => $billingAddress->getPostcode(), - "country" => $billingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName() : "", - "country_code" => $billingAddress->getCountry() - ); $shippingAddress = $order->getShippingAddress(); $street = $shippingAddress->getStreet(); - $data["shipping_address"] = array( - "name" => $shippingAddress->getName(), - "address1" => $street[0], - "address2" => count($street) > 1 ? $street[1] : "", - "city" => $shippingAddress->getCity(), - "province" => $shippingAddress->getRegion() ? $shippingAddress->getRegion() : "", - "province_code" => $shippingAddress->getRegionCode() ? $shippingAddress->getRegionCode() : "", - "postal_code" => $shippingAddress->getPostcode(), - "country" => $shippingAddress->getCountry() ? Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName() : "", - "country_code" => $shippingAddress->getCountry() - ); - + if ($shippingAddress->getName()) { + $data['shipping_address']['name'] = $shippingAddress->getName() + } + if ($street[0]) { + $data['shipping_address']['address1'] = $street[0]; + } + if ($street[1]) { + $data['shipping_address']['address2'] = $street[1]; + } + if ($shippingAddress->getCity()) { + $data['shipping_address']['city'] = $shippingAddress->getCity(); + } + if ($shippingAddress->getRegion()) { + $data['shipping_address']['province'] = $shippingAddress->getRegion(); + } + if ($shippingAddress->getRegionCode()) { + $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); + } + if ($shippingAddress->getPostCode()) { + $data['shipping_address']['postal_code'] = $shippingAddress->getPostCode(); + } + if ($shippingAddress->getCountry()) { + $data['shipping_address']['country'] = Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName(); + $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); + } //company if ($billingAddress->getCompany()) { From f53bc01fc013eb853ef8c190e08ebb552a1f6cb9 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Thu, 2 Feb 2017 12:14:35 -0300 Subject: [PATCH 27/53] closes #128 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index d0c3d439e..d66d5a127 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -371,7 +371,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $shippingAddress = $order->getShippingAddress(); $street = $shippingAddress->getStreet(); if ($shippingAddress->getName()) { - $data['shipping_address']['name'] = $shippingAddress->getName() + $data['shipping_address']['name'] = $shippingAddress->getName(); } if ($street[0]) { $data['shipping_address']['address1'] = $street[0]; From 474537718d54ee1d00bc92ab45c33ffbe32343f8 Mon Sep 17 00:00:00 2001 From: Santiago Date: Thu, 2 Feb 2017 14:54:43 -0300 Subject: [PATCH 28/53] Fix for financial and fullfilment statuses. --- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 85 ++++++++++--------- 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 955af7d94..9d7fafca1 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -209,7 +209,14 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $data['order_total'] = $order->getGrandTotal(); $data['tax_total'] = $order->getTaxAmount(); $data['shipping_total'] = $order->getShippingAmount(); - $data['financial_status'] = $this->_getMailChimpStatus($order); + $statusArray = $this->_getMailChimpStatus($order); + if (isset($statusArray['financial_status'])) { + $data['financial_status'] = $statusArray['financial_status']; + } + if (isset($statusArray['fullfilment_status'])) { + $data['fullfilment_status'] = $statusArray['fullfilment_status']; + } + $data['processed_at_foreign'] = $order->getCreatedAt(); $data['updated_at_foreign'] = $order->getUpdatedAt(); if ($order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { @@ -224,7 +231,6 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $data['cancelled_at_foreign'] = $orderCancelDate; } } - $data['processed_at_foreign'] = $order->getCreatedAt(); $data['lines'] = array(); //order lines @@ -309,10 +315,12 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } } } else { - $id = $customers['customers'][0]['id']; - $data['customer'] = array( - 'id' => $id - ); + if (isset($customers['customers'][0]['id'])) { + $id = $customers['customers'][0]['id']; + $data['customer'] = array( + 'id' => $id + ); + } } if($order->getCustomerFirstname()) { $data["customer"]["first_name"] = $order->getCustomerFirstname(); @@ -406,57 +414,54 @@ protected function _isModifiedOrder($order) protected function _getMailChimpStatus($order) { - switch ($order->getState()) { - case 'complete': - $status = self::COMPLETE; - break; - case 'pending': - $status = self::PENDING; - break; - case 'processing': - $status = $this->_getMailChimpPendingStatus($order); - break; - case 'canceled': - $status = self::CANCELED; - break; - default: - $status = self::PENDING; - break; - } - return $status; - } - - protected function _getMailChimpPendingStatus($order) - { - $mailChimpStatus = null; + $mailChimpFinancialStatus = null; + $mailChimpFullfilmentStatus = null; $totalItemsOrdered = $order->getData('total_qty_ordered'); $shippedItemAmount = 0; $invoicedItemAmount = 0; + $refundedItemAmount = 0; + $mailChimpStatus = array(); foreach ($order->getAllVisibleItems() as $item){ $shippedItemAmount += $item->getQtyShipped(); $invoicedItemAmount += $item->getQtyInvoiced(); + $refundedItemAmount += $item->getQtyRefunded(); } - if ($invoicedItemAmount > 0) { - if ($totalItemsOrdered > $invoicedItemAmount) { - $mailChimpStatus = self::PARTIALLY_PAID; + if ($shippedItemAmount > 0) { + if ($totalItemsOrdered > $shippedItemAmount) { + $mailChimpFullfilmentStatus = self::PARTIALLY_SHIPPED; } else { - $mailChimpStatus = self::PAID; + $mailChimpFullfilmentStatus = self::SHIPPED; } } - if ($shippedItemAmount > 0) { - if ($totalItemsOrdered > $shippedItemAmount) { - $mailChimpStatus = (!$mailChimpStatus) ? self::PARTIALLY_SHIPPED : $mailChimpStatus.','.self::PARTIALLY_SHIPPED; + if ($refundedItemAmount > 0) { + if ($totalItemsOrdered > $refundedItemAmount) { + $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED; } else { - $mailChimpStatus = (!$mailChimpStatus) ? self::SHIPPED : $mailChimpStatus.','.self::SHIPPED; + $mailChimpFinancialStatus = self::REFUNDED; + } + } + if ($invoicedItemAmount > 0) { + if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) { + if ($totalItemsOrdered > $invoicedItemAmount) { + $mailChimpFinancialStatus = self::PARTIALLY_PAID; + } else { + $mailChimpFinancialStatus = self::PAID; + } } + } - if (!$mailChimpStatus) { - $mailChimpStatus = self::PENDING; + if (!$mailChimpFinancialStatus) { + $mailChimpFinancialStatus = self::PENDING; } + if ($mailChimpFinancialStatus) { + $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus; + } + if ($mailChimpFullfilmentStatus) { + $mailChimpStatus['fullfilment_status'] = $mailChimpFullfilmentStatus; + } return $mailChimpStatus; - } public function update($order) From 773df66e1ea072b3b5997d61ff23fbae0832d888 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 3 Feb 2017 10:32:24 -0300 Subject: [PATCH 29/53] system.log error when order is created fixed. --- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 3d22f627e..e0affad1c 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -407,8 +407,8 @@ public function newOrder(Varien_Event_Observer $observer) } $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $resource = $product->getResource(); + $resource->saveAttribute($product, 'mailchimp_sync_modified'); } return $observer; } From 8a8ddb2cbc2a26972da44c348d0558df77d4d68e Mon Sep 17 00:00:00 2001 From: gonzalo Date: Fri, 3 Feb 2017 10:37:28 -0300 Subject: [PATCH 30/53] closes #117 --- .../community/Ebizmarts/MailChimp/Helper/Data.php | 14 ++++++++++---- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index c50cdcb98..e6d7e8d49 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -216,8 +216,11 @@ public function resetErrors() foreach ($collection as $product) { $product->setData("mailchimp_sync_delta", null); $product->setData("mailchimp_sync_error", ''); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $resource = $product->getResource(); + $resource->saveAttribute($product, 'mailchimp_sync_delta'); + $resource->saveAttribute($product, 'mailchimp_sync_error'); +// $product->setMailchimpUpdateObserverRan(true); +// $product->save(); } // reset subscribers with errors @@ -240,8 +243,11 @@ public function resetErrors() foreach ($collection as $customer) { $customer->setData("mailchimp_sync_delta", '0000-00-00 00:00:00'); $customer->setData("mailchimp_sync_error", ''); - $customer->setMailchimpUpdateObserverRan(true); - $customer->save(); + $resource = $customer->getResource(); + $resource->saveAttribute($customer, 'mailchimp_sync_delta'); + $resource->saveAttribute($customer, 'mailchimp_sync_error'); +// $customer->setMailchimpUpdateObserverRan(true); +// $customer->save(); } // reset orders with errors diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index d0c3d439e..d66d5a127 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -371,7 +371,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $shippingAddress = $order->getShippingAddress(); $street = $shippingAddress->getStreet(); if ($shippingAddress->getName()) { - $data['shipping_address']['name'] = $shippingAddress->getName() + $data['shipping_address']['name'] = $shippingAddress->getName(); } if ($street[0]) { $data['shipping_address']['address1'] = $street[0]; From 19fa44327b78ef1cc820cc8d7004285efa9ae401 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 3 Feb 2017 10:46:06 -0300 Subject: [PATCH 31/53] Removed all product and customer old save methods. --- .../MailChimp/Model/Api/Customers.php | 1 - .../Ebizmarts/MailChimp/Model/Observer.php | 24 +++++-------------- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index e03e419f9..a4e7b5224 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -58,7 +58,6 @@ public function createBatchJson($mailchimpStoreId) $customer->setData("mailchimp_sync_delta", Varien_Date::now()); $customer->setData("mailchimp_sync_error", ""); $customer->setData("mailchimp_sync_modified", 0); - $customer->setMailchimpUpdateObserverRan(true); $this->_saveCustomer($customer); } $counter++; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index e0affad1c..2c2deebb9 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -192,12 +192,6 @@ public function customerSaveBefore(Varien_Event_Observer $observer) { $customer = $observer->getEvent()->getCustomer(); - if ($customer->getMailchimpUpdateObserverRan()) { - return $observer; - } else { - $customer->setMailchimpUpdateObserverRan(true); - } - //update mailchimp ecommerce data for that customer Mage::getModel('mailchimp/api_customers')->update($customer); return $observer; @@ -212,12 +206,6 @@ public function customerSaveBefore(Varien_Event_Observer $observer) public function productSaveBefore(Varien_Event_Observer $observer) { $product = $observer->getEvent()->getProduct(); - - if ($product->getMailchimpUpdateObserverRan()) { - return $observer; - } else { - $product->setMailchimpUpdateObserverRan(true); - } //update mailchimp ecommerce data for that product variant Mage::getModel('mailchimp/api_products')->update($product); return $observer; @@ -431,8 +419,8 @@ public function newCreditMemo(Varien_Event_Observer $observer) } $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $resource = $product->getResource(); + $resource->saveAttribute($product, 'mailchimp_sync_modified'); } $creditMemo->getOrder()->setMailchimpSyncModified(1); return $observer; @@ -456,8 +444,8 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) } $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $resource = $product->getResource(); + $resource->saveAttribute($product, 'mailchimp_sync_modified'); } $creditMemo->getOrder()->setMailchimpSyncModified(1); return $observer; @@ -476,8 +464,8 @@ public function itemCancel(Varien_Event_Observer$observer) if ($item->getProductType()!='bundle' && $item->getProductType()!='configurable') { $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); - $product->setMailchimpUpdateObserverRan(true); - $product->save(); + $resource = $product->getResource(); + $resource->saveAttribute($product, 'mailchimp_sync_modified'); } return $observer; } From 26ad3d8ad3576721beca232e54d75a400e423fc3 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 3 Feb 2017 11:23:42 -0300 Subject: [PATCH 32/53] Added verification for address on orders to avoid error when nothing is placed in the street field. --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 7f0e94b89..d0b93f01e 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -381,10 +381,10 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if ($shippingAddress->getName()) { $data['shipping_address']['name'] = $shippingAddress->getName(); } - if ($street[0]) { + if (isset($street[0]) && $street[0]) { $data['shipping_address']['address1'] = $street[0]; } - if ($street[1]) { + if (isset($street[1]) && $street[1]) { $data['shipping_address']['address2'] = $street[1]; } if ($shippingAddress->getCity()) { From 57899248c518bdb469e4d7d584318f60e7ff56e4 Mon Sep 17 00:00:00 2001 From: Santiago Date: Fri, 3 Feb 2017 12:09:01 -0300 Subject: [PATCH 33/53] Send correct store name when creating MailChimp Store. closes #129 --- 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 e6d7e8d49..2ce5183f2 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -83,7 +83,8 @@ public function getConfigValue($path, $storeId = null, $returnParentValueIfNull */ public function getMCStoreName() { - return Mage::getStoreConfig('web/unsecure/base_url'); + $storeView = Mage::app()->getDefaultStoreView(); + return $storeView->getWebsite()->getDefaultStore()->getFrontendName(); } /** From f60b00408614bd21838476314ea36ddbcd08c315 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Fri, 3 Feb 2017 16:31:35 -0300 Subject: [PATCH 34/53] change the name of the store when change in general/store information #130 --- .../Ebizmarts/MailChimp/Helper/Data.php | 10 ++++++++ .../Ebizmarts/MailChimp/Model/Api/Stores.php | 6 +++++ .../Model/System/Config/Backend/Name.php | 25 +++++++++++++++++++ .../Ebizmarts/MailChimp/etc/system.xml | 11 ++++++++ lib/Ebizmarts/Mailchimp/EcommerceStores.php | 3 ++- 5 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index e6d7e8d49..e5f384215 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -399,4 +399,14 @@ public function getApi() } return $api; } + public function changeName($name) + { + if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE)) { + try { + Mage::getModel('mailchimp/api_stores')->modifyName($name); + } catch (Mailchimp_Error $e) { + Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); + } + } + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index a6e309183..3a2a5f1aa 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -92,4 +92,10 @@ public function deleteStore($storeId) $resource = Mage::getResourceModel('mailchimp/synchbatches'); $connection->update($resource->getMainTable(), array('status'=>'canceled'), "status = 'pending'"); } + public function modifyName($name) + { + $api = Mage::helper('mailchimp')->getApi(); + $storeId = Mage::helper('mailchimp')->getMCStoreId(); + $api->ecommerce->stores->edit($storeId,$name); + } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php new file mode 100644 index 000000000..daca30732 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php @@ -0,0 +1,25 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2/3/17 4:40 PM + * @file: Name.php + */ +class Ebizmarts_MailChimp_Model_System_Config_Backend_Name extends Mage_Core_Model_Config_Data +{ + protected function _afterSave() { + if ($this->isValueChanged()) { + $name = $this->getValue(); + if ($name == '') { + Mage::getConfig()->cleanCache(); + $name = Mage::app()->getDefaultStoreView()->getWebsite()->getDefaultStore()->getFrontendName(); + } + Mage::helper('mailchimp')->changeName($name); + } + } +} \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index 23b1ce55c..030bd00df 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -8,6 +8,17 @@ + + + + + + mailchimp/system_config_backend_name + + + + + mailchimp-section diff --git a/lib/Ebizmarts/Mailchimp/EcommerceStores.php b/lib/Ebizmarts/Mailchimp/EcommerceStores.php index 16f379230..8d9ce1fa0 100644 --- a/lib/Ebizmarts/Mailchimp/EcommerceStores.php +++ b/lib/Ebizmarts/Mailchimp/EcommerceStores.php @@ -88,10 +88,11 @@ public function get($id=null,$fields=null,$excludeFields=null,$count=null,$offse * @return mixed * @throws Mailchimp_Error */ - public function edit($storeId, $isSyncing, $currencyCode = null, $platform = null, $domain = null, $emailAddress = null, + public function edit($storeId, $name = null, $platform = null, $domain = null, $isSyncing = null, $emailAddress = null, $currencyCode = null, $moneyFormat = null, $primaryLocale=null, $timezone = null, $phone=null, $address=null) { $_params=array(); + if($name) $_params['name'] = $name; if($platform) $_params['platform'] = $platform; if($domain) $_params['domain'] = $domain; if($emailAddress) $_params['email_address'] = $emailAddress; From 3018e348e2db81537ee9e352618b226481153a1d Mon Sep 17 00:00:00 2001 From: gonzalo Date: Fri, 3 Feb 2017 17:09:11 -0300 Subject: [PATCH 35/53] change the name of the store when change in system/manage stores closes #130 --- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 8 ++++++++ app/code/community/Ebizmarts/MailChimp/etc/config.xml | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 2c2deebb9..6b0998b2c 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -482,4 +482,12 @@ public function addOrderViewMonkey(Varien_Event_Observer $observer){ } } + public function changeStoreName(Varien_Event_Observer $observer) + { + $group = $observer->getGroup(); + $storeName = Mage::getStoreConfig('general/store_information/name'); + if ($storeName == '') { + Mage::helper('mailchimp')->changeName($group->getName()); + } + } } diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index cf9faa5e5..7a574c5a0 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -11,6 +11,14 @@ + + + + mailchimp/observer + changeStoreName + + + From 606013a042940694d9b3bbd0844d1f9b75c45d08 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Fri, 3 Feb 2017 17:24:04 -0300 Subject: [PATCH 36/53] fix the postal code in the shipping address --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index d0b93f01e..cc29f8ce8 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -396,8 +396,8 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if ($shippingAddress->getRegionCode()) { $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); } - if ($shippingAddress->getPostCode()) { - $data['shipping_address']['postal_code'] = $shippingAddress->getPostCode(); + if ($shippingAddress->getPostcode()) { + $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); } if ($shippingAddress->getCountry()) { $data['shipping_address']['country'] = Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName(); From 6cac0e234d5ebcc9442692a960a20a24f0e72297 Mon Sep 17 00:00:00 2001 From: vs7 Date: Sun, 5 Feb 2017 23:28:27 +0300 Subject: [PATCH 37/53] Fix typo in filename --- modman | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modman b/modman index adcfac855..e5cee9e17 100644 --- a/modman +++ b/modman @@ -6,5 +6,5 @@ app/design/frontend/base/default/template/* app/design/frontend/base/default app/etc/modules/* app/etc/modules/ js/ebizmarts/mailchimp/* js/ebizmarts/mailchimp/ skin/adminhtml/default/default/ebizmarts/* skin/adminhtml/default/default/ebizmarts/ -getMailChimpResponse.php getMailChimpResponse.php -m4mlogs.sh m4mlogs.sh \ No newline at end of file +getMailchimpResponse.php getMailchimpResponse.php +m4mlogs.sh m4mlogs.sh From b02add2cc33e5fe3ce02f37b91cb4a4d5335379f Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 6 Feb 2017 16:25:06 -0300 Subject: [PATCH 38/53] Typo in fulfillment status fixed. closes #132 --- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index d0b93f01e..32e0cb971 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -74,7 +74,7 @@ protected function _getModifiedOrders($mailchimpStoreId) $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); if (!empty($orderJson)) { $batchArray[$this->_counter]['method'] = "PATCH"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getIncrementId(); $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); $batchArray[$this->_counter]['body'] = $orderJson; @@ -213,8 +213,8 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if (isset($statusArray['financial_status'])) { $data['financial_status'] = $statusArray['financial_status']; } - if (isset($statusArray['fullfilment_status'])) { - $data['fullfilment_status'] = $statusArray['fullfilment_status']; + if (isset($statusArray['fulfillment_status'])) { + $data['fulfillment_status'] = $statusArray['fulfillment_status']; } $data['processed_at_foreign'] = $order->getCreatedAt(); @@ -438,7 +438,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $jsonData = json_encode($data); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Order ".$order->getId()." json encode failed"); + Mage::helper('mailchimp')->logError("Order ".$order->getIncrementId()." json encode failed"); } return $jsonData; @@ -458,7 +458,7 @@ protected function _isModifiedOrder($order) protected function _getMailChimpStatus($order) { $mailChimpFinancialStatus = null; - $mailChimpFullfilmentStatus = null; + $mailChimpFulfillmentStatus = null; $totalItemsOrdered = $order->getData('total_qty_ordered'); $shippedItemAmount = 0; $invoicedItemAmount = 0; @@ -472,9 +472,9 @@ protected function _getMailChimpStatus($order) } if ($shippedItemAmount > 0) { if ($totalItemsOrdered > $shippedItemAmount) { - $mailChimpFullfilmentStatus = self::PARTIALLY_SHIPPED; + $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED; } else { - $mailChimpFullfilmentStatus = self::SHIPPED; + $mailChimpFulfillmentStatus = self::SHIPPED; } } if ($refundedItemAmount > 0) { @@ -501,8 +501,8 @@ protected function _getMailChimpStatus($order) if ($mailChimpFinancialStatus) { $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus; } - if ($mailChimpFullfilmentStatus) { - $mailChimpStatus['fullfilment_status'] = $mailChimpFullfilmentStatus; + if ($mailChimpFulfillmentStatus) { + $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus; } return $mailChimpStatus; } From 4e2299b056b1138c895cf3f7fefeefa7a0d36fc3 Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 6 Feb 2017 16:50:49 -0300 Subject: [PATCH 39/53] Typo in Landing Page. closes #123 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 32e0cb971..dfe90420a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -202,7 +202,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if ($order->getMailchimpCampaignId()) { $data['campaign_id'] = $order->getMailchimpCampaignId(); } - if ($order->getMailchimpLAndingPage()) { + if ($order->getMailchimpLandingPage()) { $data['landing_site'] = $order->getMailchimpLandingPage(); } $data['currency_code'] = $order->getOrderCurrencyCode(); From 346896d297536166f5e46749e1171a67acdf07df Mon Sep 17 00:00:00 2001 From: Santiago Date: Mon, 6 Feb 2017 17:18:38 -0300 Subject: [PATCH 40/53] Canceled order status sent to MailChimp properly. closes #133 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index dfe90420a..8c7c3b676 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -494,6 +494,10 @@ protected function _getMailChimpStatus($order) } } + + if (!$mailChimpFinancialStatus && $order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { + $mailChimpFinancialStatus = self::CANCELED; + } if (!$mailChimpFinancialStatus) { $mailChimpFinancialStatus = self::PENDING; } From 7f221ff79ad58e159dfaf7b53add526190c538f5 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Mon, 6 Feb 2017 17:37:32 -0300 Subject: [PATCH 41/53] closes #123 --- js/ebizmarts/mailchimp/campaignCatcher.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index 5e8f6b902..babad6903 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -2,6 +2,7 @@ var urlparams = location.search.substr(1).split('&'); var params = new Array(); var mc_cid = null; + var isMailchimp = false; for (var i = 0; i < urlparams.length; i++) { var param = urlparams[i].split('='); var key = param[0]; @@ -10,14 +11,13 @@ params[key] = val; } if(key=='utm_source') { - var reg = /^mailchimp-/; + var reg = /^mailchimp$/; if(reg.exec(val)) { - var aux =val.split('-'); - mc_cid = aux[1]; + isMailchimp = true; } } else { - if (key=='mc_cid') { + if (key=='mc_cid'||(isMailchimp && key=='utm_campaign')) { mc_cid = val; } } @@ -25,7 +25,7 @@ if (mc_cid) { createCookie('mailchimp_campaign_id' , mc_cid); - createCookie('maichimp_landing_page', location); + createCookie('mailchimp_landing_page', location); } } From e7466157d4ede12a30a7d65af1c1588e6f26ba52 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Tue, 7 Feb 2017 13:45:07 -0300 Subject: [PATCH 42/53] fix issue with landing page --- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 6b0998b2c..287cd583c 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -254,7 +254,7 @@ public function removeCampaignData(Varien_Event_Observer $observer) Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); } if( ($this->_getLandingCookie())) { - Mage::getModel('core/cookie')->delete('maichimp_landing_page'); + Mage::getModel('core/cookie')->delete('mailchimp_landing_page'); } return $observer; } @@ -275,8 +275,8 @@ protected function _getCampaignCookie() } protected function _getLandingCookie() { - $cookie = Mage::getModel('core/cookie')->get('maichimp_landing_page'); - if ($cookie && Mage::getModel('core/cookie')->getLifetime('maichimp_landing_page') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { + $cookie = Mage::getModel('core/cookie')->get('mailchimp_landing_page'); + if ($cookie && Mage::getModel('core/cookie')->getLifetime('mailchimp_landing_page') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { return $cookie; } else { return null; @@ -381,7 +381,7 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) public function newOrder(Varien_Event_Observer $observer) { if( ($this->_getLandingCookie())) { - Mage::getModel('core/cookie')->delete('maichimp_landing_page'); + Mage::getModel('core/cookie')->delete('mailchimp_landing_page'); } if ($this->_getCampaignCookie()) { Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); From fac0397d0a7dd88aa318c76da35de4d6409d716e Mon Sep 17 00:00:00 2001 From: Santiago Date: Tue, 7 Feb 2017 16:05:49 -0300 Subject: [PATCH 43/53] Send discounts within orders. closes #134 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 10682ed85..7dc073d90 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -208,6 +208,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $data['currency_code'] = $order->getOrderCurrencyCode(); $data['order_total'] = $order->getGrandTotal(); $data['tax_total'] = $order->getTaxAmount(); + $data['discount_total'] = abs($order->getDiscountAmount()); $data['shipping_total'] = $order->getShippingAmount(); $statusArray = $this->_getMailChimpStatus($order); if (isset($statusArray['financial_status'])) { @@ -259,6 +260,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) "product_variant_id" => $variant, "quantity" => (int)$item->getQtyOrdered(), "price" => $item->getPrice(), + "discount" => $item->getDiscountAmount() ); } } @@ -498,6 +500,7 @@ protected function _getMailChimpStatus($order) if (!$mailChimpFinancialStatus && $order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { $mailChimpFinancialStatus = self::CANCELED; } + if (!$mailChimpFinancialStatus) { $mailChimpFinancialStatus = self::PENDING; } From cd1c2aa79750ffae3f40c3e1f49c0a664dd5a06a Mon Sep 17 00:00:00 2001 From: gonzalo Date: Tue, 7 Feb 2017 16:41:29 -0300 Subject: [PATCH 44/53] closes #135 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index f0fe8863f..ddab259e5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -322,6 +322,12 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) ); } } + $store = Mage::getModel('core/store')->load($order->getStoreId()); + $data['order_URL'] = $store->getUrl('sales/order/view/',array( + 'order_id'=>$order->getId(), + '_nosid' => true, + '_secure' => true + )); if($order->getCustomerFirstname()) { $data["customer"]["first_name"] = $order->getCustomerFirstname(); } From 6426f182833974a5ee46f00f1a4463f900a2b9ac Mon Sep 17 00:00:00 2001 From: gonzalo Date: Tue, 7 Feb 2017 20:19:20 -0300 Subject: [PATCH 45/53] exclude mailchimp campaign id when campaing get from facebook --- js/ebizmarts/mailchimp/campaignCatcher.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index babad6903..2df701483 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -17,22 +17,21 @@ } } else { - if (key=='mc_cid'||(isMailchimp && key=='utm_campaign')) { + if (key=='mc_cid') { mc_cid = val; } } } if (mc_cid) { - createCookie('mailchimp_campaign_id' , mc_cid); - createCookie('mailchimp_landing_page', location); + Mage.Cookies.set('mailchimp_campaign_id' , mc_cid); + Mage.Cookies.set('mailchimp_landing_page', location); + } + if(isMailchimp) { + Mage.cookie.clear('mailchimp_campaign_id'); + Mage.Cookies.set('mailchimp_landing_page', location); } } - - function createCookie(name, value) { - Mage.Cookies.set(name,value); - } - if (document.loaded) { getCampaign; } else { From d5cae4ffc53e5eb0d1d4183ba091da4c905d29e0 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 8 Feb 2017 11:55:34 -0300 Subject: [PATCH 46/53] Send order modifications properly. closes #133 --- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 50e3df76d..ef45a5dc3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -74,7 +74,7 @@ protected function _getModifiedOrders($mailchimpStoreId) $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); if (!empty($orderJson)) { $batchArray[$this->_counter]['method'] = "PATCH"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getIncrementId(); + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); $batchArray[$this->_counter]['body'] = $orderJson; @@ -325,7 +325,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } } $store = Mage::getModel('core/store')->load($order->getStoreId()); - $data['order_URL'] = $store->getUrl('sales/order/view/',array( + $data['order_url'] = $store->getUrl('sales/order/view/',array( 'order_id'=>$order->getId(), '_nosid' => true, '_secure' => true @@ -446,7 +446,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $jsonData = json_encode($data); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Order ".$order->getIncrementId()." json encode failed"); + Mage::helper('mailchimp')->logError("Order ".$order->getEntityId()." json encode failed"); } return $jsonData; From c5769d20942e17be13ce74081efd67d99332408d Mon Sep 17 00:00:00 2001 From: gonzalo Date: Wed, 8 Feb 2017 14:34:33 -0300 Subject: [PATCH 47/53] fix for landing_site fix for the grid to mark the monkey when campaign is from facebook delete the campaign_id when comes from facebook --- .../Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php | 2 +- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 4 ++++ js/ebizmarts/mailchimp/campaignCatcher.js | 4 ++-- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php index d4d30892c..b9514e394 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php @@ -15,7 +15,7 @@ class Ebizmarts_MailChimp_Block_Adminhtml_Sales_Order_Grid_Renderer_Mailchimp ex public function render(Varien_Object $row) { $order = Mage::getModel('sales/order')->load($row->getData('entity_id')); - if ($order->getMailchimpAbandonedcartFlag() || $order->getMailchimpCampaignId()) { + if ($order->getMailchimpAbandonedcartFlag() || $order->getMailchimpCampaignId() || $order->getMailchimpLandingPage()) { $result = ''; } else { $result = ''; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 287cd583c..011b01e2e 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -266,6 +266,10 @@ public function removeCampaignData(Varien_Event_Observer $observer) */ protected function _getCampaignCookie() { + $landingCookie = $this->_getLandingCookie(); + if ( preg_match("/utm_source=mailchimp/")) { + return null; + } $cookie = Mage::getModel('core/cookie')->get('mailchimp_campaign_id'); if ($cookie && Mage::getModel('core/cookie')->getLifetime('mailchimp_campaign_id') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { return $cookie; diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index 2df701483..06fed1cf9 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -23,12 +23,12 @@ } } - if (mc_cid) { + if (mc_cid&&!isMailchimp) { Mage.Cookies.set('mailchimp_campaign_id' , mc_cid); Mage.Cookies.set('mailchimp_landing_page', location); } if(isMailchimp) { - Mage.cookie.clear('mailchimp_campaign_id'); + Mage.Cookies.clear('mailchimp_campaign_id'); Mage.Cookies.set('mailchimp_landing_page', location); } } From 336015b73a5ef136d81e5ce5d5eb0ff9d171c060 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 8 Feb 2017 15:37:10 -0300 Subject: [PATCH 48/53] Fix is_syncing flag modification. --- app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php | 2 +- app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index c18197c79..b9d016b17 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -120,7 +120,7 @@ public function _sendEcommerceBatch($mailchimpStoreId) } } elseif (Mage::helper('mailchimp')->getMCIsSyncing()) { $isSyncing = false; - $mailchimpApi->ecommerce->stores->edit($mailchimpStoreId, $isSyncing); + $mailchimpApi->ecommerce->stores->edit($mailchimpStoreId, null, null, null, $isSyncing); Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING, 0); Mage::getConfig()->cleanCache(); } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index ef45a5dc3..196beccdc 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -92,7 +92,6 @@ protected function _getModifiedOrders($mailchimpStoreId) Mage::helper('mailchimp')->logError($e->getMessage()); } } - return $batchArray; } From 09893b186cfd792e77a7ca174a49c48fd6149ce4 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Wed, 8 Feb 2017 15:55:26 -0300 Subject: [PATCH 49/53] delete the campaign_id when comes from facebook --- app/code/community/Ebizmarts/MailChimp/Model/Observer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 011b01e2e..7dc33820a 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -267,7 +267,7 @@ public function removeCampaignData(Varien_Event_Observer $observer) protected function _getCampaignCookie() { $landingCookie = $this->_getLandingCookie(); - if ( preg_match("/utm_source=mailchimp/")) { + if ( preg_match("/utm_source=mailchimp/",$landingCookie)) { return null; } $cookie = Mage::getModel('core/cookie')->get('mailchimp_campaign_id'); From 2a78203f8744f4d29bde6eee8fecd95c4990e519 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 8 Feb 2017 17:09:53 -0300 Subject: [PATCH 50/53] Use printf in stead of echo in getMailchimpResponse script. --- getMailchimpResponse.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/getMailchimpResponse.php b/getMailchimpResponse.php index e9a4ba46d..27938dc34 100644 --- a/getMailchimpResponse.php +++ b/getMailchimpResponse.php @@ -1,8 +1,8 @@ status == 'finished') { @@ -57,9 +57,9 @@ $r = curl_exec($ch); curl_close($ch); fclose($fd); - echo "$batchId.response.tar.gz\n"; + printf("$batchId.response.tar.gz\n"); } catch(Exception $e) { - echo $e->getMessage(); + printf($e->getMessage()); } } // else { From 847fd65389f6411eca482fb0754c6060bf79a606 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 8 Feb 2017 17:36:11 -0300 Subject: [PATCH 51/53] Skip shipping address whens sending orders if it doesn't exists --- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 100 +++++++++--------- 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 196beccdc..1c2acaa8d 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -29,7 +29,7 @@ class Ebizmarts_MailChimp_Model_Api_Orders /** * Set the request for orders to be created on MailChimp - * + * * @param $mailchimpStoreId * @return array */ @@ -38,7 +38,7 @@ public function createBatchJson($mailchimpStoreId) $batchArray = array(); $this->_firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_FIRSTDATE); $this->_counter = 0; - $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_ORDER.'_'. Mage::helper('mailchimp')->getDateMicrotime(); + $this->_batchId = Ebizmarts_MailChimp_Model_Config::IS_ORDER . '_' . Mage::helper('mailchimp')->getDateMicrotime(); // get all the carts modified but not converted in orders $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId)); @@ -56,8 +56,8 @@ protected function _getModifiedOrders($mailchimpStoreId) ->addAttributeToSelect('entity_id') ->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())) ->addFieldToFilter('mailchimp_sync_modified', array('eq' => 1)); - if($this->_firstDate) { - $collection->addFieldToFilter('created_at',array('from' => $this->_firstDate)); + if ($this->_firstDate) { + $collection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } $collection->getSelect()->limit(self::BATCH_LIMIT); @@ -106,8 +106,8 @@ protected function _getNewOrders($mailchimpStoreId) array('eq' => ''), array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) )); - if($this->_firstDate) { - $collection->addFieldToFilter('created_at',array('from' => $this->_firstDate)); + if ($this->_firstDate) { + $collection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } $collection->getSelect()->limit(self::BATCH_LIMIT); @@ -188,11 +188,11 @@ protected function _getNewOrders($mailchimpStoreId) /** * Set all the data for each order to be sent * - * @param $orderFromCollection + * @param $order * @param $mailchimpStoreId * @return string */ - protected function GeneratePOSTPayload($order,$mailchimpStoreId) + protected function GeneratePOSTPayload($order, $mailchimpStoreId) { // $order = Mage::getModel('sales/order')->load($orderFromCollection->getEntityId()); @@ -237,7 +237,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $items = $order->getAllVisibleItems(); $itemCount = 0; foreach ($items as $item) { - if ($item->getProductType()==Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { + if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { $options = $item->getProductOptions(); $sku = $options['simple_sku']; $variant = Mage::getModel('catalog/product')->getIdBySku($sku); @@ -251,7 +251,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $syncDelta = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), 'mailchimp_sync_delta', $order->getStoreId()); $syncError = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), 'mailchimp_sync_error', $order->getStoreId()); - if ($syncDelta&&$syncError==0) { + if ($syncDelta && $syncError == 0) { $itemCount++; $data["lines"][] = array( "id" => (string)$itemCount, @@ -324,15 +324,15 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) } } $store = Mage::getModel('core/store')->load($order->getStoreId()); - $data['order_url'] = $store->getUrl('sales/order/view/',array( - 'order_id'=>$order->getId(), + $data['order_url'] = $store->getUrl('sales/order/view/', array( + 'order_id' => $order->getId(), '_nosid' => true, '_secure' => true )); - if($order->getCustomerFirstname()) { + if ($order->getCustomerFirstname()) { $data["customer"]["first_name"] = $order->getCustomerFirstname(); } - if($order->getCustomerLastname()) { + if ($order->getCustomerLastname()) { $data["customer"]["last_name"] = $order->getCustomerLastname(); } $billingAddress = $order->getBillingAddress(); @@ -382,43 +382,45 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) if ($billingAddress->getName()) { $data['billing_address']['name'] = $billingAddress->getName(); } - - $shippingAddress = $order->getShippingAddress(); - $street = $shippingAddress->getStreet(); - if ($shippingAddress->getName()) { - $data['shipping_address']['name'] = $shippingAddress->getName(); - } - if (isset($street[0]) && $street[0]) { - $data['shipping_address']['address1'] = $street[0]; - } - if (isset($street[1]) && $street[1]) { - $data['shipping_address']['address2'] = $street[1]; - } - if ($shippingAddress->getCity()) { - $data['shipping_address']['city'] = $shippingAddress->getCity(); - } - if ($shippingAddress->getRegion()) { - $data['shipping_address']['province'] = $shippingAddress->getRegion(); - } - if ($shippingAddress->getRegionCode()) { - $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); - } - if ($shippingAddress->getPostcode()) { - $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); - } - if ($shippingAddress->getCountry()) { - $data['shipping_address']['country'] = Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName(); - $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); - } - //company if ($billingAddress->getCompany()) { $data["customer"]["company"] = $billingAddress->getCompany(); $data["billing_address"]["company"] = $billingAddress->getCompany(); } - if ($shippingAddress->getCompamy()) { - $data["shipping_address"]["company"] = $billingAddress->getCompany(); + + $shippingAddress = $order->getShippingAddress(); + if ($shippingAddress) { + $street = $shippingAddress->getStreet(); + if ($shippingAddress->getName()) { + $data['shipping_address']['name'] = $shippingAddress->getName(); + } + if (isset($street[0]) && $street[0]) { + $data['shipping_address']['address1'] = $street[0]; + } + if (isset($street[1]) && $street[1]) { + $data['shipping_address']['address2'] = $street[1]; + } + if ($shippingAddress->getCity()) { + $data['shipping_address']['city'] = $shippingAddress->getCity(); + } + if ($shippingAddress->getRegion()) { + $data['shipping_address']['province'] = $shippingAddress->getRegion(); + } + if ($shippingAddress->getRegionCode()) { + $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); + } + if ($shippingAddress->getPostcode()) { + $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); + } + if ($shippingAddress->getCountry()) { + $data['shipping_address']['country'] = Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName(); + $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); + } + if ($shippingAddress->getCompamy()) { + $data["shipping_address"]["company"] = $shippingAddress->getCompany(); + } } + //customer orders data $orderCollection = Mage::getModel('sales/order')->getCollection() ->addFieldToFilter('state', array('eq' => 'complete')) @@ -427,7 +429,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) ->addFieldToFilter('mailchimp_sync_delta', array('neq' => '')) ->addFieldToFilter('mailchimp_sync_delta', array('gt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())) ->addFieldToFilter('mailchimp_sync_error', array('eq' => "")); - if($this->_firstDate) { + if ($this->_firstDate) { $orderCollection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } $totalOrders = 1; @@ -445,7 +447,7 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId) $jsonData = json_encode($data); } catch (Exception $e) { //json encode failed - Mage::helper('mailchimp')->logError("Order ".$order->getEntityId()." json encode failed"); + Mage::helper('mailchimp')->logError("Order " . $order->getEntityId() . " json encode failed"); } return $jsonData; @@ -472,7 +474,7 @@ protected function _getMailChimpStatus($order) $refundedItemAmount = 0; $mailChimpStatus = array(); - foreach ($order->getAllVisibleItems() as $item){ + foreach ($order->getAllVisibleItems() as $item) { $shippedItemAmount += $item->getQtyShipped(); $invoicedItemAmount += $item->getQtyInvoiced(); $refundedItemAmount += $item->getQtyRefunded(); @@ -499,7 +501,7 @@ protected function _getMailChimpStatus($order) $mailChimpFinancialStatus = self::PAID; } } - + } if (!$mailChimpFinancialStatus && $order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { From 480da2aaa597bd1279491ba7bb0135fb0fd0dd90 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 8 Feb 2017 17:50:36 -0300 Subject: [PATCH 52/53] Coding standard fixes --- .../Block/Adminhtml/Mailchimperrors/Grid.php | 3 +- .../Block/Adminhtml/Mailchimperrors/Link.php | 1 + .../Block/Adminhtml/Mergevars/Add.php | 9 ++-- .../Block/Adminhtml/Mergevars/Add/Form.php | 21 +++++--- .../Sales/Order/Grid/Renderer/Mailchimp.php | 1 + .../Sales/Order/View/Info/Monkey.php | 1 + .../System/Config/Form/Field/Mapfields.php | 11 +++- .../Adminhtml/System/Config/OauthWizard.php | 1 + .../MailChimp/Block/Popup/Emailcatcher.php | 4 ++ .../Ebizmarts/MailChimp/Helper/Data.php | 15 +++++- .../Ebizmarts/MailChimp/Model/Api/Batches.php | 18 ++++--- .../Ebizmarts/MailChimp/Model/Api/Carts.php | 45 ++++++++++++++-- .../MailChimp/Model/Api/Customers.php | 43 ++++++++++++--- .../Ebizmarts/MailChimp/Model/Api/Orders.php | 54 ++++++++++++++++--- .../MailChimp/Model/Api/Products.php | 18 ++++--- .../Ebizmarts/MailChimp/Model/Api/Stores.php | 3 +- .../MailChimp/Model/Api/Subscribers.php | 8 +-- .../Ebizmarts/MailChimp/Model/Email/Queue.php | 10 +++- .../MailChimp/Model/Email/Template.php | 16 +++++- .../Ebizmarts/MailChimp/Model/Observer.php | 44 +++++++++++---- .../MailChimp/Model/ProcessWebhook.php | 6 +-- .../Model/System/Config/Backend/Name.php | 4 +- .../Model/System/Config/Source/Account.php | 1 + .../Model/System/Config/Source/Userinfo.php | 1 + .../Adminhtml/EcommerceController.php | 4 ++ .../Adminhtml/MailchimperrorsController.php | 10 ++-- .../Adminhtml/MergevarsController.php | 5 +- .../MailChimp/controllers/CartController.php | 2 + getMailchimpResponse.php | 12 +++-- js/ebizmarts/mailchimp/campaignCatcher.js | 5 +- lib/Ebizmarts/Mailchimp.php | 6 +++ lib/Ebizmarts/Mailchimp/Exceptions.php | 1 + lib/Ebizmarts/Mailchimp/Root.php | 2 + lib/Mandrill/Mandrill.php | 4 +- 34 files changed, 311 insertions(+), 78 deletions(-) diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php index e0a824b6f..c39f12955 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Grid.php @@ -82,7 +82,8 @@ protected function _prepareColumns() 'sortable' => false ) ); - $this->addColumn('action_donwload', array( + $this->addColumn( + 'action_donwload', array( 'header' => $this->helper('mailchimp')->__('Download Response'), 'width' => 15, 'sortable' => false, diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php index c5261df84..d0a5bf3d1 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors/Link.php @@ -38,6 +38,7 @@ public function render(Varien_Object $row) $displayText = $this->__('Something went wrong when retrieving original item.'); break; } + return $displayText; } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php index 484f9bfa9..eff666e63 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add.php @@ -6,9 +6,11 @@ * File : Add.php * Module : Ebizmarts_MailChimp */ -class Ebizmarts_Mailchimp_Block_Adminhtml_Mergevars_Add extends Mage_Adminhtml_Block_Widget_Form_Container { +class Ebizmarts_Mailchimp_Block_Adminhtml_Mergevars_Add extends Mage_Adminhtml_Block_Widget_Form_Container +{ protected $_mode = 'add'; - public function __construct() { + public function __construct() + { $this->_controller = 'adminhtml_mergevars'; $this->_blockGroup = 'mailchimp'; @@ -26,7 +28,8 @@ public function getHeaderText() { return Mage::helper('mailchimp')->__('New Field Type'); } - public function _prepareForm() { + public function _prepareForm() + { } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php index 0ba2fbff3..122d998cc 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mergevars/Add/Form.php @@ -8,34 +8,41 @@ */ class Ebizmarts_Mailchimp_Block_Adminhtml_Mergevars_Add_Form extends Mage_Adminhtml_Block_Widget_Form { - protected function _prepareForm() { + protected function _prepareForm() + { $form = new Varien_Data_Form(array('id' => 'edit_form', 'action' => $this->getUrl('*/*/saveadd'), 'method' => 'post')); $fieldset = $form->addFieldset('base_fieldset', array('legend' => Mage::helper('mailchimp')->__('Mergevars Data'))); - $fieldset->addField('mergevar_label', 'text', array( + $fieldset->addField( + 'mergevar_label', 'text', array( 'name' => 'mergevar[label]', 'label' => Mage::helper('mailchimp')->__('MergeVar Name'), 'id' => 'mergevar_label', 'title' => Mage::helper('mailchimp')->__('MergeVar Name'), 'required' => true - )); - $fieldset->addField('mergevar_fieldtype','select',array( + ) + ); + $fieldset->addField( + 'mergevar_fieldtype', 'select', array( 'name' => 'mergevar[fieldtype]', 'label' => Mage::helper('mailchimp')->__('Field Type'), 'id' => 'mergevar_fieldtype', 'values' => Mage::getSingleton('mailchimp/system_config_source_fieldtype')->getFieldTypes(), 'required' => true - )); + ) + ); - $fieldset->addField('mergevar_value', 'text', array( + $fieldset->addField( + 'mergevar_value', 'text', array( 'name' => 'mergevar[value]', 'label' => Mage::helper('mailchimp')->__('Value for case entry'), 'id' => 'mergevar_value', 'title' => Mage::helper('mailchimp')->__('Value for case entry'), 'note' => 'This value should be added in the case of Data.php file', 'required' => true - )); + ) + ); diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php index b9514e394..ee8237443 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Sales/Order/Grid/Renderer/Mailchimp.php @@ -20,6 +20,7 @@ public function render(Varien_Object $row) } else { $result = ''; } + return $result; } } \ No newline at end of file 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 21f565742..a6c0ed0b3 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 @@ -20,6 +20,7 @@ public function isReferred() { $ret = true; } + return $ret; } public function getCampaign() diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php index e16427291..2bf29fe2c 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/Form/Field/Mapfields.php @@ -43,6 +43,7 @@ public function __construct() $this->_customerAttributes[$option['attribute_id']] = $option['frontend_label']; } } + $customFieldTypes = unserialize( Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS) ); @@ -53,6 +54,7 @@ public function __construct() $this->_customerAttributes[$value] = $label; } } + ksort($this->_customerAttributes); } @@ -61,6 +63,7 @@ protected function _renderCellTemplate($columnName) if (empty($this->_columns[$columnName])) { throw new Exception('Wrong column name specified.'); } + $column = $this->_columns[$columnName]; $inputName = $this->getElement()->getName() . '[#{_id}][' . $columnName . ']'; @@ -69,18 +72,22 @@ protected function _renderCellTemplate($columnName) foreach ($this->_customerAttributes as $att => $name) { $rendered .= ''; } + $rendered .= ''; } else { return ''; } + return $rendered; } - protected function _getMailChimpValue(){ + protected function _getMailChimpValue() + { return Mage::getSingleton('core/session')->getMailchimpValue(); } - protected function _getMailChimpLabel(){ + protected function _getMailChimpLabel() + { return Mage::getSingleton('core/session')->getMailchimpLabel(); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php index d78516c55..1f80b4740 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/OauthWizard.php @@ -21,6 +21,7 @@ protected function _prepareLayout() if (!$this->getTemplate()) { $this->setTemplate('ebizmarts/mailchimp/system/config/oauth_wizard.phtml'); } + return $this; } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php b/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php index 56c19995f..f7f466f5d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php @@ -52,9 +52,11 @@ protected function _handleCookie() if (isset($cookieValues[1])) { $fName = $cookieValues[1]; } + if (isset($cookieValues[2])) { $lName = $cookieValues[2]; } + if ($subscribeCookie == 'true') { $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email); if (!$subscriber->getId()) { @@ -65,10 +67,12 @@ protected function _handleCookie() $subscriberFname = filter_var($fName, FILTER_SANITIZE_STRING); $subscriber->setSubscriberFirstname($subscriberFname); } + if ($lName) { $subscriberLname = filter_var($lName, FILTER_SANITIZE_STRING); $subscriber->setSubscriberLastname($subscriberLname); } + $subscriber->setStoreId($storeId) ->subscribe($email); return 'location.reload'; diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index 20613ab05..48e969891 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -30,6 +30,7 @@ protected function _getConfigScopeId($storeId = null, $websiteId = null) $websiteId = Mage::getModel('core/website')->load($code)->getId(); $storeId = Mage::app()->getWebsite($websiteId)->getDefaultStore()->getId(); } + $scopeArray['websiteId'] = $websiteId; $scopeArray['storeId'] = $storeId; return $scopeArray; @@ -55,6 +56,7 @@ public function getConfigValue($path, $storeId = null, $returnParentValueIfNull } else { $scopeArray['storeId'] = $storeId; } + if (!$returnParentValueIfNull) { if (isset($scopeArray['websiteId']) && $scopeArray['websiteId']) { //Website scope @@ -73,6 +75,7 @@ public function getConfigValue($path, $storeId = null, $returnParentValueIfNull } } } + return $configValue; } @@ -134,12 +137,15 @@ public function resetMCEcommerceData($deleteDataInMailchimp=false) } catch(Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } + //clear store config values Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID); } + if ($ecommerceEnabled && $apikey && $listId) { $this->createStore($listId); } + //reset mailchimp minimum date to sync flag Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCMINSYNCDATEFLAG, Varien_Date::now()); Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTORE_RESETED, 1); @@ -186,7 +192,7 @@ public function logRequest($message, $batchId=null) } else { $logDir = Mage::getBaseDir('var') . DS . 'log'; $fileName = $logDir.DS.$batchId.'.Request.log'; - file_put_contents($fileName,$message); + file_put_contents($fileName, $message); } } } @@ -308,6 +314,7 @@ public function deleteStore() } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } + //clear store config values Mage::getConfig()->deleteConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID); } @@ -327,6 +334,7 @@ public function createMergeFields() } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } + if (count($mailchimpFields) > 0) { foreach ($maps as $map) { $customAtt = $map['magento']; @@ -338,6 +346,7 @@ public function createMergeFields() $alreadyExists = true; } } + if (!$alreadyExists) { foreach ($customFieldTypes as $customFieldType) { if ($customFieldType['value'] == $chimpTag) { @@ -346,9 +355,11 @@ public function createMergeFields() } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } + $created = true; } } + if (!$created) { $attrSetId = Mage::getResourceModel('eav/entity_attribute_collection') ->setEntityTypeFilter(1) @@ -360,6 +371,7 @@ public function createMergeFields() $label = $option['frontend_label']; } } + try { if ($label) { //Shipping and Billing Address @@ -398,6 +410,7 @@ public function getApi() if ($apiKey != null && $apiKey != "") { $api = new Ebizmarts_Mailchimp($apiKey, null, 'Mailchimp4Magento' . (string)Mage::getConfig()->getNode('modules/Ebizmarts_MailChimp/version')); } + return $api; } public function changeName($name) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index b9d016b17..073ba4e89 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -54,6 +54,7 @@ protected function _getResults($storeId, $isMailChimpStoreId = false) $item->save(); } } + $baseDir = Mage::getBaseDir(); if (is_dir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $item->getBatchId())) { rmdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $item->getBatchId()); @@ -74,7 +75,6 @@ public function _sendEcommerceBatch($mailchimpStoreId) { try { if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::helper('mailchimp')->isEcomSyncDataEnabled()) { - $batchArray = array(); //customer operations @@ -131,13 +131,12 @@ public function _sendEcommerceBatch($mailchimpStoreId) Mage::log($batchArray); } } - } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); - } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } + return null; } @@ -160,10 +159,12 @@ protected function _sendSubscriberBatches() break; } } + $this->_getResults(0, false); if ($subscriberLimit > 0) { list($batchResponses[], $subscriberLimit) = $this->sendStoreSubscriberBatch(0, $subscriberLimit); } + return $batchResponses; } @@ -210,10 +211,10 @@ public function sendStoreSubscriberBatch($storeId, $limit) } } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); - } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } + return null; } @@ -252,6 +253,7 @@ public function getBatchResponse($batchId) $files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d; } } + unlink($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar'); unlink($fileName . '.tar.gz'); } @@ -261,6 +263,7 @@ public function getBatchResponse($batchId) } catch (Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } + return $files; } @@ -291,6 +294,7 @@ protected function processEachResponseFile($files, $batchId) } } } + if ($errorDetails == "") { $errorDetails = $response->detail; } @@ -302,7 +306,7 @@ protected function processEachResponseFile($files, $batchId) $p = Mage::getModel('catalog/product')->load($id); if ($p->getId() == $id) { $p->setData("mailchimp_sync_error", $error); - $p->getResource()->saveAttribute($p,'mailchimp_sync_error'); + $p->getResource()->saveAttribute($p, 'mailchimp_sync_error'); } else { Mage::helper('mailchimp')->logError("Error: product " . $id . " not found"); } @@ -311,7 +315,7 @@ protected function processEachResponseFile($files, $batchId) $c = Mage::getModel('customer/customer')->load($id); if ($c->getId() == $id) { $c->setData("mailchimp_sync_error", $error); - $c->getResource()->saveAttribute($c,'mailchimp_sync_error'); + $c->getResource()->saveAttribute($c, 'mailchimp_sync_error'); } else { Mage::helper('mailchimp')->logError("Error: customer " . $id . " not found"); } @@ -349,6 +353,7 @@ protected function processEachResponseFile($files, $batchId) Mage::helper('mailchimp')->logError("Error: no identification " . $type . " found"); break; } + $mailchimpErrors->setType($response->type); $mailchimpErrors->setTitle($response->title); $mailchimpErrors->setStatus($item->status_code); @@ -360,6 +365,7 @@ protected function processEachResponseFile($files, $batchId) Mage::helper('mailchimp')->logError($error); } } + unlink($file); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index bfbb7f703..188d3b3be 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -29,6 +29,7 @@ public function createBatchJson($mailchimpStoreId) if (!Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_ACTIVE)) { return $allCarts; } + $this->_firstDate = Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_FIRSTDATE); $this->_counter = 0; @@ -61,6 +62,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) if ($this->_firstDate) { $convertedCarts->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } + // limit the collection $convertedCarts->getSelect()->limit(self::BATCH_LIMIT); foreach ($convertedCarts as $cart) { @@ -80,6 +82,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) $this->_counter += 1; } } + $allCartsForEmail->clear(); $allCarts[$this->_counter]['method'] = 'DELETE'; $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; @@ -90,6 +93,7 @@ protected function _getConvertedQuotes($mailchimpStoreId) $this->_saveCart($cart); $this->_counter += 1; } + return $allCarts; } @@ -138,13 +142,16 @@ protected function _getModifiedQuotes($mailchimpStoreId) $this->_counter += 1; } } + $allCartsForEmail->clear(); } + if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { $cart->setData("mailchimp_sync_delta", Varien_Date::now()); $this->_saveCart($cart); continue; } + // send the products that not already sent $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId); if (count($productData)) { @@ -153,6 +160,7 @@ protected function _getModifiedQuotes($mailchimpStoreId) $this->_counter += 1; } } + if (count($cart->getAllVisibleItems())) { $cartJson = $this->_makeCart($cart, $mailchimpStoreId); if ($cartJson!="") { @@ -163,9 +171,11 @@ protected function _getModifiedQuotes($mailchimpStoreId) $this->_counter += 1; } } + $cart->setData("mailchimp_sync_delta", Varien_Date::now()); $this->_saveCart($cart); } + return $allCarts; } @@ -178,10 +188,12 @@ protected function _getNewQuotes($mailchimpStoreId) $allCarts = array(); $newCarts = Mage::getModel('sales/quote')->getCollection(); $newCarts->addFieldToFilter('is_active', array('eq'=>1)) - ->addFieldToFilter('mailchimp_sync_delta', array( + ->addFieldToFilter( + 'mailchimp_sync_delta', array( array('eq' => '0000-00-00 00:00:00'), array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) - )); + ) + ); $newCarts->addFieldToFilter('created_at', array('from'=>$this->_firstDate)); $newCarts->addFieldToFilter('customer_email', array('notnull'=>true)); $newCarts->addFieldToFilter('items_count', array('gt'=>0)); @@ -192,6 +204,7 @@ protected function _getNewQuotes($mailchimpStoreId) $this->_saveCart($cart); continue; } + $customer = Mage::getModel("customer/customer"); $customer->setWebsiteId(Mage::getModel('core/store')->load($cart->getStoreId())->getWebsiteId()); $customer->loadByEmail($cart->getCustomerEmail()); @@ -207,14 +220,17 @@ protected function _getNewQuotes($mailchimpStoreId) $this->_saveCart($cartForEmail); $this->_counter += 1; } + $allCartsForEmail->clear(); } + // don't send the carts for guest customers who are registered if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { $cart->setData("mailchimp_sync_delta", Varien_Date::now()); $this->_saveCart($cart); continue; } + // send the products that not already sent $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId); if (count($productData)) { @@ -223,6 +239,7 @@ protected function _getNewQuotes($mailchimpStoreId) $this->_counter += 1; } } + $cartJson = $this->_makeCart($cart, $mailchimpStoreId); if ($cartJson!="") { $allCarts[$this->_counter]['method'] = 'POST'; @@ -234,6 +251,7 @@ protected function _getNewQuotes($mailchimpStoreId) $this->_counter += 1; } } + return $allCarts; } @@ -267,6 +285,7 @@ protected function _makeCart($cart,$mailchimpStoreId) if ($campaignId) { $oneCart['campaign_id'] = $campaignId; } + $oneCart['checkout_url'] = $this->_getCheckoutUrl($cart); $oneCart['currency_code'] = $cart->getQuoteCurrencyCode(); $oneCart['order_total'] = $cart->getGrandTotal(); @@ -280,18 +299,22 @@ protected function _makeCart($cart,$mailchimpStoreId) if ($item->getProductType()=='bundle'||$item->getProductType()=='grouped') { continue; } + if ($item->getProductType()==Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) { $variant = null; if ($item->getOptionByCode('simple_product')) { $variant = $item->getOptionByCode('simple_product')->getProduct(); } + if (!$variant) { continue; } + $variantId = $variant->getId(); } else { $variantId = $item->getProductId(); } + //id can not be 0 so we add 1 to $itemCount before setting the id. $itemCount++; $line['id'] = (string)$itemCount; @@ -307,14 +330,13 @@ protected function _makeCart($cart,$mailchimpStoreId) $oneCart['lines'] = $lines; //enconde to JSON try { - $jsonData = json_encode($oneCart); - } catch (Exception $e) { //json encode failed Mage::helper('mailchimp')->logError("Carts " . $cart->getId() . " json encode failed"); } } + return $jsonData; } // @todo calculate the checkout url for the cart @@ -334,6 +356,7 @@ protected function _getCustomer($cart,$mailchimpStoreId) } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } + if (isset($customers['total_items']) && $customers['total_items'] > 0) { $customer = array( 'id' => $customers['customers'][0]['id'] @@ -355,14 +378,17 @@ protected function _getCustomer($cart,$mailchimpStoreId) ); } } + $firstName = $cart->getCustomerFirstname(); if ($firstName) { $customer["first_name"] = $firstName; } + $lastName = $cart->getCustomerLastname(); if ($lastName) { $customer["last_name"] = $lastName; } + $billingAddress = $cart->getBillingAddress(); if ($billingAddress) { $street = $billingAddress->getStreet(); @@ -370,34 +396,42 @@ protected function _getCustomer($cart,$mailchimpStoreId) if ($street[0]) { $address['address1'] = $street[0]; } + if (count($street) > 1) { $address['address1'] = $street[1]; } + if ($billingAddress->getCity()) { $address['city'] = $billingAddress->getCity(); } + if ($billingAddress->getRegion()) { $address['province'] = $billingAddress->getRegion(); } + if ($billingAddress->getRegionCode()) { $address['province_code'] = $billingAddress->getRegionCode(); } + if ($billingAddress->getPostcode()) { $address['postal_code'] = $billingAddress->getPostcode(); } + if ($billingAddress->getCountry()) { - $address['country'] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); $address['country_code'] = $billingAddress->getCountry(); } + if (count($address)) { $customer['address'] = $address; } } + //company if ($billingAddress->getCompany()) { $customer["company"] = $billingAddress->getCompany(); } + return $customer; } protected function _getApi() @@ -405,6 +439,7 @@ protected function _getApi() if (!$this->_api) { $this->_api = Mage::helper('mailchimp')->getApi(); } + return $this->_api; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index a4e7b5224..f45c2ce51 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -60,8 +60,10 @@ public function createBatchJson($mailchimpStoreId) $customer->setData("mailchimp_sync_modified", 0); $this->_saveCustomer($customer); } + $counter++; } + return $customerArray; } @@ -80,14 +82,16 @@ protected function _buildCustomerData($customer) ->addFieldToFilter('state', 'complete') ->addAttributeToFilter('customer_id', array('eq' => $customer->getId())); if($firstDate) { - $orderCollection->addFieldToFilter('created_at',array('from' => $firstDate)); + $orderCollection->addFieldToFilter('created_at', array('from' => $firstDate)); } + $totalOrders = 0; $totalAmountSpent = 0; foreach ($orderCollection as $order) { $totalOrders++; $totalAmountSpent += (int)$order->getGrandTotal(); } + $data["orders_count"] = $totalOrders; $data["total_spent"] = $totalAmountSpent; @@ -100,35 +104,45 @@ protected function _buildCustomerData($customer) if ($street[0]) { $customerAddress["address1"] = $street[0]; } + if (count($street) > 1) { $customerAddress["address2"] = $street[1]; } + if ($address->getCity()) { $customerAddress["city"] = $address->getCity(); } + if ($address->getRegion()) { $customerAddress["province"] = $address->getRegion(); } + if ($address->getRegionCode()) { $customerAddress["province_code"] = $address->getRegionCode(); } + if ($address->getPostcode()) { $customerAddress["postal_code"] = $address->getPostcode(); } + if ($address->getCountry()) { $customerAddress["country"] = Mage::getModel('directory/country')->loadByCode($address->getCountry())->getName(); $customerAddress["country_code"] = $address->getCountry(); } + if (count($address)) { $data["address"] = $customerAddress; } + //company if ($address->getCompany()) { $data["company"] = $address->getCompany(); } + break; } } + $mergeFields = $this->getMergeVars($customer); if (is_array($mergeFields)) { $data = array_merge($mergeFields, $data); @@ -159,6 +173,7 @@ public function getMergeVars($object) } else { $customer = $object; } + foreach ($maps as $map) { $customAtt = $map['magento']; $chimpTag = $map['mailchimp']; @@ -181,6 +196,7 @@ public function getMergeVars($object) $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[1])}()); } } + if ($address) { $street = $address->getStreet(); $mergeVars[$key] = array( @@ -216,6 +232,7 @@ public function getMergeVars($object) } break; } + // } } else { switch ($attributeCode) { @@ -239,6 +256,7 @@ public function getMergeVars($object) } else { $firstName = $customer->getFirstname(); } + if ($firstName) { $mergeVars[$key] = $firstName; } @@ -249,6 +267,7 @@ public function getMergeVars($object) } else { $lastName = $customer->getLastname(); } + if ($lastName) { $mergeVars[$key] = $lastName; } @@ -256,6 +275,7 @@ public function getMergeVars($object) } } } + switch ($customAtt) { case 'billing_company': case 'shipping_company': @@ -266,6 +286,7 @@ public function getMergeVars($object) $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); } } + if ($address) { $company = $address->getCompany(); if ($company) { @@ -282,6 +303,7 @@ public function getMergeVars($object) $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); } } + if ($address) { $telephone = $address->getTelephone(); if ($telephone) { @@ -298,6 +320,7 @@ public function getMergeVars($object) $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); } } + if ($address) { $countryCode = $address->getCountry(); if ($countryCode) { @@ -315,6 +338,7 @@ public function getMergeVars($object) $address = Mage::getModel('customer/address')->load($customer->{'getDefault' . ucfirst($addr[0])}()); } } + if ($address) { $zipCode = $address->getPostcode(); if ($zipCode) { @@ -325,10 +349,12 @@ public function getMergeVars($object) } } } + return (!empty($mergeVars)) ? $mergeVars : null; } - public function createGuestCustomer($guestId, $order) { + public function createGuestCustomer($guestId, $order) + { $guestCustomer = Mage::getModel('customer/customer')->setId($guestId); foreach ($order->getData() as $key => $value) { $keyArray = explode('_', $key); @@ -336,27 +362,32 @@ public function createGuestCustomer($guestId, $order) { $guestCustomer->{'set' . ucfirst($keyArray[1])}($value); } } + return $guestCustomer; } - public function getOptin() { + public function getOptin() + { if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMERS_OPTIN, 0)) { $optin = true; } else { $optin = false; } + return $optin; } protected function _saveCustomer($customer) { if($customer->dataHasChangedFor('mailchimp_sync_delta')) { - $customer->getResource()->saveAttribute($customer,'mailchimp_sync_delta'); + $customer->getResource()->saveAttribute($customer, 'mailchimp_sync_delta'); } + if($customer->dataHasChangedFor('mailchimp_sync_error')) { - $customer->getResource()->saveAttribute($customer,'mailchimp_sync_error'); + $customer->getResource()->saveAttribute($customer, 'mailchimp_sync_error'); } + if($customer->dataHasChangedFor('mailchimp_sync_modified')) { - $customer->getResource()->saveAttribute($customer,'mailchimp_sync_modified'); + $customer->getResource()->saveAttribute($customer, 'mailchimp_sync_modified'); } } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 1c2acaa8d..2da8c1ebb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -59,6 +59,7 @@ protected function _getModifiedOrders($mailchimpStoreId) if ($this->_firstDate) { $collection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } + $collection->getSelect()->limit(self::BATCH_LIMIT); foreach ($collection as $item) { @@ -71,17 +72,18 @@ protected function _getModifiedOrders($mailchimpStoreId) $this->_counter++; } } + $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); if (!empty($orderJson)) { $batchArray[$this->_counter]['method'] = "PATCH"; $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId(); $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); $batchArray[$this->_counter]['body'] = $orderJson; - } else { $error = Mage::helper('mailchimp')->__('Something went wrong when retreiving product information.'); $order->setData("mailchimp_sync_error", $error); } + //update order delta $order->setData("mailchimp_sync_delta", Varien_Date::now()); $order->setMailchimpSyncModified(0); @@ -92,6 +94,7 @@ protected function _getModifiedOrders($mailchimpStoreId) Mage::helper('mailchimp')->logError($e->getMessage()); } } + return $batchArray; } @@ -101,14 +104,17 @@ protected function _getNewOrders($mailchimpStoreId) //create missing products first $collection = Mage::getModel('sales/order')->getCollection() ->addAttributeToSelect('entity_id') - ->addFieldToFilter('mailchimp_sync_delta', array( + ->addFieldToFilter( + 'mailchimp_sync_delta', array( array('null' => true), array('eq' => ''), array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag()) - )); + ) + ); if ($this->_firstDate) { $collection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } + $collection->getSelect()->limit(self::BATCH_LIMIT); foreach ($collection as $item) { @@ -121,17 +127,18 @@ protected function _getNewOrders($mailchimpStoreId) $this->_counter++; } } + $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId); if (!empty($orderJson)) { $batchArray[$this->_counter]['method'] = "POST"; $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); $batchArray[$this->_counter]['body'] = $orderJson; - } else { $error = Mage::helper('mailchimp')->__('Something went wrong when retreiving product information.'); $order->setData("mailchimp_sync_error", $error); } + //update order delta $order->setData("mailchimp_sync_delta", Varien_Date::now()); $order->setMailchimpSyncModified(0); @@ -142,6 +149,7 @@ protected function _getNewOrders($mailchimpStoreId) Mage::helper('mailchimp')->logError($e->getMessage()); } } + return $batchArray; } @@ -201,9 +209,11 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) if ($order->getMailchimpCampaignId()) { $data['campaign_id'] = $order->getMailchimpCampaignId(); } + if ($order->getMailchimpLandingPage()) { $data['landing_site'] = $order->getMailchimpLandingPage(); } + $data['currency_code'] = $order->getOrderCurrencyCode(); $data['order_total'] = $order->getGrandTotal(); $data['tax_total'] = $order->getTaxAmount(); @@ -213,6 +223,7 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) if (isset($statusArray['financial_status'])) { $data['financial_status'] = $statusArray['financial_status']; } + if (isset($statusArray['fulfillment_status'])) { $data['fulfillment_status'] = $statusArray['fulfillment_status']; } @@ -227,10 +238,12 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) $orderCancelDate = $comment->getCreatedAt(); } } + if ($orderCancelDate) { $data['cancelled_at_foreign'] = $orderCancelDate; } } + $data['lines'] = array(); //order lines @@ -247,6 +260,7 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) } else { $variant = $item->getProductId(); } + // load the product and check if the product was already sent to mailchimp $syncDelta = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), 'mailchimp_sync_delta', $order->getStoreId()); $syncError = Mage::getResourceModel('catalog/product')->getAttributeRawValue($item->getProductId(), 'mailchimp_sync_error', $order->getStoreId()); @@ -263,10 +277,12 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) ); } } + if (!$itemCount) { unset($data['lines']); return ""; } + //customer data $api = $this->_getApi(); $customers = array(); @@ -275,6 +291,7 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); } + if (!$this->_isModifiedOrder($order)) { if (isset($customers['total_items']) && $customers['total_items'] > 0) { $id = $customers['customers'][0]['id']; @@ -308,6 +325,7 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) } } catch (Mailchimp_Error $e) { } + $data["customer"] = array( "id" => ($order->getCustomerId()) ? $order->getCustomerId() : $guestId = "CUSTOMER-" . Mage::helper('mailchimp')->getDateMicrotime(), "email_address" => ($custEmailAddr) ? $custEmailAddr : $order->getCustomerEmail(), @@ -323,18 +341,23 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) ); } } + $store = Mage::getModel('core/store')->load($order->getStoreId()); - $data['order_url'] = $store->getUrl('sales/order/view/', array( + $data['order_url'] = $store->getUrl( + 'sales/order/view/', array( 'order_id' => $order->getId(), '_nosid' => true, '_secure' => true - )); + ) + ); if ($order->getCustomerFirstname()) { $data["customer"]["first_name"] = $order->getCustomerFirstname(); } + if ($order->getCustomerLastname()) { $data["customer"]["last_name"] = $order->getCustomerLastname(); } + $billingAddress = $order->getBillingAddress(); $street = $billingAddress->getStreet(); $address = array(); @@ -379,9 +402,11 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) if (count($address)) { $data["customer"]["address"] = $address; } + if ($billingAddress->getName()) { $data['billing_address']['name'] = $billingAddress->getName(); } + //company if ($billingAddress->getCompany()) { $data["customer"]["company"] = $billingAddress->getCompany(); @@ -394,28 +419,36 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) if ($shippingAddress->getName()) { $data['shipping_address']['name'] = $shippingAddress->getName(); } + if (isset($street[0]) && $street[0]) { $data['shipping_address']['address1'] = $street[0]; } + if (isset($street[1]) && $street[1]) { $data['shipping_address']['address2'] = $street[1]; } + if ($shippingAddress->getCity()) { $data['shipping_address']['city'] = $shippingAddress->getCity(); } + if ($shippingAddress->getRegion()) { $data['shipping_address']['province'] = $shippingAddress->getRegion(); } + if ($shippingAddress->getRegionCode()) { $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); } + if ($shippingAddress->getPostcode()) { $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); } + if ($shippingAddress->getCountry()) { $data['shipping_address']['country'] = Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName(); $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); } + if ($shippingAddress->getCompamy()) { $data["shipping_address"]["company"] = $shippingAddress->getCompany(); } @@ -432,12 +465,14 @@ protected function GeneratePOSTPayload($order, $mailchimpStoreId) if ($this->_firstDate) { $orderCollection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); } + $totalOrders = 1; $totalAmountSpent = (int)$order->getGrandTotal(); foreach ($orderCollection as $orderAlreadySent) { $totalOrders++; $totalAmountSpent += (int)$orderAlreadySent->getGrandTotal(); } + $data["customer"]["orders_count"] = $totalOrders; $data["customer"]["total_spent"] = $totalAmountSpent; $jsonData = ""; @@ -479,6 +514,7 @@ protected function _getMailChimpStatus($order) $invoicedItemAmount += $item->getQtyInvoiced(); $refundedItemAmount += $item->getQtyRefunded(); } + if ($shippedItemAmount > 0) { if ($totalItemsOrdered > $shippedItemAmount) { $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED; @@ -486,6 +522,7 @@ protected function _getMailChimpStatus($order) $mailChimpFulfillmentStatus = self::SHIPPED; } } + if ($refundedItemAmount > 0) { if ($totalItemsOrdered > $refundedItemAmount) { $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED; @@ -493,6 +530,7 @@ protected function _getMailChimpStatus($order) $mailChimpFinancialStatus = self::REFUNDED; } } + if ($invoicedItemAmount > 0) { if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) { if ($totalItemsOrdered > $invoicedItemAmount) { @@ -501,7 +539,6 @@ protected function _getMailChimpStatus($order) $mailChimpFinancialStatus = self::PAID; } } - } if (!$mailChimpFinancialStatus && $order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) { @@ -515,9 +552,11 @@ protected function _getMailChimpStatus($order) if ($mailChimpFinancialStatus) { $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus; } + if ($mailChimpFulfillmentStatus) { $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus; } + return $mailChimpStatus; } @@ -539,6 +578,7 @@ protected function _getApi() if (!$this->_api) { $this->_api = Mage::helper('mailchimp')->getApi(); } + return $this->_api; } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 70ef4c4e8..3f280af11 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -64,6 +64,7 @@ public function createBatchJson($mailchimpStoreId) continue; } } + return $batchArray; } protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId) @@ -94,12 +95,12 @@ protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId) $bodyData = $this->_buildProductData($product, false, $variantProducts); try { $body = json_encode($bodyData); - } catch (Exception $e) { //json encode failed Mage::helper('mailchimp')->logError("Product " . $product->getId() . " json encode failed"); return array(); } + $data = array(); $data['method'] = "POST"; $data['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products"; @@ -137,17 +138,17 @@ protected function _buildOldProductRequest($product,$batchId,$mailchimpStoreId) $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"); continue; } + $productdata['body'] = $body; $operations[] = $productdata; } - } + return $operations; } protected function _buildProductData($product, $isVarient = true, $variants = null) @@ -177,7 +178,6 @@ protected function _buildProductData($product, $isVarient = true, $variants = nu $data["backorders"] = (string)$stock->getBackorders(); $data["visibility"] = $product->getVisibility(); - } else { //this is for a root product if($product->getDescription()) { @@ -222,6 +222,7 @@ public function sendModifiedProduct($order, $mailchimpStoreId) if ($product->getId()!=$item->getProductId()||$product->getTypeId()=='bundle'||$product->getTypeId()=='grouped') { continue; } + if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()) { $data[] = $this->_buildOldProductRequest($product, $batchId, $mailchimpStoreId); $this->_setProductNoError($product); @@ -232,6 +233,7 @@ public function sendModifiedProduct($order, $mailchimpStoreId) $this->_saveProduct($product); } } + return $data; } protected function _setProductNoError($product) @@ -244,13 +246,15 @@ protected function _setProductNoError($product) protected function _saveProduct($product) { if($product->dataHasChangedFor('mailchimp_sync_delta')) { - $product->getResource()->saveAttribute($product,'mailchimp_sync_delta'); + $product->getResource()->saveAttribute($product, 'mailchimp_sync_delta'); } + if($product->dataHasChangedFor('mailchimp_sync_error')) { - $product->getResource()->saveAttribute($product,'mailchimp_sync_error'); + $product->getResource()->saveAttribute($product, 'mailchimp_sync_error'); } + if($product->dataHasChangedFor('mailchimp_sync_modified')) { - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); + $product->getResource()->saveAttribute($product, 'mailchimp_sync_modified'); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index 3a2a5f1aa..a63ef8771 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -43,7 +43,6 @@ public function getMailChimpStore() } return $storeExists; - } else { throw new Exception('You must provide a MailChimp API key'); } @@ -96,6 +95,6 @@ public function modifyName($name) { $api = Mage::helper('mailchimp')->getApi(); $storeId = Mage::helper('mailchimp')->getMCStoreId(); - $api->ecommerce->stores->edit($storeId,$name); + $api->ecommerce->stores->edit($storeId, $name); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 6bbd9d139..638b49bfb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -41,7 +41,6 @@ public function createBatchJson($listId, $storeId, $limit) //enconde to JSON try { $subscriberJson = json_encode($data); - } catch (Exception $e) { //json encode failed $errorMessage = "Subscriber ".$subscriber->getSubscriberId()." json encode failed"; @@ -59,8 +58,10 @@ public function createBatchJson($listId, $storeId, $limit) $subscriber->setData("mailchimp_sync_error", ""); $subscriber->save(); } + $counter++; } + return $subscriberArray; } @@ -72,6 +73,7 @@ protected function _buildSubscriberData($subscriber) if ($mergeVars) { $data["merge_fields"] = $mergeVars; } + $data["status_if_new"] = $this->_getMCStatus($subscriber->getStatus()); return $data; @@ -116,8 +118,7 @@ protected function _getMCStatus($status = null) $confirmationFlagPath = Mage_Newsletter_Model_Subscriber::XML_PATH_CONFIRMATION_FLAG; if ($status == Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) { $status = 'unsubscribed'; - } elseif ( - Mage::helper('mailchimp')->getConfigValue($confirmationFlagPath) && + } elseif (Mage::helper('mailchimp')->getConfigValue($confirmationFlagPath) && ($status == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE || $status == Mage_Newsletter_Model_Subscriber::STATUS_UNCONFIRMED) ) { @@ -125,6 +126,7 @@ protected function _getMCStatus($status = null) } elseif ($status == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED) { $status = 'subscribed'; } + return $status; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php index c01028d62..57f7e1607 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php @@ -34,13 +34,14 @@ public function send() if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_ACTIVE, $storeId)) { $parameters = new Varien_Object($message->getMessageParameters()); $mailer = $this->getMail($storeId); - $mailer->setFrom($parameters->getFromEmail(),$parameters->getFromName()); + $mailer->setFrom($parameters->getFromEmail(), $parameters->getFromName()); $mailer->setSubject($parameters->getSubject()); if ($parameters->getIsPlain()) { $mailer->setBodyText($message->getMessageBody()); } else { $mailer->setBodyHtml($message->getMessageBody()); } + try { foreach ($message->getRecipients() as $recipient) { list($email, $name, $type) = $recipient; @@ -54,12 +55,15 @@ public function send() break; } } + if ($parameters->getReplyTo() !== null) { $mailer->setReplyTo($parameters->getReplyTo()); } + if ($parameters->getReturnTo() !== null) { $mailer->setReturnPath($parameters->getReturnTo()); } + try { Mage::dispatchEvent( 'fooman_emailattachments_before_send_queue', @@ -74,6 +78,7 @@ public function send() } catch (Exception $e) { Mage::logException($e); } + unset($mailer); $message->setProcessedAt(Varien_Date::formatDate(true)); $message->save(); @@ -113,6 +118,7 @@ public function send() if ($parameters->getReplyTo() !== null) { $mailer->setReplyTo($parameters->getReplyTo()); } + if ($parameters->getReturnTo() !== null) { $mailer->setReturnPath($parameters->getReturnTo()); } @@ -139,6 +145,7 @@ public function send() } } } + return $this; } @@ -151,6 +158,7 @@ public function getMail($storeId) if (!Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_ACTIVE, $storeId)) { return null; } + Mage::helper('mailchimp/mandrill')->log("store: $storeId API: " . Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)); $mail = new Mandrill_Message(Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)); return $mail; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php index 302ac940b..88d9305dc 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php @@ -25,10 +25,12 @@ public function send($email, $name = null, array $variables = array()) if (!Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_ACTIVE)) { return parent::send($email, $name, $variables); } + if (!$this->isValidForSend()) { Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted return false; } + $emails = array_values((array)$email); $names = is_array($name) ? $name : (array)$name; $names = array_values($names); @@ -58,6 +60,7 @@ public function send($email, $name = null, array $variables = array()) $returnPathEmail = null; break; } + $mail = $this->getMail(); $max = count($emails); for ($i = 0; $i < $max; $i++) { @@ -73,6 +76,7 @@ public function send($email, $name = null, array $variables = array()) ); } } + foreach ($mail->getBcc() as $bcc) { $email['to'][] = array( 'email' => $bcc, @@ -92,10 +96,12 @@ public function send($email, $name = null, array $variables = array()) $senderExists = true; } } + if(!$senderExists) { $email['from_email'] = Mage::getStoreConfig('trans_email/ident_general/email'); } + $headers = $mail->getHeaders(); $headers[] = Mage::helper('mailchimp/mandrill')->getUserAgent(); $email['headers'] = $headers; @@ -126,6 +132,7 @@ public function send($email, $name = null, array $variables = array()) if ($att = $mail->getAttachments()) { $email['attachments'] = $att; } + if ($this->isPlain()) $email['text'] = $message; else @@ -134,24 +141,28 @@ public function send($email, $name = null, array $variables = array()) if ($this->hasQueue() && $this->getQueue() instanceof Mage_Core_Model_Email_Queue) { $emailQueue = $this->getQueue(); $emailQueue->setMessageBody($message); - $emailQueue->setMessageParameters(array( + $emailQueue->setMessageParameters( + array( 'subject' => $subject, 'return_path_email' => $returnPathEmail, 'is_plain' => $this->isPlain(), 'from_email' => $this->getSenderEmail(), 'from_name' => $this->getSenderName() - )) + ) + ) ->addRecipients($emails, $names, Mage_Core_Model_Email_Queue::EMAIL_TYPE_TO) ->addRecipients($this->_bccEmails, array(), Mage_Core_Model_Email_Queue::EMAIL_TYPE_BCC); $emailQueue->addMessageToQueue(); return true; } + try { $result = $mail->messages->send($email); } catch (Exception $e) { Mage::logException($e); return false; } + return true; } @@ -165,6 +176,7 @@ public function getMail() if (!Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_ACTIVE, $storeId)) { return parent::getMail(); } + if ($this->_mail) { return $this->_mail; } else { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 7dc33820a..b30de65f7 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -47,11 +47,13 @@ protected function _createWebhook($listId) 'wkey' => $webhooksKey, '_nosid' => true, '_secure' => true, - )); + ) + ); if (FALSE != strstr($hookUrl, '?', true)) { $hookUrl = strstr($hookUrl, '?', true); } + $api = Mage::helper('mailchimp')->getApi(); if (Mage::helper('mailchimp')->getConfigValue(Ebizmarts_MailChimp_Model_Config::GENERAL_TWO_WAY_SYNC)) { $events = array( @@ -82,6 +84,7 @@ protected function _createWebhook($listId) 'api' => true ); } + try { $response = $api->lists->webhooks->getAll($listId); $createWebhook = true; @@ -92,6 +95,7 @@ protected function _createWebhook($listId) } } } + if ($createWebhook) { $api->lists->webhooks->add($listId, $hookUrl, $events, $sources); } @@ -161,14 +165,14 @@ public function alterNewsletterGrid(Varien_Event_Observer $observer) if (!isset($block)) { return $this; } - if ($block instanceof Mage_Adminhtml_Block_Newsletter_Subscriber_Grid) { + if ($block instanceof Mage_Adminhtml_Block_Newsletter_Subscriber_Grid) { $block->addColumnAfter( 'firstname', array( 'header' => Mage::helper('newsletter')->__('Customer First Name'), 'index' => 'customer_firstname', 'renderer' => 'mailchimp/adminhtml_newsletter_subscriber_renderer_firstname', - ), 'type' + ), 'type' ); $block->addColumnAfter( @@ -176,9 +180,10 @@ public function alterNewsletterGrid(Varien_Event_Observer $observer) 'header' => Mage::helper('newsletter')->__('Customer Last Name'), 'index' => 'customer_lastname', 'renderer' => 'mailchimp/adminhtml_newsletter_subscriber_renderer_lastname' - ), 'firstname' + ), 'firstname' ); } + return $observer; } @@ -233,6 +238,7 @@ public function orderSaveBefore(Varien_Event_Observer $observer) } else { $order->setMailchimpUpdateObserverRan(true); } + //update mailchimp ecommerce data for that product variant Mage::getModel('mailchimp/api_orders')->update($order); $landingCookie = $this->_getLandingCookie(); @@ -253,9 +259,11 @@ public function removeCampaignData(Varien_Event_Observer $observer) if ($this->_getCampaignCookie()) { Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); } - if( ($this->_getLandingCookie())) { + + if(($this->_getLandingCookie())) { Mage::getModel('core/cookie')->delete('mailchimp_landing_page'); } + return $observer; } @@ -267,9 +275,10 @@ public function removeCampaignData(Varien_Event_Observer $observer) protected function _getCampaignCookie() { $landingCookie = $this->_getLandingCookie(); - if ( preg_match("/utm_source=mailchimp/",$landingCookie)) { + if (preg_match("/utm_source=mailchimp/", $landingCookie)) { return null; } + $cookie = Mage::getModel('core/cookie')->get('mailchimp_campaign_id'); if ($cookie && Mage::getModel('core/cookie')->getLifetime('mailchimp_campaign_id') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) { return $cookie; @@ -306,9 +315,10 @@ public function addColumnToSalesOrderGrid($observer) 'renderer' => 'mailchimp/adminhtml_sales_order_grid_renderer_mailchimp', 'sortable' => false, 'width' => 70 - ), 'created_at' + ), 'created_at' ); } + return $observer; } @@ -322,15 +332,14 @@ protected function _createMailChimpStore() if (!$mailchimpStore) { Mage::helper('mailchimp')->resetMCEcommerceData(); } + if (!Mage::helper('mailchimp')->getMCStoreId()) { $warningMessage = 'The MailChimp store was not created properly, please save your configuration to create it.'; Mage::getSingleton('adminhtml/session')->addWarning($warningMessage); } - } catch (Mailchimp_Error $e) { Mage::helper('mailchimp')->logError($e->getFriendlyMessage()); Mage::getSingleton('adminhtml/session')->addError($e->getFriendlyMessage()); - } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } @@ -364,14 +373,17 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) } } } + $campaignId = $this->_getCampaignCookie(); if ($campaignId) { $quote->setMailchimpCampaignId($campaignId); } + $landingCookie = $this->_getLandingCookie(); if ($landingCookie) { $quote->setMailchimpLandingPage($landingCookie); } + return $observer; } @@ -384,12 +396,14 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) */ public function newOrder(Varien_Event_Observer $observer) { - if( ($this->_getLandingCookie())) { + if(($this->_getLandingCookie())) { Mage::getModel('core/cookie')->delete('mailchimp_landing_page'); } + if ($this->_getCampaignCookie()) { Mage::getModel('core/cookie')->delete('mailchimp_campaign_id'); } + $order = $observer->getEvent()->getOrder(); $items = $order->getAllItems(); foreach ($items as $item) @@ -397,11 +411,13 @@ public function newOrder(Varien_Event_Observer $observer) if ($item->getProductType()=='bundle' || $item->getProductType()=='configurable') { continue; } + $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); $resource = $product->getResource(); $resource->saveAttribute($product, 'mailchimp_sync_modified'); } + return $observer; } @@ -421,11 +437,13 @@ public function newCreditMemo(Varien_Event_Observer $observer) if ($item->getProductType()=='bundle' || $item->getProductType()=='configurable') { continue; } + $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); $resource = $product->getResource(); $resource->saveAttribute($product, 'mailchimp_sync_modified'); } + $creditMemo->getOrder()->setMailchimpSyncModified(1); return $observer; } @@ -446,11 +464,13 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) if ($item->getProductType()=='bundle' || $item->getProductType()=='configurable') { continue; } + $product = Mage::getModel('catalog/product')->load($item->getProductId()); $product->setData('mailchimp_sync_modified', 1); $resource = $product->getResource(); $resource->saveAttribute($product, 'mailchimp_sync_modified'); } + $creditMemo->getOrder()->setMailchimpSyncModified(1); return $observer; } @@ -471,10 +491,12 @@ public function itemCancel(Varien_Event_Observer$observer) $resource = $product->getResource(); $resource->saveAttribute($product, 'mailchimp_sync_modified'); } + return $observer; } - public function addOrderViewMonkey(Varien_Event_Observer $observer){ + public function addOrderViewMonkey(Varien_Event_Observer $observer) + { $block = $observer->getBlock(); if(($block->getNameInLayout() == 'order_info') && ($child = $block->getChild('mailchimp.order.info.monkey.block'))){ $transport = $observer->getTransport(); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index 8a06df91c..8f32be413 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -98,7 +98,6 @@ protected function _clean(array $data) protected function _subscribe(array $data) { try { - $subscriber = Mage::getModel('newsletter/subscriber') ->loadByEmail($data['data']['email']); if ($subscriber->getId()) { @@ -110,12 +109,13 @@ protected function _subscribe(array $data) $subscriberFname = filter_var($data['data']['fname'], FILTER_SANITIZE_STRING); $subscriber->setSubscriberFirstname($subscriberFname); } + if (isset($data['data']['lname'])) { $subscriberLname = filter_var($data['data']['lname'], FILTER_SANITIZE_STRING); $subscriber->setSubscriberLastname($subscriberLname); } - $subscriber->subscribe($data['data']['email']); + $subscriber->subscribe($data['data']['email']); } } catch (Exception $e) { Mage::logException($e); @@ -139,7 +139,6 @@ protected function _unsubscribe(array $data) if ($subscriber->getId()) { try { - switch ($data['data']['action']) { case 'delete' : //if config setting "Webhooks Delete action" is set as "Delete customer account" @@ -171,6 +170,7 @@ protected function _profile(array $data) } else { $toUpdate = $subscriber; } + $toUpdate->setFirstname($data['data']['merges']['FNAME']); $toUpdate->setLastname($data['data']['merges']['LNAME']); $toUpdate->save(); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php index daca30732..b7b54ccce 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php @@ -12,13 +12,15 @@ */ class Ebizmarts_MailChimp_Model_System_Config_Backend_Name extends Mage_Core_Model_Config_Data { - protected function _afterSave() { + protected function _afterSave() + { if ($this->isValueChanged()) { $name = $this->getValue(); if ($name == '') { Mage::getConfig()->cleanCache(); $name = Mage::app()->getDefaultStoreView()->getWebsite()->getDefaultStore()->getFrontendName(); } + Mage::helper('mailchimp')->changeName($name); } } 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 0054fd3eb..19ba9acba 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 @@ -91,6 +91,7 @@ public function toOptionArray() $label = Mage::helper('mailchimp')->__($text); $returnArray = array_merge($returnArray, array(array('value' => 7, 'label' => $label))); } + return $returnArray; } elseif (!$this->_accountDetails) { return array(array('value' => '', 'label' => $helper->__('--- Enter your API KEY first ---'))); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php index aebc5c06e..f0e98dc54 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Userinfo.php @@ -35,6 +35,7 @@ public function __construct() } } } + if ((!is_array($this->_account_details) || isset($this->_account_details['status'])) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::MANDRILL_APIKEY, $storeId)) { $api = new Mandrill_Message(Mage::getStoreConfig(Ebizmarts_Mailchimp_Model_Config::MANDRILL_APIKEY, $storeId)); try { diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php index 883866d90..0771bd4dd 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/EcommerceController.php @@ -21,6 +21,7 @@ public function resetLocalErrorsAction() { $result = 0; } + Mage::app()->getResponse()->setBody($result); } public function resetEcommerceDataAction() @@ -37,6 +38,7 @@ public function resetEcommerceDataAction() catch(Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } + Mage::app()->getResponse()->setBody($result); } @@ -53,6 +55,7 @@ public function createMergeFieldsAction() catch(Exception $e) { Mage::helper('mailchimp')->logError($e->getMessage()); } + Mage::app()->getResponse()->setBody($result); } @@ -65,6 +68,7 @@ protected function _isAllowed() $acl = 'system/config/mailchimp'; break; } + return Mage::getSingleton('admin/session')->isAllowed($acl); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php index 226255089..610029ed1 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php @@ -29,8 +29,8 @@ public function gridAction() public function downloadresponseAction() { $batch_id = $this->getRequest()->getParam('batch_id'); - $this->getResponse()->setHeader('Content-disposition','attachment; filename='.$batch_id.'.json'); - $this->getResponse()->setHeader('Content-type','application/json'); + $this->getResponse()->setHeader('Content-disposition', 'attachment; filename='.$batch_id.'.json'); + $this->getResponse()->setHeader('Content-type', 'application/json'); $files = Mage::getModel('mailchimp/api_batches')->getBatchResponse($batch_id); $fileContent = array(); foreach ($files as $file) { @@ -39,13 +39,16 @@ public function downloadresponseAction() // $fileContent [] = $item; $fileContent [] = array('status_code'=>$item->status_code,'operation_id'=>$item->operation_id,'response'=>json_decode($item->response)); } + unlink($file); } + $baseDir = Mage::getBaseDir(); if (is_dir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batch_id)) { rmdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batch_id); } - $this->getResponse()->setBody(json_encode($fileContent,JSON_PRETTY_PRINT)); + + $this->getResponse()->setBody(json_encode($fileContent, JSON_PRETTY_PRINT)); return; } protected function _isAllowed() @@ -57,6 +60,7 @@ protected function _isAllowed() $acl = 'newsletter/mailchimp/mailchimperrors'; break; } + return Mage::getSingleton('admin/session')->isAllowed($acl); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php index bd4ade79f..c32239596 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php @@ -12,7 +12,8 @@ class Ebizmarts_MailChimp_Adminhtml_MergevarsController extends Mage_Adminhtml_Controller_Action { - public function addmergevarAction(){ + public function addmergevarAction() + { $this->loadLayout(); $this->renderLayout(); @@ -31,6 +32,7 @@ public function saveaddAction() if(!$customFieldTypes){ $customFieldTypes = array(); } + $customFieldTypes[] = array('label' => $label, 'value' => $value, 'field_type' => $fieldType); Mage::getConfig()->saveConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_CUSTOM_MAP_FIELDS, serialize($customFieldTypes)); Mage::getConfig()->cleanCache(); @@ -49,6 +51,7 @@ protected function _isAllowed() $acl = 'system/config/mailchimp'; break; } + return Mage::getSingleton('admin/session')->isAllowed($acl); } } \ No newline at end of file diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php index 73551be20..12ceda92a 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php @@ -25,6 +25,7 @@ public function loadquoteAction() if (isset($params['mc_cid'])) { $url .= '?mc_cid='.$params['mc_cid']; } + if ((!isset($params['token']) || (isset($params['token']) && $params['token'] != $quote->getMailchimpToken()))) { Mage::getSingleton('customer/session')->addNotice("Your token cart is incorrect"); $this->_redirect($url); @@ -45,6 +46,7 @@ public function loadquoteAction() if (isset($params['mc_cid'])) { $url .= '?mc_cid='.$params['mc_cid']; } + $this->getResponse()->setRedirect($url, 301); //$this->_redirect('customer/account/login',array('?','mc_cid='.$params['mc_cid'])); } diff --git a/getMailchimpResponse.php b/getMailchimpResponse.php index 27938dc34..6bf0bc742 100644 --- a/getMailchimpResponse.php +++ b/getMailchimpResponse.php @@ -4,6 +4,7 @@ printf("You must call like:\n\t getMailchimpResponse apikey batchid\n"); return; } + $apiKey = $argv[1]; $batchId = $argv[2]; @@ -18,7 +19,8 @@ $curl = curl_init(); -curl_setopt_array($curl, array( +curl_setopt_array( + $curl, array( CURLOPT_URL => "https://$dc.api.mailchimp.com/3.0/batches/$batchId", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", @@ -32,8 +34,9 @@ "accept: application/json", "cache-control: no-cache", "content-type: application/json" - ), -)); + ), + ) +); $response = curl_exec($curl); $err = curl_error($curl); @@ -47,7 +50,7 @@ if ($jsonResponse->status == 'finished') { $fileUrl = $jsonResponse->response_body_url; // check if the file is not expired - parse_str($fileUrl,$fileParams); + parse_str($fileUrl, $fileParams); try { $fd = fopen("$batchId.response.tar.gz", 'w'); $ch = curl_init(); @@ -62,6 +65,7 @@ printf($e->getMessage()); } } + // else { // echo "Error: the batch is not finished or have errors\n"; // echo "Error ".$jsonResponse->title." Detail: ".$jsonResponse->detail."\n"; diff --git a/js/ebizmarts/mailchimp/campaignCatcher.js b/js/ebizmarts/mailchimp/campaignCatcher.js index 06fed1cf9..304289d84 100755 --- a/js/ebizmarts/mailchimp/campaignCatcher.js +++ b/js/ebizmarts/mailchimp/campaignCatcher.js @@ -1,4 +1,5 @@ - function getCampaign() { + function getCampaign() +{ var urlparams = location.search.substr(1).split('&'); var params = new Array(); var mc_cid = null; @@ -10,6 +11,7 @@ if (key && val) { params[key] = val; } + if(key=='utm_source') { var reg = /^mailchimp$/; if(reg.exec(val)) { @@ -27,6 +29,7 @@ Mage.Cookies.set('mailchimp_campaign_id' , mc_cid); Mage.Cookies.set('mailchimp_landing_page', location); } + if(isMailchimp) { Mage.Cookies.clear('mailchimp_campaign_id'); Mage.Cookies.set('mailchimp_landing_page', location); diff --git a/lib/Ebizmarts/Mailchimp.php b/lib/Ebizmarts/Mailchimp.php index 4d84c2480..c6e2c7502 100755 --- a/lib/Ebizmarts/Mailchimp.php +++ b/lib/Ebizmarts/Mailchimp.php @@ -123,6 +123,7 @@ require_once dirname(__FILE__) . '/Mailchimp/Templates.php'; require_once dirname(__FILE__) . '/Mailchimp/TemplatesDefaultContent.php'; } + class Ebizmarts_Mailchimp { protected $_apiKey; @@ -141,6 +142,7 @@ public function __construct($apiKey=null,$opts=array(),$userAgent=null) if (!$apiKey) { throw new Mailchimp_Error('You must provide a MailChimp API key'); } + $this->_apiKey = $apiKey; $dc = 'us1'; if (strstr($this->_apiKey, "-")) { @@ -149,12 +151,14 @@ public function __construct($apiKey=null,$opts=array(),$userAgent=null) $dc = "us1"; } } + $this->_root = str_replace('https://api', 'https://' . $dc . '.api', $this->_root); $this->_root = rtrim($this->_root, '/') . '/'; if (!isset($opts['timeout']) || !is_int($opts['timeout'])) { $opts['timeout'] = 600; } + if (isset($opts['debug'])) { $this->_debug = true; } @@ -165,11 +169,13 @@ public function __construct($apiKey=null,$opts=array(),$userAgent=null) if (isset($opts['CURLOPT_FOLLOWLOCATION']) && $opts['CURLOPT_FOLLOWLOCATION'] === true) { curl_setopt($this->_ch, CURLOPT_FOLLOWLOCATION, true); } + if ($userAgent) { curl_setopt($this->_ch, CURLOPT_USERAGENT, $userAgent); } else { curl_setopt($this->_ch, CURLOPT_USERAGENT, 'Ebizmart-MailChimp-PHP/3.0.0'); } + curl_setopt($this->_ch, CURLOPT_HEADER, false); curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->_ch, CURLOPT_CONNECTTIMEOUT, 30); diff --git a/lib/Ebizmarts/Mailchimp/Exceptions.php b/lib/Ebizmarts/Mailchimp/Exceptions.php index c10d38137..cf0e771e0 100644 --- a/lib/Ebizmarts/Mailchimp/Exceptions.php +++ b/lib/Ebizmarts/Mailchimp/Exceptions.php @@ -48,6 +48,7 @@ public function getFriendlyMessage() if (array_key_exists("field", $error) && $error['field']) { $errorDetails .= $error["field"] . " : "; } + $errorDetails .= $error["message"]; } } diff --git a/lib/Ebizmarts/Mailchimp/Root.php b/lib/Ebizmarts/Mailchimp/Root.php index b8115c896..d2577d4f3 100644 --- a/lib/Ebizmarts/Mailchimp/Root.php +++ b/lib/Ebizmarts/Mailchimp/Root.php @@ -18,9 +18,11 @@ public function info($fields=null, $excludeFields=null) if ($fields) { $_params['fields'] = $fields; } + if ($excludeFields) { $_params['exclude_fields'] = $excludeFields; } + return $this->_master->call('', $_params, Ebizmarts_Mailchimp::GET); } } \ No newline at end of file diff --git a/lib/Mandrill/Mandrill.php b/lib/Mandrill/Mandrill.php index 24fb41dab..192cae01e 100755 --- a/lib/Mandrill/Mandrill.php +++ b/lib/Mandrill/Mandrill.php @@ -33,7 +33,6 @@ require_once(dirname(__FILE__) . '/Mandrill/Senders.php'); require_once(dirname(__FILE__) . '/Mandrill/Metadata.php'); require_once(dirname(__FILE__) . '/Mandrill/Exceptions.php'); - } class Mandrill_Mandrill @@ -89,6 +88,7 @@ public function __construct($apikey = null) if (!ini_get('open_basedir')) { curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true); } + curl_setopt($this->ch, CURLOPT_HEADER, false); curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 30); @@ -144,6 +144,7 @@ public function call($url, $params) $this->log(stream_get_contents($curl_buffer)); fclose($curl_buffer); } + $this->log('Completed in ' . number_format($time * 1000, 2) . 'ms'); $this->log('Got response: ' . $response_body); @@ -174,6 +175,7 @@ public function readConfigs() if ($apikey) return $apikey; } } + return false; } From a8ea9adcdb0aed8de001094c702bd38e37fb5a96 Mon Sep 17 00:00:00 2001 From: Santiago Date: Wed, 8 Feb 2017 17:55:13 -0300 Subject: [PATCH 53/53] Added code sniffer ignore for external Mandrill library. --- lib/Mandrill/Mandrill/Exceptions.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/Mandrill/Mandrill/Exceptions.php b/lib/Mandrill/Mandrill/Exceptions.php index 1134a5d49..60622501b 100755 --- a/lib/Mandrill/Mandrill/Exceptions.php +++ b/lib/Mandrill/Mandrill/Exceptions.php @@ -1,5 +1,6 @@