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 d4d30892c..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
@@ -15,11 +15,12 @@ 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 = '';
}
+
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 dbf7c6ec7..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;
}
@@ -83,7 +86,8 @@ public function getConfigValue($path, $storeId = null, $returnParentValueIfNull
*/
public function getMCStoreName()
{
- return parse_url(Mage::getBaseUrl(), PHP_URL_HOST);
+ $storeView = Mage::app()->getDefaultStoreView();
+ return $storeView->getWebsite()->getDefaultStore()->getFrontendName();
}
/**
@@ -133,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);
@@ -185,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);
}
}
}
@@ -216,8 +223,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 +250,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
@@ -301,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);
}
@@ -320,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'];
@@ -331,6 +346,7 @@ public function createMergeFields()
$alreadyExists = true;
}
}
+
if (!$alreadyExists) {
foreach ($customFieldTypes as $customFieldType) {
if ($customFieldType['value'] == $chimpTag) {
@@ -339,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)
@@ -353,6 +371,7 @@ public function createMergeFields()
$label = $option['frontend_label'];
}
}
+
try {
if ($label) {
//Shipping and Billing Address
@@ -391,6 +410,17 @@ 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)
+ {
+ 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/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php
index 27f358d9f..073ba4e89 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php
@@ -45,10 +45,16 @@ 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())) {
rmdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $item->getBatchId());
@@ -69,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
@@ -83,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
@@ -115,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();
}
@@ -126,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;
}
@@ -155,10 +159,12 @@ protected function _sendSubscriberBatches()
break;
}
}
+
$this->_getResults(0, false);
if ($subscriberLimit > 0) {
list($batchResponses[], $subscriberLimit) = $this->sendStoreSubscriberBatch(0, $subscriberLimit);
}
+
return $batchResponses;
}
@@ -205,19 +211,18 @@ 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;
}
/**
* @param $batchId
- * @param $storeId
* @return array
*/
- protected function getBatchResponse($batchId, $storeId = 0)
+ public function getBatchResponse($batchId)
{
$files = array();
try {
@@ -248,14 +253,17 @@ protected function getBatchResponse($batchId, $storeId = 0)
$files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d;
}
}
+
unlink($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar');
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());
}
+
return $files;
}
@@ -286,6 +294,7 @@ protected function processEachResponseFile($files, $batchId)
}
}
}
+
if ($errorDetails == "") {
$errorDetails = $response->detail;
}
@@ -297,8 +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->setMailchimpUpdateObserverRan(true);
- $p->save();
+ $p->getResource()->saveAttribute($p, 'mailchimp_sync_error');
} else {
Mage::helper('mailchimp')->logError("Error: product " . $id . " not found");
}
@@ -307,8 +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->setMailchimpUpdateObserverRan(true);
- $c->save();
+ $c->getResource()->saveAttribute($c, 'mailchimp_sync_error');
} else {
Mage::helper('mailchimp')->logError("Error: customer " . $id . " not found");
}
@@ -317,6 +324,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");
@@ -344,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);
@@ -355,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 b0e4218bf..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) {
@@ -76,10 +78,11 @@ 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;
}
}
+
$allCartsForEmail->clear();
$allCarts[$this->_counter]['method'] = 'DELETE';
$allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId;
@@ -87,9 +90,10 @@ 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 +121,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,17 +138,20 @@ 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;
}
}
+
$allCartsForEmail->clear();
}
+
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
$productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId);
if (count($productData)) {
@@ -150,6 +160,7 @@ protected function _getModifiedQuotes($mailchimpStoreId)
$this->_counter += 1;
}
}
+
if (count($cart->getAllVisibleItems())) {
$cartJson = $this->_makeCart($cart, $mailchimpStoreId);
if ($cartJson!="") {
@@ -160,9 +171,11 @@ protected function _getModifiedQuotes($mailchimpStoreId)
$this->_counter += 1;
}
}
+
$cart->setData("mailchimp_sync_delta", Varien_Date::now());
- $cart->save();
+ $this->_saveCart($cart);
}
+
return $allCarts;
}
@@ -175,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));
@@ -186,9 +201,10 @@ 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");
$customer->setWebsiteId(Mage::getModel('core/store')->load($cart->getStoreId())->getWebsiteId());
$customer->loadByEmail($cart->getCustomerEmail());
@@ -201,17 +217,20 @@ 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();
}
+
// 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
$productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId);
if (count($productData)) {
@@ -220,6 +239,7 @@ protected function _getNewQuotes($mailchimpStoreId)
$this->_counter += 1;
}
}
+
$cartJson = $this->_makeCart($cart, $mailchimpStoreId);
if ($cartJson!="") {
$allCarts[$this->_counter]['method'] = 'POST';
@@ -227,10 +247,11 @@ 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;
}
}
+
return $allCarts;
}
@@ -257,13 +278,14 @@ 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);
if ($campaignId) {
$oneCart['campaign_id'] = $campaignId;
}
+
$oneCart['checkout_url'] = $this->_getCheckoutUrl($cart);
$oneCart['currency_code'] = $cart->getQuoteCurrencyCode();
$oneCart['order_total'] = $cart->getGrandTotal();
@@ -277,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;
@@ -304,21 +330,20 @@ 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
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;
}
@@ -331,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']
@@ -352,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();
@@ -367,33 +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'] = $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;
}
}
+
//company
if ($billingAddress->getCompany()) {
$customer["company"] = $billingAddress->getCompany();
}
+
return $customer;
}
protected function _getApi()
@@ -401,6 +439,16 @@ protected function _getApi()
if (!$this->_api) {
$this->_api = Mage::helper('mailchimp')->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..f45c2ce51 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php
@@ -58,16 +58,18 @@ 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);
- $customer->save();
+ $this->_saveCustomer($customer);
}
+
$counter++;
}
+
return $customerArray;
}
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,12 +81,17 @@ 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) {
$totalOrders++;
$totalAmountSpent += (int)$order->getGrandTotal();
}
+
$data["orders_count"] = $totalOrders;
$data["total_spent"] = $totalAmountSpent;
@@ -92,25 +99,50 @@ 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();
}
+
break;
}
}
+
$mergeFields = $this->getMergeVars($customer);
if (is_array($mergeFields)) {
$data = array_merge($mergeFields, $data);
@@ -121,7 +153,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);
}
@@ -142,6 +173,7 @@ public function getMergeVars($object)
} else {
$customer = $object;
}
+
foreach ($maps as $map) {
$customAtt = $map['magento'];
$chimpTag = $map['mailchimp'];
@@ -164,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(
@@ -199,6 +232,7 @@ public function getMergeVars($object)
}
break;
}
+
// }
} else {
switch ($attributeCode) {
@@ -222,6 +256,7 @@ public function getMergeVars($object)
} else {
$firstName = $customer->getFirstname();
}
+
if ($firstName) {
$mergeVars[$key] = $firstName;
}
@@ -232,6 +267,7 @@ public function getMergeVars($object)
} else {
$lastName = $customer->getLastname();
}
+
if ($lastName) {
$mergeVars[$key] = $lastName;
}
@@ -239,6 +275,7 @@ public function getMergeVars($object)
}
}
}
+
switch ($customAtt) {
case 'billing_company':
case 'shipping_company':
@@ -249,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) {
@@ -265,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) {
@@ -281,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) {
@@ -298,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) {
@@ -308,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);
@@ -319,15 +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');
+ }
+
+ 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/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php
index 1df249f4b..2da8c1ebb 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php
@@ -13,56 +13,83 @@ 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;
/**
* Set the request for orders to be created on MailChimp
- *
+ *
* @param $mailchimpStoreId
* @return array
*/
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();
+
+ // get all the carts modified but not converted in orders
+ $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId));
+ // get new carts
+ $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId));
+
+ return $batchArray;
+ }
+
+ protected function _getModifiedOrders($mailchimpStoreId)
+ {
+ $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())
- ));
- $collection->getSelect()->limit(self::BATCH_LIMIT);
+ ->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));
+ }
- $batchArray = array();
+ $collection->getSelect()->limit(self::BATCH_LIMIT);
- $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.');
$order->setData("mailchimp_sync_error", $error);
}
+
//update order delta
$order->setData("mailchimp_sync_delta", Varien_Date::now());
+ $order->setMailchimpSyncModified(0);
+ $order->setMailchimpUpdateObserverRan(true);
$order->save();
- $counter++;
+ $this->_counter++;
} catch (Exception $e) {
Mage::helper('mailchimp')->logError($e->getMessage());
}
@@ -71,20 +98,12 @@ public function createBatchJson($mailchimpStoreId)
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)
{
+ $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(
array('null' => true),
@@ -92,33 +111,96 @@ public function createCanceledBatchJson($mailchimpStoreId)
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->setMailchimpUpdateObserverRan(true);
$order->save();
+ $this->_counter++;
+ } catch (Exception $e) {
+ Mage::helper('mailchimp')->logError($e->getMessage());
}
- $counter++;
}
return $batchArray;
}
+ /**
+ * Set the orders to be removed from MailChimp because they were canceled
+ *
+ * @param $mailchimpStoreId
+ * @return array
+ */
+// public function createCanceledBatchJson($mailchimpStoreId)
+// {
+// //create missing products first
+// $collection = Mage::getModel('sales/order')->getCollection()
+// ->addAttributeToSelect('status')
+// ->addAttributeToSelect('mailchimp_sync_delta')
+// ->addAttributeToSelect('entity_id')
+// ->addFieldToFilter('state', 'canceled')
+// ->addFieldToFilter(
+// 'mailchimp_sync_delta', array(
+// array('null' => true),
+// array('eq' => ''),
+// array('lt' => Mage::helper('mailchimp')->getMCMinSyncDateFlag())
+// )
+// );
+// $collection->getSelect()->limit(self::BATCH_LIMIT);
+//
+// $batchArray = array();
+// $counter = 0;
+// foreach ($collection as $order) {
+// if (!empty($orderJson)) {
+// $batchArray[$counter]['method'] = "DELETE";
+// $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $order->getEntityId();
+//
+// //update order delta
+// $order->setData("mailchimp_sync_delta", Varien_Date::now());
+// $order->save();
+// }
+// $counter++;
+// }
+//
+// return $batchArray;
+// }
+
/**
* Set all the data for each order to be sent
*
- * @param $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());
@@ -127,29 +209,63 @@ 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();
+ $data['discount_total'] = abs($order->getDiscountAmount());
$data['shipping_total'] = $order->getShippingAmount();
+ $statusArray = $this->_getMailChimpStatus($order);
+ if (isset($statusArray['financial_status'])) {
+ $data['financial_status'] = $statusArray['financial_status'];
+ }
+
+ if (isset($statusArray['fulfillment_status'])) {
+ $data['fulfillment_status'] = $statusArray['fulfillment_status'];
+ }
+
$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) {
+ if ($comment->getStatus() === Mage_Sales_Model_Order::STATE_CANCELED) {
+ $orderCancelDate = $comment->getCreatedAt();
+ }
+ }
+
+ if ($orderCancelDate) {
+ $data['cancelled_at_foreign'] = $orderCancelDate;
+ }
+ }
+
$data['lines'] = array();
//order lines
$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);
+ if (!$variant) {
+ continue;
+ }
} 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());
- if ($syncDelta&&$syncError==0) {
+ if ($syncDelta && $syncError == 0) {
$itemCount++;
$data["lines"][] = array(
"id" => (string)$itemCount,
@@ -157,13 +273,16 @@ protected function GeneratePOSTPayload($order,$mailchimpStoreId)
"product_variant_id" => $variant,
"quantity" => (int)$item->getQtyOrdered(),
"price" => $item->getPrice(),
+ "discount" => $item->getDiscountAmount()
);
}
}
+
if (!$itemCount) {
- return "";
unset($data['lines']);
+ return "";
}
+
//customer data
$api = $this->_getApi();
$customers = array();
@@ -172,59 +291,169 @@ 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 ((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 {
+ $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()) ? $order->getCustomerId() : $guestId = "CUSTOMER-" . Mage::helper('mailchimp')->getDateMicrotime(),
+ "email_address" => ($custEmailAddr) ? $custEmailAddr : $order->getCustomerEmail(),
+ "opt_in_status" => Mage::getModel('mailchimp/api_customers')->getOptin()
+ );
+ }
}
- if($order->getCustomerLastname()) {
- $data["customer"]["last_name"] = $order->getCustomerLastname();
+ } else {
+ if (isset($customers['customers'][0]['id'])) {
+ $id = $customers['customers'][0]['id'];
+ $data['customer'] = array(
+ 'id' => $id
+ );
}
}
+
+ $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();
+ }
+
+ if ($order->getCustomerLastname()) {
+ $data["customer"]["last_name"] = $order->getCustomerLastname();
+ }
+
$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];
+ $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();
+ }
+
//company
if ($billingAddress->getCompany()) {
$data["customer"]["company"] = $billingAddress->getCompany();
+ $data["billing_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'))
@@ -233,29 +462,112 @@ 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) {
$totalOrders++;
$totalAmountSpent += (int)$orderAlreadySent->getGrandTotal();
}
+
$data["customer"]["orders_count"] = $totalOrders;
$data["customer"]["total_spent"] = $totalAmountSpent;
$jsonData = "";
//enconde to JSON
try {
-
$jsonData = json_encode($data);
-
} catch (Exception $e) {
//json encode failed
- Mage::helper('mailchimp')->logError("Order ".$order->getId()." json encode failed");
+ Mage::helper('mailchimp')->logError("Order " . $order->getEntityId() . " json encode failed");
}
return $jsonData;
}
+ /**
+ * Return true if order has been already sent to MailChimp and has been modified afterwards.
+ *
+ * @param $order
+ * @return bool
+ */
+ protected function _isModifiedOrder($order)
+ {
+ return ($order->getMailchimpSyncModified() && $order->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag());
+ }
+
+ protected function _getMailChimpStatus($order)
+ {
+ $mailChimpFinancialStatus = null;
+ $mailChimpFulfillmentStatus = null;
+ $totalItemsOrdered = $order->getData('total_qty_ordered');
+ $shippedItemAmount = 0;
+ $invoicedItemAmount = 0;
+ $refundedItemAmount = 0;
+ $mailChimpStatus = array();
+
+ foreach ($order->getAllVisibleItems() as $item) {
+ $shippedItemAmount += $item->getQtyShipped();
+ $invoicedItemAmount += $item->getQtyInvoiced();
+ $refundedItemAmount += $item->getQtyRefunded();
+ }
+
+ if ($shippedItemAmount > 0) {
+ if ($totalItemsOrdered > $shippedItemAmount) {
+ $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED;
+ } else {
+ $mailChimpFulfillmentStatus = self::SHIPPED;
+ }
+ }
+
+ if ($refundedItemAmount > 0) {
+ if ($totalItemsOrdered > $refundedItemAmount) {
+ $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED;
+ } else {
+ $mailChimpFinancialStatus = self::REFUNDED;
+ }
+ }
+
+ if ($invoicedItemAmount > 0) {
+ if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) {
+ if ($totalItemsOrdered > $invoicedItemAmount) {
+ $mailChimpFinancialStatus = self::PARTIALLY_PAID;
+ } else {
+ $mailChimpFinancialStatus = self::PAID;
+ }
+ }
+ }
+
+ if (!$mailChimpFinancialStatus && $order->getState() == Mage_Sales_Model_Order::STATE_CANCELED) {
+ $mailChimpFinancialStatus = self::CANCELED;
+ }
+
+ if (!$mailChimpFinancialStatus) {
+ $mailChimpFinancialStatus = self::PENDING;
+ }
+
+ if ($mailChimpFinancialStatus) {
+ $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus;
+ }
+
+ if ($mailChimpFulfillmentStatus) {
+ $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus;
+ }
+
+ return $mailChimpStatus;
+ }
+
+ public function update($order)
+ {
+ if (Mage::helper('mailchimp')->isEcomSyncDataEnabled()) {
+ $order->setData('mailchimp_sync_error', '');
+ $order->setData('mailchimp_sync_modified', 1);
+ }
+ }
+
/**
* Get Api Object
*
@@ -266,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 e2b7cfb55..3f280af11 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,17 +36,14 @@ 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()) {
$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,20 +54,17 @@ 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;
}
}
+
return $batchArray;
}
protected function _buildNewProductRequest($product,$batchId,$mailchimpStoreId)
@@ -100,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";
@@ -143,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)
@@ -183,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()) {
@@ -228,23 +222,40 @@ 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->_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
diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php
index a6e309183..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');
}
@@ -92,4 +91,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/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/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/Model/Email/Queue.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php
index 6d0c7ac19..57f7e1607 100644
--- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php
@@ -34,48 +34,57 @@ 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());
}
- 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;
+ }
+ }
- )
- );
- $mailer->send();
+ if ($parameters->getReplyTo() !== null) {
+ $mailer->setReplyTo($parameters->getReplyTo());
+ }
+
+ if ($parameters->getReturnTo() !== null) {
+ $mailer->setReturnPath($parameters->getReturnTo());
+ }
+
+ try {
+ Mage::dispatchEvent(
+ 'fooman_emailattachments_before_send_queue',
+ array(
+ 'mailer' => $mailer,
+ 'message' => $message,
+ 'mail_transport' => false
+
+ )
+ );
+ $mailer->send();
+ } catch (Exception $e) {
+ Mage::logException($e);
+ }
+
+ unset($mailer);
+ $message->setProcessedAt(Varien_Date::formatDate(true));
+ $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) {
@@ -109,6 +118,7 @@ public function send()
if ($parameters->getReplyTo() !== null) {
$mailer->setReplyTo($parameters->getReplyTo());
}
+
if ($parameters->getReturnTo() !== null) {
$mailer->setReturnPath($parameters->getReturnTo());
}
@@ -135,6 +145,7 @@ public function send()
}
}
}
+
return $this;
}
@@ -147,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 cd607a080..b30de65f7 100755
--- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php
+++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php
@@ -38,17 +38,22 @@ 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
- ));
+ '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(
@@ -79,6 +84,7 @@ protected function _createWebhook($listId)
'api' => true
);
}
+
try {
$response = $api->lists->webhooks->getAll($listId);
$createWebhook = true;
@@ -89,6 +95,7 @@ protected function _createWebhook($listId)
}
}
}
+
if ($createWebhook) {
$api->lists->webhooks->add($listId, $hookUrl, $events, $sources);
}
@@ -158,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(
@@ -173,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;
}
@@ -189,12 +197,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;
@@ -209,12 +211,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;
@@ -227,9 +223,27 @@ 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->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);
}
}
@@ -245,6 +259,11 @@ 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('mailchimp_landing_page');
+ }
+
return $observer;
}
@@ -255,6 +274,11 @@ public function removeCampaignData(Varien_Event_Observer $observer)
*/
protected function _getCampaignCookie()
{
+ $landingCookie = $this->_getLandingCookie();
+ 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;
@@ -262,6 +286,15 @@ protected function _getCampaignCookie()
return null;
}
}
+ protected function _getLandingCookie()
+ {
+ $cookie = Mage::getModel('core/cookie')->get('mailchimp_landing_page');
+ if ($cookie && Mage::getModel('core/cookie')->getLifetime('mailchimp_landing_page') == Mage::getStoreConfig(Mage_Core_Model_Cookie::XML_PATH_COOKIE_LIFETIME, Mage::app()->getStore()->getId())) {
+ return $cookie;
+ } else {
+ return null;
+ }
+ }
/**
* Add column to associate orders gained from MailChimp campaigns and automations.
@@ -282,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;
}
@@ -298,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());
}
@@ -340,10 +373,17 @@ 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;
}
@@ -356,9 +396,14 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer)
*/
public function newOrder(Varien_Event_Observer $observer)
{
+ 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)
@@ -366,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);
- $product->setMailchimpUpdateObserverRan(true);
- $product->save();
+ $resource = $product->getResource();
+ $resource->saveAttribute($product, 'mailchimp_sync_modified');
}
+
return $observer;
}
@@ -390,11 +437,14 @@ 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);
- $product->setMailchimpUpdateObserverRan(true);
- $product->save();
+ $resource = $product->getResource();
+ $resource->saveAttribute($product, 'mailchimp_sync_modified');
}
+
+ $creditMemo->getOrder()->setMailchimpSyncModified(1);
return $observer;
}
@@ -414,11 +464,14 @@ 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);
- $product->setMailchimpUpdateObserverRan(true);
- $product->save();
+ $resource = $product->getResource();
+ $resource->saveAttribute($product, 'mailchimp_sync_modified');
}
+
+ $creditMemo->getOrder()->setMailchimpSyncModified(1);
return $observer;
}
@@ -435,12 +488,15 @@ 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;
}
- 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();
@@ -452,4 +508,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/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
new file mode 100644
index 000000000..b7b54ccce
--- /dev/null
+++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Name.php
@@ -0,0 +1,27 @@
+
+ * @copyright Ebizmarts (http://ebizmarts.com)
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
+ * @date: 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/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 61091c07f..0771bd4dd 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()
{
@@ -21,6 +21,7 @@ public function resetLocalErrorsAction()
{
$result = 0;
}
+
Mage::app()->getResponse()->setBody($result);
}
public function resetEcommerceDataAction()
@@ -28,6 +29,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());
@@ -36,6 +38,7 @@ public function resetEcommerceDataAction()
catch(Exception $e) {
Mage::helper('mailchimp')->logError($e->getMessage());
}
+
Mage::app()->getResponse()->setBody($result);
}
@@ -52,6 +55,7 @@ public function createMergeFieldsAction()
catch(Exception $e) {
Mage::helper('mailchimp')->logError($e->getMessage());
}
+
Mage::app()->getResponse()->setBody($result);
}
@@ -64,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 3d28515c3..610029ed1 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()
{
@@ -26,15 +26,41 @@ 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;
}
+
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 60224e38a..c32239596 100644
--- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php
+++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php
@@ -9,10 +9,11 @@
* @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(){
+ 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/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml
index 9eff0014a..7a574c5a0 100755
--- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml
+++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml
@@ -3,14 +3,22 @@
- 1.1.3
+ 1.1.5
- 1.1.3
+ 1.1.5
+
+
+
+ mailchimp/observer
+ changeStoreName
+
+
+
@@ -35,14 +43,6 @@
-
-
-
- mailchimp/observer
- removeCampaignData
-
-
-
@@ -52,6 +52,46 @@
+
+
+
+ mailchimp/observer
+ orderSaveBefore
+
+
+
+
+
+
+ mailchimp/observer
+ newOrder
+
+
+
+
+
+
+ mailchimp/observer
+ newCreditmemo
+
+
+
+
+
+
+ mailchimp/observer
+ cancelCreditmemo
+
+
+
+
+
+
+ mailchimp/observer
+ itemCancel
+
+
+
@@ -120,6 +160,9 @@
*
+
+ *
+
diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml
index 46dd422ff..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
@@ -211,6 +222,19 @@
0
0
+
+
+ date
+ mailchimp/adminhtml_system_config_date
+ 209
+ 1
+ 1
+ 1
+
+
+ 1
+
+
button
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.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
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..1fed48157
--- /dev/null
+++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.4-1.1.5.php
@@ -0,0 +1,39 @@
+
+ * @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_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 '';
+ 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
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'); ?>
\ No newline at end of file
diff --git a/getMailchimpResponse.php b/getMailchimpResponse.php
index e9a4ba46d..6bf0bc742 100644
--- a/getMailchimpResponse.php
+++ b/getMailchimpResponse.php
@@ -1,9 +1,10 @@
"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);
@@ -41,13 +44,13 @@
curl_close($curl);
if ($err) {
- echo "cURL Error #:" . $err;
+ printf("cURL Error #:" . $err);
} else {
$jsonResponse = json_decode($response);
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();
@@ -57,11 +60,12 @@
$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 {
// 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 9dab2e976..304289d84 100755
--- a/js/ebizmarts/mailchimp/campaignCatcher.js
+++ b/js/ebizmarts/mailchimp/campaignCatcher.js
@@ -1,6 +1,9 @@
- function getCampaign() {
+ function getCampaign()
+{
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];
@@ -8,17 +11,30 @@
if (key && val) {
params[key] = val;
}
+
+ if(key=='utm_source') {
+ var reg = /^mailchimp$/;
+ if(reg.exec(val)) {
+ isMailchimp = true;
+ }
+ }
+ else {
+ if (key=='mc_cid') {
+ mc_cid = val;
+ }
+ }
}
- if (params['mc_cid']) {
- createCookie('mailchimp_campaign_id' , params['mc_cid'], 3600*3);
+ if (mc_cid&&!isMailchimp) {
+ Mage.Cookies.set('mailchimp_campaign_id' , mc_cid);
+ Mage.Cookies.set('mailchimp_landing_page', location);
}
- }
- function createCookie(name, value) {
- Mage.Cookies.set(name,value);
+ if(isMailchimp) {
+ Mage.Cookies.clear('mailchimp_campaign_id');
+ Mage.Cookies.set('mailchimp_landing_page', location);
+ }
}
-
if (document.loaded) {
getCampaign;
} else {
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/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;
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/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;
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;
}
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 @@