diff --git a/CHANGELOG.md b/CHANGELOG.md index 8492bc54e..bbcc273a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,22 +1,32 @@ # Changelog -## [1.1.18](https://github.com/mailchimp/mc-magento/releases/tag/1.1.18) - 2019-09-13 +## [1.1.19](https://github.com/mailchimp/mc-magento/releases/tag/1.1.19) - 2020-01-03 +**Changed** +- Refactor collection filters to avoid doing joins, where, etc outside resources. [\#1119](https://github.com/mailchimp/mc-magento/issues/1119) +- Allow translation of texts on app/code/community/Ebizmarts/MailChimp/controllers/CartController.php [\#1118](https://github.com/mailchimp/mc-magento/issues/1118) +- Add Mailchimp configuration link at Newsletter -> Mailchimp menu [\#1107](https://github.com/mailchimp/mc-magento/issues/1107) +- Log the product id if is not supported by Mailchimp [\#1101](https://github.com/mailchimp/mc-magento/issues/1101) +- Exceptions not treated properly. [\#1098](https://github.com/mailchimp/mc-magento/issues/1098) +- Unnecessary function call: getProductResourceModel() [\#1094](https://github.com/mailchimp/mc-magento/issues/1094) +- Mysql4 classes are obsolete for M1.6+ [\#1089](https://github.com/mailchimp/mc-magento/issues/1089) +- Unify error logging methods. [\#1065](https://github.com/mailchimp/mc-magento/issues/1065) +- Unify Ecommerce Items Classes [\#1064](https://github.com/mailchimp/mc-magento/issues/1064) +- Create option in backend adminhtml to subsribe customers [\#450](https://github.com/mailchimp/mc-magento/issues/450) + **Fixed** -- Product resend internal problem [\#1066](https://github.com/mailchimp/mc-magento/issues/1066) -- Notice: Undefined index: NOT SENT in app/code/community/Ebizmarts/MailChimp/Helper/Data.php [\#1050](https://github.com/mailchimp/mc-magento/issues/1050) -- Use empty function correctly [\#1039](https://github.com/mailchimp/mc-magento/issues/1039) -- Fix for bug preventing carts from synchronising [\#1029](https://github.com/mailchimp/mc-magento/issues/1029) -- Problems when resending Ecommerce Data [\#1024](https://github.com/mailchimp/mc-magento/issues/1024) -- PHP notice when MC API call fails [\#1021](https://github.com/mailchimp/mc-magento/issues/1021) -- Cannot resend Ecommerce data from particular scope [\#1017](https://github.com/mailchimp/mc-magento/issues/1017) -- Handle json_encode errors correctly [\#1010](https://github.com/mailchimp/mc-magento/issues/1010) +- Serializer error when Magento is compiled. [\#1116](https://github.com/mailchimp/mc-magento/issues/1116) +- Missing getWebhooks() function on Lib. [\#1115](https://github.com/mailchimp/mc-magento/issues/1115) +- Fix incorrect class declaration in function setEcommerceSyncDataItemValues [\#1103](https://github.com/mailchimp/mc-magento/issues/1103) +## [1.1.18](https://github.com/mailchimp/mc-magento/releases/tag/1.1.18) - 2019-10-07 **Changed** +- Avoid sending carts until the initial sync finishes [\#1073](https://github.com/mailchimp/mc-magento/issues/1073) +- Remove GENERAL_ECOMMMINSYNCDATEFLAG usages. [\#1072](https://github.com/mailchimp/mc-magento/issues/1072) +- Allow campaignCatcher.js to save campaign for URL with style domain.com/mc_cid/{#campaignIdNumber} [\#1071](https://github.com/mailchimp/mc-magento/issues/1071) - Fix for re-using synch batch models causing batch responses to not be processed [\#1057](https://github.com/mailchimp/mc-magento/issues/1057) - Apply MEQP1 code standar [\#1055](https://github.com/mailchimp/mc-magento/issues/1055) - Validate API key field at Mailchimp configuration [\#1052](https://github.com/mailchimp/mc-magento/issues/1052) - Add Invalid API Key message when adding a new Mailchimp Store [\#1045](https://github.com/mailchimp/mc-magento/issues/1045) -- Remove redundant system config and template file [\#1043](https://github.com/mailchimp/mc-magento/pull/1043) -- Stop flagging Customers as modified after an order is made. [\#1027](https://github.com/mailchimp/mc-magento/issues/1027) +- Stop sending order_total and total_spent in Customer data. [\#1027](https://github.com/mailchimp/mc-magento/issues/1027) - Improve batch behavior [\#1025](https://github.com/mailchimp/mc-magento/issues/1025) - Serialize/Unserialize deprecated - MEQP [\#1019](https://github.com/mailchimp/mc-magento/issues/1019) - Improve performance when resetting errors [\#975](https://github.com/mailchimp/mc-magento/issues/975) @@ -24,14 +34,23 @@ - How can we clean the table mailchimp_ecommerce_sync_data [\#897](https://github.com/mailchimp/mc-magento/issues/897) - Certain Merge fields not transferred [\#425](https://github.com/mailchimp/mc-magento/issues/425) +**Fixed** +- Product resend problem [\#1066](https://github.com/mailchimp/mc-magento/issues/1066) +- Notice: Undefined index: NOT SENT in app/code/community/Ebizmarts/MailChimp/Helper/Data.php [\#1050](https://github.com/mailchimp/mc-magento/issues/1050) +- Use empty function correctly [\#1039](https://github.com/mailchimp/mc-magento/issues/1039) +- Fix for infinite sync of carts with unsupported products and emptied carts not being removed [\#1032](https://github.com/mailchimp/mc-magento/issues/1032) +- Problems when resending Ecommerce Data [\#1024](https://github.com/mailchimp/mc-magento/issues/1024) +- PHP notice when MC API call fails [\#1021](https://github.com/mailchimp/mc-magento/issues/1021) +- Cannot resend Ecommerce data from particular scope [\#1017](https://github.com/mailchimp/mc-magento/issues/1017) +- Uncaught Error: Call to undefined method Ebizmarts_MailChimp_Model_Api_Products::joinMailchimpSyncDataWithoutWhere() in /mc-magento/app/code/community/Ebizmarts/MailChimp/Helper/Data.php:3274 [\#1014](https://github.com/mailchimp/mc-magento/issues/1014) +- Handle json_encode errors correctly [\#1010](https://github.com/mailchimp/mc-magento/issues/1010) + ## [1.1.17](https://github.com/mailchimp/mc-magento/releases/tag/1.1.17) - 2019-07-23 **Changed** - Avoid sending Subscriber via cron job when setting "Use Magento Emails" enabled. [\#996](https://github.com/mailchimp/mc-magento/issues/996) - Rename delete customer account option [\#992](https://github.com/mailchimp/mc-magento/issues/992) -- Coding standards fix [\#989](https://github.com/mailchimp/mc-magento/pull/989) - Change "List" appearances to "Audience" [\#977](https://github.com/mailchimp/mc-magento/issues/977) - Encrypt sensitive data [\#955](https://github.com/mailchimp/mc-magento/issues/955) -- Improve logging [\#947](https://github.com/mailchimp/mc-magento/pull/947) - Add default merge var for province/state [\#937](https://github.com/mailchimp/mc-magento/issues/937) - Add the options to resend all the ecommerce data or resend only the products, customers, orders or quotes [\#891](https://github.com/mailchimp/mc-magento/issues/891) - Improve logging [\#886](https://github.com/mailchimp/mc-magento/issues/886) @@ -55,7 +74,6 @@ - Error syncing order with disabled product [\#943](https://github.com/mailchimp/mc-magento/issues/943) - Orders don't sync with Mailchimp when the order have a child disabled product [\#930](https://github.com/mailchimp/mc-magento/issues/930) - Interest groups in checkout success with the option disabled [\#927](https://github.com/mailchimp/mc-magento/issues/927) -- Fixed grammar in success message after group subscription in order success page. [\#925](https://github.com/mailchimp/mc-magento/pull/925) - Problem with disabled products and multi-stores [\#913](https://github.com/mailchimp/mc-magento/issues/913) - Missing template: group/types.phtml [\#912](https://github.com/mailchimp/mc-magento/issues/912) - MC 1.1.15 Reset Local Errors gives an error [\#911](https://github.com/mailchimp/mc-magento/issues/911) @@ -97,16 +115,15 @@ - Add subscription option on order success page [\#770](https://github.com/mailchimp/mc-magento/issues/770) ## [1.1.14](https://github.com/mailchimp/mc-magento/releases/tag/1.1.14) - 2019-01-16 +**Fixed** +- Orders belonging to deleted stores do not show correct syncing status under "synced to MailChimp" column [\#840](https://github.com/mailchimp/mc-magento/issues/840) +- Change modified abandoned carts sending method from DELETE -> POST to PATCH [\#836](https://github.com/mailchimp/mc-magento/issues/836) + **Changed** -- create a reference to the Mailchimp tutorials [\#847](https://github.com/mailchimp/mc-magento/pull/847) - Replace old MailChimp logo with the new one. [\#839](https://github.com/mailchimp/mc-magento/issues/839) - Send subscription confirmation email via Magento [\#793](https://github.com/mailchimp/mc-magento/issues/793) - Add support for List Groups [\#514](https://github.com/mailchimp/mc-magento/issues/514) -**Fixed** -- Orders belonging to deleted stores do not show correct syncing status under "synced to MailChimp" column [\#840](https://github.com/mailchimp/mc-magento/issues/840) -- Change modified abandoned carts sending method from DELETE -> POST to PATCH [\#836](https://github.com/mailchimp/mc-magento/issues/836) - ## [1.1.13](https://github.com/mailchimp/mc-magento/releases/tag/1.1.13) - 2018-12-11 **Changed** - Add option to not send Promo Codes and Promo Rules [\#824](https://github.com/mailchimp/mc-magento/issues/824) @@ -121,10 +138,8 @@ - Remove addFilterToMap from order grid observer [\#744](https://github.com/mailchimp/mc-magento/issues/744) - Avoid re-creating the store after Reset. [\#741](https://github.com/mailchimp/mc-magento/issues/741) - Stop syncing process if no connection to MailChimp's API available. [\#738](https://github.com/mailchimp/mc-magento/issues/738) -- Send most recently created promo codes first [\#736](https://github.com/mailchimp/mc-magento/pull/736) - No Double Opt-in Option for MailChimp for Magento [\#727](https://github.com/mailchimp/mc-magento/issues/727) - Capitalization at Newsletter top menu [\#718](https://github.com/mailchimp/mc-magento/issues/718) -- Index customer_id on sales_flat_order [\#712](https://github.com/mailchimp/mc-magento/pull/712) - Add translations file. [\#689](https://github.com/mailchimp/mc-magento/issues/689) - Order confirmation email is bypassing Aschroder_SMTPPro [\#673](https://github.com/mailchimp/mc-magento/issues/673) - Remove disabled products to aovid using them in promotions. [\#582](https://github.com/mailchimp/mc-magento/issues/582) @@ -143,7 +158,6 @@ - Incorrect store domain when setting up at website level. [\#754](https://github.com/mailchimp/mc-magento/issues/754) - Send products with no description available [\#747](https://github.com/mailchimp/mc-magento/issues/747) - Error Report when Export Orders CSV or Excel [\#732](https://github.com/mailchimp/mc-magento/issues/732) -- Set subcribers correct language in mailchimp during signup #729 [\#730](https://github.com/mailchimp/mc-magento/pull/730) - Synced status not reporting correctly in orders grid [\#726](https://github.com/mailchimp/mc-magento/issues/726) - Upgrade to 1.1.2 : You cannot define a correlation name 'mc' more than once [\#725](https://github.com/mailchimp/mc-magento/issues/725) - Clear mail object after sending message [\#719](https://github.com/mailchimp/mc-magento/issues/719) @@ -165,8 +179,6 @@ **Changed** - Add new message for store creation error. [\#681](https://github.com/mailchimp/mc-magento/issues/681) - Request: add ability to send the actual BRAND/Manufacturer in the Vendor field [\#672](https://github.com/mailchimp/mc-magento/issues/672) -- Subscriber resend issue482 [\#671](https://github.com/mailchimp/mc-magento/pull/671) -- add guest checkout name to subscriber data [\#664](https://github.com/mailchimp/mc-magento/pull/664) - Sort categories by name [\#659](https://github.com/mailchimp/mc-magento/issues/659) - query optimizations 1 [\#583](https://github.com/mailchimp/mc-magento/issues/583) - Add resend for subscriber data [\#482](https://github.com/mailchimp/mc-magento/issues/482) @@ -185,7 +197,6 @@ - Small and thumbnail images not sent [\#589](https://github.com/mailchimp/mc-magento/issues/589) - All orders marked with Mailchimp logo even if they're not coming from Mailchimp [\#576](https://github.com/mailchimp/mc-magento/issues/576) - Child product update when parent has not been sent yet [\#575](https://github.com/mailchimp/mc-magento/issues/575) -- Removes exception in order grid if for example a used payment method has [\#563](https://github.com/mailchimp/mc-magento/pull/563) - Images are not sent in certain versions of PHP [\#559](https://github.com/mailchimp/mc-magento/issues/559) - When Mandrill disabled in default scope and enabled in certain store views email sending fails. [\#550](https://github.com/mailchimp/mc-magento/issues/550) - When api key is changed deleteCurrentWebhook method fails [\#548](https://github.com/mailchimp/mc-magento/issues/548) @@ -194,11 +205,9 @@ **Changed** - Load campaignCatcher.js async [\#624](https://github.com/mailchimp/mc-magento/issues/624) - Improve performance when retrieving the last date of purchase [\#619](https://github.com/mailchimp/mc-magento/issues/619) -- Cache management page - Do not flush cache [\#594](https://github.com/mailchimp/mc-magento/pull/594) - add index [\#584](https://github.com/mailchimp/mc-magento/issues/584) - Added Mailchimperrors grid column Created At [\#569](https://github.com/mailchimp/mc-magento/issues/569) - Put a column in the order grid to show if the order was synced [\#557](https://github.com/mailchimp/mc-magento/issues/557) -- load MCJs async [\#546](https://github.com/mailchimp/mc-magento/pull/546) - Send parent price for not visible products belonging to a configurable [\#538](https://github.com/mailchimp/mc-magento/issues/538) - Check if webhook exists after batch process and create it if missing [\#535](https://github.com/mailchimp/mc-magento/issues/535) - Ebizmarts_MailChimp properties are not defined correctly [\#361](https://github.com/mailchimp/mc-magento/issues/361) @@ -300,10 +309,8 @@ - Ignore already exists error [\#360](https://github.com/mailchimp/mc-magento/issues/360) - Send out of stock products [\#353](https://github.com/mailchimp/mc-magento/issues/353) - Modify webhook creation [\#340](https://github.com/mailchimp/mc-magento/issues/340) -- Set limit on Collection to 1. [\#333](https://github.com/mailchimp/mc-magento/pull/333) - New Feature: flag is_syncing [\#323](https://github.com/mailchimp/mc-magento/issues/323) - API Products constant array declaration unsupported in PHP 5.5 [\#316](https://github.com/mailchimp/mc-magento/issues/316) -- Do not translate customer group [\#315](https://github.com/mailchimp/mc-magento/pull/315) - Send order id in stead of increment id in operation id for batches. [\#286](https://github.com/mailchimp/mc-magento/issues/286) - Sent orderId in stead of incrementId in operation id in Orders.php [\#281](https://github.com/mailchimp/mc-magento/issues/281) - Split cron jobs. [\#277](https://github.com/mailchimp/mc-magento/issues/277) @@ -322,14 +329,10 @@ ## [1.1.7](https://github.com/mailchimp/mc-magento/releases/tag/1.1.7) - 2017-06-01 **Fixed** - All orders are marked with landing page & as coming from MailChimp. [\#239](https://github.com/mailchimp/mc-magento/issues/239) -- Added fix for storage foreach [\#223](https://github.com/mailchimp/mc-magento/pull/223) - Guest orders are not synced [\#150](https://github.com/mailchimp/mc-magento/issues/150) - Integrity constraint violation when syncing e-commerce data [\#147](https://github.com/mailchimp/mc-magento/issues/147) **Changed** -- Fix case mixing and make class namespace/prefix the same for all classes [\#207](https://github.com/mailchimp/mc-magento/pull/207) -- Error in `getBatchResponse` method when `/var/mailchimp` directory does not exist [\#203](https://github.com/mailchimp/mc-magento/pull/203) -- Added pagination for too huge collections in data-upgrade [\#192](https://github.com/mailchimp/mc-magento/pull/192) - Recommend products no images when only configurable product has images [\#140](https://github.com/mailchimp/mc-magento/issues/140) ## [1.1.6](https://github.com/mailchimp/mc-magento/releases/tag/1.1.6) - 2017-03-30 @@ -400,7 +403,6 @@ - Utilty to download the batch response [\#66](https://github.com/mailchimp/mc-magento/issues/66) - Add the Batch Id to the mailchimp error grid [\#65](https://github.com/mailchimp/mc-magento/issues/65) - Generate one log per each batch [\#64](https://github.com/mailchimp/mc-magento/issues/64) -- Feature composer modman support [\#62](https://github.com/mailchimp/mc-magento/pull/62) - Add composer.json and modman support [\#61](https://github.com/mailchimp/mc-magento/issues/61) **Fixed** @@ -408,7 +410,6 @@ - Invalid country code error shown in MailChimp_Errors.log [\#72](https://github.com/mailchimp/mc-magento/issues/72) - Customers generating resource not found error [\#71](https://github.com/mailchimp/mc-magento/issues/71) - Carts not existing on MailChimp being deleted before getting sent. [\#70](https://github.com/mailchimp/mc-magento/issues/70) -- #68 - fix of bug which caused campaign_id not being associated with o… [\#69](https://github.com/mailchimp/mc-magento/pull/69) - campaign_id isn't associated to order when cookie lifetime != 3600 [\#68](https://github.com/mailchimp/mc-magento/issues/68) ## [1.1.1](https://github.com/mailchimp/mc-magento/releases/tag/1.1.1) - 2016-09-13 diff --git a/README.md b/README.md index c683341a7..ee6764a4a 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Integration to sync all the Magento data (Newsletter subscriber, Customers, Orde The integration includes a Mandrill SMTP module that overrides the one integrated from Magento, you will need to enable Mandrill with its API key from your Mandrill account (mandrillapp.com) for the transactional emails to work. If you want to use the Mailchimp integration without Mandrill for SMTP, contact our support so we can tell you how to set that up. -## Features +## Main Features * Two way sync between a MailChimp list and Magento’s newsletter * Responsive Email Catcher Popup when accessing the site @@ -22,7 +22,7 @@ Magento Community Edition (1.7 or above) or Magento Enterprise (1.11 or above) MailChimp Account -## Installation +## Step Installation To get a copy of the project up and running on your local machine for development and testing purposes, just clone this repository on your Magento’s root directory and flush the Magento’s cache. @@ -30,7 +30,7 @@ Alternatively, use modman to install this module. ``modman clone https://github.com/mailchimp/mc-magento.git -b 'master'`` -## Module Configuriation +## Module Configuration To enable MailChimp For Magento: @@ -42,7 +42,7 @@ To enable MailChimp For Magento: More guides and tutorials about the Mailchimp integration with Magento can be found on the [tutorial page of Mailchimp](https://mailchimp.com/help/connect-or-disconnect-mailchimp-for-magento/). -## Report issues +## Report Issues For reporting issues, follow this [guidelines](https://github.com/mailchimp/mc-magento/wiki/Issue-reporting-guidelines) or your issue will be rejected. diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors.php index 4b07d6a58..2ed1394a9 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimperrors.php @@ -1,4 +1,5 @@ getScopeArrayIfValueExists(); + if ($scopeArray !== false) { $jsCondition = 'true'; } else { @@ -107,8 +108,9 @@ protected function getScopeArrayIfValueExists() $helper = $this->makeHelper(); $currentMCStoreId = Mage::registry('current_mailchimpstore')->getStoreid(); $keyIfExist = $helper->getScopeByMailChimpStoreId($currentMCStoreId); + if ($keyIfExist === null) { - $keyIfExist = 'false'; + $keyIfExist = false; } return $keyIfExist; diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php index c6facfddf..afa3704eb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Mailchimpstores/Edit/Form.php @@ -56,7 +56,7 @@ protected function _prepareForm() $prefix = ''; $storeId = $s->getStoreId(); - if(!$helper->ping($storeId)) { + if (!$helper->ping($storeId)) { $prefix = '[Invalid]: '; } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php index d96d589f1..773d8409e 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Notifications.php @@ -1,4 +1,5 @@ makeHelper(); if ($helper->isImageCacheFlushed() && $helper->isEcomSyncDataEnabledInAnyScope()) { - $message = 'Important: '. + $message = 'Important: ' . 'Image cache has been flushed please ' . '' - . 'resend the products in order to update image URL'; + . 'resend the products in order to update image URL'; return $message; } } @@ -32,8 +33,8 @@ public function getMessage() { $helper = $this->makeHelper(); $message = 'Are you sure you want to delete the local data in order to send all items again?\n' - .'Automations will work normally but the synchronization process for the old data will take ' - . 'longer than resetting the MailChimp store.'; + . 'Automations will work normally but the synchronization process for the old data will take ' + . 'longer than resetting the MailChimp store.'; return $helper->__($message); } @@ -59,7 +60,6 @@ public function getUrlForResendEcommerce() } - /** * @return Ebizmarts_MailChimp_Helper_Data */ diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php index 67a74ed07..2eb30e6ca 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/System/Config/ResetErrors.php @@ -1,4 +1,5 @@ makeHelper(); $scopeArray = $helper->getCurrentScope(); + if ($helper->isSubscriptionEnabled($scopeArray['scope_id'], $scopeArray['scope']) || $scopeArray['scope_id'] == 0 ) { diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php b/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php index 4b3fcf842..93deaf83b 100755 --- a/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Popup/Emailcatcher.php @@ -1,4 +1,5 @@ getStore()->getId(); + return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ENABLE_POPUP, $storeId) - && Mage::getStoreConfig( - Ebizmarts_MailChimp_Model_Config::POPUP_CAN_CANCEL, - $storeId - ); + && Mage::getStoreConfig( + Ebizmarts_MailChimp_Model_Config::POPUP_CAN_CANCEL, + $storeId + ); } protected function _popupHeading() { $storeId = Mage::app()->getStore()->getId(); + return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::POPUP_HEADING, $storeId); } protected function _popupMessage() { $storeId = Mage::app()->getStore()->getId(); + return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::POPUP_TEXT, $storeId); } protected function _modalSubscribe() { $storeId = Mage::app()->getStore()->getId(); + return Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::POPUP_SUBSCRIPTION, $storeId); } @@ -53,6 +58,7 @@ protected function _handleCookie() $cookieValues = explode('/', $emailCookie); $email = $cookieValues[0]; $email = str_replace(' ', '+', $email); + if (isset($cookieValues[1])) { $fName = $cookieValues[1]; } @@ -63,6 +69,7 @@ protected function _handleCookie() if ($subscribeCookie == 'true') { $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email); + if (!$subscriber->getId()) { $subscriber = Mage::getModel('newsletter/subscriber') ->setStoreId($storeId); @@ -78,6 +85,7 @@ protected function _handleCookie() } $subscriber->subscribe($email); + return 'location.reload'; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Curl.php b/app/code/community/Ebizmarts/MailChimp/Helper/Curl.php new file mode 100644 index 000000000..8b15b248f --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Curl.php @@ -0,0 +1,57 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 9/5/19 3:55 PM + * @file: Curl.php + */ + +class Ebizmarts_MailChimp_Helper_Curl extends Mage_Core_Helper_Abstract +{ + /** + * @param array $options + * @return array An array with... + */ + public function curlExec($url, $httpMethod, $curlOptions = array(), $params = array()) + { + if ($url === false) { + return array('error' => "It's required an URL to be requested with any http method."); + } + + if ($httpMethod === false) { + return array('error' => "It's required to specify the HTTP method."); + } + + $curlError = null; + $curl = new Mage_HTTP_Client_Curl(); + + foreach ($curlOptions as $key => $value) { + if (isset($value)) { + $curl->setOption($key, $value); + } + } + + $curlResult = null; + + try { + if ($httpMethod == Zend_Http_Client::GET) { + $curl->get($url); + } elseif ($httpMethod == Zend_Http_Client::POST) { + $curl->post($url, $params); + } + + $curlResult = $curl->getBody(); + } catch (Exception $e) { + $curlError = $e->getMessage(); + } + + return array('response' => $curlResult, 'error' => $curlError); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index d9f027d1d..ddc6178d1 100644 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -32,12 +32,8 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract const DATA_SENT_TO_MAILCHIMP = 'SENT'; const BATCH_STATUS_LOG = 'Mailchimp_Batch_Status.log'; - const BATCH_CANCELED = 'canceled'; - const BATCH_COMPLETED = 'completed'; const BATCH_PENDING = 'pending'; - const BATCH_ERROR = 'error'; - protected $_countersSendBatch = array(); protected $_countersSubscribers = array(); @@ -48,7 +44,7 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract * * @var array */ - public static $MAILCHIMP_LANGUAGES = array( + public static $LANGUAGES = array( 'en', // English 'ar', // Arabic 'af', // Afrikaans @@ -105,9 +101,9 @@ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract /** * Get Config value for certain scope. * - * @param $path - * @param $scopeId - * @param null $scope + * @param $path + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -125,8 +121,8 @@ public function getConfigValueForScope($path, $scopeId, $scope = null) /** * Get storeId and/or websiteId if scope selected on back end * - * @param null $storeId - * @param null $websiteId + * @param null $storeId + * @param null $websiteId * @return array */ public function getConfigScopeId($storeId = null, $websiteId = null) @@ -143,6 +139,7 @@ public function getConfigScopeId($storeId = null, $websiteId = null) $scopeArray['websiteId'] = $websiteId; $scopeArray['storeId'] = $storeId; + return $scopeArray; } @@ -155,6 +152,7 @@ public function getCurrentScope() { $scopeIdArray = $this->getConfigScopeId(); $scopeArray = array(); + if (isset($scopeIdArray['websiteId'])) { $scopeArray['scope'] = 'websites'; $scopeArray['scope_id'] = $scopeIdArray['websiteId']; @@ -181,17 +179,17 @@ public function getScopeName($scopeArray) if (isset($scopeArray['scope'])) { switch ($scopeArray['scope']) { - case 'stores': - $store = $this->getMageApp()->getStore($scopeArray[1]); - $storeName = $store->getName(); - break; - case 'websites': - $website = $this->getMageApp()->getWebsite($scopeArray[1]); - $storeName = $website->getName(); - break; - case 'default': - $storeName = 'Default Config'; - break; + case 'stores': + $store = $this->getMageApp()->getStore($scopeArray['scope_id']); + $storeName = $store->getName(); + break; + case 'websites': + $website = $this->getMageApp()->getWebsite($scopeArray['scope_id']); + $storeName = $website->getName(); + break; + case 'default': + $storeName = 'Default Config'; + break; } } @@ -211,6 +209,7 @@ public function isUsingConfigStoreName($scopeId, $scope) $scopeId, $scope ); + if ($storeName == '') { $usingConfigName = false; } else { @@ -256,6 +255,7 @@ public function getStoreRelation() { $stores = $this->getMageApp()->getStores(); $storeRelation = array(); + foreach ($stores as $storeId => $store) { if ($this->isEcomSyncDataEnabled($storeId)) { $mcStoreId = $this->getMCStoreId($storeId); @@ -299,22 +299,23 @@ public function getMagentoStoresForMCStoreIdByScope($scopeId, $scope) /** * Validate if api key exists, could still be incorrect * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed */ public function validateApiKey($scopeId, $scope = null) { $apiKey = $this->getApiKey($scopeId, $scope); $isApiKeyValid = $apiKey !== null && $apiKey != ""; + return $isApiKeyValid; } /** * Return if module is enabled for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed */ public function isMailChimpEnabled($scopeId, $scope = null) @@ -328,14 +329,14 @@ public function isMailChimpEnabled($scopeId, $scope = null) */ public function isUseMagentoEmailsEnabled($scopeId) { - return (int) $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL, $scopeId); + return (int)$this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL, $scopeId); } /** * Return if module is enabled and list selected for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed */ public function isSubscriptionEnabled($scopeId, $scope = null) @@ -350,8 +351,8 @@ public function isSubscriptionEnabled($scopeId, $scope = null) /** * Return Api Key if exists for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -362,6 +363,7 @@ public function getApiKey($scopeId, $scope = null) $scopeId, $scope ); + return $this->decryptData($apiKey); } @@ -388,8 +390,8 @@ public function encryptData($data) } /** - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -405,8 +407,8 @@ public function getWebhookDeleteAction($scopeId, $scope = null) /** * Get local store_id value of the MC store for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -422,8 +424,8 @@ public function getMCStoreId($scopeId, $scope = null) /** * Delete all data related to the configured store in a given scope. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope */ public function deletePreviousConfiguredMCStoreLocalData($mailchimpStoreId, $scopeId, $scope = 'stores') { @@ -464,8 +466,8 @@ public function deletePreviousConfiguredMCStoreLocalData($mailchimpStoreId, $sco /** * Delete all data related to the configured store in a given scope. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope */ public function deleteAllConfiguredMCStoreLocalData($mailchimpStoreId, $scopeId, $scope = 'stores') { @@ -477,7 +479,7 @@ public function deleteAllConfiguredMCStoreLocalData($mailchimpStoreId, $scopeId, } /** - * @return Ebizmarts_MailChimp_Model_Mysql4_SynchBatches + * @return Ebizmarts_MailChimp_Model_Resource_SynchBatches */ protected function getSyncBatchesResource() { @@ -489,19 +491,10 @@ public function deleteAllMCStoreData($mailchimpStoreId) //Delete default configurations for this store. $config = $this->getConfig(); $config->deleteConfig( - Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", - 'default', - 0 + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SYNC_DATE . "_$mailchimpStoreId", 'default', 0 ); $config->deleteConfig( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", - 'default', - 0 - ); - $config->deleteConfig( - Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", - 'default', - 0 + Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL . "_$mailchimpStoreId", 'default', 0 ); //Delete local ecommerce data and errors for this store. @@ -510,6 +503,7 @@ public function deleteAllMCStoreData($mailchimpStoreId) //Delete particular scopes configuraion flags for this store $scopeArrayIfExist = $this->getScopeByMailChimpStoreId($mailchimpStoreId); + if ($scopeArrayIfExist !== false) { $this->deleteAllConfiguredMCStoreLocalData( $mailchimpStoreId, @@ -522,8 +516,8 @@ public function deleteAllMCStoreData($mailchimpStoreId) /** * Return if Ecommerce configuration is enabled for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -539,8 +533,8 @@ public function isEcommerceEnabled($scopeId, $scope = null) /** * Get general list configured for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -556,8 +550,8 @@ public function getGeneralList($scopeId, $scope = null) /** * Get map fields configured for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -573,8 +567,8 @@ public function getMapFields($scopeId, $scope = null) /** * Get custom merge fields configured for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -588,8 +582,8 @@ public function getCustomMergeFieldsSerialized($scopeId, $scope = null) /** * Get if Abandoned Cart module is enabled. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -605,8 +599,8 @@ public function isAbandonedCartEnabled($scopeId, $scope = null) /** * Get date configured for carts to be sent for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -622,8 +616,8 @@ public function getAbandonedCartFirstDate($scopeId, $scope = null) /** * Get date configured for ecommerce data to be sent for the given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -640,9 +634,9 @@ public function getEcommerceFirstDate($scopeId, $scope = null) * Get local is_syncing value of the MC store. * If data was saved in the old way get it from the scope and update it to the new way. * - * @param $mailchimpStoreId - * @param int $scopeId - * @param string $scope + * @param $mailchimpStoreId + * @param int $scopeId + * @param string $scope * @return mixed|null * @throws Mage_Core_Exception */ @@ -681,60 +675,6 @@ public function getMCIsSyncing($mailchimpStoreId, $scopeId = 0, $scope = 'stores return ($syncingFlag !== null) ? $syncingFlag : $oldSyncingFlag; } - /** - * Minimum date for which ecommerce data needs to be uploaded. - * If data was saved in the old way get it from the scope and update it to the new way. - * - * @param $mailchimpStoreId - * @param $scopeId - * @param null $scope - * @return mixed|null - * @throws Mage_Core_Exception - */ - public function getEcommMinSyncDateFlag($mailchimpStoreId, $scopeId, $scope = null) - { - $oldEcommMinsyncDateFlag = $this->getConfigValueForScope( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, - $scopeId, - $scope - ); - $ecommMinsyncDateFlag = $this->getConfigValueForScope( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", - 0, - 'stores' - ); - - //Save old value in new place. - if ($ecommMinsyncDateFlag === null && $this->validateDate($oldEcommMinsyncDateFlag)) { - $configValue = array( - array( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG . "_$mailchimpStoreId", - $oldEcommMinsyncDateFlag - ) - ); - $this->saveMailchimpConfig($configValue, 0, 'default'); - } - - //Delete old entry if exists particularly in this scope. - if ($oldEcommMinsyncDateFlag !== null - && $this->getIfConfigExistsForScope( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, - $scopeId, - $scope - ) - ) { - $config = $this->getConfig(); - $config->deleteConfig( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG, - $scope, - $scopeId - ); - $config->cleanCache(); - } - - return ($ecommMinsyncDateFlag !== null) ? $ecommMinsyncDateFlag : $oldEcommMinsyncDateFlag; - } - /** * Get if logs are enabled. * Logs can only be enabled in default scope. @@ -750,8 +690,8 @@ public function getLogsEnabled() /** * Get if two way sync is enabled for given scope. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -767,8 +707,8 @@ public function getTwoWaySyncEnabled($scopeId = 0, $scope = null) /** * Get webhook Id. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -784,8 +724,8 @@ public function getWebhookId($scopeId = 0, $scope = null) /** * Get if monkey should be displayed in order grid. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -801,8 +741,8 @@ public function getMonkeyInGrid($scopeId = 0, $scope = null) /** * Get if Email Catcher popup is enabled for given scope. * - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -812,8 +752,8 @@ public function isEmailCatcherEnabled($scopeId = 0, $scope = null) } /** - * @param int $scopeId - * @param null $scope + * @param int $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -842,6 +782,8 @@ public function getDateSyncFinishByMailChimpStoreId($mailchimpStoreId) } /** + * Set the values to send all the items again. + * * @param $scopeId * @param $scope * @param null $filters @@ -867,10 +809,10 @@ public function resendMCEcommerceData($scopeId, $scope, $filters = null) * Remove items from mailchimp_ecommerce_sync_data table to allow them to be sent. * If scopeId is 0 remova from all scopes. * - * @param $scopeId - * @param $scope - * @param bool $deleteErrorsOnly - * @param null $filters + * @param $scopeId + * @param $scope + * @param bool $deleteErrorsOnly + * @param null $filters * @throws Mage_Core_Exception */ public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = false, $filters = null) @@ -885,6 +827,7 @@ public function removeEcommerceSyncData($scopeId, $scope, $deleteErrorsOnly = fa /** * @param null $filters + * @throws Mage_Core_Exception */ public function removeAllEcommerceSyncDataErrors($filters = null) { @@ -906,9 +849,9 @@ public function removeAllEcommerceSyncDataErrors($filters = null) } /** - * @param $mailchimpStoreId - * @param bool $deleteErrorsOnly - * @param null $filters + * @param $mailchimpStoreId + * @param bool $deleteErrorsOnly + * @param null $filters */ public function removeEcommerceSyncDataByMCStore($mailchimpStoreId, $deleteErrorsOnly = false, $filters = null) { @@ -940,9 +883,9 @@ public function removeEcommerceSyncDataByMCStore($mailchimpStoreId, $deleteError /** * Check if Ecommerce data is configured to be sent. * - * @param $scopeId - * @param null $scope - * @param bool $isStoreCreation + * @param $scopeId + * @param null $scope + * @param bool $isStoreCreation * @return bool * @throws Mage_Core_Exception */ @@ -971,8 +914,10 @@ public function isEcomSyncDataEnabled($scopeId, $scope = null, $isStoreCreation public function isEcomSyncDataEnabledInAnyScope() { $stores = $this->getMageApp()->getStores(); + foreach ($stores as $storeId => $store) { $ecomEnabled = $this->isEcomSyncDataEnabled($storeId); + if ($ecomEnabled) { return true; } @@ -1026,8 +971,8 @@ public function logBatchQuantity($message) /** * Save request made to MailChimp's API in "MailChimp_Requests.log" file. * - * @param $message - * @param null $batchId + * @param $message + * @param null $batchId */ public function logRequest($message, $batchId = null) { @@ -1038,20 +983,21 @@ public function logRequest($message, $batchId = null) Mage::log($message, null, 'MailChimp_Failing_Requests.log', true); } elseif ($logRequestEnabled) { $logDir = Mage::getBaseDir('var') . DS . 'log'; + $fileHelper = $this->getFileHelper(); - if (!file_exists($logDir)) { - mkdir($logDir, 0750); + if (!$fileHelper->fileExists($logDir, false)) { + $fileHelper->mkDir($logDir, 0750); } $logDir .= DS . 'MailChimp_Requests'; - if (!file_exists($logDir)) { - mkdir($logDir, 0750); + if (!$fileHelper->fileExists($logDir, false)) { + $fileHelper->mkDir($logDir, 0750); } $fileName = $logDir . DS . $batchId . '.Request.log'; $oldPermission = umask(0033); - file_put_contents($fileName, $message); + $fileHelper->filePutContent($fileName, $message); umask($oldPermission); } } @@ -1064,6 +1010,7 @@ protected function isRequestLogEnabled() { $logEnabled = false; $logConfig = $this->getLogsEnabled(); + if ($logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::REQUEST_LOG || $logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::BOTH ) { @@ -1081,6 +1028,7 @@ public function isErrorLogEnabled() { $logEnabled = false; $logConfig = $this->getLogsEnabled(); + if ($logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::ERROR_LOG || $logConfig == Ebizmarts_MailChimp_Model_System_Config_Source_Log::BOTH ) { @@ -1095,7 +1043,7 @@ public function isErrorLogEnabled() */ public function getWebhooksKey() { - $crypt = md5((string)$this->getConfig()->getNode('global/crypt/key')); + $crypt = hash('md5', (string)$this->getConfig()->getNode('global/crypt/key')); $key = substr($crypt, 0, (strlen($crypt) / 2)); return $key; @@ -1105,8 +1053,8 @@ public function getWebhooksKey() * Reset error messages from Products, Subscribers, Customers, Orders, Quotes * and set them to be sent again for given scope. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @throws Mage_Core_Exception */ public function resetErrors($scopeId, $scope = 'stores') @@ -1122,10 +1070,10 @@ public function resetErrors($scopeId, $scope = 'stores') * Clear mailchimp_errors grid for given scope. * Exclude subscriber if flag set to true. * - * @param $scopeId - * @param $scope - * @param bool $excludeSubscribers - * @param null $filters + * @param $scopeId + * @param $scope + * @param bool $excludeSubscribers + * @param null $filters * @throws Mage_Core_Exception */ public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false, $filters = null) @@ -1134,6 +1082,7 @@ public function clearErrorGrid($scopeId, $scope, $excludeSubscribers = false, $f $this->handleOldErrors(); $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); + if ($excludeSubscribers) { $this->clearErrorGridByMCStore($mailchimpStoreId, $filters); } else { @@ -1154,7 +1103,7 @@ public function clearErrorGridByMCStore($mailchimpStoreId, $filters = null) $where[] = $connection->quoteInto("mailchimp_store_id = ?", $mailchimpStoreId); if ($filters !== null) { - $where[] = $connection->quoteInto('type IN (?)', $filters); + $where[] = $connection->quoteInto('regtype IN (?)', $filters); } $connection->delete($tableName, $where); @@ -1190,16 +1139,26 @@ public function handleOldErrors() $errorCollection = Mage::getModel('mailchimp/mailchimperrors')->getCollection() ->addFieldToFilter('type', array('neq' => 'SUB')) ->addFieldToFilter('mailchimp_store_id', array('eq' => '')); + foreach ($errorCollection as $error) { $storeId = $error->getStoreId(); $mailchimpStoreId = $this->getMCStoreId($storeId); + if ($mailchimpStoreId) { - $error->setMailchimpStoreId($mailchimpStoreId) - ->save(); + $this->_saveErrorItem($error, $mailchimpStoreId); } } } + /** + * @param $error + * @param $mailchimpStoreId + */ + protected function _saveErrorItem($error, $mailchimpStoreId) + { + $error->setMailchimpStoreId($mailchimpStoreId)->save(); + } + /** * @param $scopeId * @param $scope @@ -1267,14 +1226,14 @@ protected function getLastCustomerSent($scopeId, $scope) { $lastCustomerSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); - $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() + $syncDataCollection = $this->getMailchimpEcommerceSyncDataModel()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER)) ->setOrder('related_id', 'DESC') ->setPageSize(1); if ($syncDataCollection->getSize()) { - $customerSyncData = $syncDataCollection->getFirstItem(); + $customerSyncData = $syncDataCollection->getLastItem(); $lastCustomerSent = $customerSyncData->getRelatedId(); } @@ -1290,14 +1249,14 @@ protected function getLastProductSent($scopeId, $scope) { $lastProductSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); - $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() + $syncDataCollection = $this->getMailchimpEcommerceSyncDataModel()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_PRODUCT)) ->setOrder('related_id', 'DESC') ->setPageSize(1); if ($syncDataCollection->getSize()) { - $productSyncData = $syncDataCollection->getFirstItem(); + $productSyncData = $syncDataCollection->getLastItem(); $lastProductSent = $productSyncData->getRelatedId(); } @@ -1313,14 +1272,14 @@ protected function getLastOrderSent($scopeId, $scope) { $lastOrderSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); - $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() + $syncDataCollection = $this->getMailchimpEcommerceSyncDataModel()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_ORDER)) ->setOrder('related_id', 'DESC') ->setPageSize(1); if ($syncDataCollection->getSize()) { - $orderSyncData = $syncDataCollection->getFirstItem(); + $orderSyncData = $syncDataCollection->getLastItem(); $lastOrderSent = $orderSyncData->getRelatedId(); } @@ -1336,14 +1295,14 @@ protected function getLastCartSent($scopeId, $scope) { $lastCartSent = null; $mcStoreId = $this->getMCStoreId($scopeId, $scope); - $syncDataCollection = $this->getModelMailchimpEcommerceSyncData()->getCollection() + $syncDataCollection = $this->getMailchimpEcommerceSyncDataModel()->getCollection() ->addFieldToFilter('mailchimp_store_id', array('eq' => $mcStoreId)) ->addFieldToFilter('type', array('eq' => Ebizmarts_MailChimp_Model_Config::IS_QUOTE)) ->setOrder('related_id', 'DESC') ->setPageSize(1); if ($syncDataCollection->getSize()) { - $cartSyncData = $syncDataCollection->getFirstItem(); + $cartSyncData = $syncDataCollection->getLastItem(); $lastCartSent = $cartSyncData->getRelatedId(); } @@ -1366,7 +1325,7 @@ protected function getLastPromoCodeSent($scopeId, $scope) ->setPageSize(1); if ($syncDataCollection->getSize()) { - $promoCodeSyncData = $syncDataCollection->getFirstItem(); + $promoCodeSyncData = $syncDataCollection->getLastItem(); $lastPromoCodeSent = $promoCodeSyncData->getRelatedId(); } @@ -1387,7 +1346,7 @@ public function createMergeFields($scopeId, $scope) $maps = $this->unserialize($this->getMapFields($scopeId, $scope)); $customFieldTypes = $this->unserialize($this->getCustomMergeFieldsSerialized($scopeId, $scope)); - if (count($maps) > 30 ) { + if (count($maps) > 30) { $success = 2; } else { try { @@ -1406,23 +1365,7 @@ public function createMergeFields($scopeId, $scope) } if (!empty($mailchimpFields)) { - foreach ($maps as $map) { - $customAtt = $map['magento']; - $chimpTag = $map['mailchimp']; - $alreadyExists = false; - - foreach ($mailchimpFields['merge_fields'] as $mailchimpField) { - if ($mailchimpField['tag'] == $chimpTag || strtoupper($chimpTag) == 'EMAIL') { - $alreadyExists = true; - } - } - - if (!$alreadyExists) { - $this->_createCustomFieldTypes($customFieldTypes, $api, $customAtt, $listId, $chimpTag); - } - } - - $success = 1; + $success = $this->_mapFieldsIteration($maps, $mailchimpFields, $customFieldTypes, $api, $listId); } } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $this->logError($e->getMessage()); @@ -1432,9 +1375,48 @@ public function createMergeFields($scopeId, $scope) return $success; } + /** + * @param $maps + * @param $mailchimpFields + * @param $customFieldTypes + * @param $api + * @param $listId + * @return int + */ + protected function _mapFieldsIteration($maps, $mailchimpFields, $customFieldTypes, $api, $listId) + { + foreach ($maps as $map) { + $customAtt = $map['magento']; + $chimpTag = $map['mailchimp']; + $alreadyExists = false; + + foreach ($mailchimpFields['merge_fields'] as $mailchimpField) { + if ($mailchimpField['tag'] == $chimpTag || strtoupper($chimpTag) == 'EMAIL') { + $alreadyExists = true; + } + } + + if (!$alreadyExists) { + $this->_createCustomFieldTypes($customFieldTypes, $api, $customAtt, $listId, $chimpTag); + } + } + + $success = 1; + + return $success; + } + + /** + * @param $customFieldTypes + * @param $api + * @param $customAtt + * @param $listId + * @param $chimpTag + */ protected function _createCustomFieldTypes($customFieldTypes, $api, $customAtt, $listId, $chimpTag) { $created = false; + foreach ($customFieldTypes as $customFieldType) { if ($customFieldType['value'] == $customAtt) { try { @@ -1459,6 +1441,7 @@ protected function _createCustomFieldTypes($customFieldTypes, $api, $customAtt, ->addSetInfo() ->getData(); $label = null; + foreach ($attrSetId as $option) { if ($option['attribute_id'] == $customAtt && $option['frontend_label']) { $label = $option['frontend_label']; @@ -1509,15 +1492,16 @@ protected function _addMergeFieldByLabel($api, $label, $customAtt, $listId, $chi /** * Get Api object for given scope. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return Ebizmarts_MailChimp|null - * @throws Exception + * @throws Ebizmarts_MailChimp_Helper_Data_ApiKeyException */ public function getApi($scopeId, $scope = null) { $apiKey = $this->getApiKey($scopeId, $scope); $api = null; + if ($apiKey != null && $apiKey != "") { $timeOut = $this->getConfigValueForScope( Ebizmarts_MailChimp_Model_Config::GENERAL_TIME_OUT, @@ -1528,7 +1512,7 @@ public function getApi($scopeId, $scope = null) $apiKey, array('timeout' => $timeOut), 'Mailchimp4Magento' - . (string)$this->getConfig()->getNode('modules/Ebizmarts_MailChimp/version') + . (string)$this->getConfig()->getNode('modules/Ebizmarts_MailChimp/version') ); } else { $e = new Ebizmarts_MailChimp_Helper_Data_ApiKeyException('You must provide a MailChimp API key'); @@ -1550,6 +1534,7 @@ public function getApi($scopeId, $scope = null) public function getApiByKey($apiKey) { $api = null; + if ($apiKey != null && $apiKey != "") { $api = new Ebizmarts_MailChimp( $apiKey, @@ -1565,86 +1550,6 @@ public function getApiByKey($apiKey) return $api; } - /** - * Save entry for ecommerce_sync_data table overwriting old item if exists or creating a new one if it does not. - * - * @param $itemId - * @param $itemType - * @param $mailchimpStoreId - * @param null $syncDelta - * @param null $syncError - * @param int $syncModified - * @param null $syncDeleted - * @param null $token - * @param null $syncedFlag - * @param bool $saveOnlyIfexists - * @param null $deletedRelatedId - * @param bool $allowBatchRemoval - */ - public function saveEcommerceSyncData( - $itemId, - $itemType, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncDeleted = null, - $token = null, - $syncedFlag = null, - $saveOnlyIfexists = false, - $deletedRelatedId = null, - $allowBatchRemoval = true - ) { - $ecommerceSyncDataItem = $this->getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId); - - if (!$saveOnlyIfexists || $ecommerceSyncDataItem->getMailchimpSyncDelta()) { - $this->setEcommerceSyncDataItemValues( - $itemType, $syncDelta, $syncError, $syncModified, $syncDeleted, - $token, $syncedFlag, $deletedRelatedId, $allowBatchRemoval, $ecommerceSyncDataItem - ); - - $ecommerceSyncDataItem->save(); - } - } - - /** - * Load Ecommerce Sync Data Item if exists or set the values for a new one and return it. - * - * @param $itemId - * @param $itemType - * @param $mailchimpStoreId - * @return Varien_Object - */ - public function getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId) - { - $collection = $this->getModelMailchimpEcommerceSyncData()->getCollection() - ->addFieldToFilter('related_id', array('eq' => $itemId)) - ->addFieldToFilter('type', array('eq' => $itemType)) - ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId)) - ->setCurPage(1) - ->setPageSize(1); - - if ($collection->getSize()) { - $ecommerceSyndDataItem = $collection->getFirstItem(); - } else { - $ecommerceSyndDataItem = $this->getModelMailchimpEcommerceSyncData() - ->setData("related_id", $itemId) - ->setData("type", $itemType) - ->setData("mailchimp_store_id", $mailchimpStoreId); - } - - return $ecommerceSyndDataItem; - } - - public function getAllEcommerceSyncDataItemsPerId($itemId, $itemType) - { - $collection = $this->getModelMailchimpEcommerceSyncData()->getCollection() - ->addFieldToFilter('related_id', array('eq' => $itemId)) - ->addFieldToFilter('type', array('eq' => $itemType)); - - return $collection; - } - /** * Filter collection by all the stores associated to MailChimp for given scope. * @@ -1657,6 +1562,7 @@ public function addStoresToFilter($collection, $scopeId, $scope) { $filterArray = array(); $storesForScope = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope); + if ($storesForScope) { if ($scopeId === 0) { $filterArray[] = array('eq' => 0); @@ -1688,6 +1594,7 @@ public function getMailChimpScopeByStoreId($storeId) Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID, $mailChimpStoreId ); + return $mailchimpScope; } @@ -1701,6 +1608,7 @@ public function getMailChimpScopeByStoreId($storeId) public function getDefaultStoreIdForMailChimpScope($magentoStoreId) { $scopeArray = $this->getMailChimpScopeByStoreId($magentoStoreId); + if ($scopeArray) { if ($scopeArray['scope'] == 'websites') { $magentoStoreId = $this->getMageApp() @@ -1723,10 +1631,10 @@ public function getDefaultStoreIdForMailChimpScope($magentoStoreId) /** * Save configValues on core_config_data for given scope. * - * @param $configValues - * @param $scopeId - * @param $scope - * @param bool $cleanCache + * @param $configValues + * @param $scopeId + * @param $scope + * @param bool $cleanCache */ public function saveMailchimpConfig($configValues, $scopeId, $scope, $cleanCache = true) { @@ -1765,22 +1673,23 @@ public function getImageUrlById($productId, $magentoStoreId) $productResourceModel = $this->getProductResourceModel(); $productModel = $this->getProductModel(); $configImageSize = $this->getImageSize($magentoStoreId); + switch ($configImageSize) { - case self::DEFAULT_SIZE: - $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; - break; - case self::SMALL_SIZE: - $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_SMALL; - break; - case self::THUMBNAIL_SIZE: - $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_THUMBNAIL; - break; - case self::ORIGINAL_SIZE: - $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; - break; - default: - $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; - break; + case self::DEFAULT_SIZE: + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; + break; + case self::SMALL_SIZE: + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_SMALL; + break; + case self::THUMBNAIL_SIZE: + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_THUMBNAIL; + break; + case self::ORIGINAL_SIZE: + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; + break; + default: + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; + break; } $productImage = $productResourceModel->getAttributeRawValue($productId, $imageSize, $magentoStoreId); @@ -1791,6 +1700,7 @@ public function getImageUrlById($productId, $magentoStoreId) } else { $curStore = $this->getCurrentStoreId(); $this->setCurrentStore($magentoStoreId); + if ($configImageSize == self::ORIGINAL_SIZE) { $imageUrl = $this->getOriginalPath($productImage); } else { @@ -1838,6 +1748,7 @@ protected function getImageUrlForSize($imageSize, $productModel) { $upperCaseImage = (string)$this->getImageFunctionName($imageSize); $imageUrl = $productModel->$upperCaseImage(); + return $imageUrl; } @@ -1863,6 +1774,7 @@ public function setImageSizeVarToArray($imageSize) public function setWordToCamelCase($imageArray) { $upperCaseImage = ''; + foreach ($imageArray as $word) { $word = ucwords($word); $upperCaseImage .= $word; @@ -1880,6 +1792,7 @@ public function setWordToCamelCase($imageArray) public function setFunctionName($functionName) { $functionName = "get" . $functionName . "Url"; + return $functionName; } @@ -1895,8 +1808,8 @@ protected function _getImageHelper() } /** - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -1915,6 +1828,7 @@ public function getImageSize($scopeId, $scope = null) public function getProductResourceModel() { $productResourceModel = Mage::getResourceModel('catalog/product'); + return $productResourceModel; } @@ -1924,6 +1838,7 @@ public function getProductResourceModel() protected function getProductModel() { $productModel = Mage::getModel('catalog/product'); + return $productModel; } @@ -1942,6 +1857,7 @@ public function getMageApp() public function getCurrentStoreId() { $curStore = $this->getMageApp()->getStore()->getId(); + return $curStore; } @@ -1980,6 +1896,7 @@ protected function getCoreWebsite() public function customMergeFieldAlreadyExists($value, $scopeId, $scope) { $customMergeFields = $this->getCustomMergeFields($scopeId, $scope); + foreach ($customMergeFields as $customMergeField) { if ($customMergeField['value'] == $value) { return true; @@ -1992,8 +1909,8 @@ public function customMergeFieldAlreadyExists($value, $scopeId, $scope) /** * Get custom merge fields for given scope as an array. * - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return array|mixed */ public function getCustomMergeFields($scopeId, $scope = null) @@ -2053,8 +1970,8 @@ public function getMCJs() /** * Retrieve store data and save the MCJs URL for the current store in config table. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return bool * @throws Mage_Core_Exception */ @@ -2249,7 +2166,8 @@ function ($customer, $mailchimpStoreId) { $syncModified = $customer->getMailchimpSyncModified(); } - $this->saveEcommerceSyncData( + $ecommerceSyncData = $this->getMailchimpEcommerceSyncDataModel(); + $ecommerceSyncData->saveEcommerceSyncData( $customerId, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId, @@ -2313,7 +2231,8 @@ function ($product, $mailchimpStoreId) { $syncModified = $product->getMailchimpSyncModified(); } - $this->saveEcommerceSyncData( + $ecommerceSyncData = $this->getMailchimpEcommerceSyncDataModel(); + $ecommerceSyncData->saveEcommerceSyncData( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId, @@ -2378,7 +2297,8 @@ function ($order, $mailchimpStoreId) { $syncModified = $order->getMailchimpSyncModified(); } - $this->saveEcommerceSyncData( + $ecommerceSyncData = $this->getMailchimpEcommerceSyncDataModel(); + $ecommerceSyncData->saveEcommerceSyncData( $orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId, @@ -2409,6 +2329,7 @@ protected function _migrateCartsFrom115($mailchimpStoreId, $initialTime) $readConnection = $resource->getConnection('core_read'); $tableName = $resource->getTableName('sales/quote'); $quoteFields = $readConnection->describeTable($tableName); + if (isset($quoteFields['mailchimp_sync_delta'])) { $mailchimpTableName = $resource->getTableName('mailchimp/ecommercesyncdata'); $quoteCollection = Mage::getResourceModel('sales/quote_collection'); @@ -2435,6 +2356,7 @@ function ($quote, $mailchimpStoreId) { $token = null; $quoteObject = $this->getSalesOrderModel()->load($quoteId); $syncDelta = $quoteObject->getMailchimpSyncDelta(); + if ($quote->getMailchimpSyncError()) { $syncError = $quote->getMailchimpSyncError(); } @@ -2447,7 +2369,8 @@ function ($quote, $mailchimpStoreId) { $token = $quote->getMailchimpToken(); } - $this->saveEcommerceSyncData( + $ecommerceSyncData = $this->getMailchimpEcommerceSyncDataModel(); + $ecommerceSyncData->saveEcommerceSyncData( $quoteId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId, @@ -2473,6 +2396,7 @@ function ($quote, $mailchimpStoreId) { . $this->__(' See error details below.') ); $this->logError($e->getMessage()); + return false; } } @@ -2492,17 +2416,17 @@ protected function delete115MigrationConfigData() /** * Helper function for data migration from version 1.1.5. * - * @param $collection - * @param $mailchimpStoreId - * @param $initialTime - * @param Closure $callback + * @param $collection + * @param $mailchimpStoreId + * @param $initialTime + * @param Closure $callback * @return bool */ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initialTime, Closure $callback) { $dateHelper = $this->getDateHelper(); - $finished = false; + if (!$collection->getSize()) { $finished = true; } @@ -2514,7 +2438,7 @@ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initi do { $collection->setCurPage($currentPage); - $collection->load(); + $this->_loadItemCollection($collection); foreach ($collection as $collectionItem) { $callback($collectionItem, $mailchimpStoreId); @@ -2525,6 +2449,7 @@ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initi // if not done, the same page will be loaded each loop // - will also free memory $collection->clear(); + if ($dateHelper->timePassed($initialTime)) { break; } @@ -2533,9 +2458,18 @@ protected function _makeForCollectionItem($collection, $mailchimpStoreId, $initi $finished = true; } } while ($currentPage <= $pages); + return $finished; } + /** + * @param $collection + */ + protected function _loadItemCollection($collection) + { + $collection->load(); + } + /** * Migrate data from version 1.1.6. * @@ -2545,6 +2479,7 @@ protected function _migrateFrom116($initialTime) { $this->_setIsSyncingIfFinishedInAllStores(true); $finished = $this->_migrateOrdersFrom116($initialTime); + if ($finished) { $this->_setIsSyncingIfFinishedInAllStores(false); $arrayMigrationConfigData = array('115' => false, '116' => true, '1164' => false); @@ -2560,8 +2495,10 @@ protected function _migrateFrom116($initialTime) protected function _setIsSyncingIfFinishedInAllStores($syncValue) { $stores = $this->getMageApp()->getStores(); + foreach ($stores as $storeId => $store) { $ecommEnabled = $this->isEcomSyncDataEnabled($storeId); + if ($ecommEnabled) { $this->setIsSyncingIfFinishedPerScope($syncValue, $storeId); } @@ -2578,9 +2515,11 @@ protected function _migrateOrdersFrom116($initialTime) { $dateHelper = $this->getDateHelper(); $finished = false; + if (!$dateHelper->timePassed($initialTime)) { $finished = true; $stores = $this->getMageApp()->getStores(); + foreach ($stores as $storeId => $store) { if ($this->isEcomSyncDataEnabled($storeId)) { Mage::getModel('mailchimp/api_batches')->replaceAllOrders($initialTime, $storeId); @@ -2611,11 +2550,13 @@ public function migrationFinished() 0, 'default' ); + $migrateFrom116 = $this->getConfigValueForScope( Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_116, 0, 'default' ); + $migrateFrom1164 = $this->getConfigValueForScope( Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_FROM_1164, 0, @@ -2640,6 +2581,7 @@ public function delete116MigrationConfigData() 'default', 0 ); + foreach ($stores as $storeId => $store) { $this->getConfig()->deleteConfig( Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, @@ -2657,10 +2599,11 @@ public function delete116MigrationConfigData() protected function _migrateFrom1164($initialTime) { $dateHelper = $this->getDateHelper(); + if (!$dateHelper->timePassed($initialTime)) { - $write_connection = $this->getCoreResource()->getConnection('core_write'); + $writeConnection = $this->getCoreResource()->getConnection('core_write'); $resource = Mage::getResourceModel('mailchimp/ecommercesyncdata'); - $write_connection->update($resource->getMainTable(), array('batch_id' => '1'), "batch_id = 0"); + $writeConnection->update($resource->getMainTable(), array('batch_id' => '1'), "batch_id = 0"); $arrayMigrationConfigData = array('115' => false, '116' => false, '1164' => true); $this->handleDeleteMigrationConfigData($arrayMigrationConfigData); } @@ -2711,9 +2654,11 @@ public function handleDeleteMigrationConfigData($arrayMigrationConfigData) public function getMagentoStoreIdsByListId($listId) { $storeIds = Mage::registry('mailchimp_store_ids_for_list_' . $listId); + if ($storeIds === null) { $stores = $this->getMageApp()->getStores(); $storeIds = array(); + foreach ($stores as $storeId => $store) { if ($this->isSubscriptionEnabled($storeId)) { $storeListId = $this->getConfigValueForScope( @@ -2744,15 +2689,15 @@ public function getMagentoStoreIdsByListId($listId) public function loadListSubscriber($listId, $email) { $subscriber = null; - $storeIds = $this->getMagentoStoreIdsByListId($listId); //add store id 0 for those created from the back end. $storeIds[] = 0; + if (!empty($storeIds)) { $subscriber = Mage::getModel('newsletter/subscriber')->getCollection() ->addFieldToFilter('store_id', array('in' => $storeIds)) ->addFieldToFilter('subscriber_email', $email) - ->getFirstItem(); + ->setPageSize(1)->getLastItem(); if (!$subscriber->getId()) { /** @@ -2762,6 +2707,7 @@ public function loadListSubscriber($listId, $email) $subscriber = Mage::getModel('newsletter/subscriber'); $subscriber->setEmail($email); $customer = $this->loadListCustomer($listId, $email); + if ($customer) { $subscriber->setStoreId($customer->getStoreId()); $subscriber->setCustomerId($customer->getId()); @@ -2792,13 +2738,14 @@ public function loadListSubscriber($listId, $email) public function loadListCustomer($listId, $email) { $customer = null; - $storeIds = $this->getMagentoStoreIdsByListId($listId); + if (!empty($storeIds)) { $customer = Mage::getResourceModel('customer/customer_collection') ->addFieldToFilter('store_id', array('in' => $storeIds)) ->addFieldToFilter('email', array('eq' => $email)) - ->getFirstItem(); + ->setPageSize(1)->getLastItem(); + if ($customer->getId()) { $customer = Mage::getModel('customer/customer')->load($customer->getId()); } else { @@ -2810,8 +2757,8 @@ public function loadListCustomer($listId, $email) } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope */ public function handleWebhookChange($scopeId, $scope = 'stores') { @@ -2822,6 +2769,7 @@ public function handleWebhookChange($scopeId, $scope = 'stores') ); $listId = $this->getGeneralList($scopeId, $scope); $this->deleteCurrentWebhook($webhookScope['scope_id'], $webhookScope['scope'], $listId); + if ($this->isSubscriptionEnabled($scopeId, $scope)) { $this->createNewWebhook($webhookScope['scope_id'], $webhookScope['scope'], $listId); } @@ -2839,9 +2787,10 @@ protected function deleteCurrentWebhook($scopeId, $scope, $listId) $api = $this->getApi($scopeId, $scope); $webhookId = $this->getWebhookId($scopeId, $scope); $apiKey = $this->getApiKey($scopeId, $scope); + if ($webhookId && $apiKey && $listId) { try { - $api->lists->webhooks->delete($listId, $webhookId); + $api->getLists()->getWebhooks()->delete($listId, $webhookId); } catch (MailChimp_Error $e) { $this->logError($e->getFriendlyMessage()); } catch (Exception $e) { @@ -2869,22 +2818,35 @@ protected function deleteCurrentWebhook($scopeId, $scope, $listId) protected function _deletedWebhooksByListId($api, $listId, $webhookUrl) { - $webhooks = $api->lists->webhooks->getAll($listId); + $webhooks = $api->getLists()->getWebhooks()->getAll($listId); + foreach ($webhooks['webhooks'] as $webhook) { if (strpos($webhook['url'], $webhookUrl) !== false) { - $api->lists->webhooks->delete($listId, $webhook['id']); + $this->deleteWebhookFromList($api->getLists()->getWebhooks(), $listId, $webhook['id']); } } } + /** + * @param $apiWebhook + * @param $listId + * @param $webhookId + */ + public function deleteWebhookFromList($apiWebhook, $listId, $webhookId) + { + $apiWebhook->delete($listId, $webhookId); + } + /** * Returns true on successful creation, or error message if it fails */ public function createNewWebhook($scopeId, $scope, $listId) { $hookUrl = $this->getWebhookUrl(); + try { $api = $this->getApi($scopeId, $scope); + if ($this->getTwoWaySyncEnabled($scopeId, $scope)) { $events = array( 'subscribe' => true, @@ -2916,21 +2878,24 @@ public function createNewWebhook($scopeId, $scope, $listId) } try { - $response = $api->lists->webhooks->getAll($listId); + $response = $api->getLists()->getWebhooks()->getAll($listId); $createWebhook = true; + if (isset($response['total_items']) && $response['total_items'] > 0) { foreach ($response['webhooks'] as $webhook) { if ($webhook['url'] == $hookUrl) { $createWebhook = false; + break; } } } if ($createWebhook) { - $newWebhook = $api->lists->webhooks->add($listId, $hookUrl, $events, $sources); + $newWebhook = $api->getLists()->getWebhooks()->add($listId, $hookUrl, $events, $sources); $newWebhookId = $newWebhook['id']; $configValues = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_WEBHOOK_ID, $newWebhookId)); $this->saveMailchimpConfig($configValues, $scopeId, $scope); + return true; } else { return $this->__('The webhook already exists.'); @@ -2983,14 +2948,15 @@ protected function getWebhookUrl() } /** - * @param $path - * @param $scopeId - * @param string $scope + * @param $path + * @param $scopeId + * @param string $scope * @return array|null */ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') { $websiteId = null; + if ($scope == 'stores') { $websiteId = Mage::getModel('core/store')->load($scopeId)->getWebsiteId(); $scopeIdsArray = array($scopeId, $websiteId, 0); @@ -3001,8 +2967,8 @@ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') $configCollection = Mage::getResourceModel('core/config_data_collection') ->addFieldToFilter('path', array('eq' => $path)) ->addFieldToFilter('scope_id', array('in' => $scopeIdsArray)); - $scopeSoFar = null; + foreach ($configCollection as $config) { //Discard possible extra website or store if ($this->isExtraEntry($config, $scope, $scopeId, $websiteId)) { @@ -3010,19 +2976,19 @@ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') } switch ($config->getScope()) { - case 'stores': + case 'stores': + $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope()); + break; + case 'websites': + if (!$scopeSoFar || $scopeSoFar['scope'] == 'default') { $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope()); - break; - case 'websites': - if (!$scopeSoFar || $scopeSoFar['scope'] == 'default') { - $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope()); - } - break; - case 'default': - if ($scopeSoFar['scope'] != 'stores') { - $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope()); - } - break; + } + break; + case 'default': + if ($scopeSoFar['scope'] != 'stores') { + $scopeSoFar = array('scope_id' => $config->getScopeId(), 'scope' => $config->getScope()); + } + break; } } @@ -3032,9 +2998,9 @@ public function getRealScopeForConfig($path, $scopeId, $scope = 'stores') /** * Return true if the configPath has been saved specifically for the given scope. * - * @param $configPath - * @param $scopeId - * @param string $scope + * @param $configPath + * @param $scopeId + * @param string $scope * @return bool|mixed * @throws Mage_Core_Exception */ @@ -3045,16 +3011,19 @@ public function getIfConfigExistsForScope($configPath, $scopeId, $scope = 'store $configAssociatedToScope = Mage::registry( 'mailchimp_' . $configName . '_exists_for_scope_' . $scope . '_' . $scopeId ); + if ($configAssociatedToScope === null) { $configAssociatedToScope = false; $collection = Mage::getResourceModel('core/config_data_collection') ->addFieldToFilter('path', array('eq' => $configPath)) ->addFieldToFilter('scope', array('eq' => $scope)) ->addFieldToFilter('scope_id', array('eq' => $scopeId)); + if ($collection->getSize()) { foreach ($collection as $config) { if ($config->getValue() !== null) { $configAssociatedToScope = true; + break; } } } @@ -3081,9 +3050,11 @@ public function getScopeByMailChimpStoreId($mailChimpStoreId) $mailchimpScope = null; $collection = Mage::getResourceModel('core/config_data_collection') ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID)) - ->addFieldToFilter('value', array('eq' => $mailChimpStoreId)); + ->addFieldToFilter('value', array('eq' => $mailChimpStoreId)) + ->setPageSize(1); + if ($collection->getSize()) { - $configEntry = $collection->getFirstItem(); + $configEntry = $collection->getLastItem(); $mailchimpScope = array('scope' => $configEntry->getScope(), 'scope_id' => $configEntry->getScopeId()); } @@ -3102,9 +3073,11 @@ public function getFirstScopeFromConfig($path, $value) $mailchimpScope = null; $collection = Mage::getResourceModel('core/config_data_collection') ->addFieldToFilter('path', array('eq' => $path)) - ->addFieldToFilter('value', array('eq' => $value)); + ->addFieldToFilter('value', array('eq' => $value)) + ->setPageSize(1); + if ($collection->getSize()) { - $configEntry = $collection->getFirstItem(); + $configEntry = $collection->getLastItem(); $mailchimpScope = array('scope' => $configEntry->getScope(), 'scope_id' => $configEntry->getScopeId()); } @@ -3136,6 +3109,7 @@ public function updateSubscriberSyndData( $syncDeleted = null ) { $subscriber = Mage::getModel('newsletter/subscriber')->load($itemId); + if ($subscriber->getId()) { if ($syncDelta) { $subscriber->setData("mailchimp_sync_delta", $syncDelta); @@ -3146,6 +3120,7 @@ public function updateSubscriberSyndData( } $subscriber->setData("mailchimp_sync_modified", $syncModified); + if ($syncDeleted) { $subscriber->setData("mailchimp_sync_deleted", $syncDeleted); } @@ -3158,8 +3133,8 @@ public function updateSubscriberSyndData( /** * Get date configured for subscriber data to be sent for the given scope. * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3201,8 +3176,8 @@ public function getApiStores() } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3216,8 +3191,8 @@ public function getCheckoutSubscribeValue($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return bool * @throws Mage_Core_Exception */ @@ -3231,9 +3206,9 @@ public function isCheckoutSubscribeEnabled($scopeId, $scope = 'stores') /** * Modify is_syncing value if initial sync finished in given scope. * - * @param $syncValue - * @param $scopeId - * @param string $scope + * @param $syncValue + * @param $scopeId + * @param string $scope * @throws Mage_Core_Exception */ protected function setIsSyncingIfFinishedPerScope($syncValue, $scopeId, $scope = 'stores') @@ -3242,6 +3217,7 @@ protected function setIsSyncingIfFinishedPerScope($syncValue, $scopeId, $scope = $mailchimpApi = $this->getApi($scopeId, $scope); $mailchimpStoreId = $this->getMCStoreId($scopeId, $scope); $isSyncing = $this->getMCIsSyncing($mailchimpStoreId, $scopeId, $scope); + if ($mailchimpStoreId && $isSyncing != 1) { $this->getApiStores()->editIsSyncing($mailchimpApi, $syncValue, $mailchimpStoreId); } @@ -3251,9 +3227,9 @@ protected function setIsSyncingIfFinishedPerScope($syncValue, $scopeId, $scope = } /** - * @param $value - * @param $scopeId - * @param string $scope + * @param $value + * @param $scopeId + * @param string $scope */ public function setResendTurn($value, $scopeId, $scope = 'stores') { @@ -3262,8 +3238,8 @@ public function setResendTurn($value, $scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3277,8 +3253,8 @@ public function getResendTurn($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3292,8 +3268,8 @@ public function getResendEnabled($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3307,8 +3283,8 @@ public function getCustomerResendLastId($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3322,8 +3298,8 @@ public function getProductResendLastId($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3337,8 +3313,8 @@ public function getOrderResendLastId($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3352,8 +3328,8 @@ public function getCartResendLastId($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3375,6 +3351,7 @@ public function getPromoCodeResendLastId($scopeId, $scope = 'stores') public function addResendFilter($collection, $magentoStoreId, $itemType) { $resendEnabled = $this->getResendEnabled($magentoStoreId); + if ($resendEnabled) { $resendTurn = $this->getResendTurn($magentoStoreId); $keyCol = 'entity_id'; @@ -3415,20 +3392,21 @@ public function addResendFilter($collection, $magentoStoreId, $itemType) /** * Check if all items have been sent and delete config values used in the resend process * - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope */ public function handleResendFinish($scopeId, $scope = 'stores') { $allItemsSent = $this->allResendItemsSent($scopeId, $scope); + if ($allItemsSent) { $this->deleteResendConfigValues($scopeId, $scope); } } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope */ protected function deleteResendConfigValues($scopeId, $scope = 'stores') { @@ -3444,8 +3422,8 @@ protected function deleteResendConfigValues($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return bool */ protected function allResendItemsSent($scopeId, $scope = 'stores') @@ -3479,6 +3457,7 @@ public function handleResendDataBefore() $resendTurn = $this->getResendTurn($scopeId, $scope); $resendEnabled = $this->getResendEnabled($scopeId, $scope); $ecommEnabled = $this->isEcomSyncDataEnabled($scopeId, $scope); + if ($ecommEnabled && $resendEnabled && $resendTurn) { $this->setIsSyncingIfFinishedPerScope(true, $scopeId, $scope); } @@ -3491,11 +3470,13 @@ public function handleResendDataBefore() public function handleResendDataAfter() { $configCollection = $this->getResendTurnConfigCollection(); + foreach ($configCollection as $config) { $scope = $config->getScope(); $scopeId = $config->getScopeId(); $resendTurn = $this->getResendTurn($scopeId, $scope); $ecommEnabled = $this->isEcomSyncDataEnabled($scopeId, $scope); + if ($ecommEnabled) { if ($resendTurn) { $this->setIsSyncingIfFinishedPerScope(false, $scopeId, $scope); @@ -3520,6 +3501,7 @@ public function handleResendDataAfter() protected function allResendItemsSentPerStoreView($storeId) { $customerId = $this->getCustomerResendLastId($storeId); + if ($customerId) { $isMissingCustomer = $this->isMissingItemLowerThanId( $customerId, @@ -3531,6 +3513,7 @@ protected function allResendItemsSentPerStoreView($storeId) } $productId = $this->getProductResendLastId($storeId); + if ($productId) { $isMissingProduct = $this->isMissingItemLowerThanId( $productId, @@ -3542,6 +3525,7 @@ protected function allResendItemsSentPerStoreView($storeId) } $orderId = $this->getOrderResendLastId($storeId); + if ($orderId) { $isMissingOrder = $this->isMissingItemLowerThanId( $orderId, @@ -3553,6 +3537,7 @@ protected function allResendItemsSentPerStoreView($storeId) } $cartId = $this->getCartResendLastId($storeId); + if ($cartId) { $isMissingCart = $this->isMissingItemLowerThanId( $cartId, @@ -3580,6 +3565,7 @@ protected function allResendItemsSentPerStoreView($storeId) protected function allResendItemsSentPerScope($stores) { $allItemsSent = true; + foreach ($stores as $store) { if ($store instanceof Mage_Core_Model_Store) { $storeId = $store->getId(); @@ -3588,6 +3574,7 @@ protected function allResendItemsSentPerScope($stores) } $allItemsSentInCurrentStore = $this->allResendItemsSentPerStoreView($storeId); + if (!$allItemsSentInCurrentStore) { $allItemsSent = false; } @@ -3687,6 +3674,7 @@ protected function isMissingOrderLowerThanId($itemId, $storeId) ->addFieldToFilter('store_id', array('eq' => $storeId)) ->addFieldToFilter('entity_id', array('lteq' => $itemId)); $firstDate = $this->getEcommerceFirstDate($storeId); + if ($firstDate) { $orderCollection->addFieldToFilter('created_at', array('gt' => $firstDate)); } @@ -3694,6 +3682,7 @@ protected function isMissingOrderLowerThanId($itemId, $storeId) Mage::getModel('mailchimp/api_orders') ->joinMailchimpSyncDataWithoutWhere($orderCollection, $mailchimpStoreId); $orderCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($orderCollection->getSize()) { $isMissing = true; } else { @@ -3718,6 +3707,7 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) ->addFieldToFilter('customer_email', array('notnull' => true)) ->addFieldToFilter('items_count', array('gt' => 0)); $firstDate = $this->getAbandonedCartFirstDate($storeId); + if ($firstDate) { $quoteCollection->addFieldToFilter('updated_at', array('gt' => $firstDate)); } @@ -3725,6 +3715,7 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) Mage::getModel('mailchimp/api_carts') ->joinMailchimpSyncDataWithoutWhere($quoteCollection, $mailchimpStoreId); $quoteCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null"); + if ($quoteCollection->getSize()) { $isMissing = true; } else { @@ -3735,17 +3726,19 @@ protected function isMissingQuoteLowerThanId($itemId, $storeId) } /** - * @param $campaignId - * @param $scopeId - * @param string $scope + * @param $campaignId + * @param $scopeId + * @param string $scope * @return null */ public function getMailChimpCampaignNameById($campaignId, $scopeId, $scope = 'stores') { $campaignName = null; + try { $api = $this->getApi($scopeId, $scope); $campaignData = $api->campaigns->get($campaignId); + if (isset($campaignData['settings'])) { if (isset($campaignData['settings']['title'])) { $campaignName = $campaignData['settings']['title']; @@ -3824,7 +3817,7 @@ public function getPromoRuleAmountLimit() public function getCartAmountLimit() { return $this->getConfigValueForScope( - Ebizmarts_MailChimp_Model_Config::CART_AMOUNT, + Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_AMOUNT, 0, 'default' ); @@ -3844,8 +3837,8 @@ public function getSubscriberAmountLimit() } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return string * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception @@ -3854,6 +3847,7 @@ public function getStoreLanguageCode($scopeId, $scope = 'stores') { $isAdmin = $this->isAdmin(); $userLangCode = Mage::app()->getLocale()->getLocaleCode(); + if ($isAdmin || '' == $lang = $this->_langToMCLanguage($userLangCode)) { // IS Admin OR if users lang is not supported, try store views default locale $userLangCode = $this->getConfigValueForScope( @@ -3868,8 +3862,8 @@ public function getStoreLanguageCode($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3879,8 +3873,8 @@ public function getStoreTimeZone($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -3897,6 +3891,7 @@ public function getAllMailChimpStoreIds() $collection = Mage::getResourceModel('core/config_data_collection') ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::GENERAL_MCSTOREID)); $mailchimpStoreIdsArray = array(); + foreach ($collection as $row) { $scopeData = $row->getScope() . '_' . $row->getScopeId(); $mailchimpStoreIdsArray[$scopeData] = $row->getValue(); @@ -3906,13 +3901,14 @@ public function getAllMailChimpStoreIds() } /** - * @param $subscriber - * @param bool $forceUpdateStatus + * @param $subscriber + * @param bool $forceUpdateStatus */ public function subscribeMember($subscriber, $forceUpdateStatus = false) { $subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED); $subscriber->setSubscriberConfirmCode($subscriber->randomSequence()); + if ($forceUpdateStatus) { $subscriber->setMailchimpSyncModified(1); } @@ -4004,6 +4000,7 @@ protected function getResendTurnConfigCollection() { $configCollection = Mage::getResourceModel('core/config_data_collection') ->addFieldToFilter('path', array('eq' => Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN)); + return $configCollection; } @@ -4070,6 +4067,7 @@ public function isNewApiKeyForSameAccount($oldApiKey, $newApiKey) $api = $this->getApiByKey($newApiKey); $newInfo = $api->getRoot()->info('account_id'); $newAccountId = $newInfo['account_id']; + if ($oldAccountId == $newAccountId) { $isNewApiKeyForSameAccount = true; } @@ -4085,8 +4083,8 @@ public function isNewApiKeyForSameAccount($oldApiKey, $newApiKey) } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope */ public function resendSubscribers($scopeId, $scope = 'stores') { @@ -4112,19 +4110,20 @@ protected function getAllStoresForScope($scopeId, $scope) $storesResult = array(); switch ($scope) { - case 'default': - $stores = $this->getMageApp()->getStores(); - foreach ($stores as $storeId => $store) { - $storesResult[] = $storeId; - } - break; - case 'websites': - $website = $this->getCoreWebsite()->load($scopeId); - $storesResult = $website->getStoreIds(); - break; - case 'stores': - $storesResult[] = $scopeId; - break; + case 'default': + $stores = $this->getMageApp()->getStores(); + + foreach ($stores as $storeId => $store) { + $storesResult[] = $storeId; + } + break; + case 'websites': + $website = $this->getCoreWebsite()->load($scopeId); + $storesResult = $website->getStoreIds(); + break; + case 'stores': + $storesResult[] = $scopeId; + break; } return $storesResult; @@ -4140,11 +4139,13 @@ protected function makeWhereString($connection, $scopeId, $scope) { $storesForScope = $this->getMagentoStoresForMCStoreIdByScope($scopeId, $scope); $whereString = "mailchimp_campaign_id IS NOT NULL"; + if (!empty($storesForScope)) { $whereString .= " AND ("; } $counter = 0; + foreach ($storesForScope as $storeId) { if ($counter) { $whereString .= " OR "; @@ -4164,18 +4165,19 @@ protected function makeWhereString($connection, $scopeId, $scope) /** * Convert language into Mailchimp compatible language code. * - * @param string $languageCode + * @param string $languageCode * @return string Returns empty string if not MC Language match found */ protected function _langToMCLanguage($languageCode = '') { $mailchimpLanguage = ''; - if (in_array($languageCode, self::$MAILCHIMP_LANGUAGES)) { + if (in_array($languageCode, self::$LANGUAGES)) { $mailchimpLanguage = $languageCode; } else { $langIso = substr($languageCode, 0, 2); - if (in_array($langIso, self::$MAILCHIMP_LANGUAGES)) { + + if (in_array($langIso, self::$LANGUAGES)) { $mailchimpLanguage = $langIso; } } @@ -4184,8 +4186,8 @@ protected function _langToMCLanguage($languageCode = '') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return bool * @throws Mage_Core_Exception */ @@ -4199,8 +4201,8 @@ public function isSubscriptionConfirmationEnabled($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param null $scope + * @param $scopeId + * @param null $scope * @return mixed * @throws Mage_Core_Exception */ @@ -4258,6 +4260,7 @@ protected function getSyncFlagDataArray($dat) $textArray = explode(': ', $dat['label']); //textArray indexes = 0 -> label / 1 -> status $textArray = $this->fixTimeTextIfNecessary($textArray); + return $textArray; } @@ -4291,9 +4294,11 @@ protected function isDate($textArray) public function getListIdByApiKeyAndMCStoreId($apiKey, $mailchimpStoreId) { $listId = false; + try { $api = $this->getApiByKey($apiKey); $mcStore = $api->getEcommerce()->getStores()->get($mailchimpStoreId, 'list_id'); + if (isset($mcStore['list_id'])) { $listId = $mcStore['list_id']; } @@ -4316,9 +4321,11 @@ public function getListIdByApiKeyAndMCStoreId($apiKey, $mailchimpStoreId) public function getListInterestCategoriesByKeyAndList($apiKey, $listId) { $interestGroupsArray = array(); + try { $api = $this->getApiByKey($apiKey); $interestCategories = $api->getLists()->getInterestCategory()->getAll($listId, 'categories'); + foreach ($interestCategories['categories'] as $interestCategory) { $interestGroupsArray[] = array( 'id' => $interestCategory['id'], @@ -4338,8 +4345,8 @@ public function getListInterestCategoriesByKeyAndList($apiKey, $listId) } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return array * @throws Exception */ @@ -4348,6 +4355,7 @@ public function getListInterestGroups($scopeId, $scope = 'stores') $interestGroupsArray = array(); $api = $this->getApi($scopeId, $scope); $listId = $this->getGeneralList($scopeId, $scope); + try { $apiInterestCategory = $api->getLists()->getInterestCategory(); $interestCategories = $apiInterestCategory->getAll($listId, 'categories'); @@ -4375,8 +4383,8 @@ public function getListInterestGroups($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -4390,8 +4398,8 @@ public function getLocalInterestCategories($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -4405,8 +4413,8 @@ public function getCheckoutSuccessHtmlBefore($scopeId, $scope = 'stores') } /** - * @param $scopeId - * @param string $scope + * @param $scopeId + * @param string $scope * @return mixed * @throws Mage_Core_Exception */ @@ -4437,6 +4445,7 @@ public function getInterest($storeId) $api = $this->getApi($storeId); $listId = $this->getGeneralList($storeId); + try { $apiInterestCategory = $api->getLists()->getInterestCategory(); $allInterest = $apiInterestCategory->getAll($listId); @@ -4456,6 +4465,7 @@ public function getInterest($storeId) foreach ($interest as $interestId) { $mailchimpInterest = $apiInterestCategoryInterest->getAll($listId, $interestId); + foreach ($mailchimpInterest['interests'] as $mi) { $rc[$mi['category_id']]['category'][$mi['display_order']] = array( @@ -4473,10 +4483,10 @@ public function getInterest($storeId) } /** - * @param $customerId - * @param $subscriberId - * @param $storeId - * @param null $interest + * @param $customerId + * @param $subscriberId + * @param $storeId + * @param null $interest * @return array|null * @throws Mage_Core_Exception * @throws MailChimp_Error @@ -4562,10 +4572,10 @@ public function arrayDecode($encodedArray) } /** - * @param $params - * @param $storeId - * @param null $customerId - * @param null $subscriber + * @param $params + * @param $storeId + * @param null $customerId + * @param null $subscriber * @throws Mage_Core_Model_Store_Exception */ public function saveInterestGroupData($params, $storeId, $customerId = null, $subscriber = null) @@ -4681,6 +4691,7 @@ public function getAllApiKeys() foreach ($stores as $storeId => $store) { try { $apiKey = $this->getApiKey($storeId); + if (!isset($ret[$apiKey])) { $ret[$apiKey] = $apiKey; } @@ -4784,13 +4795,13 @@ public function isInterestGroupEnabled($scopeId = 0, $scope = null) /** * @return Ebizmarts_MailChimp_Model_Ecommercesyncdata */ - protected function getModelMailchimpEcommerceSyncData() + protected function getMailchimpEcommerceSyncDataModel() { return Mage::getModel('mailchimp/ecommercesyncdata'); } /** - * @param $index + * @param $index * @param int $increment */ public function modifyCounterSentPerBatch($index, $increment = 1) @@ -4816,7 +4827,7 @@ public function getCountersSentPerBatch() } /** - * @param $index + * @param $index * @param int $increment */ public function modifyCounterSubscribers($index, $increment = 1) @@ -4842,7 +4853,7 @@ public function getCountersSubscribers() } /** - * @param $index + * @param $index * @param bool $hasError * @param int $increment */ @@ -4854,15 +4865,15 @@ public function modifyCounterDataSentToMailchimp($index, $hasError = false, $inc if ($hasError === true) { $count = isset($counterGetResponsesBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP]) ? $counterGetResponsesBatch[$index][self::DATA_NOT_SENT_TO_MAILCHIMP] - : $increment; + : 0; $statusChanged = self::DATA_NOT_SENT_TO_MAILCHIMP; } else { $count = isset($counterGetResponsesBatch[$index][self::DATA_SENT_TO_MAILCHIMP]) ? $counterGetResponsesBatch[$index][self::DATA_SENT_TO_MAILCHIMP] - : $increment; + : 0; } - $this->setCountersDataSentToMailchimp($index, $statusChanged, $count); + $this->setCountersDataSentToMailchimp($index, $statusChanged, $count + $increment); } public function resetCountersDataSentToMailchimp() @@ -4917,6 +4928,7 @@ public function isApiKeyObscure($apiKey) public function getApiKeyValue() { $scopeArray = $this->getCurrentScope(); + return $this->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); } @@ -5029,27 +5041,33 @@ public function restoreAllCanceledBatches($mailchimpStore) /** * Generates a storable representation of a value using the default adapter. * - * @param mixed $value - * @param array $options + * @param mixed $value + * @param array $options * @return string * @throws Zend_Serializer_Exception */ public function serialize($value, array $options = array()) { - return Zend_Serializer::serialize($value, $options); + $parser = Mage::getModel('dataflow/convert_parser_serialize'); + $parser->setData($value); + $parser->unparse(); + return $parser->getData(); } /** * Creates a PHP value from a stored representation using the default adapter. * - * @param string $serialized - * @param array $options + * @param string $serialized + * @param array $options * @return mixed * @throws Zend_Serializer_Exception */ public function unserialize($serialized, array $options = array()) { - return Zend_Serializer::unserialize($serialized, $options); + $parser = Mage::getModel('dataflow/convert_parser_serialize'); + $parser->setData($serialized); + $parser->parse(); + return $parser->getData(); } /** @@ -5071,52 +5089,10 @@ public function ping($storeId) } /** - * @param $itemType - * @param $syncDelta - * @param $syncError - * @param $syncModified - * @param $syncDeleted - * @param $token - * @param $syncedFlag - * @param $deletedRelatedId - * @param $allowBatchRemoval - * @param Varien_Object $ecommerceSyncDataItem + * @return Ebizmarts_MailChimp_Helper_File */ - protected function setEcommerceSyncDataItemValues($itemType, $syncDelta, $syncError, $syncModified, $syncDeleted, $token, $syncedFlag, $deletedRelatedId, $allowBatchRemoval, Varien_Object $ecommerceSyncDataItem) + protected function getFileHelper() { - if ($syncDelta) { - $ecommerceSyncDataItem->setData("mailchimp_sync_delta", $syncDelta); - } elseif ($allowBatchRemoval === true) { - $ecommerceSyncDataItem->setData("batch_id", null); - } - - if ($allowBatchRemoval === -1) { - $ecommerceSyncDataItem->setData("batch_id", '-1'); - } - - if ($syncError) { - $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); - } - - //Always set modified value to 0 when saving sync delta or errors. - $ecommerceSyncDataItem->setData("mailchimp_sync_modified", $syncModified); - if ($syncDeleted !== null) { - $ecommerceSyncDataItem->setData("mailchimp_sync_deleted", $syncDeleted); - if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT && $syncError == '') { - $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); - } - } - - if ($token) { - $ecommerceSyncDataItem->setData("mailchimp_token", $token); - } - - if ($deletedRelatedId) { - $ecommerceSyncDataItem->setData("deleted_related_id", $deletedRelatedId); - } - - if ($syncedFlag !== null) { - $ecommerceSyncDataItem->setData("mailchimp_synced_flag", $syncedFlag); - } + return Mage::helper('mailchimp/file'); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Date.php b/app/code/community/Ebizmarts/MailChimp/Helper/Date.php index b1bfdedb2..ddd7950d5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Date.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Date.php @@ -63,9 +63,9 @@ public function getCurrentDateTime() * Return date in given format in UTC * or the timezone of the current store ($useStoreTime = true). * - * @param string $format - * @param $date - * @param bool $avoidOffset + * @param string $format + * @param $date + * @param bool $avoidOffset * @return mixed * @throws Mage_Core_Model_Store_Exception */ @@ -89,7 +89,7 @@ public function formatDate($date = null, $format = 'Y-m-d', $useStoreTime = fals protected function _convertUTCToStoreTimestamp($timestamp) { $timeZone = Mage::app()->getStore()->getConfig('general/locale/timezone'); - $offSet = Mage::getModel('core/date')->calculateOffset($timeZone); + $offSet = Mage::getModel('core/date')->calculateOffset($timeZone); return ($timestamp + $offSet); } diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/File.php b/app/code/community/Ebizmarts/MailChimp/Helper/File.php new file mode 100644 index 000000000..7c55372e6 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Helper/File.php @@ -0,0 +1,118 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 9/5/19 3:55 PM + * @file: Curl.php + */ + +class Ebizmarts_MailChimp_Helper_File extends Mage_Core_Helper_Abstract +{ + /** + * @var $_ioFile Varien_Io_File + */ + protected $_ioFile; + + public function __construct() + { + $this->_ioFile = new Varien_Io_File(); + } + + /** + * @return Varien_Io_File + */ + public function getIoFile() + { + return $this->_ioFile; + } + + /** + * @param string $file + * @return string + */ + public function dirName($file = '.') + { + return $this->_ioFile->dirname($file); + } + + /** + * @param $dir + * @param int $mode + * @param bool $recursive + * @return bool + */ + public function mkDir($dir, $mode = 0777, $recursive = true) + { + return $this->_ioFile->mkdir($dir, $mode, $recursive); + } + + /** + * @param $directory + * @param bool $recursive + * @return bool + */ + public function rmDir($directory, $recursive = false) + { + return $this->_ioFile->rmdir($directory, $recursive); + } + + /** + * @param $filename + * @param $src + * @param null $mode + * @return bool|int + */ + public function write($filename, $src, $mode = null) + { + return $this->_ioFile->write($filename, $src, $mode); + } + + /** + * @param $file + * @param bool $onlyFile + * @return bool + */ + public function fileExists($file, $onlyFile = true) + { + return $this->_ioFile->fileExists($file, $onlyFile); + } + + /** + * @param $filename + * @return bool + */ + public function unlink($filename) + { + return $this->rm($filename); + } + + /** + * @param $filename + * @return bool + */ + public function rm($filename) + { + return $this->_ioFile->rm($filename); + } + + /** + * @param $filename + * @param $content + * @return int + */ + public function filePutContent($filename, $content) + { + return $this->_ioFile->filePutContent($filename, $content); + } + + public function read($filename){ + return $this->_ioFile->read($filename); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php b/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php index 42717d178..e18314f74 100644 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Mandrill.php @@ -1,4 +1,5 @@ _mailchimpHelper = Mage::helper('mailchimp'); $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); - $this->_apiCustomers = Mage::getModel('mailchimp/api_customers'); + $this->_mailchimpCurlHelper = Mage::helper('mailchimp/curl'); + $this->_apiProducts = Mage::getModel('mailchimp/api_products'); + $this->_apiCustomers = Mage::getModel('mailchimp/api_customers'); $this->_apiCarts = Mage::getModel('mailchimp/api_carts'); $this->_apiOrders = Mage::getModel('mailchimp/api_orders'); $this->_apiPromoRules = Mage::getModel('mailchimp/api_promoRules'); @@ -79,6 +86,14 @@ protected function getHelper() return $this->_mailchimpHelper; } + /** + * @return Ebizmarts_MailChimp_Helper_Curl + */ + protected function getMailchimpCurlHelper() + { + return $this->_mailchimpCurlHelper; + } + /** * @return Ebizmarts_MailChimp_Helper_Date */ @@ -182,7 +197,8 @@ public function getMagentoBaseDir() */ public function batchDirExists($baseDir, $batchId) { - return is_dir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); + return $this->getMailchimpFileHelper() + ->fileExists($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, false); } /** @@ -192,7 +208,8 @@ public function batchDirExists($baseDir, $batchId) */ public function removeBatchDir($baseDir, $batchId) { - return rmdir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); + return $this->getMailchimpFileHelper() + ->rmDir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); } /** @@ -243,20 +260,15 @@ public function handleSubscriberBatches() /** * Get results of batch operations sent to MailChimp. * - * @param $magentoStoreId - * @param bool $isEcommerceData + * @param $magentoStoreId + * @param bool $isEcommerceData * @throws Mage_Core_Exception */ - public function _getResults( - $magentoStoreId, - $isEcommerceData = true, - $status = Ebizmarts_MailChimp_Helper_Data::BATCH_PENDING - ) + public function _getResults($magentoStoreId, $isEcommerceData = true, $status = Ebizmarts_MailChimp_Helper_Data::BATCH_PENDING) { $helper = $this->getHelper(); $mailchimpStoreId = $helper->getMCStoreId($magentoStoreId); - $collection = $this->getSyncBatchesModel()->getCollection() - ->addFieldToFilter('status', array('eq' => $status)); + $collection = $this->getSyncBatchesModel()->getCollection()->addFieldToFilter('status', array('eq' => $status)); if ($isEcommerceData) { $collection->addFieldToFilter('store_id', array('eq' => $mailchimpStoreId)); @@ -267,25 +279,13 @@ public function _getResults( } if ($enabled) { - $helper->logBatchStatus('Get results from Mailchimp for Magento store '.$magentoStoreId); + $helper->logBatchStatus('Get results from Mailchimp for Magento store ' . $magentoStoreId); foreach ($collection as $item) { try { $batchId = $item->getBatchId(); $files = $this->getBatchResponse($batchId, $magentoStoreId); - - if (!empty($files)) { - if (isset($files['error'])) { - $item->setStatus('error'); - $item->save(); - $helper->logBatchStatus('There was an error getting the result '); - } else { - $this->processEachResponseFile($files, $batchId, $mailchimpStoreId, $magentoStoreId); - $item->setStatus('completed'); - $item->save(); - } - } - + $this->_saveItemStatus($item, $files, $batchId, $mailchimpStoreId, $magentoStoreId); $baseDir = $this->getMagentoBaseDir(); if ($this->batchDirExists($baseDir, $batchId)) { @@ -298,6 +298,31 @@ public function _getResults( } } + /** + * @param $item + * @param $files + * @param $batchId + * @param $mailchimpStoreId + * @param $magentoStoreId + * @throws Mage_Core_Exception + */ + protected function _saveItemStatus($item, $files, $batchId, $mailchimpStoreId, $magentoStoreId) + { + $helper = $this->getHelper(); + + if (!empty($files)) { + if (isset($files['error'])) { + $item->setStatus('error'); + $item->save(); + $helper->logBatchStatus('There was an error getting the result '); + } else { + $this->processEachResponseFile($files, $batchId, $mailchimpStoreId, $magentoStoreId); + $item->setStatus('completed'); + $item->save(); + } + } + } + /** * Send Customers, Products, Orders, Carts to MailChimp store for given scope. * Return true if MailChimp store is reset in the process. @@ -309,52 +334,80 @@ public function _sendEcommerceBatch($magentoStoreId) { $helper = $this->getHelper(); $mailchimpStoreId = $helper->getMCStoreId($magentoStoreId); + try { $this->deleteUnsentItems(); + if ($helper->isEcomSyncDataEnabled($magentoStoreId)) { $helper->resetCountersSentPerBatch(); $batchArray = array(); //customer operations $helper->logBatchStatus('Generate Customers Payload'); $apiCustomers = $this->getApiCustomers(); - $customersArray = $apiCustomers->createBatchJson($mailchimpStoreId, $magentoStoreId); + $apiCustomers->setMailchimpStoreId($mailchimpStoreId); + $apiCustomers->setMagentoStoreId($magentoStoreId); + + $customersArray = $apiCustomers->createBatchJson(); $customerAmount = count($customersArray); $batchArray['operations'] = $customersArray; + //product operations $helper->logBatchStatus('Generate Products Payload'); + $apiProducts = $this->getApiProducts(); - $productsArray = $apiProducts->createBatchJson($mailchimpStoreId, $magentoStoreId); + $apiProducts->setMailchimpStoreId($mailchimpStoreId); + $apiProducts->setMagentoStoreId($magentoStoreId); + + $productsArray = $apiProducts->createBatchJson(); $productAmount = count($productsArray); $batchArray['operations'] = array_merge($batchArray['operations'], $productsArray); - //cart operations - $helper->logBatchStatus('Generate Carts Payload'); - $apiCarts = $this->getApiCarts(); - $cartsArray = $apiCarts->createBatchJson($mailchimpStoreId, $magentoStoreId); - $batchArray['operations'] = array_merge($batchArray['operations'], $cartsArray); + + if ($helper->getMCIsSyncing($mailchimpStoreId, $magentoStoreId) === 1) { + $helper->logBatchStatus('No Carts will be synced until the store is completely synced'); + } else { + //cart operations + $helper->logBatchStatus('Generate Carts Payload'); + $apiCarts = $this->getApiCarts(); + $apiCarts->setMailchimpStoreId($mailchimpStoreId); + $apiCarts->setMagentoStoreId($magentoStoreId); + + $cartsArray = $apiCarts->createBatchJson(); + $batchArray['operations'] = array_merge($batchArray['operations'], $cartsArray); + } + //order operations $helper->logBatchStatus('Generate Orders Payload'); $apiOrders = $this->getApiOrders(); - $ordersArray = $apiOrders->createBatchJson($mailchimpStoreId, $magentoStoreId); + $apiOrders->setMailchimpStoreId($mailchimpStoreId); + $apiOrders->setMagentoStoreId($magentoStoreId); + + $ordersArray = $apiOrders->createBatchJson(); $orderAmount = count($ordersArray); $batchArray['operations'] = array_merge($batchArray['operations'], $ordersArray); + if ($helper->getPromoConfig($magentoStoreId) == self::SEND_PROMO_ENABLED) { //promo rule operations $helper->logBatchStatus('Generate Promo Rules Payload'); $apiPromoRules = $this->getApiPromoRules(); - $promoRulesArray = $apiPromoRules->createBatchJson($mailchimpStoreId, $magentoStoreId); + $apiPromoRules->setMailchimpStoreId($mailchimpStoreId); + $apiPromoRules->setMagentoStoreId($magentoStoreId); + + $promoRulesArray = $apiPromoRules->createBatchJson(); $batchArray['operations'] = array_merge($batchArray['operations'], $promoRulesArray); + //promo code operations $helper->logBatchStatus('Generate Promo Codes Payload'); $apiPromoCodes = $this->getApiPromoCodes(); - $promoCodesArray = $apiPromoCodes->createBatchJson($mailchimpStoreId, $magentoStoreId); + $apiPromoCodes->setMailchimpStoreId($mailchimpStoreId); + $apiPromoCodes->setMagentoStoreId($magentoStoreId); + + $promoCodesArray = $apiPromoCodes->createBatchJson(); $batchArray['operations'] = array_merge($batchArray['operations'], $promoCodesArray); } //deleted product operations - $deletedProductsArray = $apiProducts->createDeletedProductsBatchJson( - $mailchimpStoreId, - $magentoStoreId - ); + $helper->logBatchStatus('Generate Deleted Products Payload'); + $deletedProductsArray = $apiProducts->createDeletedProductsBatchJson(); $batchArray['operations'] = array_merge($batchArray['operations'], $deletedProductsArray); $batchJson = null; $batchResponse = null; @@ -369,6 +422,7 @@ public function _sendEcommerceBatch($magentoStoreId) $helper->logError($e->getMessage()); } catch (MailChimp_Error $e) { $helper->logError($e->getFriendlyMessage()); + if ($batchJson && !isset($batchResponse['id'])) { $helper->logRequest($batchJson); } @@ -389,9 +443,12 @@ public function _sendEcommerceBatch($magentoStoreId) * @param $batchArray * @param $mailchimpStoreId * @param $magentoStoreId + * @throws Ebizmarts_MailChimp_Helper_Data_ApiKeyException * @throws Mage_Core_Exception * @throws MailChimp_Error + * @throws MailChimp_HttpError */ + protected function _processBatchOperations($batchArray, $mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); @@ -401,17 +458,16 @@ protected function _processBatchOperations($batchArray, $mailchimpStoreId, $mage $batchJson = json_encode($batchArray); if ($batchJson === false) { - $helper->logRequest('Json encode error '.json_last_error_msg()); + $helper->logRequest('Json encode error ' . json_last_error_msg()); } elseif (empty($batchJson)) { $helper->logRequest('An empty operation was detected'); } else { + $helper->logBatchStatus('Send batch operation'); $batchResponse = $mailchimpApi->getBatchOperation()->add($batchJson); $helper->logRequest($batchJson, $batchResponse['id']); //save batch id to db $batch = $this->getSyncBatchesModel(); - $batch->setStoreId($mailchimpStoreId) - ->setBatchId($batchResponse['id']) - ->setStatus($batchResponse['status']); + $batch->setStoreId($mailchimpStoreId)->setBatchId($batchResponse['id'])->setStatus($batchResponse['status']); $batch->save(); $this->markItemsAsSent($batchResponse['id'], $mailchimpStoreId); $this->_showResumeEcommerce($batchResponse['id'], $magentoStoreId); @@ -433,21 +489,13 @@ protected function _updateSyncingFlag( $orderAmount, $mailchimpStoreId, $magentoStoreId - ) - { + ) { $helper = $this->getHelper(); $dateHelper = $this->getDateHelper(); $itemAmount = ($customerAmount + $productAmount + $orderAmount); $syncingFlag = $helper->getMCIsSyncing($mailchimpStoreId, $magentoStoreId); - if ($this->shouldFlagAsSyncing( - $magentoStoreId, - $syncingFlag, - $itemAmount, - $helper, - $mailchimpStoreId - ) - ) { + if ($this->shouldFlagAsSyncing($syncingFlag, $itemAmount, $helper)) { //Set is syncing per scope in 1 until sync finishes. $configValue = array( array(Ebizmarts_MailChimp_Model_Config::GENERAL_MCISSYNCING . "_$mailchimpStoreId", 1) @@ -598,6 +646,7 @@ protected function _sendSubscriberBatches() public function sendStoreSubscriberBatch($storeId, $limit) { $helper = $this->getHelper(); + try { if ($helper->isSubscriptionEnabled($storeId)) { $helper->resetCountersSubscribers(); @@ -614,8 +663,9 @@ public function sendStoreSubscriberBatch($storeId, $limit) if (!empty($batchArray['operations'])) { $batchJson = json_encode($batchArray); + if ($batchJson === false) { - $helper->logRequest('Json encode error '.json_last_error_msg()); + $helper->logRequest('Json encode error ' . json_last_error_msg()); } elseif ($batchJson == '') { $helper->logRequest('An empty operation was detected'); } else { @@ -631,6 +681,7 @@ public function sendStoreSubscriberBatch($storeId, $limit) ->setStatus($batchResponse['status']); $batch->save(); $this->_showResumeSubscriber($batchResponse['id'], $storeId); + return array($batchResponse, $limit); } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $helper->logError($e->getMessage()); @@ -658,34 +709,37 @@ public function sendStoreSubscriberBatch($storeId, $limit) public function getBatchResponse($batchId, $magentoStoreId) { $helper = $this->getHelper(); + $fileHelper = $this->getMailchimpFileHelper(); $files = array(); + try { $baseDir = $this->getMagentoBaseDir(); $api = $helper->getApi($magentoStoreId); + if ($api) { // check the status of the job $response = $api->batchOperation->status($batchId); + if (isset($response['status']) && $response['status'] == 'finished') { // get the tar.gz file with the results $fileUrl = urldecode($response['response_body_url']); $fileName = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '.tar.gz'; $fd = fopen($fileName, 'w'); - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $fileUrl); - curl_setopt($ch, CURLOPT_FILE, $fd); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects - $r = curl_exec($ch); + $curlOptions = array( + CURLOPT_RETURNTRANSFER => 1, + CURLOPT_FILE => $fd, + CURLOPT_FOLLOWLOCATION => true, // this will follow redirects + ); + + $curlHelper = $this->getMailchimpCurlHelper(); + $curlResult = $curlHelper->curlExec($fileUrl, Zend_Http_Client::GET, $curlOptions); - curl_close($ch); fclose($fd); - mkdir( - $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, - 0750, - true - ); + $fileHelper->mkDir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId, 0750, true); $archive = new Mage_Archive(); - if (file_exists($fileName)) { + + if ($fileHelper->fileExists($fileName)) { $files = $this->_unpackBatchFile($files, $batchId, $archive, $fileName, $baseDir); } } @@ -708,30 +762,27 @@ public function getBatchResponse($batchId, $magentoStoreId) /** * @param $files * @param $batchId - * @param $archive + * @param $archive Mage_Archive * @param $fileName * @param $baseDir * @return array */ protected function _unpackBatchFile($files, $batchId, $archive, $fileName, $baseDir) { - $archive->unpack($fileName, $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); - $archive->unpack( - $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar', - $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId - ); - $dir = scandir($baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId); - foreach ($dir as $d) { - $name = pathinfo($d); - if ($name['extension'] == 'json') { - $files[] = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $d; + $path = $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId; + $archive->unpack($fileName, $path); + $archive->unpack($path . DS . $batchId . '.tar', $path); + $fileHelper = $this->getMailchimpFileHelper(); + $dirItems = new DirectoryIterator($path); + + foreach ($dirItems as $index => $dirItem) { + + if ($dirItem->isFile() && $dirItem->getExtension() == 'json'){ + $files[] = $path . DS . $dirItem->getBasename(); } } - - unlink( - $baseDir . DS . 'var' . DS . 'mailchimp' . DS . $batchId . '/' . $batchId . '.tar' - ); - unlink($fileName); + $fileHelper->rm($path . DS . $batchId . '.tar'); + $fileHelper->rm($fileName); return $files; } @@ -747,26 +798,27 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, { $helper = $this->getHelper(); $helper->resetCountersDataSentToMailchimp(); + $fileHelper = $this->getMailchimpFileHelper(); foreach ($files as $file) { - $items = json_decode(file_get_contents($file)); + $fileContent = $fileHelper->read($file); + $items = json_decode($fileContent, true); if ($items !== false) { foreach ($items as $item) { - $line = explode('_', $item->operation_id); + $line = explode('_', $item['operation_id']); $store = explode('-', $line[0]); $type = $line[1]; $id = $line[3]; - if ($item->status_code != 200) { + if ($item['status_code'] != 200) { $mailchimpErrors = Mage::getModel('mailchimp/mailchimperrors'); - //parse error - $response = json_decode($item->response); + $response = json_decode($item['response'], true); $errorDetails = $this->_processFileErrors($response); if (strstr($errorDetails, 'already exists')) { - $this->setItemAsModified($helper, $mailchimpStoreId, $id, $type); + $this->setItemAsModified($mailchimpStoreId, $id, $type); $helper->modifyCounterDataSentToMailchimp($type); continue; } @@ -781,13 +833,13 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, 0, null, null, - null, + 0, true ); - $mailchimpErrors->setType($response->type); - $mailchimpErrors->setTitle($response->title); - $mailchimpErrors->setStatus($item->status_code); + $mailchimpErrors->setType($response['type']); + $mailchimpErrors->setTitle($response['title']); + $mailchimpErrors->setStatus($item['status_code']); $mailchimpErrors->setErrors($errorDetails); $mailchimpErrors->setRegtype($type); $mailchimpErrors->setOriginalId($id); @@ -802,7 +854,7 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, $helper->modifyCounterDataSentToMailchimp($type, true); $helper->logError($error); } else { - $syncDataItem = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); + $syncDataItem = $this->getDataProduct($mailchimpStoreId, $id, $type); if (!$syncDataItem->getMailchimpSyncModified()) { $syncModified = $this->enableMergeFieldsSending($type, $syncDataItem); @@ -825,9 +877,8 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, } } - unlink($file); + $fileHelper->rm($file); } - $this->_showResumeDataSentToMailchimp($magentoStoreId); } @@ -840,11 +891,10 @@ protected function processEachResponseFile($files, $batchId, $mailchimpStoreId, */ protected function _getError($type, $mailchimpStoreId, $id, $response) { - $error = $response->title . " : " . $response->detail; - $helper = $this->getHelper(); + $error = $response['title'] . " : " . $response['detail']; if ($type == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT) { - $dataProduct = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); + $dataProduct = $this->getDataProduct($mailchimpStoreId, $id, $type); $isProductDisabledInMagento = Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO; if ($dataProduct->getMailchimpSyncDeleted() @@ -865,17 +915,17 @@ protected function _processFileErrors($response) { $errorDetails = ""; - if (!empty($response->errors)) { - foreach ($response->errors as $error) { - if (isset($error->field) && isset($error->message)) { + if (!empty($response['errors'])) { + foreach ($response['errors'] as $error) { + if (isset($error['field']) && isset($error['message'])) { $errorDetails .= $errorDetails != "" ? " / " : ""; - $errorDetails .= $error->field . " : " . $error->message; + $errorDetails .= $error['field'] . " : " . $error['message']; } } } if ($errorDetails == "") { - $errorDetails = $response->detail; + $errorDetails = $response['detail']; } return $errorDetails; @@ -911,7 +961,7 @@ public function replaceAllOrders($initialTime, $magentoStoreId) $batchJson = json_encode($batchArray); if ($batchJson === false) { - $helper->logRequest('Json encode error: '.json_last_error_msg()); + $helper->logRequest('Json encode error: ' . json_last_error_msg()); } elseif ($batchJson == '') { $helper->logRequest('An empty operation was detected'); } else { @@ -942,16 +992,16 @@ public function replaceAllOrders($initialTime, $magentoStoreId) } /** - * @param $itemId - * @param $itemType - * @param $mailchimpStoreId - * @param null $syncDelta - * @param null $syncError - * @param int $syncModified - * @param null $syncDeleted - * @param null $token - * @param null $syncedFlag - * @param bool $saveOnlyIfexists + * @param $itemId + * @param $itemType + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param null $syncDeleted + * @param null $token + * @param null $syncedFlag + * @param bool $saveOnlyIfExists */ protected function saveSyncData( $itemId, @@ -963,14 +1013,15 @@ protected function saveSyncData( $syncDeleted = null, $token = null, $syncedFlag = null, - $saveOnlyIfexists = false - ) - { + $saveOnlyIfExists = false + ) { $helper = $this->getHelper(); + if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER) { $helper->updateSubscriberSyndData($itemId, $syncDelta, $syncError, 0, null); } else { - $helper->saveEcommerceSyncData( + $ecommerceSyncData = $this->getMailchimpEcommerceSyncDataModel(); + $ecommerceSyncData->saveEcommerceSyncData( $itemId, $itemType, $mailchimpStoreId, @@ -980,13 +1031,21 @@ protected function saveSyncData( $syncDeleted, $token, $syncedFlag, - $saveOnlyIfexists, + $saveOnlyIfExists, null, false ); } } + /** + * @return Ebizmarts_MailChimp_Model_Ecommercesyncdata + */ + protected function getMailchimpEcommerceSyncDataModel() + { + return Mage::getModel('mailchimp/ecommercesyncdata'); + } + /** * @param $storeId * @param $syncedDateArray @@ -1063,17 +1122,16 @@ public function handleSyncingValue($syncedDateArray) } /** - * @param $helper * @param $mailchimpStoreId * @param $id * @param $type */ - protected function setItemAsModified($helper, $mailchimpStoreId, $id, $type) + protected function setItemAsModified($mailchimpStoreId, $id, $type) { $isMarkedAsDeleted = null; if ($type == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT) { - $dataProduct = $this->getDataProduct($helper, $mailchimpStoreId, $id, $type); + $dataProduct = $this->getDataProduct($mailchimpStoreId, $id, $type); $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); $isProductDisabledInMagento = Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO; @@ -1121,19 +1179,14 @@ protected function setItemAsModified($helper, $mailchimpStoreId, $id, $type) } /** - * @param $magentoStoreId * @param $syncingFlag * @param $itemAmount * @param $helper - * @param $mailchimpStoreId * @return bool */ - protected function shouldFlagAsSyncing($magentoStoreId, $syncingFlag, $itemAmount, $helper, $mailchimpStoreId) + protected function shouldFlagAsSyncing($syncingFlag, $itemAmount, $helper) { - return $syncingFlag === null - && $itemAmount !== 0 - || $helper->validateDate($syncingFlag) - && $syncingFlag < $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId); + return $syncingFlag === null && $itemAmount !== 0 || $helper->validateDate($syncingFlag); } /** @@ -1147,15 +1200,14 @@ protected function shouldFlagAsSynced($syncingFlag, $itemAmount) } /** - * @param $helper * @param $mailchimpStoreId * @param $id * @param $type * @return Varien_Object */ - protected function getDataProduct($helper, $mailchimpStoreId, $id, $type) + protected function getDataProduct($mailchimpStoreId, $id, $type) { - return $helper->getEcommerceSyncDataItem($id, $type, $mailchimpStoreId); + return $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem($id, $type, $mailchimpStoreId); } /** @@ -1168,7 +1220,7 @@ protected function _showResumeEcommerce($batchId, $storeId) $helper = $this->getHelper(); $countersSentPerBatch = $helper->getCountersSentPerBatch(); - if (!empty($countersSentPerBatch) || $helper->getCountersSentPerBatch() != null) { + if (!empty($countersSentPerBatch) || $countersSentPerBatch != null) { $helper->logBatchStatus("Sent batch $batchId for Magento store $storeId"); $helper->logBatchQuantity($helper->getCountersSentPerBatch()); } else { @@ -1252,12 +1304,20 @@ protected function isFirstArrival(Varien_Object $syncDataItem) */ protected function enableMergeFieldsSending($type, Varien_Object $syncDataItem) { - $syncModified = 0 ; - if ($type == Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER - && $this->isFirstArrival($syncDataItem)) { + $syncModified = 0; + + if ($type == Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER && $this->isFirstArrival($syncDataItem)) { $syncModified = 1; } return $syncModified; } + + /** + * @return Ebizmarts_MailChimp_Helper_File + */ + protected function getMailchimpFileHelper() + { + return Mage::helper('mailchimp/file'); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php index 522e1da86..28d52781a 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -9,7 +9,7 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_Carts +class Ebizmarts_MailChimp_Model_Api_Carts extends Ebizmarts_MailChimp_Model_Api_ItemSynchronizer { const BATCH_LIMIT = 100; @@ -21,20 +21,34 @@ class Ebizmarts_MailChimp_Model_Api_Carts protected $_token = null; /** - * @param $mailchimpStoreId - * @param $magentoStoreId + * @var $_ecommerceQuotesCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Quote_Collection + */ + protected $_ecommerceQuotesCollection; + + + /** * @return array */ - public function createBatchJson($mailchimpStoreId, $magentoStoreId) + public function createBatchJson() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + + $this->_ecommerceQuotesCollection = $this->createEcommerceQuoteCollection(); + $this->_ecommerceQuotesCollection->setStoreId($magentoStoreId); + $this->_ecommerceQuotesCollection->setMailchimpStoreId($mailchimpStoreId); + $helper = $this->getHelper(); - $dateHelper = $this->getDateHelper(); + $oldStore = $helper->getCurrentStoreId(); + $helper->setCurrentStore($magentoStoreId); + $allCarts = array(); if (!$helper->isAbandonedCartEnabled($magentoStoreId)) { return $allCarts; } + $dateHelper = $this->getDateHelper(); $this->_firstDate = $helper->getAbandonedCartFirstDate($magentoStoreId); $this->setCounter(0); @@ -45,29 +59,31 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . '_' . $date ); + $resendTurn = $helper->getResendTurn($magentoStoreId); if (!$resendTurn) { // get all the carts converted in orders (must be deleted on mailchimp) - $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId)); + $allCarts = array_merge($allCarts, $this->_getConvertedQuotes()); // get all the carts modified but not converted in orders - $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId)); + $allCarts = array_merge($allCarts, $this->_getModifiedQuotes()); } // get new carts - $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId)); + $allCarts = array_merge($allCarts, $this->_getNewQuotes()); + $helper->setCurrentStore($oldStore); return $allCarts; } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) + public function _getConvertedQuotes() { - $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $batchId = $this->getBatchId(); $allCarts = array(); $convertedCarts = $this->getQuoteCollection(); @@ -75,26 +91,16 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) $convertedCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); $convertedCarts->addFieldToFilter('is_active', array('eq' => 0)); //join with mailchimp_ecommerce_sync_data table to filter by sync data. - $convertedCarts->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id " - . "AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') + $this->joinLeftEcommerceSyncData($convertedCarts); + // be sure that the quotes are already in mailchimp and not deleted limit the collection + $this->getEcommerceQuoteCollection()->addWhere( + $convertedCarts, "m4m.mailchimp_sync_deleted = 0", $this->getBatchLimitFromConfig() ); - // be sure that the quotes are already in mailchimp and not deleted - $convertedCarts->getSelect()->where("m4m.mailchimp_sync_deleted = 0"); - // limit the collection - $convertedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($convertedCarts as $cart) { $cartId = $cart->getEntityId(); // we need to delete all the carts associated with this email - $allCartsForEmail = $this->getAllCartsByEmail( - $cart->getCustomerEmail(), - $mailchimpStoreId, - $magentoStoreId - ); + $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail()); foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); @@ -107,15 +113,8 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) . $alreadySentCartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData( - $alreadySentCartId, - $mailchimpStoreId, - null, - null, - 0, - null, - 1 - ); + + $this->markSyncDataAsDeleted($alreadySentCartId); $this->setCounter($this->getCounter() + 1); } } @@ -126,15 +125,8 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData( - $cartId, - $mailchimpStoreId, - null, - null, - 0, - null, - 1 - ); + + $this->markSyncDataAsDeleted($cartId); $this->setCounter($this->getCounter() + 1); } @@ -142,14 +134,14 @@ public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) + public function _getModifiedQuotes() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $helper = $this->getHelper(); - $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); $batchId = $this->getBatchId(); $allCarts = array(); $modifiedCarts = $this->getQuoteCollection(); @@ -158,20 +150,12 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) // select carts for the current Magento store id $modifiedCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); //join with mailchimp_ecommerce_sync_data table to filter by sync data. - $modifiedCarts->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" - . Ebizmarts_MailChimp_Model_Config::IS_QUOTE - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') + $this->joinLeftEcommerceSyncData($modifiedCarts); + // be sure that the quotes are already in mailchimp and not deleted limited + $this->getEcommerceQuoteCollection()->addWhere( + $modifiedCarts, "m4m.mailchimp_sync_deleted = 0 AND m4m.mailchimp_sync_delta < updated_at", + $this->getBatchLimitFromConfig() ); - // be sure that the quotes are already in mailchimp and not deleted - $modifiedCarts->getSelect()->where( - "m4m.mailchimp_sync_deleted = 0 - AND m4m.mailchimp_sync_delta < updated_at" - ); - // limit the collection - $modifiedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($modifiedCarts as $cart) { $cartId = $cart->getEntityId(); @@ -180,14 +164,12 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) */ $customer = $this->getCustomerModel(); $customer->setWebsiteId($this->getWebSiteIdFromMagentoStoreId($magentoStoreId)); - $customer->loadByEmail($cart->getCustomerEmail()); + $cartCustomerEmail = $cart->getCustomerEmail(); + $customer->loadByEmail($cartCustomerEmail); - if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->getAllCartsByEmail( - $cart->getCustomerEmail(), - $mailchimpStoreId, - $magentoStoreId - ); + $customerEmail = $customer->getEmail(); + if ($customerEmail != $cartCustomerEmail) { + $allCartsForEmail = $this->getAllCartsByEmail($cartCustomerEmail); foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); @@ -201,16 +183,9 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) . $alreadySentCartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData( - $alreadySentCartId, - $mailchimpStoreId, - null, - null, - 0, - null, - 1 - ); - $this->setCounter($this->getCounter() + 1); + + $this->markSyncDataAsDeleted($cartId); + $this->setCounter($counter + 1); } } @@ -218,18 +193,18 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) } // avoid carts abandoned as guests when customer email associated to a registered customer. - if (!$cart->getCustomerId() && $customer->getEmail() == $cart->getCustomerEmail()) { - $this->_updateSyncData($cartId, $mailchimpStoreId); + if (!$cart->getCustomerId() && $customerEmail == $cartCustomerEmail) { + $this->addSyncData($cartId); continue; } // send the products that not already sent - $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts); - $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId, true); + $allCarts = $this->addProductNotSentData($cart, $allCarts); + $cartJson = $this->makeCart($cart, true); if ($cartJson !== false) { if (!empty($cartJson)) { - $this->getHelper()->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::QUO_MOD); + $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::QUO_MOD); $counter = $this->getCounter(); $allCarts[$counter]['method'] = 'PATCH'; @@ -237,39 +212,27 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; $allCarts[$counter]['body'] = $cartJson; $this->setCounter($this->getCounter() + 1); - $this->_updateSyncData( - $cartId, - $mailchimpStoreId, - null, - null, - 0, - null, - null, - $this->getToken() - ); + + $this->addSyncDataToken($cartId, $this->getToken()); } else { $error = $helper->__('There is not supported products in this cart.'); - - $this->_updateSyncData($cartId, $mailchimpStoreId, null, $error, 0); + $this->addSyncDataError($cartId, $error); } } else { $jsonErrorMessage = json_last_error_msg(); + $this->addSyncDataError($cartId, $jsonErrorMessage, $this->getToken()); - $this->_updateSyncData( - $cartId, - $mailchimpStoreId, - null, + //json encode failed + $this->logSyncError( $jsonErrorMessage, + Ebizmarts_MailChimp_Model_Config::IS_QUOTE, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', 0, - null, - null, - $this->getToken(), - false, - -1 + $cart->getId(), + 0 ); - - //json encode failed - $helper->logError("Carts " . $cart->getId() . " json encode failed (".$jsonErrorMessage.")"); } $this->setToken(null); @@ -279,13 +242,14 @@ public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array|mixed * @throws Mage_Core_Exception */ - public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) + public function _getNewQuotes() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $helper = $this->getHelper(); $dateHelper = $this->getDateHelper(); $batchId = $this->getBatchId(); @@ -303,38 +267,35 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) } //join with mailchimp_ecommerce_sync_data table to filter by sync data. - $this->joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId); + $this->joinLeftEcommerceSyncData($newCarts); // be sure that the quotes are already in mailchimp and not deleted - $newCarts->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); - // limit the collection - $newCarts->getSelect()->limit($this->getBatchLimitFromConfig()); + $this->getEcommerceQuoteCollection()->addWhere( + $newCarts, "m4m.mailchimp_sync_delta IS NULL", $this->getBatchLimitFromConfig() + ); foreach ($newCarts as $cart) { $cartId = $cart->getEntityId(); $orderCollection = $this->getOrderCollection(); + $cartCustomerEmail = $cart->getCustomerEmail(); $orderCollection->addFieldToFilter( - 'main_table.customer_email', - array('eq' => $cart->getCustomerEmail()) + 'main_table.customer_email', array('eq' => $cartCustomerEmail) ); $orderCollection->addFieldToFilter('main_table.updated_at', array('from' => $cart->getUpdatedAt())); //if cart is empty or customer has an order made after the abandonment skip current cart. $allVisibleItems = $cart->getAllVisibleItems(); if (empty($allVisibleItems) || $orderCollection->getSize()) { - $this->_updateSyncData($cartId, $mailchimpStoreId); + $this->addSyncData($cartId); continue; } $customer = $this->getCustomerModel(); $customer->setWebsiteId($this->getWebSiteIdFromMagentoStoreId($magentoStoreId)); - $customer->loadByEmail($cart->getCustomerEmail()); + $customer->loadByEmail($cartCustomerEmail); + $customerEmail = $customer->getEmail(); - if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->getAllCartsByEmail( - $cart->getCustomerEmail(), - $mailchimpStoreId, - $magentoStoreId - ); + if ($customerEmail != $cartCustomerEmail) { + $allCartsForEmail = $this->getAllCartsByEmail($cartCustomerEmail); foreach ($allCartsForEmail as $cartForEmail) { $counter = $this->getCounter(); @@ -346,30 +307,23 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) . $alreadySentCartId; $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; $allCarts[$counter]['body'] = ''; - $this->_updateSyncData( - $alreadySentCartId, - $mailchimpStoreId, - null, - null, - 0, - null, - 1 - ); - $this->setCounter($this->getCounter() + 1); + + $this->markSyncDataAsDeleted($alreadySentCartId); + $this->setCounter($counter + 1); } $allCartsForEmail->clear(); } // don't send the carts for guest customers who are registered - if (!$cart->getCustomerId() && $customer->getEmail() == $cart->getCustomerEmail()) { - $this->_updateSyncData($cartId, $mailchimpStoreId); + if (!$cart->getCustomerId() && $customerEmail == $cartCustomerEmail) { + $this->addSyncData($cartId); continue; } // send the products that not already sent - $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts); - $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); + $allCarts = $this->addProductNotSentData($cart, $allCarts); + $cartJson = $this->makeCart($cart); if ($cartJson !== false) { if (!empty($cartJson)) { @@ -381,38 +335,41 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; $allCarts[$counter]['body'] = $cartJson; $this->setCounter($this->getCounter() + 1); - $this->_updateSyncData( - $cartId, - $mailchimpStoreId, - null, - null, - 0, - null, - null, - $this->getToken() - ); + + $this->addSyncDataToken($cartId, $this->getToken()); } else { $error = $helper->__('There is not supported products in this cart.'); - $this->_updateSyncData( - $cartId, $mailchimpStoreId, $dateHelper->getCurrentDateTime(), - $error, 0 + + $this->addSyncDataError( + $cartId, + $error, + null, + false, + $dateHelper->getCurrentDateTime() ); } } else { $jsonErrorMessage = json_last_error_msg(); - $this->_updateSyncData( - $cartId, $mailchimpStoreId, - $dateHelper->getCurrentDateTime(), + + $this->addSyncDataError( + $cartId, $jsonErrorMessage, - 0, - null, - null, null, false, - -1 + $dateHelper->getCurrentDateTime() ); + //json encode failed - $helper->logError("Carts " . $cart->getId() . " json encode failed (".$jsonErrorMessage.")"); + $this->logSyncError( + $jsonErrorMessage, + Ebizmarts_MailChimp_Model_Config::IS_QUOTE, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $cart->getId(), + 0 + ); } $this->setToken(null); @@ -425,42 +382,36 @@ public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) * Get all existing carts in the current store view for a given email address. * * @param $email - * @param $mailchimpStoreId - * @param $magentoStoreId * @return object */ - public function getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) + public function getAllCartsByEmail($email) { - $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); $allCartsForEmail = $this->getQuoteCollection(); $allCartsForEmail->addFieldToFilter('is_active', array('eq' => 1)); - $allCartsForEmail->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + $allCartsForEmail->addFieldToFilter('store_id', array('eq' => $this->getMagentoStoreId())); $allCartsForEmail->addFieldToFilter('customer_email', array('eq' => $email)); - $allCartsForEmail->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" - . Ebizmarts_MailChimp_Model_Config::IS_QUOTE - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + $this->joinLeftEcommerceSyncData($allCartsForEmail); // be sure that the quotes are already in mailchimp and not deleted - $allCartsForEmail->getSelect()->where( - "m4m.mailchimp_sync_deleted = 0 " - . "AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'" - ); + $where = "m4m.mailchimp_sync_deleted = 0 " + . "AND m4m.mailchimp_store_id = '" + . $this->getMailchimpStoreId() . "'"; + $this->getEcommerceQuoteCollection()->addWhere($allCartsForEmail, $where); return $allCartsForEmail; } /** * @param $cart - * @param $magentoStoreId * @param $isModified * @return string */ - public function _makeCart($cart, $mailchimpStoreId, $magentoStoreId, $isModified = false) + public function makeCart($cart, $isModified = false) { + $magentoStoreId = $this->getMagentoStoreId(); + $apiProduct = $this->getApiProducts(); + $apiProduct->setMagentoStoreId($magentoStoreId); + $campaignId = $cart->getMailchimpCampaignId(); $oneCart = array(); $oneCart['id'] = $cart->getEntityId(); @@ -481,9 +432,7 @@ public function _makeCart($cart, $mailchimpStoreId, $magentoStoreId, $isModified $oneCart['order_total'] = $cart->getGrandTotal(); $oneCart['tax_total'] = 0; // get all items on the cart - $lines = $this->_processCartLines( - $cart->getAllVisibleItems(), $mailchimpStoreId, $magentoStoreId, $apiProduct - ); + $lines = $this->_processCartLines($cart->getAllVisibleItems(), $apiProduct); $jsonData = ""; @@ -498,21 +447,22 @@ public function _makeCart($cart, $mailchimpStoreId, $magentoStoreId, $isModified /** * @param $items - * @param $mailchimpStoreId - * @param $magentoStoreId - * @param $apiProduct + * @param $apiProduct Ebizmarts_MailChimp_Model_Api_Products * @return array */ - protected function _processCartLines($items, $mailchimpStoreId, $magentoStoreId, $apiProduct) + protected function _processCartLines($items, $apiProduct) { - $helper = $this->getHelper(); + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $lines = array(); $itemCount = 0; foreach ($items as $item) { $productId = $item->getProductId(); $isTypeProduct = $this->isTypeProduct(); - $productSyncData = $helper->getEcommerceSyncDataItem($productId, $isTypeProduct, $mailchimpStoreId); + $productSyncData = $this->getMailchimpEcommerceSyncDataModel() + ->getEcommerceSyncDataItem($productId, $isTypeProduct, $mailchimpStoreId); $line = array(); if ($item->getProductType() == 'bundle' || $item->getProductType() == 'grouped') { @@ -550,7 +500,7 @@ protected function _processCartLines($items, $mailchimpStoreId, $magentoStoreId, if (!$isProductEnabled) { // update disabled products to remove the product from mailchimp after sending the order - $apiProduct->updateDisabledProducts($productId, $mailchimpStoreId); + $apiProduct->updateDisabledProducts($productId); } } } @@ -568,7 +518,7 @@ protected function _processCartLines($items, $mailchimpStoreId, $magentoStoreId, protected function _getCheckoutUrl($cart, $isModified) { if (!$isModified) { - $token = md5(rand(0, 9999999)); + $token = hash('md5', rand(0, 9999999)); } else { $token = $cart->getMailchimpToken(); } @@ -588,7 +538,7 @@ protected function _getCheckoutUrl($cart, $isModified) protected function getBatchLimitFromConfig() { $helper = $this->getHelper(); - return $helper->getCustomerAmountLimit(); + return $helper->getCartAmountLimit(); } /** @@ -601,7 +551,7 @@ protected function getBatchLimitFromConfig() public function _getCustomer($cart, $magentoStoreId) { $customer = array( - "id" => md5(strtolower($cart->getCustomerEmail())), + "id" => hash('md5', strtolower($cart->getCustomerEmail())), "email_address" => $cart->getCustomerEmail(), "opt_in_status" => $this->getApiCustomersOptIn($magentoStoreId) ); @@ -679,100 +629,34 @@ protected function _addBillingAddress($address, $billingAddress) } /** - * @param $cartId - * @param $mailchimpStoreId - * @param null $syncDelta - * @param null $syncError - * @param int $syncModified - * @param null $syncedFlag - * @param null $syncDeleted - * @param null $token - * @param bool $saveOnlyIfExists - * @param bool $allowBatchRemoval - */ - protected function _updateSyncData( - $cartId, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncedFlag = null, - $syncDeleted = null, - $token = null, - $saveOnlyIfExists = false, - $allowBatchRemoval = true - ) { - $helper = $this->getHelper(); - $helper->saveEcommerceSyncData( - $cartId, - Ebizmarts_MailChimp_Model_Config::IS_QUOTE, - $mailchimpStoreId, - $syncDelta, - $syncError, - $syncModified, - $syncDeleted, - $token, - $syncedFlag, - $saveOnlyIfExists, - null, - $allowBatchRemoval - ); - } - - /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @param $cart * @param $allCarts * @return mixed */ - public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts) + public function addProductNotSentData($cart, $allCarts) { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $helper = $this->getHelper(); - $productData = $this->getApiProducts()->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId); + $apiProducts = $this->getApiProducts(); + $apiProducts->setMailchimpStoreId($mailchimpStoreId); + $apiProducts->setMagentoStoreId($magentoStoreId); + + $productData = $apiProducts->sendModifiedProduct($cart); $productDataArray = $helper->addEntriesToArray($allCarts, $productData, $this->getCounter()); $allCarts = $productDataArray[0]; $this->setCounter($productDataArray[1]); - return $allCarts; - } - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function getHelper() - { - return Mage::helper('mailchimp'); - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function getDateHelper() - { - return Mage::helper('mailchimp/date'); - } - - /** - * @param $newCarts - * @param $mailchimpStoreId - */ - public function joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId) - { - $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); - $newCarts->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + return $allCarts; } /** - * @return mixed + * @param Mage_Sales_Model_Resource_Quote_Collection $preFilteredCollection */ - public function getMailchimpEcommerceDataTableName() + public function joinLeftEcommerceSyncData($preFilteredCollection) { - return Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $this->_ecommerceQuotesCollection->joinLeftEcommerceSyncData($preFilteredCollection); } /** @@ -907,10 +791,39 @@ protected function isTypeProduct() } /** - * @return false|Mage_Core_Model_Abstract + * @return Ebizmarts_MailChimp_Model_Api_Products */ protected function getApiProducts() { return Mage::getModel('mailchimp/api_products'); } + + /** + * @return string + */ + protected function getItemType() + { + return Ebizmarts_MailChimp_Model_Config::IS_QUOTE; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Quote_Collection + */ + public function createEcommerceQuoteCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Quote_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_quote_collection'); + + return $collection; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Quote_Collection + */ + public function getEcommerceQuoteCollection() + { + return $this->_ecommerceQuotesCollection; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index dc6bb10cf..e0994e298 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -10,15 +10,10 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_Customers +class Ebizmarts_MailChimp_Model_Api_Customers extends Ebizmarts_MailChimp_Model_Api_ItemSynchronizer { const BATCH_LIMIT = 100; - /** - * @var Ebizmarts_MailChimp_Helper_Data - */ - protected $_mailchimpHelper; - protected $_mailchimpDateHelper; protected $_optInConfiguration; protected $_optInStatusForStore; protected $_locale; @@ -27,10 +22,15 @@ class Ebizmarts_MailChimp_Model_Api_Customers protected $_mailchimpStoreId; protected $_batchId; + /** + * @var $_ecommerceCustomersCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Customers_Collection + */ + protected $_ecommerceCustomersCollection; + public function __construct() { - $this->_mailchimpHelper = $this->makeHelper(); - $this->_mailchimpDateHelper = $this->makeDateHelper(); + parent::__construct(); + $this->_optInConfiguration = array(); $this->_locale = Mage::app()->getLocale(); $this->_directoryRegionModel = Mage::getModel('directory/region'); @@ -79,19 +79,25 @@ public function makeCustomersNotSentCollection($customerIdsToSync) } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array * @throws Mage_Core_Exception */ - public function createBatchJson($mailchimpStoreId, $magentoStoreId) + public function createBatchJson() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + + $this->_ecommerceCustomersCollection = $this->createEcommerceCustomersCollection(); + $this->_ecommerceCustomersCollection->setMailchimpStoreId($mailchimpStoreId); + $this->_ecommerceCustomersCollection->setStoreId($magentoStoreId); + $this->setMailchimpStoreId($mailchimpStoreId); $this->setMagentoStoreId($magentoStoreId); - $helper = $this->getMailChimpHelper(); + $helper = $this->getHelper(); $customersCollection = array(); $customerIds = $this->getCustomersToSync(); + if (!empty($customerIds)) { $customersCollection = $this->makeCustomersNotSentCollection($customerIds); } @@ -101,8 +107,8 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) $this->setOptInStatusForStore($this->getOptIn($this->getBatchMagentoStoreId())); $subscriber = $this->getSubscriberModel(); $listId = $helper->getGeneralList($magentoStoreId); - $counter = 0; + foreach ($customersCollection as $customer) { $data = $this->_buildCustomerData($customer); $customerJson = json_encode($data); @@ -110,20 +116,15 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) if (false !== $customerJson) { if (!empty($customerJson)) { $isSubscribed = $this->isSubscribed($subscriber, $customer); - $dataCustomer = $helper->getEcommerceSyncDataItem( + $dataCustomer = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $customer->getId(), Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId ); - $this->incrementCounterSentPerBatch( - $dataCustomer, - $helper - ); + $this->incrementCounterSentPerBatch($dataCustomer, $helper); $customerArray[$counter] = $this->makePutBatchStructure($customerJson, $customer); - $this->_updateSyncData( - $customer->getId(), $mailchimpStoreId, null, null, 0, null - ); + $this->addSyncData($customer->getId()); $counter++; if (!$isSubscribed) { @@ -143,22 +144,22 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) } } } else { - $this->_updateSyncData( - $customer->getId(), $mailchimpStoreId, - $this->getMailChimpDateHelper()->getCurrentDateTime(), 'Customer with no data', 0 + $this->addSyncDataError( + $customer->getId(), + 'Customer with no data', + null, + false, + $this->getDateHelper()->getCurrentDateTime() ); } } else { $jsonErrorMessage = $this->logCouldNotEncodeCustomerError($customer); - $this->_updateSyncData( + $this->addSyncDataError( $customer->getId(), - $mailchimpStoreId, - $this->getMailChimpDateHelper()->getCurrentDateTime(), $jsonErrorMessage, - 0, null, false, - -1 + $this->getDateHelper()->getCurrentDateTime() ); } } @@ -228,7 +229,7 @@ protected function makePutBatchStructure($customerJson, $customer) protected function _buildCustomerData($customer) { $data = array(); - $data["id"] = md5(strtolower($this->getCustomerEmail($customer))); + $data["id"] = hash('md5', strtolower($this->getCustomerEmail($customer))); $data["email_address"] = $this->getCustomerEmail($customer); $data["first_name"] = $this->getCustomerFirstname($customer); $data["last_name"] = $this->getCustomerLastname($customer); @@ -251,8 +252,8 @@ protected function getCustomerAddressData($customer) { $data = array(); $customerAddress = array(); - $street = explode("\n", $customer->getStreet()); + if (count($street) > 1) { $customerAddress["address1"] = $street[0]; $customerAddress["address2"] = $street[1]; @@ -272,6 +273,7 @@ protected function getCustomerAddressData($customer) if ($customer->getRegionId()) { $customerAddress["province_code"] = $this->_directoryRegionModel->load($customer->getRegionId())->getCode(); + if (!$customerAddress["province_code"]) { unset($customerAddress["province_code"]); } @@ -308,10 +310,9 @@ protected function getCountryNameByCode($countryCode) * @param $customerId * @param $storeId */ - public function update($customerId, $storeId) + public function update($customerId) { - $mailchimpStoreId = $this->_mailchimpHelper->getMCStoreId($storeId); - $this->_updateSyncData($customerId, $mailchimpStoreId, null, null, 1, null, true, false); + $this->markSyncDataAsModified($customerId); } /** @@ -338,52 +339,14 @@ protected function getOptInConfiguration($magentoStoreId) return $this->_optInConfiguration[$magentoStoreId]; } - /** - * update customer sync data - * - * @param int $customerId - * @param string $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncedFlag - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval - */ - protected function _updateSyncData( - $customerId, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncedFlag = null, - $saveOnlyIfexists = false, - $allowBatchRemoval = true - ) { - $this->_mailchimpHelper->saveEcommerceSyncData( - $customerId, - Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, - $mailchimpStoreId, - $syncDelta, - $syncError, - $syncModified, - null, - null, - $syncedFlag, - $saveOnlyIfexists, - null, - $allowBatchRemoval - ); - } - /** * @return void */ protected function makeBatchId() { $this->_batchId = "storeid-{$this->getBatchMagentoStoreId()}_"; - $this->_batchId .= Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER . '_'; - $this->_batchId .= $this->_mailchimpDateHelper->getDateMicrotime(); + $this->_batchId .= $this->getItemType() . '_'; + $this->_batchId .= $this->getDateHelper()->getDateMicrotime(); } /** @@ -401,31 +364,11 @@ protected function joinDefaultBillingAddress($collection) } /** - * @param $collection + * @param $collection Mage_Customer_Model_Resource_Customer_Collection */ protected function joinMailchimpSyncData($collection) { - $joinCondition = "m4m.related_id = e.entity_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; - $mailchimpTableName = $this->getSyncdataTableName(); - - $collection->getSelect()->joinLeft( - array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $this->_mailchimpStoreId), - array() - ); - - $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1"); - } - - /** - * @return string - */ - public function getSyncDataTableName() - { - $mailchimpTableName = Mage::getSingleton('core/resource') - ->getTableName('mailchimp/ecommercesyncdata'); - - return $mailchimpTableName; + $this->_ecommerceCustomersCollection->joinLeftEcommerceSyncData($collection); } /** @@ -435,7 +378,7 @@ public function getSyncDataTableName() */ protected function isEcommerceCustomerOptInConfigEnabled($magentoStoreId) { - $configValue = $this->_mailchimpHelper->getConfigValueForScope( + $configValue = $this->getHelper()->getConfigValueForScope( Ebizmarts_MailChimp_Model_Config::ECOMMERCE_CUSTOMERS_OPTIN, $magentoStoreId ); @@ -459,7 +402,7 @@ protected function checkEcommerceOptInConfigAndUpdateStorage($magentoStoreId) */ protected function getBatchLimitFromConfig() { - $helper = $this->_mailchimpHelper; + $helper = $this->getHelper(); return $helper->getCustomerAmountLimit(); } @@ -497,9 +440,16 @@ protected function getCustomerLastname($customer) protected function logCouldNotEncodeCustomerError($customer) { $jsonErrorMessage = json_last_error_msg(); - $this->_mailchimpHelper->logError( - "Customer " . $customer->getId() . " json encode failed (".$jsonErrorMessage.") on store " - . $this->getBatchMagentoStoreId() + + $this->logSyncError( + $jsonErrorMessage, + Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, + ($customer->getStoreId() === 0) ? $customer->getMailchimpStoreView() : $customer->getStoreId(), + 'magento_side_error', + 'Json Encode Failure', + 0, + $customer->getId(), + 0 ); return $jsonErrorMessage; } @@ -510,19 +460,31 @@ protected function logCouldNotEncodeCustomerError($customer) */ protected function logCouldNotEncodeMailchimpTags($customer, $mailchimpTags) { - $this->_mailchimpHelper->logError( - "MailChimp tags encode failed, Customer " . $customer->getId() . " on store " . - $this->getBatchMagentoStoreId()." mergeFields:" + $jsonErrorMessage = json_last_error_msg(); + + $this->logSyncError( + $jsonErrorMessage, + Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, + ($customer->getStoreId() === 0) ? $customer->getMailchimpStoreView() : $customer->getStoreId(), + 'magento_side_error', + 'Json Encode Failure', + 0, + $customer->getId(), + 0 ); - $this->_mailchimpHelper->logError($mailchimpTags); } /** - * @return Object + * @return Mage_Customer_Model_Resource_Customer_Collection */ protected function getCustomerResourceCollection() { - return Mage::getResourceModel('customer/customer_collection'); + /** + * @var $collection Mage_Customer_Model_Resource_Customer_Collection + */ + $collection = Mage::getResourceModel('customer/customer_collection'); + + return $collection; } /** @@ -533,48 +495,6 @@ protected function getBatchMagentoStoreId() return $this->_magentoStoreId; } - /** - * @param $collection - * @param null $mailchimpStoreId - */ - public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId = null) - { - if (!$mailchimpStoreId) { - $mailchimpStoreId = $this->_mailchimpStoreId; - } - - $joinCondition = "m4m.related_id = e.entity_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; - $mailchimpTableName = $this->getSyncDataTableName(); - - $collection->getSelect()->joinLeft( - array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $mailchimpStoreId), - array( - "m4m.related_id", - "m4m.type", - "m4m.mailchimp_store_id", - "m4m.mailchimp_sync_delta", - "m4m.mailchimp_sync_modified" - ) - ); - } - - /** - * @param $mailchimpStoreId - */ - protected function setMailchimpStoreId($mailchimpStoreId) - { - $this->_mailchimpStoreId = $mailchimpStoreId; - } - - /** - * @param $magentoStoreId - */ - protected function setMagentoStoreId($magentoStoreId) - { - $this->_magentoStoreId = $magentoStoreId; - } - /** * @return false|Mage_Core_Model_Abstract */ @@ -584,38 +504,6 @@ protected function getSubscriberModel() return $subscriber; } - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function makeHelper() - { - return Mage::helper('mailchimp'); - } - - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function getMailChimpHelper() - { - return $this->_mailchimpHelper; - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function makeDateHelper() - { - return Mage::helper('mailchimp/date'); - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function getMailChimpDateHelper() - { - return $this->_mailchimpDateHelper; - } - /** * @param $customer * @param $listId @@ -631,10 +519,10 @@ protected function makePatchBatchStructure($customer, $listId, $mergeFields) if ($mergeFieldJSON === false) { $this->logCouldNotEncodeMailchimpTags($customer, $mergeFields); } else { - $md5HashEmail = md5(strtolower($customer->getEmail())); + $hashedEmail = hash('md5', strtolower($customer->getEmail())); $batchData = array(); $batchData['method'] = "PATCH"; - $batchData['path'] = "/lists/" . $listId . "/members/" . $md5HashEmail; + $batchData['path'] = "/lists/" . $listId . "/members/" . $hashedEmail; $batchData['operation_id'] = "{$this->_batchId}_{$customerId}_SUB"; $batchData['body'] = $mergeFieldJSON; } @@ -650,7 +538,7 @@ protected function makePatchBatchStructure($customer, $listId, $mergeFields) protected function isSubscribed($subscriber, $customer) { if ($subscriber->loadByEmail($customer->getEmail())->getSubscriberId() - && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED ) { + && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED) { return true; } else { return false; @@ -726,13 +614,13 @@ protected function incrementCounterSentPerBatch( /** * Send merge fields for transactional members * - * @param $magentoStoreId + * @param $magentoStoreId * @param Varien_Object $dataCustomer - * @param $subscriber - * @param $customer - * @param $listId - * @param $counter - * @param array $customerArray + * @param $subscriber + * @param $customer + * @param $listId + * @param $counter + * @param array $customerArray * @return array */ protected function sendMailchimpTags( @@ -749,8 +637,7 @@ protected function sendMailchimpTags( $magentoStoreId, $subscriber, $customer, - $listId, - $counter + $listId ); if ($batchData !== null) { @@ -762,4 +649,33 @@ protected function sendMailchimpTags( return array($customerArray, $counter); } + /** + * @return string + */ + protected function getItemType() + { + return Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Customers_Collection + */ + public function getEcommerceCustomersCollection() + { + return $this->getEcommerceCustomersCollection(); + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Customers_Collection + */ + public function createEcommerceCustomersCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Customers_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_customers_collection'); + + return $collection; + } + } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/ItemSynchronizer.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/ItemSynchronizer.php new file mode 100755 index 000000000..f471b46f2 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/ItemSynchronizer.php @@ -0,0 +1,321 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + */ +class Ebizmarts_MailChimp_Model_Api_ItemSynchronizer +{ + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $_mailchimpHelper; + + /** + * @var Ebizmarts_MailChimp_Helper_Date + */ + protected $_mailchimpDateHelper; + + /** + * @return mixed + */ + public function getMailchimpStoreId() + { + return $this->_mailchimpStoreId; + } + + /** + * @param mixed $mailchimpStoreId + */ + public function setMailchimpStoreId($mailchimpStoreId) + { + $this->_mailchimpStoreId = $mailchimpStoreId; + } + + protected $_mailchimpStoreId; + + protected $_magentoStoreId; + + /** + * @return mixed + */ + public function getMagentoStoreId() + { + return $this->_magentoStoreId; + } + + /** + * @param mixed $magentoStoreId + */ + public function setMagentoStoreId($magentoStoreId) + { + $this->_magentoStoreId = $magentoStoreId; + } + + public function __construct() + { + $this->_mailchimpHelper = Mage::helper('mailchimp'); + $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); + } + + /** + * @param $id + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param null $syncedFlag + * @param null $syncDeleted + * @param null $token + * @param bool $saveOnlyIfExists + * @param bool $allowBatchRemoval + * @param int $deletedRelatedId + */ + protected function _updateSyncData( + $id, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncDeleted = null, + $syncedFlag = null, + $token = null, + $saveOnlyIfExists = false, + $allowBatchRemoval = true, + $deletedRelatedId = null + ) { + $type = $this->getItemType(); + + if (!empty($type)) { + $ecommerceSyncData = $this->getMailchimpEcommerceSyncDataModel(); + $ecommerceSyncData->saveEcommerceSyncData( + $id, + $type, + $this->getMailchimpStoreId(), + $syncDelta, + $syncError, + $syncModified, + $syncDeleted, + $token, + $syncedFlag, + $saveOnlyIfExists, + $deletedRelatedId, + $allowBatchRemoval + ); + } + } + + protected function addDeletedRelatedId($id, $relatedId) + { + $this->_updateSyncData( + $id, + null, + null, + 0, + 1, + null, + null, + true, + false, + $relatedId + ); + } + + protected function addSyncDataError( + $id, + $error, + $token = null, + $saveOnlyIfExists = false, + $syncDelta = null + ) { + $type = $this->getItemType(); + + $this->logSyncError( + $error, + $type, + $this->getMagentoStoreId(), + 'magento_side_error', + 'Invalid Magento Resource', + 0, + $id, + 0 + ); + + $this->_updateSyncData( + $id, + $syncDelta, + $error, + 0, + null, + 0, + $token, + $saveOnlyIfExists, + -1 + ); + } + + protected function addSyncData($id) + { + $this->_updateSyncData($id); + } + + protected function addSyncDataToken($id, $token) + { + $this->_updateSyncData( + $id, + null, + null, + 0, + null, + null, + $token + ); + } + + protected function markSyncDataAsModified($id) + { + $this->_updateSyncData($id, null, null, 1); + } + + protected function markSyncDataAsDeleted($id, $syncedFlag = null) + { + $this->_updateSyncData( + $id, + null, + null, + 0, + 1, + $syncedFlag + ); + } + + /** + * @param $error + * @param $type + * @param $title + * @param $status + * @param $originalId + * @param $batchId + * @param $storeId + * @param $regType + */ + protected function logSyncError( + $error, + $regType, + $storeId, + $type, + $title, + $status, + $originalId, + $batchId + ) { + $this->getHelper()->logError($error); + + try { + $this->_logMailchimpError( + $error, $type, $title, + $status, $originalId, $batchId, $storeId, $regType + ); + } catch (Exception $e) { + $this->getHelper()->logError($e->getMessage()); + } + } + + /** + * @param $error + * @param $type + * @param $title + * @param $status + * @param $originalId + * @param $batchId + * @param $storeId + * @param $regType + * + * @throws Exception + */ + protected function _logMailchimpError( + $error, + $type, + $title, + $status, + $originalId, + $batchId, + $storeId, + $regType + ) { + $mailchimpErrors = Mage::getModel('mailchimp/mailchimperrors'); + + $mailchimpErrors->setType($type); + $mailchimpErrors->setTitle($title); + $mailchimpErrors->setStatus($status); + $mailchimpErrors->setErrors($error); + $mailchimpErrors->setRegtype($regType); + $mailchimpErrors->setOriginalId($originalId); + $mailchimpErrors->setBatchId($batchId); + $mailchimpErrors->setStoreId($storeId); + $mailchimpErrors->setMailchimpStoreId($this->getMailchimpStoreId()); + + $mailchimpErrors->save(); + } + + /** + * @return Ebizmarts_MailChimp_Helper_Data + */ + protected function getHelper() + { + return $this->_mailchimpHelper; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Date + */ + protected function getDateHelper() + { + return $this->_mailchimpDateHelper; + } + + /** + * @return mixed + */ + public function getMailchimpEcommerceDataTableName() + { + return $this->getCoreResource() + ->getTableName('mailchimp/ecommercesyncdata'); + } + + /** + * @return Ebizmarts_MailChimp_Model_Ecommercesyncdata + */ + public function getMailchimpEcommerceSyncDataModel() + { + return new Ebizmarts_MailChimp_Model_Ecommercesyncdata(); + } + + /** + * @param $magentoStoreId + * @return mixed + */ + public function getWebSiteIdFromMagentoStoreId($magentoStoreId) + { + return Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId(); + } + + /** + * @return Mage_Core_Model_Resource + */ + public function getCoreResource() + { + return Mage::getSingleton('core/resource'); + } + + /** + * @return string + */ + protected function getItemType() + { + return null; + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index 6af6e227d..b9757e8fe 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -9,9 +9,8 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_Orders +class Ebizmarts_MailChimp_Model_Api_Orders extends Ebizmarts_MailChimp_Model_Api_ItemSynchronizer { - const BATCH_LIMIT = 50; const BATCH_LIMIT_ONLY_ORDERS = 500; const PAID = 'paid'; @@ -22,25 +21,37 @@ class Ebizmarts_MailChimp_Model_Api_Orders const REFUNDED = 'refunded'; const PARTIALLY_REFUNDED = 'partially_refunded'; const CANCELED = 'canceled'; - const COMPLETE = 'complete'; protected $_firstDate; protected $_counter; protected $_batchId; protected $_api = null; protected $_listsCampaignIds = array(); + /** + * @var $_ecommerceOrdersCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Orders_Collection + */ + protected $_ecommerceOrdersCollection; + /** * Set the request for orders to be created on MailChimp * - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array * @throws Mage_Core_Exception */ - public function createBatchJson($mailchimpStoreId, $magentoStoreId) + public function createBatchJson() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + + $this->_ecommerceOrdersCollection = $this->createEcommerceOrdersCollection(); + $this->_ecommerceOrdersCollection->setMailchimpStoreId($mailchimpStoreId); + $this->_ecommerceOrdersCollection->setStoreId($magentoStoreId); + $helper = $this->getHelper(); $dateHelper = $this->getDateHelper(); + $oldStore = $helper->getCurrentStoreId(); + $helper->setCurrentStore($magentoStoreId); + $batchArray = array(); $this->_firstDate = $helper->getEcommerceFirstDate($magentoStoreId); $this->_counter = 0; @@ -52,50 +63,48 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) if (!$resendTurn) { // get all the orders modified - $batchArray = array_merge($batchArray, $this->_getModifiedOrders($mailchimpStoreId, $magentoStoreId)); + $batchArray = array_merge($batchArray, $this->_getModifiedOrders()); } // get new orders - $batchArray = array_merge($batchArray, $this->_getNewOrders($mailchimpStoreId, $magentoStoreId)); + $batchArray = array_merge($batchArray, $this->_getNewOrders()); + $helper->setCurrentStore($oldStore); return $batchArray; } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) + protected function _getModifiedOrders() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $helper = $this->getHelper(); $dateHelper = $this->getDateHelper(); - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); $batchArray = array(); $modifiedOrders = $this->getResourceModelOrderCollection(); // select orders for the current Magento store id $modifiedOrders->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); //join with mailchimp_ecommerce_sync_data table to filter by sync data. - $modifiedOrders->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" - . Ebizmarts_MailChimp_Model_Config::IS_ORDER - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + $this->_ecommerceOrdersCollection->joinLeftEcommerceSyncData($modifiedOrders); // be sure that the order are already in mailchimp and not deleted - $modifiedOrders->getSelect()->where("m4m.mailchimp_sync_modified = 1"); - // limit the collection - $modifiedOrders->getSelect()->limit($this->getBatchLimitFromConfig()); + $this->_ecommerceOrdersCollection->addWhere( + $modifiedOrders, + "m4m.mailchimp_sync_modified = 1", + $this->getBatchLimitFromConfig() + ); foreach ($modifiedOrders as $item) { - try { $orderId = $item->getEntityId(); - $order = Mage::getModel('sales/order')->load($orderId); + + try { + $order = $this->_getOrderById($orderId); $incrementId = $order->getIncrementId(); //create missing products first - $batchArray = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray); - $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); + $batchArray = $this->addProductNotSentData($order, $batchArray); + $orderJson = $this->GeneratePOSTPayload($order); if ($orderJson !== false) { if (!empty($orderJson)) { @@ -107,37 +116,53 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; $batchArray[$this->_counter]['body'] = $orderJson; //update order delta - $this->_updateSyncData($orderId, $mailchimpStoreId); + $this->addSyncData($orderId); $this->_counter++; } else { $error = $helper->__('Something went wrong when retrieving product information.'); - $this->_updateSyncData( + + $this->addSyncDataError( $orderId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $error, - 0, - 0 + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); continue; } } else { $jsonErrorMsg = json_last_error_msg(); - $helper->logError("Order " . $order->getEntityId() . " json encode failed (".$jsonErrorMsg.")"); + $this->logSyncError( + $jsonErrorMsg, + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + + ); - $this->_updateSyncData( + $this->addSyncDataError( $orderId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $jsonErrorMsg, - 0, - 0, + null, false, - -1 + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); } } catch (Exception $e) { - $helper->logError($e->getMessage()); + $this->logSyncError( + $e->getMessage(), + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + ); } } @@ -145,13 +170,14 @@ protected function _getModifiedOrders($mailchimpStoreId, $magentoStoreId) } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array * @throws Mage_Core_Exception */ - protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) + protected function _getNewOrders() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $helper = $this->getHelper(); $dateHelper = $this->getDateHelper(); @@ -165,20 +191,21 @@ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) $newOrders->addFieldToFilter('created_at', array('gt' => $this->_firstDate)); } - $this->joinMailchimpSyncDataWithoutWhere($newOrders, $mailchimpStoreId); - // be sure that the orders are not in mailchimp - $newOrders->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); - // limit the collection - $newOrders->getSelect()->limit($this->getBatchLimitFromConfig()); + $this->_ecommerceOrdersCollection->joinLeftEcommerceSyncData($newOrders); + $this->_ecommerceOrdersCollection->addWhere( + $newOrders, + "m4m.mailchimp_sync_delta IS NULL", + $this->getBatchLimitFromConfig() + ); foreach ($newOrders as $item) { - try { $orderId = $item->getEntityId(); - $order = Mage::getModel('sales/order')->load($orderId); + try { + $order = $this->_getOrderById($orderId); //create missing products first - $batchArray = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray); + $batchArray = $this->addProductNotSentData($order, $batchArray); - $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); + $orderJson = $this->GeneratePOSTPayload($order); if ($orderJson !== false) { if (!empty($orderJson)) { @@ -189,70 +216,89 @@ protected function _getNewOrders($mailchimpStoreId, $magentoStoreId) $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; $batchArray[$this->_counter]['body'] = $orderJson; //update order delta - $this->_updateSyncData($orderId, $mailchimpStoreId); + $this->addSyncData($orderId); $this->_counter++; } else { $error = $helper->__('Something went wrong when retrieving product information.'); - $this->_updateSyncData( + + $this->addSyncDataError( $orderId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $error, - 0, - 0 + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); continue; } } else { $jsonErrorMsg = json_last_error_msg(); - $helper->logError("Order " . $order->getEntityId() . " json encode failed (".$jsonErrorMsg.")"); + $this->logSyncError( + "Order " . $order->getEntityId() . " json encode failed (".$jsonErrorMsg.")", + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + ); - $this->_updateSyncData( + $this->addSyncDataError( $orderId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $jsonErrorMsg, - 0, - 0, + null, false, - -1 + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); } } catch (Exception $e) { - $helper->logError($e->getMessage()); + $this->logSyncError( + $e->getMessage(), + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + ); } } return $batchArray; } + /** + * @param $id + * @return Mage_Core_Model_Abstract + */ + protected function _getOrderById($id) + { + return Mage::getModel('sales/order')->load($id); + } + /** * Set all the data for each order to be sent * * @param $order - * @param $mailchimpStoreId - * @param $magentoStoreId * @return false|string * @throws Mage_Core_Model_Store_Exception */ - public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) + public function GeneratePOSTPayload($order) { - $helper = $this->getHelper(); - $oldStore = $helper->getCurrentStoreId(); - $helper->setCurrentStore($magentoStoreId); + $magentoStoreId = $this->getMagentoStoreId(); - $data = $this->_getPayloadData($order, $magentoStoreId); - $lines = $this->_getPayloadDataLines($order, $mailchimpStoreId, $magentoStoreId); + $data = $this->_getPayloadData($order); + $lines = $this->_getPayloadDataLines($order); $data['lines'] = $lines['lines']; if (!$lines['itemsCount']) { unset($data['lines']); - $helper->setCurrentStore($oldStore); return ""; } //customer data - $data["customer"]["id"] = md5(strtolower($order->getCustomerEmail())); + $data["customer"]["id"] = hash('md5', strtolower($order->getCustomerEmail())); $data["customer"]["email_address"] = $order->getCustomerEmail(); $data["customer"]["opt_in_status"] = false; @@ -293,7 +339,7 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) $this->_getPayloadBilling($data, $billingAddress, $street); } - $shippingAddress = $order->getShippingAddress(); + $shippingAddress = $order->getShippingAddress(); if ($shippingAddress) { $this->_getPayloadShipping($data, $shippingAddress); @@ -303,24 +349,22 @@ public function GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId) //encode to JSON $jsonData = json_encode($data); - $helper->setCurrentStore($oldStore); return $jsonData; } /** * @param $order - * @param $magentoStoreId * @return array * @throws Exception */ - protected function _getPayloadData($order, $magentoStoreId) + protected function _getPayloadData($order) { $data = array(); $data['id'] = $order->getIncrementId(); $dataPromo = $this->getPromoData($order); $mailchimpCampaignId = $order->getMailchimpCampaignId(); - if ($this->shouldSendCampaignId($mailchimpCampaignId, $magentoStoreId)) { + if ($this->shouldSendCampaignId($mailchimpCampaignId, $order->getEntityId())) { $data['campaign_id'] = $mailchimpCampaignId; } @@ -364,14 +408,16 @@ protected function _getPayloadData($order, $magentoStoreId) /** * @param $order - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - protected function _getPayloadDataLines($order, $mailchimpStoreId, $magentoStoreId) + protected function _getPayloadDataLines($order) { - $helper = $this->getHelper(); + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $apiProduct = $this->getApiProduct(); + $apiProduct->setMailchimpStoreId($mailchimpStoreId); + $apiProduct->setMagentoStoreId($magentoStoreId); $lines = array(); $items = $order->getAllVisibleItems(); @@ -380,12 +426,13 @@ protected function _getPayloadDataLines($order, $mailchimpStoreId, $magentoStore foreach ($items as $item) { $productId = $item->getProductId(); $isTypeProduct = $this->isTypeProduct(); - $productSyncData = $helper->getEcommerceSyncDataItem($productId, $isTypeProduct, $mailchimpStoreId); + $productSyncData = $this->getMailchimpEcommerceSyncDataModel() + ->getEcommerceSyncDataItem($productId, $isTypeProduct, $mailchimpStoreId); if ($this->isItemConfigurable($item)) { $options = $item->getProductOptions(); $sku = $options['simple_sku']; - $variant = $this->getModelProduct()->getIdBySku($sku); + $variant = $this->_getProductIdBySku($sku); if (!$variant) { continue; @@ -399,7 +446,7 @@ protected function _getPayloadDataLines($order, $mailchimpStoreId, $magentoStore } $productSyncError = $productSyncData->getMailchimpSyncError(); - $isProductEnabled = $apiProduct->isProductEnabled($productId, $magentoStoreId); + $isProductEnabled = $apiProduct->isProductEnabled($productId); if (!$isProductEnabled || ($productSyncData->getMailchimpSyncDelta() && $productSyncError == '')) { $itemCount++; @@ -414,7 +461,7 @@ protected function _getPayloadDataLines($order, $mailchimpStoreId, $magentoStore if (!$isProductEnabled) { // update disabled products to remove the product from mailchimp after sending the order - $apiProduct->updateDisabledProducts($productId, $mailchimpStoreId); + $apiProduct->updateDisabledProducts($productId); } } } @@ -666,60 +713,12 @@ protected function _getFinancialFulfillmentStatus($orderItems, $totalItemsOrdere public function update($orderId, $magentoStoreId) { $helper = $this->getHelper(); + if ($helper->isEcomSyncDataEnabled($magentoStoreId)) { - $mailchimpStoreId = $helper->getMCStoreId($magentoStoreId); - $this->_updateSyncData( - $orderId, - $mailchimpStoreId, - null, - null, - 1, - null, - true, - false - ); + $this->markSyncDataAsModified($orderId); } } - /** - * update customer sync data - * - * @param int $orderId - * @param string $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncedFlag - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval - */ - protected function _updateSyncData( - $orderId, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncedFlag = null, - $saveOnlyIfexists = false, - $allowBatchRemoval = true - ) { - $helper = $this->getHelper(); - $helper->saveEcommerceSyncData( - $orderId, - Ebizmarts_MailChimp_Model_Config::IS_ORDER, - $mailchimpStoreId, - $syncDelta, - $syncError, - $syncModified, - null, - null, - $syncedFlag, - $saveOnlyIfexists, - null, - $allowBatchRemoval - ); - } - /** * Replace all orders with old id with the increment id on MailChimp. * @@ -742,32 +741,36 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS $magentoStoreId, 'stores' ); - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); $batchArray = array(); $config = array(); $orderCollection = $this->getResourceModelOrderCollection(); // select carts for the current Magento store id $orderCollection->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + if ($lastId) { $orderCollection->addFieldToFilter('entity_id', array('gt' => $lastId)); } - $orderCollection->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" - . Ebizmarts_MailChimp_Model_Config::IS_ORDER - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + if(empty($this->_ecommerceOrdersCollection)){ + $this->_ecommerceOrdersCollection = $this->createEcommerceOrdersCollection(); + $this->_ecommerceOrdersCollection->setMailchimpStoreId($mailchimpStoreId); + $this->_ecommerceOrdersCollection->setStoreId($magentoStoreId); + } + + $this->_ecommerceOrdersCollection->joinLeftEcommerceSyncData($orderCollection); + // be sure that the orders are not in mailchimp - $orderCollection->getSelect()->where( - "m4m.mailchimp_sync_delta IS NOT NULL AND m4m.mailchimp_sync_error = ''" + $this->_ecommerceOrdersCollection->addWhere( + $orderCollection, + "m4m.mailchimp_sync_delta IS NOT NULL AND m4m.mailchimp_sync_error = ''", + self::BATCH_LIMIT_ONLY_ORDERS ); - $orderCollection->getSelect()->limit(self::BATCH_LIMIT_ONLY_ORDERS); + foreach ($orderCollection as $order) { //Delete order $orderId = $order->getEntityId(); $config = array(array(Ebizmarts_MailChimp_Model_Config::GENERAL_MIGRATE_LAST_ORDER_ID, $orderId)); + if (!$dateHelper->timePassed($initialTime)) { $batchArray[$this->_counter]['method'] = "DELETE"; $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $orderId; @@ -776,7 +779,7 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS $this->_counter += 1; //Create order - $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); + $orderJson = $this->GeneratePOSTPayload($order); if ($orderJson !== false) { if (!empty($orderJson)) { @@ -789,25 +792,23 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS $error = $helper->__( 'Something went wrong when retrieving product information during migration from 1.1.6.' ); - $this->_updateSyncData( + $this->addSyncDataError( $orderId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $error, - 0, - 0 + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); continue; } } else { $error = $helper->__("Json error during migration from 1.1.6"); - $this->_updateSyncData( + $this->addSyncDataError( $orderId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $error, - 0, - 0 + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); continue; } @@ -822,20 +823,26 @@ public function replaceAllOrdersBatch($initialTime, $mailchimpStoreId, $magentoS } $helper->saveMailchimpConfig($config, $magentoStoreId, 'stores'); + return $batchArray; } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @param $order * @param $batchArray * @return mixed */ - public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order, $batchArray) + public function addProductNotSentData($order, $batchArray) { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $helper = $this->getHelper(); - $productData = $this->getApiProduct()->sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId); + $apiProduct = $this->getApiProduct(); + $apiProduct->setMailchimpStoreId($mailchimpStoreId); + $apiProduct->setMagentoStoreId($magentoStoreId); + $productData = $apiProduct->sendModifiedProduct($order); + $productDataArray = $helper->addEntriesToArray($batchArray, $productData, $this->_counter); $batchArray = $productDataArray[0]; $this->_counter = $productDataArray[1]; @@ -843,36 +850,12 @@ public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $order return $batchArray; } - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function getHelper() - { - return Mage::helper('mailchimp'); - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function getDateHelper() - { - return Mage::helper('mailchimp/date'); - } - /** * @param $newOrders - * @param $mailchimpStoreId */ - public function joinMailchimpSyncDataWithoutWhere($newOrders, $mailchimpStoreId) + public function joinMailchimpSyncDataWithoutWhere($newOrders) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); - $newOrders->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = main_table.entity_id AND m4m.type = '" - . Ebizmarts_MailChimp_Model_Config::IS_ORDER - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); + $this->_ecommerceOrdersCollection->joinLeftEcommerceSyncData($newOrders); } /** @@ -888,12 +871,14 @@ public function getPromoData($order) if ($couponCode !== null) { $code = $this->makeSalesRuleCoupon()->load($couponCode, 'code'); + if ($code->getCouponId() !== null) { $rule = $this->makeSalesRule()->load($code->getRuleId()); + if ($rule->getRuleId() !== null) { $amountDiscounted = $order->getBaseDiscountAmount(); - $type = $rule->getSimpleAction(); + if ($type == 'by_percent') { $type = 'percentage'; } else { @@ -935,8 +920,7 @@ protected function makeSalesRule() */ public function getSyncedOrder($orderId, $mailchimpStoreId) { - $helper = $this->getHelper(); - $result = $helper->getEcommerceSyncDataItem( + $result = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $orderId, Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId @@ -983,6 +967,15 @@ protected function getModelProduct() return Mage::getModel('catalog/product'); } + /** + * @param $sku + * @return string + */ + protected function _getProductIdBySku($sku) + { + return $this->getModelProduct()->getIdBySku($sku); + } + /** * @return string */ @@ -1036,45 +1029,76 @@ protected function getResourceModelOrderCollection() /** * @param $mailchimpCampaignId - * @return bool \ return true if the campaign is from the current list. - * @throws Exception + * @param $orderId + * @return bool return true if the campaign is from the current list. + * @throws Mage_Core_Exception */ - public function shouldSendCampaignId($mailchimpCampaignId, $magentoStoreId) + public function shouldSendCampaignId($mailchimpCampaignId, $orderId) { + $magentoStoreId = $this->getMagentoStoreId(); $isCampaingFromCurrentList = false; + if ($mailchimpCampaignId) { $helper = $this->getHelper(); $listId = $helper->getGeneralList($magentoStoreId); + try { $apiKey = $helper->getApiKey($magentoStoreId); + if ($apiKey) { if (isset($this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId])) { $isCampaingFromCurrentList = $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId]; } else { $api = $helper->getApi($magentoStoreId); $campaignData = $api->getCampaign()->get($mailchimpCampaignId, 'recipients'); + if (isset($campaignData['recipients']['list_id']) && $campaignData['recipients']['list_id'] == $listId ) { $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = - $isCampaingFromCurrentList = - true; + $isCampaingFromCurrentList = true; } else { $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = - $isCampaingFromCurrentList = - false; + $isCampaingFromCurrentList = false; } } } } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = $isCampaingFromCurrentList = true; - $helper->logError($e->getMessage()); + $this->logSyncError( + $e->getMessage(), + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + ); } catch (MailChimp_Error $e) { $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = $isCampaingFromCurrentList = false; - $helper->logError($e->getFriendlyMessage()); + $this->logSyncError( + $e->getFriendlyMessage(), + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + ); } catch (Exception $e) { $this->_listsCampaignIds[$apiKey][$listId][$mailchimpCampaignId] = $isCampaingFromCurrentList = true; - $helper->logError($e->getMessage()); + $this->logSyncError( + $e->getMessage(), + Ebizmarts_MailChimp_Model_Config::IS_ORDER, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $orderId, + 0 + ); } } @@ -1096,4 +1120,33 @@ protected function getSubscriberModel() { return Mage::getModel('newsletter/subscriber'); } + + /** + * @return string + */ + protected function getItemType() + { + return Ebizmarts_MailChimp_Model_Config::IS_ORDER; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Orders_Collection + */ + public function getEcommerceOrdersCollection() + { + return $this->_ecommerceOrdersCollection; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Orders_Collection + */ + public function createEcommerceOrdersCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Orders_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_orders_collection'); + + return $collection; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 0a1fbf4bb..2249f8e55 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -9,10 +9,9 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_Products +class Ebizmarts_MailChimp_Model_Api_Products extends Ebizmarts_MailChimp_Model_Api_ItemSynchronizer { const PRODUCT_IS_ENABLED = 1; - const PRODUCT_IS_DISABLED = 2; const BATCH_LIMIT = 100; protected $_parentImageUrl = null; protected $_parentId = null; @@ -25,40 +24,45 @@ class Ebizmarts_MailChimp_Model_Api_Products */ protected $_productTypeConfigurable; - /** - * @var Ebizmarts_MailChimp_Helper_Data - */ - protected $_mailchimpHelper; - protected $_mailchimpDateHelper; protected $_visibilityOptions; protected $_productTypeConfigurableResource; public static $noChildrenIds = array(0 => array()); const PRODUCT_DISABLED_IN_MAGENTO = 'This product was deleted because it is disabled in Magento.'; + /** + * @var $_ecommerceProductsCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Product_Collection + */ + protected $_ecommerceProductsCollection; + public function __construct() { + parent::__construct(); + $this->_productTypeConfigurable = Mage::getModel('catalog/product_type_configurable'); $this->_productTypeConfigurableResource = Mage::getResourceSingleton( 'catalog/product_type_configurable' ); - $this->_mailchimpHelper = Mage::helper('mailchimp'); - $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); $this->_visibilityOptions = Mage::getModel('catalog/product_visibility')->getOptionArray(); } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception */ - public function createBatchJson($mailchimpStoreId, $magentoStoreId) + public function createBatchJson() { - $helper = $this->getMailChimpHelper(); - $dateHelper = $this->getMailChimpDateHelper(); - $oldStore = $helper->getCurrentStoreId(); + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + + $this->_ecommerceProductsCollection = $this->createEcommerceProductsCollection(); + $this->_ecommerceProductsCollection->setMailchimpStoreId($mailchimpStoreId); + $this->_ecommerceProductsCollection->setStoreId($magentoStoreId); + + $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); + $oldStoreId = $helper->getCurrentStoreId(); $helper->setCurrentStore($magentoStoreId); if ($this->isProductFlatTableEnabled()) { @@ -73,9 +77,9 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) ); } - $this->_markSpecialPrices($mailchimpStoreId, $magentoStoreId); - $collection = $this->makeProductsNotSentCollection($magentoStoreId); - $this->joinMailchimpSyncData($collection, $mailchimpStoreId); + $this->_markSpecialPrices(); + $collection = $this->makeProductsNotSentCollection(); + $this->joinMailchimpSyncData($collection); $batchArray = array(); $batchId = $this->makeBatchId($magentoStoreId); $counter = 0; @@ -83,26 +87,18 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) foreach ($collection as $product) { $productId = $product->getId(); - if ($this->shouldSendProductUpdate($mailchimpStoreId, $magentoStoreId, $product)) { - $buildUpdateOperations = $this->_buildUpdateProductRequest( - $product, - $batchId, - $mailchimpStoreId, - $magentoStoreId - ); + if ($this->shouldSendProductUpdate($product)) { + $buildUpdateOperations = $this->_buildUpdateProductRequest($product, $batchId); if ($buildUpdateOperations !== false) { - $batchArray = array_merge( - $buildUpdateOperations, - $batchArray - ); - $this->_updateSyncData($productId, $mailchimpStoreId); + $batchArray = array_merge($buildUpdateOperations, $batchArray); + $this->addSyncData($productId); } - $counter = count($batchArray); + $counter = $this->_getBatchCounter($batchArray); continue; } else { - $data = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + $data = $this->_buildNewProductRequest($product, $batchId); } if ($data !== false) { @@ -110,11 +106,12 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) $batchArray[$counter] = $data; $counter++; - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + if ($dataProduct->getId()) { $helper->modifyCounterSentPerBatch(Ebizmarts_MailChimp_Helper_Data::PRO_MOD); } else { @@ -122,40 +119,49 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) } //update product delta - $this->_updateSyncData($productId, $mailchimpStoreId); + $this->addSyncData($productId); } else { - $this->_updateSyncData( + $this->addSyncDataError( $productId, - $mailchimpStoreId, - $dateHelper->formatDate(null, 'Y-m-d H:i:s'), - "This product type is not supported on MailChimp.", - 0, + "This product type is not supported on MailChimp. (product id: $productId)", null, - 0 + false, + $dateHelper->formatDate(null, 'Y-m-d H:i:s') ); } } } - $helper->setCurrentStore($oldStore); + $helper->setCurrentStore($oldStoreId); return $batchArray; } /** - * @param $mailchimpStoreId - * @param $magentoStoreId + * @param $batchArray + * @return int + */ + protected function _getBatchCounter($batchArray) + { + return count($batchArray); + } + + /** * @return array */ - public function createDeletedProductsBatchJson($mailchimpStoreId, $magentoStoreId) + public function createDeletedProductsBatchJson() { - $deletedProducts = $this->getProductResourceCollection(); + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); - $this->joinMailchimpSyncDataDeleted($mailchimpStoreId, $deletedProducts); + $deletedProducts = $this->getProductResourceCollection(); + $this->getEcommerceProductsCollection() + ->joinMailchimpSyncDataDeleted($deletedProducts, $this->getBatchLimitFromConfig()); $batchArray = array(); $batchId = $this->makeBatchId($magentoStoreId); $counter = 0; + foreach ($deletedProducts as $product) { $data = $this->_buildDeleteProductRequest($product, $batchId, $mailchimpStoreId); @@ -164,14 +170,10 @@ public function createDeletedProductsBatchJson($mailchimpStoreId, $magentoStoreI $counter++; } - $this->_updateSyncData( + $this->addSyncDataError( $product->getId(), $mailchimpStoreId, - null, - self::PRODUCT_DISABLED_IN_MAGENTO, - 0, - null, - 0 + self::PRODUCT_DISABLED_IN_MAGENTO ); } @@ -201,13 +203,15 @@ protected function _buildDeleteProductRequest($product, $batchId, $mailchimpStor /** * @param $product * @param $batchId - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array|bool */ - protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) + protected function _buildNewProductRequest($product, $batchId) { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $variantProducts = array(); + if ($this->isSimpleProduct($product)) { $variantProducts[] = $product; } elseif ($this->isConfigurableProduct($product)) { @@ -219,26 +223,28 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId } $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts); - $body = json_encode($bodyData, JSON_HEX_APOS | JSON_HEX_QUOT); + if ($body === false) { //json encode failed $jsonErrorMsg = json_last_error_msg(); - $this->getMailChimpHelper()->logError( - "Product " . $product->getId() - . " json encode failed (".$jsonErrorMsg.")" + $this->logSyncError( + $jsonErrorMsg, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $product->getId(), + 0 ); - $this->_updateSyncData( + $this->addSyncDataError( $product->getId(), - $mailchimpStoreId, - $this->getMailChimpDateHelper()->getCurrentDateTime(), $jsonErrorMsg, - 0, null, null, - false, - -1 + $this->getDateHelper()->getCurrentDateTime() ); return false; @@ -256,14 +262,14 @@ protected function _buildNewProductRequest($product, $batchId, $mailchimpStoreId /** * @param $product * @param $batchId - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array|bool * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception */ - protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId) + protected function _buildUpdateProductRequest($product, $batchId) { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); $variantProducts = array(); $operations = array(); @@ -275,39 +281,42 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor $parentIds = $this->_productTypeConfigurableResource->getParentIdsByChild($product->getId()); foreach ($parentIds as $parentId) { - $helper = $this->getMailChimpHelper(); - $productSyncDataItem = $helper->getEcommerceSyncDataItem( + $productSyncDataItem = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $parentId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + if ($productSyncDataItem->getMailchimpSyncDelta()) { - $parent = Mage::getModel('catalog/product')->load($parentId); + $parent = $this->_getParentProduct($parentId); $variantProducts = $this->makeProductChildrenArray( $product, - $magentoStoreId, true ); $bodyData = $this->_buildProductData($parent, $magentoStoreId, false, $variantProducts); - $body = json_encode($bodyData, JSON_HEX_APOS | JSON_HEX_QUOT); + if ($body === false) { $jsonErrorMsg = json_last_error_msg(); - $this->getMailChimpHelper()->logError( - "Product " . $parent->getId() - . " json encode failed (".$jsonErrorMsg.")" - ); - $this->_updateSyncData( - $parent->getId(), - $mailchimpStoreId, - $this->getMailChimpDateHelper()->getCurrentDateTime(), + $this->logSyncError( $jsonErrorMsg, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', 0, + $product->getId(), + 0 + ); + + $this->addSyncDataError( + $product->getId(), + $jsonErrorMsg, null, null, - false, - -1 + $this->getDateHelper()->getCurrentDateTime() ); + return false; } @@ -322,7 +331,6 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor } elseif ($this->isConfigurableProduct($product)) { $variantProducts = $this->makeProductChildrenArray( $product, - $magentoStoreId, true ); } else { @@ -330,30 +338,41 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor } $bodyData = $this->_buildProductData($product, $magentoStoreId, false, $variantProducts); - $body = json_encode($bodyData, JSON_HEX_APOS | JSON_HEX_QUOT); + if ($body === false) { + $jsonErrorMsg = json_last_error_msg(); //json encode failed - $this->getMailChimpHelper()->logError( - "Product " . $product->getId() - . " json encode failed (".json_last_error_msg().")" + $this->logSyncError( + $jsonErrorMsg, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $product->getId(), + 0 ); $jsonErrorMsg = json_last_error_msg(); - $this->getMailChimpHelper()->logError( - "Product " . $product->getId() - . " json encode failed (".$jsonErrorMsg.")" + + $this->logSyncError( + $jsonErrorMsg, + Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $product->getId(), + 0 ); - $this->_updateSyncData( + + $this->addSyncDataError( $product->getId(), - $mailchimpStoreId, - $this->getMailChimpDateHelper()->getCurrentDateTime(), $jsonErrorMsg, - 0, null, null, - false, - -1 + $this->getDateHelper()->getCurrentDateTime() ); return false; @@ -370,10 +389,19 @@ protected function _buildUpdateProductRequest($product, $batchId, $mailchimpStor } /** - * @param $product - * @param $magentoStoreId - * @param bool $isVariant - * @param array $variants + * @param $id + * @return Mage_Core_Model_Abstract + */ + protected function _getParentProduct($id) + { + return Mage::getModel('catalog/product')->load($id); + } + + /** + * @param $product + * @param $magentoStoreId + * @param bool $isVariant + * @param array $variants * @return array * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception @@ -383,7 +411,7 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $data = array(); $productId = $product->getId(); - $helper = $this->getMailChimpHelper(); + $helper = $this->getHelper(); $rc = $helper->getProductResourceModel(); //data applied for both root and varient products $data["id"] = $productId; @@ -416,6 +444,7 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru $data += $this->getProductVariantData($product, $magentoStoreId); } else { $description = $rc->getAttributeRawValue($productId, 'description', $magentoStoreId); + if (is_string($description)) { $data["description"] = $description; } @@ -452,16 +481,19 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru protected function _processVariants($data, $variants, $product, $magentoStoreId) { $data["variants"] = array(); + if (isset($data["image_url"])) { $this->_parentImageUrl = $data["image_url"]; } $this->_parentId = $product->getId(); + if ($this->currentProductIsVisible()) { $this->_parentUrl = $data['url']; } $price = $this->getMailchimpFinalPrice($product, $magentoStoreId); + if ($price) { $this->_parentPrice = $price; } @@ -482,97 +514,66 @@ protected function _processVariants($data, $variants, $product, $magentoStoreId) * Get stores to update and call update function after modification. * * @param $productId - * @param $mailchimpStoreId */ - public function update($productId, $mailchimpStoreId) + public function update($productId) { $parentIdArray = $this->getAllParentIds($productId); + foreach ($parentIdArray as $parentId) { - $this->_updateSyncData( - $parentId, - $mailchimpStoreId, - null, - null, - 1, - 0, - null, - true, - false - ); + $this->markSyncDataAsModified($parentId); } - $this->_updateSyncData( - $productId, - $mailchimpStoreId, - null, - null, - 1, - 0, - null, - true, - false - ); + $this->markSyncDataAsModified($productId); } /** * Get stores to update and call update function after product is disabled. * * @param $productId - * @param $mailchimpStoreId */ - public function updateDisabledProducts($productId, $mailchimpStoreId) + public function updateDisabledProducts($productId) { - $this->_updateSyncData( - $productId, - $mailchimpStoreId, - null, - '', - 0, - 1, - 0, - false, - false - ); + $this->markSyncDataAsDeleted($productId, 0); } /** * Return products belonging to an order or a cart in a valid format to be sent to MailChimp. * * @param $order - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) + public function sendModifiedProduct($order) { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + $data = array(); $batchId = $this->makeBatchId($magentoStoreId); $items = $order->getAllVisibleItems(); - $helper = $this->getMailChimpHelper(); - $dateHelper = $this->getMailChimpDateHelper(); - $syncDateFlag = $helper->getEcommMinSyncDateFlag($mailchimpStoreId, $magentoStoreId); + $dateHelper = $this->getDateHelper(); + foreach ($items as $item) { $itemProductId = $item->getProductId(); + $product = $this->loadProductById($itemProductId); $productId = $product->getId(); - $productSyncData = $helper->getEcommerceSyncDataItem( + $productSyncData = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + if ($productId != $itemProductId || $this->isBundleProduct($product) || $this->isGroupedProduct($product) ) { if ($productId) { - $this->_updateSyncData( + $this->addSyncDataError( $productId, - $mailchimpStoreId, - $dateHelper->formatDate(null, 'Y-m-d H:i:s'), - "This product type is not supported on MailChimp.", - 0, + "This product type is not supported on MailChimp. (product id: $productId)", + null, null, - 0 + $dateHelper->formatDate(null, 'Y-m-d H:i:s') ); } @@ -580,15 +581,13 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) } $syncModified = $productSyncData->getMailchimpSyncModified(); - $syncDelta = $productSyncData->getMailchimpSyncDelta(); - $isProductEnabled = $this->isProductEnabled($productId, $magentoStoreId); + $productSyncDelta = $productSyncData->getMailchimpSyncDelta(); + $isProductEnabled = $this->isProductEnabled($productId); - if ($syncModified && $syncDelta > $syncDateFlag && $isProductEnabled) { + if ($syncModified && $isProductEnabled) { $buildUpdateOperations = $this->_buildUpdateProductRequest( $product, - $batchId, - $mailchimpStoreId, - $magentoStoreId + $batchId ); if ($buildUpdateOperations !== false) { @@ -597,16 +596,16 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) $buildUpdateOperations, $data ); - $this->_updateSyncData($productId, $mailchimpStoreId); + $this->addSyncData($productId); } - } elseif (!$syncDelta || $syncDelta < $syncDateFlag || !$isProductEnabled) { - $bodyData = $this->_buildNewProductRequest($product, $batchId, $mailchimpStoreId, $magentoStoreId); + } elseif (!$productSyncDelta || !$isProductEnabled) { + $bodyData = $this->_buildNewProductRequest($product, $batchId); if ($bodyData !== false) { $data[] = $bodyData; // avoid update for disabled products to prevent send the product as modified if ($isProductEnabled) { - $this->_updateSyncData($productId, $mailchimpStoreId); + $this->addSyncData($productId); } } } @@ -615,46 +614,6 @@ public function sendModifiedProduct($order, $mailchimpStoreId, $magentoStoreId) return $data; } - /** - * update product sync data - * - * @param $productId - * @param $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncDeleted - * @param int|null $syncedFlag - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval - */ - protected function _updateSyncData( - $productId, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncDeleted = null, - $syncedFlag = null, - $saveOnlyIfexists = false, - $allowBatchRemoval = true - ) { - $this->getMailChimpHelper()->saveEcommerceSyncData( - $productId, - Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, - $mailchimpStoreId, - $syncDelta, - $syncError, - $syncModified, - $syncDeleted, - null, - $syncedFlag, - $saveOnlyIfexists, - null, - $allowBatchRemoval - ); - } - /** * @param $magentoStoreId * @return string @@ -662,7 +621,7 @@ protected function _updateSyncData( public function makeBatchId($magentoStoreId) { $batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT; - $batchId .= '_' . $this->getMailChimpDateHelper()->getDateMicrotime(); + $batchId .= '_' . $this->getDateHelper()->getDateMicrotime(); return $batchId; } @@ -671,27 +630,30 @@ public function makeBatchId($magentoStoreId) * @param $magentoStoreId * @return Mage_Catalog_Model_Resource_Product_Collection */ - public function makeProductsNotSentCollection($magentoStoreId, $isParentProduct = false) + public function makeProductsNotSentCollection($isParentProduct = false) { /** * @var Mage_Catalog_Model_Resource_Product_Collection $collection */ $collection = $this->getProductResourceCollection(); + $magentoStoreId = $this->getMagentoStoreId(); + if (!$isParentProduct) { $collection->addFinalPrice(); } $collection->addStoreFilter($magentoStoreId); - $this->_mailchimpHelper->addResendFilter( + $this->getHelper()->addResendFilter( $collection, $magentoStoreId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT ); - $this->joinQtyAndBackorders($collection); + $productsCollectionResource = $this->createEcommerceProductsCollection(); + $productsCollectionResource->joinQtyAndBackorders($collection); if (!$isParentProduct) { - $collection->getSelect()->limit($this->getBatchLimitFromConfig()); + $productsCollectionResource->limitCollection($collection, $this->getBatchLimitFromConfig()); } return $collection; @@ -702,29 +664,16 @@ public function makeProductsNotSentCollection($magentoStoreId, $isParentProduct */ protected function getBatchLimitFromConfig() { - $helper = $this->_mailchimpHelper; + $helper = $this->getHelper(); return $helper->getProductAmountLimit(); } /** - * @return string - */ - public function getSyncDataTableName() - { - $mailchimpTableName = Mage::getSingleton('core/resource') - ->getTableName('mailchimp/ecommercesyncdata'); - - return $mailchimpTableName; - } - - /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @param $product * @return bool * @throws Mage_Core_Exception */ - protected function shouldSendProductUpdate($mailchimpStoreId, $magentoStoreId, $product) + protected function shouldSendProductUpdate($product) { return $product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() @@ -786,30 +735,6 @@ protected function isConfigurableProduct($product) return $product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE; } - /** - * @param $collection - */ - public function joinQtyAndBackorders($collection) - { - $collection->joinField( - 'qty', - 'cataloginventory/stock_item', - 'qty', - 'product_id=entity_id', - '{{table}}.stock_id=1', - 'left' - ); - - $collection->joinField( - 'backorders', - 'cataloginventory/stock_item', - 'backorders', - 'product_id=entity_id', - '{{table}}.stock_id=1', - 'left' - ); - } - /** * @param $product * @param $magentoStoreId @@ -822,6 +747,7 @@ protected function getProductVariantData($product, $magentoStoreId) $data["sku"] = $sku ? $sku : ''; $price = $this->getMailChimpProductPrice($product, $magentoStoreId); + if ($price) { $data["price"] = $price; } @@ -859,18 +785,17 @@ protected function getConfigurableChildrenIds($product) } /** - * @param $product - * @param $magentoStoreId - * @param bool $isBuildUpdateProductRequest + * @param $product + * @param bool $isBuildUpdateProductRequest * @return array | return an array with the childs of the product passed by parameter */ - public function makeProductChildrenArray($product, $magentoStoreId, $isBuildUpdateProductRequest = false) + public function makeProductChildrenArray($product, $isBuildUpdateProductRequest = false) { $variantProducts[] = $product; /** * @var Mage_Catalog_Model_Resource_Product_Collection $collection */ - $collection = $this->makeProductsNotSentCollection($magentoStoreId, true); + $collection = $this->makeProductsNotSentCollection(true); $childProducts = $this->getConfigurableChildrenIds($product); $collection->addAttributeToFilter("entity_id", array("in" => $childProducts)); @@ -897,36 +822,18 @@ protected function getChildrenIdsForConfigurable($product) return $this->_productTypeConfigurable->getChildrenIds($product->getId()); } - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function getMailChimpHelper() - { - return $this->_mailchimpHelper; - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function getMailChimpDateHelper() - { - return $this->_mailchimpDateHelper; - } - /** * This function will perform the join of the collection with the table * mailchimp_ecommerce_sync_data when the programcreates the batch json * to send the product data to mailchimp * * @param $collection - * @param $mailchimpStoreId */ - public function joinMailchimpSyncData($collection, $mailchimpStoreId) + public function joinMailchimpSyncData($collection) { $joinCondition = $this->buildMailchimpDataJoin(); - $this->executeMailchimpDataJoin($collection, $mailchimpStoreId, $joinCondition); + $this->executeMailchimpDataJoin($collection, $joinCondition); $this->buildMailchimpDataWhere($collection); - } /** @@ -943,13 +850,12 @@ protected function buildMailchimpDataJoin() * to mark products as modified when special price starts/ends * * @param $collection - * @param $mailchimpStoreId */ - public function joinMailchimpSyncDataForSpecialPrices($collection, $mailchimpStoreId) + public function joinMailchimpSyncDataForSpecialPrices($collection) { $joinCondition = $this->builMailchimpDataJoinForSpecialPrices(); - $this->executeMailchimpDataJoin($collection, $mailchimpStoreId, $joinCondition); - $this->builMailchimpDataJoinForSpecialPrices($collection); + $this->executeMailchimpDataJoin($collection, $joinCondition); + $this->builMailchimpDataJoinForSpecialPrices(); } /** @@ -961,35 +867,13 @@ protected function builMailchimpDataJoinForSpecialPrices() return $joinCondition; } - /** - * @param $collection - * @param $mailchimpStoreId - * @param $joinCondition - */ - protected function executeMailchimpDataJoin($collection, $mailchimpStoreId, $joinCondition) - { - $mailchimpTableName = $this->getSyncDataTableName(); - $collection->getSelect()->joinLeft( - array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId), - array( - "m4m.related_id", - "m4m.type", - "m4m.mailchimp_store_id", - "m4m.mailchimp_sync_delta", - "m4m.mailchimp_sync_modified", - "m4m.mailchimp_synced_flag" - ) - ); - } - /** * @param $collection */ protected function buildMailchimpDataWhere($collection) { $whereCreateBatchJson = "m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1"; - $collection->getSelect()->where($whereCreateBatchJson); + $this->_ecommerceProductsCollection->addWhere($collection, $whereCreateBatchJson); } /** @@ -999,8 +883,9 @@ protected function buildMailchimpDataWhere($collection) */ public function getNotVisibleProductUrl($childId, $magentoStoreId) { - $helper = $this->getMailChimpHelper(); + $helper = $this->getHelper(); $parentId = null; + if (!$this->_parentId) { $parentId = $this->getParentId($childId); } else { @@ -1009,8 +894,8 @@ public function getNotVisibleProductUrl($childId, $magentoStoreId) if ($parentId) { $collection = $this->getProductWithAttributesById($magentoStoreId, $parentId); - $rc = $helper->getProductResourceModel(); + if ($this->_parentUrl) { $url = $this->_parentUrl; } else { @@ -1020,6 +905,7 @@ public function getNotVisibleProductUrl($childId, $magentoStoreId) $tailUrl = '#'; $count = 0; + foreach ($collection as $attribute) { if ($attribute->getAttributeId()) { $attributeId = $attribute->getAttributeId(); @@ -1058,6 +944,7 @@ public function getParentImageUrl($childId, $magentoStoreId) { $imageUrl = null; $parentId = null; + if (!$this->_parentId) { $parentId = $this->getParentId($childId); } else { @@ -1065,7 +952,7 @@ public function getParentImageUrl($childId, $magentoStoreId) } if ($parentId) { - $helper = $this->getMailChimpHelper(); + $helper = $this->getHelper(); $imageUrl = $helper->getImageUrlById($parentId, $magentoStoreId); } @@ -1091,6 +978,7 @@ public function getProductCategories($product, $magentoStoreId) $categoryIds = $product->getResource()->getCategoryIds($product); $categoryNames = array(); $categoryName = null; + if (is_array($categoryIds) && !empty($categoryIds)) { $collection = $this->makeCatalogCategory()->getCollection(); $collection->addAttributeToSelect(array('name')) @@ -1118,6 +1006,7 @@ protected function getParentId($childId) { $parentId = null; $parentIds = $this->getAllParentIds($childId); + if (!empty($parentIds)) { $parentId = $parentIds[0]; } @@ -1150,16 +1039,22 @@ protected function getProductWithAttributesById($magentoStoreId, $parentId) $collection->addStoreFilter($magentoStoreId); $collection->addFieldToFilter('entity_id', array('eq' => $parentId)); - $collection->getSelect()->joinLeft( + $this->_ecommerceProductsCollection = $this->createEcommerceProductsCollection(); + $this->_ecommerceProductsCollection->addJoinLeft( + $collection, array("super_attribute" => $tableName), 'entity_id=super_attribute.product_id' ); - $collection->getSelect()->joinLeft( - array("eav_attribute" => $eavTableName), + $this->_ecommerceProductsCollection->addJoinLeft( + $collection, array("eav_attribute" => $eavTableName), 'super_attribute.attribute_id=eav_attribute.attribute_id' ); - $collection->getSelect()->reset(Zend_Db_Select::COLUMNS)->columns('eav_attribute.attribute_id'); + + $this->_ecommerceProductsCollection->resetColumns( + $collection, Zend_Db_Select::COLUMNS, 'eav_attribute.attribute_id' + ); + return $collection; } @@ -1170,10 +1065,10 @@ protected function getProductWithAttributesById($magentoStoreId, $parentId) */ protected function getMailChimpImageUrl($product, $magentoStoreId) { - $imageUrl = $this->getMailChimpHelper() + $imageUrl = $this->getHelper() ->getMailChimpProductImageUrl( $this->_parentImageUrl, - $this->getMailChimpHelper()->getImageUrlById( + $this->getHelper()->getImageUrlById( $product->getId(), $magentoStoreId ) @@ -1197,7 +1092,7 @@ protected function getMailChimpProductPrice($product, $magentoStoreId) if (!$this->currentProductIsVisible()) { $parentId = $this->getParentId($product->getId()); if ($parentId) { - $price = $this->getProductPrice($product, $magentoStoreId); + $price = $this->getMailchimpFinalPrice($product, $magentoStoreId); } } else { if ($this->_parentPrice) { @@ -1216,19 +1111,6 @@ protected function currentProductIsVisible() return $this->_visibility != Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE; } - /** - * @param $product - * @return float - * @throws Mage_Core_Exception - */ - protected function getProductPrice($product, $magentoStoreId) - { - $helper = $this->getMailChimpHelper(); - $rc = $helper->getProductResourceModel(); - $price = $this->getMailchimpFinalPrice($product, $magentoStoreId); - return $price; - } - /** * @param $path * @param $magentoStoreId @@ -1265,26 +1147,6 @@ protected function loadProductById($productId) return Mage::getModel('catalog/product')->load($productId); } - /** - * @param $mailchimpStoreId - * @param $deletedProducts - * @param $mailchimpTableName - */ - protected function joinMailchimpSyncDataDeleted($mailchimpStoreId, $deletedProducts) - { - $mailchimpTableName = $this->getSyncDataTableName(); - $deletedProducts->getSelect()->joinLeft( - array('m4m' => $mailchimpTableName), - "m4m.related_id = e.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT - . "' AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", - array('m4m.*') - ); - $deletedProducts->getSelect()->where("m4m.mailchimp_sync_deleted = 1"); - $deletedProducts->getSelect()->where("m4m.mailchimp_sync_error = ''"); - - $deletedProducts->getSelect()->limit($this->getBatchLimitFromConfig()); - } - /** * @param string $visibility Visibility. * @return int or null @@ -1308,7 +1170,7 @@ protected function getVisibility($visibility) */ protected function getMailchimpFinalPrice($product, $magentoStoreId) { - $helper = $this->getMailChimpHelper(); + $helper = $this->getHelper(); $price = Mage::helper('tax') ->getPrice( $product, @@ -1319,32 +1181,23 @@ protected function getMailchimpFinalPrice($product, $magentoStoreId) return $price; } - /** - * @return Mage_Core_Model_Resource - */ - public function getCoreResource() - { - return Mage::getSingleton('core/resource'); - } - /** * Sync to mailchimp the special price of the products * - * @param $mailchimpStoreId - * @param $magentoStoreId */ - public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) + public function _markSpecialPrices() { /** * get the products with current special price that are not synced and mark it as modified */ $resource = $this->getCoreResource(); $connection = $resource->getConnection('core_write'); + $magentoStoreId = $this->getMagentoStoreId(); $collection = $this->getProductResourceCollection(); $collection->addStoreFilter($magentoStoreId); - $this->joinMailchimpSyncDataForSpecialPrices($collection, $mailchimpStoreId); + $this->joinMailchimpSyncDataForSpecialPrices($collection); $collection->addAttributeToFilter( 'special_price', @@ -1352,7 +1205,7 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) 'left' )->addAttributeToFilter( 'special_from_date', - array('lteq' => $this->getMailChimpDateHelper()->formatDate() . " 23:59:59"), + array('lteq' => $this->getDateHelper()->formatDate() . " 23:59:59"), 'left' )->addAttributeToFilter( 'special_from_date', @@ -1363,12 +1216,14 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) $whereCondition = $connection->quoteInto( 'm4m.mailchimp_sync_delta IS NOT NULL ' . 'AND m4m.mailchimp_sync_delta < ?', - $this->getMailChimpDateHelper()->formatDate() . " 00:00:00" + $this->getDateHelper()->formatDate() . " 00:00:00" ); - $collection->getSelect()->where($whereCondition); + + $productsCollectionResource = $this->getEcommerceProductsCollection(); + $productsCollectionResource->addWhere($collection, $whereCondition); foreach ($collection as $item) { - $this->update($item->getEntityId(), $mailchimpStoreId); + $this->update($item->getEntityId()); } /** @@ -1376,7 +1231,7 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) */ $collectionNoSpecialPrice = $this->getProductResourceCollection(); $collectionNoSpecialPrice->addStoreFilter($magentoStoreId); - $this->joinMailchimpSyncDataForSpecialPrices($collectionNoSpecialPrice, $mailchimpStoreId); + $this->joinMailchimpSyncDataForSpecialPrices($collectionNoSpecialPrice); $collectionNoSpecialPrice->addAttributeToFilter( 'special_price', @@ -1384,7 +1239,7 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) 'left' )->addAttributeToFilter( 'special_to_date', - array('lt' => $this->getMailChimpDateHelper()->formatDate() . " 00:00:00"), + array('lt' => $this->getDateHelper()->formatDate() . " 00:00:00"), 'left' )->addAttributeToFilter( 'special_to_date', @@ -1392,9 +1247,10 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) 'left' ); - $collectionNoSpecialPrice->getSelect()->where($whereCondition); + $productsCollectionResource->addWhere($collectionNoSpecialPrice, $whereCondition); + foreach ($collectionNoSpecialPrice as $item) { - $this->update($item->getEntityId(), $mailchimpStoreId); + $this->update($item->getEntityId()); } } @@ -1402,10 +1258,11 @@ public function _markSpecialPrices($mailchimpStoreId, $magentoStoreId) * @param $productId * @return bool | return true if the product is enabled in Magento. */ - public function isProductEnabled($productId, $magentoStoreId) + public function isProductEnabled($productId) { $isProductEnabled = false; - $status = $this->getCatalogProductStatusModel()->getProductStatus($productId, $magentoStoreId); + $status = $this->getCatalogProductStatusModel()->getProductStatus($productId, $this->getMagentoStoreId()); + if ($status[$productId] == self::PRODUCT_IS_ENABLED) { $isProductEnabled = true; } @@ -1420,4 +1277,42 @@ protected function getCatalogProductStatusModel() { return Mage::getModel('catalog/product_status'); } + + /** + * @return string + */ + protected function getItemType() + { + return Ebizmarts_MailChimp_Model_Config::IS_PRODUCT; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Product_Collection + */ + public function getEcommerceProductsCollection() + { + return $this->_ecommerceProductsCollection; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Product_Collection + */ + public function createEcommerceProductsCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Product_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_product_collection'); + + return $collection; + } + + /** + * @param $collection + * @param $joinCondition + */ + protected function executeMailchimpDataJoin($collection, $joinCondition) + { + $this->_ecommerceProductsCollection->executeMailchimpDataJoin($collection, $joinCondition); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php index 9d8aec2a3..c937d18a5 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoCodes.php @@ -9,57 +9,59 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_PromoCodes +class Ebizmarts_MailChimp_Model_Api_PromoCodes extends Ebizmarts_MailChimp_Model_Api_ItemSynchronizer { const BATCH_LIMIT = 50; - const TYPE_FIXED = 'fixed'; - const TYPE_PERCENTAGE = 'percentage'; - const TARGET_PER_ITEM = 'per_item'; - const TARGET_TOTAL = 'total'; - const TARGET_SHIPPING = 'shipping'; protected $_batchId; - protected $_mailchimpHelper; - protected $_mailchimpDateHelper; /** * @var Ebizmarts_MailChimp_Model_Api_PromoRules */ protected $_apiPromoRules; + /** + * @var $_ecommercePromoCodesCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoCodes_Collection + */ + protected $_ecommercePromoCodesCollection; + public function __construct() { - $this->_mailchimpHelper = Mage::helper('mailchimp'); - $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); + parent::__construct(); } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - public function createBatchJson($mailchimpStoreId, $magentoStoreId) + public function createBatchJson() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + + $this->_ecommercePromoCodesCollection = $this->createEcommercePromoCodesCollection(); + $this->_ecommercePromoCodesCollection->setMailchimpStoreId($mailchimpStoreId); + $this->_ecommercePromoCodesCollection->setStoreId($magentoStoreId); + $batchArray = array(); $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE . '_' - . Mage::helper('mailchimp/date')->getDateMicrotime(); - $batchArray = array_merge($batchArray, $this->_getDeletedPromoCodes($mailchimpStoreId)); - $batchArray = array_merge($batchArray, $this->_getNewPromoCodes($mailchimpStoreId, $magentoStoreId)); + . $this->getDateHelper()->getDateMicrotime(); + $batchArray = array_merge($batchArray, $this->_getDeletedPromoCodes()); + $batchArray = array_merge($batchArray, $this->_getNewPromoCodes()); return $batchArray; } /** - * @param $mailchimpStoreId * @return array */ - protected function _getDeletedPromoCodes($mailchimpStoreId) + protected function _getDeletedPromoCodes() { + $mailchimpStoreId = $this->getMailchimpStoreId(); $batchArray = array(); - $deletedPromoCodes = $this->makeDeletedPromoCodesCollection($mailchimpStoreId); - + $deletedPromoCodes = $this->makeDeletedPromoCodesCollection(); $counter = 0; + foreach ($deletedPromoCodes as $promoCode) { $promoCodeId = $promoCode->getRelatedId(); $promoRuleId = $promoCode->getDeletedRelatedId(); @@ -69,7 +71,7 @@ protected function _getDeletedPromoCodes($mailchimpStoreId) . '/promo-codes/' . $promoCodeId; $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $promoCodeId; $batchArray[$counter]['body'] = ''; - $this->deletePromoCodeSyncData($promoCodeId, $mailchimpStoreId); + $this->deletePromoCodeSyncData($promoCodeId); $counter++; } @@ -77,61 +79,63 @@ protected function _getDeletedPromoCodes($mailchimpStoreId) } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - protected function _getNewPromoCodes($mailchimpStoreId, $magentoStoreId) + protected function _getNewPromoCodes() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); $batchArray = array(); - $helper = $this->getMailChimpHelper(); - $dateHelper = $this->getMailChimpDateHelper(); + $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); $newPromoCodes = $this->makePromoCodesCollection($magentoStoreId); - $this->joinMailchimpSyncDataWithoutWhere($newPromoCodes, $mailchimpStoreId); + $this->joinMailchimpSyncDataWithoutWhere($newPromoCodes); // be sure that the orders are not in mailchimp $websiteId = Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId(); $autoGeneratedCondition = "salesrule.use_auto_generation = 1 AND main_table.is_primary IS NULL"; $notAutoGeneratedCondition = "salesrule.use_auto_generation = 0 AND main_table.is_primary = 1"; - $newPromoCodes->getSelect()->where( - "m4m.mailchimp_sync_delta IS NULL AND website.website_id = " . $websiteId - . " AND ( " . $autoGeneratedCondition . " OR " . $notAutoGeneratedCondition . ")" - ); + + $where = "m4m.mailchimp_sync_delta IS NULL AND website.website_id = " . $websiteId + . " AND ( " . $autoGeneratedCondition . " OR " . $notAutoGeneratedCondition . ")"; + + $this->_ecommercePromoCodesCollection->addWhere($newPromoCodes, $where); // send most recently created first $newPromoCodes->getSelect()->order(array('salesrule.rule_id DESC')); // limit the collection - $newPromoCodes->getSelect()->limit($this->getBatchLimitFromConfig()); + $this->_ecommercePromoCodesCollection->limitCollection($newPromoCodes, $this->getBatchLimitFromConfig()); + $counter = 0; + foreach ($newPromoCodes as $promoCode) { $codeId = $promoCode->getCouponId(); $ruleId = $promoCode->getRuleId(); + try { - $promoRuleSyncData = $this->getMailChimpHelper()->getEcommerceSyncDataItem( + $promoRuleSyncData = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, $mailchimpStoreId ); - if (!$promoRuleSyncData->getId() - || $promoRuleSyncData->getMailchimpSyncDelta() < $helper->getEcommMinSyncDateFlag( - $mailchimpStoreId, $magentoStoreId - ) - ) { + + if (!$promoRuleSyncData->getId()) { $promoRuleMailchimpData = $this->getApiPromoRules()->getNewPromoRule( $ruleId, $mailchimpStoreId, $magentoStoreId ); + if (!empty($promoRuleMailchimpData)) { $batchArray[$counter] = $promoRuleMailchimpData; $counter++; } else { - $this->setCodeWithParentError($mailchimpStoreId, $ruleId, $codeId); + $this->setCodeWithParentError($ruleId, $codeId); continue; } } if ($promoRuleSyncData->getMailchimpSyncError()) { - $this->setCodeWithParentError($mailchimpStoreId, $ruleId, $codeId); + $this->setCodeWithParentError($ruleId, $codeId); continue; } @@ -146,44 +150,51 @@ protected function _getNewPromoCodes($mailchimpStoreId, $magentoStoreId) $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $codeId; $batchArray[$counter]['body'] = $promoCodeJson; - $this->_updateSyncData( - $codeId, - $mailchimpStoreId, - null, - null, - 0, - null, - $promoCode->getToken() - ); + $this->addSyncDataToken($codeId, $promoCode->getToken()); $counter++; } else { $error = $helper->__('Something went wrong when retrieving the information.'); - $this->_updateSyncData( + $this->addSyncDataError( $codeId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), - $error + $error, + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); continue; } } else { $jsonErrorMsg = json_last_error_msg(); - $helper->logError("Promo code" . $codeId . " json encode failed (".$jsonErrorMsg.")"); - $this->_updateSyncData( + $this->logSyncError( + "Promo code" . $codeId . " json encode failed (".$jsonErrorMsg.")", + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $codeId, + 0 + ); + + $this->addSyncDataError( $codeId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $jsonErrorMsg, - 0, - null, null, false, - null, - -1 + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); } } catch (Exception $e) { - $helper->logError($e->getMessage()); + $this->logSyncError( + $e->getMessage(), + Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $codeId, + 0 + ); } } @@ -213,108 +224,49 @@ protected function getPromoCodeResourceCollection() */ public function makePromoCodesCollection($magentoStoreId) { - $helper = $this->getMailChimpHelper(); + $helper = $this->getHelper(); /** * @var Mage_SalesRule_Model_Resource_Coupon_Collection $collection */ $collection = $this->getPromoCodeResourceCollection(); - $helper->addResendFilter( - $collection, - $magentoStoreId, - Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE - ); - $this->addWebsiteColumn($collection); - $this->joinPromoRuleData($collection); + $helper->addResendFilter($collection, $magentoStoreId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE); + + $promoCollectionResource = $this->getEcommercePromoCodesCollection(); + $promoCollectionResource->addWebsiteColumn($collection); + $promoCollectionResource->joinPromoRuleData($collection); + return $collection; } /** - * @param $mailchimpStoreId * @return object */ - protected function makeDeletedPromoCodesCollection($mailchimpStoreId) + protected function makeDeletedPromoCodesCollection() { - $deletedPromoCodes = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection(); - $deletedPromoCodes->getSelect()->where( - "mailchimp_store_id = '" . $mailchimpStoreId + $deletedPromoCodes = $this->getMailchimpEcommerceSyncDataModel()->getCollection(); + $where = "mailchimp_store_id = '" . $this->getMailchimpStoreId() . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE - . "' AND mailchimp_sync_deleted = 1" - ); - $deletedPromoCodes->getSelect()->limit($this->getBatchLimitFromConfig()); - return $deletedPromoCodes; - } + . "' AND mailchimp_sync_deleted = 1"; - /** - * @return string - */ - public function getSyncDataTableName() - { - $mailchimpTableName = $this->getCoreResource()->getTableName('mailchimp/ecommercesyncdata'); + $this->_ecommercePromoCodesCollection->addWhere($deletedPromoCodes, $where, $this->getBatchLimitFromConfig()); - return $mailchimpTableName; + return $deletedPromoCodes; } /** * @param $collection - * @param $mailchimpStoreId */ - public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId) + public function joinMailchimpSyncDataWithoutWhere($collection) { - $joinCondition = "m4m.related_id = main_table.coupon_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; - $mailchimpTableName = $this->getSyncDataTableName(); - $collection->getSelect()->joinLeft( - array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, $mailchimpStoreId), - array( - "m4m.related_id", - "m4m.type", - "m4m.mailchimp_store_id", - "m4m.mailchimp_sync_delta", - "m4m.mailchimp_sync_modified" - ) + $columns = array( + "m4m.related_id", + "m4m.type", + "m4m.mailchimp_store_id", + "m4m.mailchimp_sync_delta", + "m4m.mailchimp_sync_modified" ); - } - /** - * update product sync data - * - * @param $codeId - * @param $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncDeleted - * @param int|null $token - * @param bool $saveOnlyIfexists - * @param null $deletedRelatedId - * @param bool $allowBatchRemoval - */ - protected function _updateSyncData( - $codeId, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncDeleted = null, - $token = null, - $saveOnlyIfexists = false, - $deletedRelatedId = null, - $allowBatchRemoval = true - ) { - $this->getMailChimpHelper()->saveEcommerceSyncData( - $codeId, - Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, - $mailchimpStoreId, - $syncDelta, - $syncError, - $syncModified, - $syncDeleted, - $token, - null, - $saveOnlyIfexists, - $deletedRelatedId, - $allowBatchRemoval - ); + $this->_ecommercePromoCodesCollection->joinLeftEcommerceSyncData($collection, $columns); } protected function generateCodeData($promoCode, $magentoStoreId) @@ -330,46 +282,6 @@ protected function generateCodeData($promoCode, $magentoStoreId) return $data; } - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function getMailChimpHelper() - { - return $this->_mailchimpHelper; - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function getMailChimpDateHelper() - { - return $this->_mailchimpDateHelper; - } - - protected function addWebsiteColumn($collection) - { - $websiteTableName = $this->getCoreResource()->getTableName('salesrule/website'); - $collection->getSelect()->joinLeft( - array('website' => $websiteTableName), - 'main_table.rule_id=website.rule_id', - array('*') - ); - } - - /** - * @param $collection - */ - protected function joinPromoRuleData($collection) - { - $salesRuleName = $this->getCoreResource()->getTableName('salesrule/rule'); - $conditions = 'main_table.rule_id=salesrule.rule_id'; - $collection->getSelect()->joinLeft( - array('salesrule' => $salesRuleName), - $conditions, - array('use_auto_generation' => 'use_auto_generation') - ); - } - protected function getRedemptionUrl($promoCode, $magentoStoreId) { $token = $this->getToken(); @@ -377,16 +289,17 @@ protected function getRedemptionUrl($promoCode, $magentoStoreId) $url = Mage::getModel('core/url')->setStore($magentoStoreId)->getUrl( 'mailchimp/cart/loadcoupon', array( - '_nosid' => true, - '_secure' => true, - 'coupon_id' =>$promoCode->getCouponId(), - 'coupon_token' => $token - ) + '_nosid' => true, + '_secure' => true, + 'coupon_id' => $promoCode->getCouponId(), + 'coupon_token' => $token + ) ) . 'mailchimp/cart/loadcoupon?coupon_id=' . $promoCode->getCouponId() . '&coupon_token=' . $token; + return $url; } @@ -395,7 +308,8 @@ protected function getRedemptionUrl($promoCode, $magentoStoreId) */ protected function getToken() { - $token = md5(rand(0, 9999999)); + $token = hash('md5', rand(0, 9999999)); + return $token; } @@ -426,25 +340,14 @@ public function markAsDeleted($codeId, $promoRuleId) */ protected function _setDeleted($codeId, $promoRuleId) { - $helper = $this->getMailChimpHelper(); - $promoCodes = $helper->getAllEcommerceSyncDataItemsPerId( + $promoCodes = $this->getMailchimpEcommerceSyncDataModel()->getAllEcommerceSyncDataItemsPerId( $codeId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE ); + foreach ($promoCodes as $promoCode) { $mailchimpStoreId = $promoCode->getMailchimpStoreId(); - $this->_updateSyncData( - $codeId, - $mailchimpStoreId, - null, - null, - 0, - 1, - null, - true, - $promoRuleId, - false - ); + $this->addDeletedRelatedId($codeId, $promoRuleId); } } @@ -455,11 +358,13 @@ protected function _setDeleted($codeId, $promoRuleId) public function deletePromoCodesSyncDataByRule($promoRule) { $promoCodeIds = $this->getPromoCodesForRule($promoRule->getRelatedId()); + foreach ($promoCodeIds as $promoCodeId) { - $promoCodeSyncDataItems = $this->getMailChimpHelper()->getAllEcommerceSyncDataItemsPerId( + $promoCodeSyncDataItems = $this->getMailchimpEcommerceSyncDataModel()->getAllEcommerceSyncDataItemsPerId( $promoCodeId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE ); + foreach ($promoCodeSyncDataItems as $promoCodeSyncDataItem) { $promoCodeSyncDataItem->delete(); } @@ -468,14 +373,13 @@ public function deletePromoCodesSyncDataByRule($promoRule) /** * @param $promoCodeId - * @param $mailchimpStoreId */ - public function deletePromoCodeSyncData($promoCodeId, $mailchimpStoreId) + public function deletePromoCodeSyncData($promoCodeId) { - $promoCodeSyncDataItem = $this->getMailChimpHelper()->getEcommerceSyncDataItem( + $promoCodeSyncDataItem = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $promoCodeId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, - $mailchimpStoreId + $this->getMailchimpStoreId() ); $promoCodeSyncDataItem->delete(); } @@ -487,24 +391,35 @@ public function deletePromoCodeSyncData($promoCodeId, $mailchimpStoreId) protected function getPromoCodesForRule($promoRuleId) { $promoCodes = array(); - $helper = $this->getMailChimpHelper(); - $promoRules = $helper->getAllEcommerceSyncDataItemsPerId( + $helper = $this->getHelper(); + $promoRules = $this->getMailchimpEcommerceSyncDataModel()->getAllEcommerceSyncDataItemsPerId( $promoRuleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE ); + foreach ($promoRules as $promoRule) { $mailchimpStoreId = $promoRule->getMailchimpStoreId(); $api = $helper->getApiByMailChimpStoreId($mailchimpStoreId); + if ($api !== null) { try { $mailChimpPromoCodes = $api->ecommerce->promoRules->promoCodes - ->getAll($mailchimpStoreId, $promoRuleId); + ->getAll($mailchimpStoreId, $promoRuleId); foreach ($mailChimpPromoCodes['promo_codes'] as $promoCode) { - $this->deletePromoCodeSyncData($promoCode['id'], $mailchimpStoreId); + $this->deletePromoCodeSyncData($promoCode['id']); } } catch (MailChimp_Error $e) { - $helper->logError($e->getFriendlyMessage()); + $this->logSyncError( + $e->getFriendlyMessage(), + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, + $this->getMagentoStoreId(), + 'magento_side_error', + 'Problem retrieving object', + 0, + $promoRuleId, + 0 + ); } } } @@ -523,29 +438,51 @@ protected function getPromoRuleIdByCouponId($promoCodeId) } /** - * @param $mailchimpStoreId * @param $ruleId * @param $codeId + * @throws Mage_Core_Model_Store_Exception */ - protected function setCodeWithParentError($mailchimpStoreId, $ruleId, $codeId) + protected function setCodeWithParentError($ruleId, $codeId) { - $dateHelper = $this->getMailChimpDateHelper(); + $dateHelper = $this->getDateHelper(); $error = Mage::helper('mailchimp')->__( 'Parent rule with id ' . $ruleId . ' has not been correctly sent.' ); - $this->_updateSyncData( + $this->addSyncDataError( $codeId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), - $error + $error, + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); } /** - * @return Mage_Core_Model_Abstract + * @return string + */ + protected function getItemType() + { + return Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoCodes_Collection + */ + public function createEcommercePromoCodesCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoCodes_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_promocodes_collection'); + + return $collection; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoCodes_Collection */ - protected function getCoreResource() + public function getEcommercePromoCodesCollection() { - return Mage::getSingleton('core/resource'); + return $this->_ecommercePromoCodesCollection; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php old mode 100644 new mode 100755 index 3ff05e956..56a5cd099 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/PromoRules.php @@ -9,24 +9,21 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ -class Ebizmarts_MailChimp_Model_Api_PromoRules +class Ebizmarts_MailChimp_Model_Api_PromoRules extends Ebizmarts_MailChimp_Model_Api_ItemSynchronizer { const BATCH_LIMIT = 50; const TYPE_FIXED = 'fixed'; const TYPE_PERCENTAGE = 'percentage'; const TARGET_PER_ITEM = 'per_item'; const TARGET_TOTAL = 'total'; - const TARGET_SHIPPING = 'shipping'; protected $_batchId; + /** - * @var Ebizmarts_MailChimp_Helper_Data - */ - protected $_mailchimpHelper; - /** - * @var Ebizmarts_MailChimp_Helper_Date + * @var $_ecommercePromoRulesCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoRules_Collection */ - protected $_mailchimpDateHelper; + protected $_ecommercePromoRulesCollection; + /** * @var Ebizmarts_MailChimp_Model_Api_PromoCodes */ @@ -34,38 +31,42 @@ class Ebizmarts_MailChimp_Model_Api_PromoRules public function __construct() { - $this->_mailchimpHelper = Mage::helper('mailchimp'); - $this->_mailchimpDateHelper = Mage::helper('mailchimp/date'); + parent::__construct(); $this->_promoCodes = Mage::getModel('mailchimp/api_promoCodes'); } /** - * @param $mailchimpStoreId - * @param $magentoStoreId * @return array */ - public function createBatchJson($mailchimpStoreId, $magentoStoreId) + public function createBatchJson() { + $mailchimpStoreId = $this->getMailchimpStoreId(); + $magentoStoreId = $this->getMagentoStoreId(); + + $this->_ecommercePromoRulesCollection = $this->createEcommercePromoRulesCollection(); + $this->_ecommercePromoRulesCollection->setMailchimpStoreId($mailchimpStoreId); + $this->_ecommercePromoRulesCollection->setStoreId($magentoStoreId); + $batchArray = array(); $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE . '_' - . $this->getMailChimpDateHelper()->getDateMicrotime(); - $batchArray = array_merge($batchArray, $this->_getModifiedAndDeletedPromoRules($mailchimpStoreId)); + . $this->getDateHelper()->getDateMicrotime(); + $batchArray = array_merge($batchArray, $this->_getModifiedAndDeletedPromoRules()); return $batchArray; } /** - * @param $mailchimpStoreId * @return array */ - protected function _getModifiedAndDeletedPromoRules($mailchimpStoreId) + protected function _getModifiedAndDeletedPromoRules() { + $mailchimpStoreId = $this->getMailchimpStoreId(); $batchArray = array(); - $deletedPromoRules = $this->makeModifiedAndDeletedPromoRulesCollection($mailchimpStoreId); - + $deletedPromoRules = $this->makeModifiedAndDeletedPromoRulesCollection(); $counter = 0; + foreach ($deletedPromoRules as $promoRule) { $ruleId = $promoRule->getRelatedId(); $batchArray[$counter]['method'] = "DELETE"; @@ -73,7 +74,7 @@ protected function _getModifiedAndDeletedPromoRules($mailchimpStoreId) $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $ruleId; $batchArray[$counter]['body'] = ''; $this->getPromoCodes()->deletePromoCodesSyncDataByRule($promoRule); - $this->deletePromoRuleSyncData($ruleId, $mailchimpStoreId); + $this->deletePromoRuleSyncData($ruleId); $counter++; } @@ -90,8 +91,9 @@ public function getNewPromoRule($ruleId, $mailchimpStoreId, $magentoStoreId) { $promoData = array(); $promoRule = $this->getPromoRule($ruleId); - $helper = $this->getMailChimpHelper(); - $dateHelper = $this->getMailChimpDateHelper(); + $helper = $this->getHelper(); + $dateHelper = $this->getDateHelper(); + try { $ruleData = $this->generateRuleData($promoRule); $promoRuleJson = json_encode($ruleData); @@ -106,37 +108,54 @@ public function getNewPromoRule($ruleId, $mailchimpStoreId, $magentoStoreId) . $dateHelper->getDateMicrotime() . '_' . $ruleId; $promoData['body'] = $promoRuleJson; //update promo rule delta - $this->_updateSyncData($ruleId, $mailchimpStoreId); + $this->addSyncData($ruleId); } else { $error = $promoRule->getMailchimpSyncError(); + if (!$error) { $error = $helper->__('Something went wrong when retrieving the information.'); } - $this->_updateSyncData( + $this->addSyncDataError( $ruleId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), - $error + $error, + null, + false, + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); } } else { $jsonErrorMsg = json_last_error_msg(); - $helper->logError("Promo rule " . $ruleId . " json encode failed (".$jsonErrorMsg.")"); + $this->logSyncError( + $jsonErrorMsg, + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $ruleId, + 0 + ); - $this->_updateSyncData( + $this->addSyncDataError( $ruleId, - $mailchimpStoreId, - $dateHelper->formatDate(null, "Y-m-d H:i:s"), $jsonErrorMsg, - 0, null, false, - -1 + $dateHelper->formatDate(null, "Y-m-d H:i:s") ); } } catch (Exception $e) { - $helper->logError($e->getMessage()); + $this->logSyncError( + $e->getMessage(), + Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, + $magentoStoreId, + 'magento_side_error', + 'Json Encode Failure', + 0, + $ruleId, + 0 + ); } return $promoData; @@ -148,6 +167,7 @@ public function getNewPromoRule($ruleId, $mailchimpStoreId, $magentoStoreId) protected function getBatchLimitFromConfig() { $batchLimit = self::BATCH_LIMIT; + return $batchLimit; } @@ -180,105 +200,39 @@ public function makePromoRulesCollection($magentoStoreId) $collection = $this->getPromoRuleResourceCollection(); $websiteId = $this->getWebsiteIdByStoreId($magentoStoreId); $collection->addWebsiteFilter($websiteId); - return $collection; - } - /** - * @param $mailchimpStoreId - * @return Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata_Collection - */ - protected function makeModifiedAndDeletedPromoRulesCollection($mailchimpStoreId) - { - $deletedPromoRules = Mage::getModel('mailchimp/ecommercesyncdata')->getCollection(); - $deletedPromoRules->getSelect()->where( - "mailchimp_store_id = '" . $mailchimpStoreId - . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE - . "' AND (mailchimp_sync_modified = 1 OR mailchimp_sync_deleted = 1)" - ); - $deletedPromoRules->getSelect()->limit($this->getBatchLimitFromConfig()); - return $deletedPromoRules; + return $collection; } /** - * @return string + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection */ - public function getSyncDataTableName() + protected function makeModifiedAndDeletedPromoRulesCollection() { - $mailchimpTableName = $this->getCoreResource()->getTableName('mailchimp/ecommercesyncdata'); + $deletedPromoRules = $this->getMailchimpEcommerceSyncDataModel()->getCollection(); - return $mailchimpTableName; - } - - /** - * @param $collection - * @param $mailchimpStoreId - */ - public function joinMailchimpSyncDataWithoutWhere($collection, $mailchimpStoreId) - { - $joinCondition = "m4m.related_id = main_table.rule_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; - $mailchimpTableName = $this->getSyncDataTableName(); - $collection->getSelect()->joinLeft( - array("m4m" => $mailchimpTableName), - sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, $mailchimpStoreId), - array( - "m4m.related_id", - "m4m.type", - "m4m.mailchimp_store_id", - "m4m.mailchimp_sync_delta", - "m4m.mailchimp_sync_modified" - ) + $this->_ecommercePromoRulesCollection->addWhere( + $deletedPromoRules, + "mailchimp_store_id = '" . $this->getMailchimpStoreId() + . "' AND type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE + . "' AND (mailchimp_sync_modified = 1 OR mailchimp_sync_deleted = 1)", + $this->getBatchLimitFromConfig() ); - } - /** - * update promo rule sync data - * - * @param int $ruleId - * @param string $mailchimpStoreId - * @param int|null $syncDelta - * @param int|null $syncError - * @param int|null $syncModified - * @param int|null $syncDeleted - * @param bool $saveOnlyIfexists - * @param bool $allowBatchRemoval - */ - protected function _updateSyncData( - $ruleId, - $mailchimpStoreId, - $syncDelta = null, - $syncError = null, - $syncModified = 0, - $syncDeleted = null, - $saveOnlyIfexists = false, - $allowBatchRemoval = true - ) { - $this->getMailChimpHelper()->saveEcommerceSyncData( - $ruleId, - Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, - $mailchimpStoreId, - $syncDelta, - $syncError, - $syncModified, - $syncDeleted, - null, - null, - $saveOnlyIfexists, - null, - $allowBatchRemoval - ); + return $deletedPromoRules; } /** * @param $ruleId - * @param $mailchimpStoreId */ - protected function deletePromoRuleSyncData($ruleId, $mailchimpStoreId) + protected function deletePromoRuleSyncData($ruleId) { - $ruleSyncDataItem = $this->getMailChimpHelper()->getEcommerceSyncDataItem( + $ruleSyncDataItem = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE, - $mailchimpStoreId + $this->getMailchimpStoreId() ); + $ruleSyncDataItem->delete(); } @@ -329,22 +283,6 @@ protected function generateRuleData($promoRule) return $data; } - /** - * @return Ebizmarts_MailChimp_Helper_Data - */ - protected function getMailChimpHelper() - { - return $this->_mailchimpHelper; - } - - /** - * @return Ebizmarts_MailChimp_Helper_Date - */ - protected function getMailChimpDateHelper() - { - return $this->_mailchimpDateHelper; - } - /** * @param $promoAction * @return string|null @@ -372,6 +310,7 @@ protected function getMailChimpType($promoAction) protected function getMailChimpTarget($promoAction) { $mailChimpTarget = null; + switch ($promoAction) { case Mage_SalesRule_Model_Rule::CART_FIXED_ACTION: case Mage_SalesRule_Model_Rule::BY_PERCENT_ACTION: @@ -398,23 +337,15 @@ public function update($ruleId) */ protected function _setModified($ruleId) { - $helper = $this->getMailChimpHelper(); - $promoRules = $helper->getAllEcommerceSyncDataItemsPerId( + $promoRules = $this->getMailchimpEcommerceSyncDataModel()->getAllEcommerceSyncDataItemsPerId( $ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE ); + foreach ($promoRules as $promoRule) { $mailchimpStoreId = $promoRule->getMailchimpStoreId(); - $this->_updateSyncData( - $ruleId, - $mailchimpStoreId, - null, - null, - 1, - null, - true, - false - ); + $this->setMailchimpStoreId($mailchimpStoreId); + $this->markSyncDataAsModified($ruleId); } } @@ -431,23 +362,12 @@ public function markAsDeleted($ruleId) */ protected function _setDeleted($ruleId) { - $helper = $this->getMailChimpHelper(); - $promoRules = $helper->getAllEcommerceSyncDataItemsPerId( - $ruleId, - Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE - ); + $promoRules = $this->getMailchimpEcommerceSyncDataModel() + ->getAllEcommerceSyncDataItemsPerId($ruleId, Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE); + foreach ($promoRules as $promoRule) { - $mailchimpStoreId = $promoRule->getMailchimpStoreId(); - $this->_updateSyncData( - $ruleId, - $mailchimpStoreId, - null, - null, - 0, - 1, - true, - false - ); + $this->setMailchimpStoreId($promoRule->getMailchimpStoreId()); + $this->markSyncDataAsDeleted($ruleId); } } @@ -458,6 +378,7 @@ protected function _setDeleted($ruleId) protected function getMailChimpDiscountAmount($promoRule) { $action = $promoRule->getSimpleAction(); + if ($action == Mage_SalesRule_Model_Rule::BY_PERCENT_ACTION) { $mailChimpDiscount = ($promoRule->getDiscountAmount() / 100); } else { @@ -484,14 +405,6 @@ protected function getWebsiteIdByStoreId($magentoStoreId) return Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId(); } - /** - * @return Mage_Core_Model_Abstract - */ - protected function getCoreResource() - { - return Mage::getSingleton('core/resource'); - } - /** * @param $data * @return bool @@ -525,4 +438,25 @@ protected function ruleHasMissingInformation($data) return $hasMissingInformation; } + + /** + * @return string + */ + protected function getItemType() + { + return Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE; + } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoRules_Collection + */ + public function createEcommercePromoRulesCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoRules_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_promorules_collection'); + + return $collection; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index 4b7052a6f..851d8d1e0 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -43,7 +43,7 @@ public function createMailChimpStore( $helper = $this->makeHelper(); $dateHelper = $this->makeDateHelper(); $date = $dateHelper->getDateMicrotime(); - $mailchimpStoreId = md5($storeName . '_' . $date); + $mailchimpStoreId = hash('md5', $storeName . '_' . $date); try { $api = $helper->getApiByKey($apiKey); @@ -170,7 +170,7 @@ public function editMailChimpStore( * @param $e MailChimp_Error * @return string */ - private function getUserFriendlyMessage($e) + protected function getUserFriendlyMessage($e) { $helper = $this->makeHelper(); $errorMessage = $e->getFriendlyMessage(); @@ -178,13 +178,13 @@ private function getUserFriendlyMessage($e) if (strstr($errorMessage, 'A store with the domain')) { $errorMessage = $helper->__( 'A Mailchimp store with the same domain already exists in this account. ' - . 'You need to have a different URLs for each scope you set up the ecommerce data. ' - . 'Possible solutions ' + . 'You need to have a different URLs for each scope you set up the ecommerce data. ' + . 'Possible solutions ' ) - . "" - . "HERE and " - . "" - . "HERE"; + . "" + . "HERE and " + . "" + . "HERE"; } else { if (is_array($e->getMailchimpErrors())) { $errorDetail = ""; @@ -215,10 +215,12 @@ private function getUserFriendlyMessage($e) * @param $apiKey * @return mixed|string * @throws Mage_Core_Exception + * @throws Ebizmarts_MailChimp_Helper_Data_ApiKeyException */ public function deleteMailChimpStore($mailchimpStoreId, $apiKey) { $helper = $this->makeHelper(); + try { $api = $helper->getApiByKey($apiKey); $response = $api->getEcommerce()->getStores()->delete($mailchimpStoreId); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php old mode 100644 new mode 100755 index fcc3e5a08..bfc5ab284 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -20,6 +20,11 @@ class Ebizmarts_MailChimp_Model_Api_Subscribers protected $_mcDateHelper; protected $_storeId; + /** + * @var $_ecommerceSubscribersCollection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Subscribers_Collection + */ + protected $_ecommerceSubscribersCollection; + public function __construct() { $mageMCHelper = Mage::helper('mailchimp'); @@ -66,7 +71,11 @@ public function createBatchJson($listId, $storeId, $limit) $this->getStoreId() ); + $this->_ecommerceSubscribersCollection = $this->getEcommerceSubscribersCollection(); + $this->_ecommerceSubscribersCollection->setStoreId($this->getStoreId()); + $subscriberArray = array(); + if ($thisScopeHasList && !$thisScopeHasSubMinSyncDateFlag || !$helper->getSubMinSyncDateFlag($this->getStoreId()) ) { @@ -101,16 +110,17 @@ public function createBatchJson($listId, $storeId, $limit) array('eq' => 1) ) ); + $collection->addFieldToFilter('mailchimp_sync_error', array('eq' => '')); - $collection->getSelect()->limit($limit); + $this->_ecommerceSubscribersCollection->limitCollection($collection, $limit); $date = $dateHelper->getDateMicrotime(); - $batchId = 'storeid-'.$this->getStoreId(). '_' .Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_'.$date; + $batchId = 'storeid-' . $this->getStoreId() . '_' + . Ebizmarts_MailChimp_Model_Config::IS_SUBSCRIBER . '_' . $date; $counter = 0; foreach ($collection as $subscriber) { $data = $this->_buildSubscriberData($subscriber); - $emailHash = md5(strtolower($subscriber->getSubscriberEmail())); - $subscriberJson = ""; + $emailHash = hash('md5', strtolower($subscriber->getSubscriberEmail())); //encode to JSON $subscriberJson = json_encode($data); @@ -128,23 +138,21 @@ public function createBatchJson($listId, $storeId, $limit) $subscriberArray[$counter]['operation_id'] = $batchId . '_' . $subscriber->getSubscriberId(); $subscriberArray[$counter]['body'] = $subscriberJson; - //update subscribers delta - $subscriber->setData("mailchimp_sync_delta", $this->_mcDateHelper->formatDate(null, 'Y-m-d H:i:s')); - $subscriber->setData("mailchimp_sync_error", ""); - $subscriber->setData("mailchimp_sync_modified", 0); - $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE); - $subscriber->save(); + $this->_saveSubscriber( + $subscriber, + '', + $this->_mcDateHelper->formatDate(null, 'Y-m-d H:i:s'), + true + ); } } else { //json encode failed $jsonErrorMsg = json_last_error_msg(); $errorMessage = "Subscriber " . $subscriber->getSubscriberId() - . " json encode failed (".$jsonErrorMsg.")"; + . " json encode failed (" . $jsonErrorMsg . ")"; $helper->logError($errorMessage); - $subscriber->setData("mailchimp_sync_error", $jsonErrorMsg); - $subscriber->setData("mailchimp_sync_modified", 0); - $subscriber->save(); + $this->_saveSubscriber($subscriber, $jsonErrorMsg); } $counter++; @@ -153,6 +161,24 @@ public function createBatchJson($listId, $storeId, $limit) return $subscriberArray; } + /** + * @param $subscriber + * @param $error + * @param null $syncDelta + * @param bool $setSource + */ + protected function _saveSubscriber($subscriber, $error, $syncDelta = null, $setSource = false) + { + if ($setSource) { + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE); + } + + $subscriber->setData("mailchimp_sync_delta", $syncDelta); + $subscriber->setData("mailchimp_sync_error", $error); + $subscriber->setData("mailchimp_sync_modified", 0); + $subscriber->save(); + } + /** * @param $subscriber * @return array @@ -174,12 +200,14 @@ protected function _buildSubscriberData($subscriber) $status = $this->translateMagentoStatusToMailchimpStatus($subscriber->getStatus()); $data["status_if_new"] = $status; + if ($subscriber->getMailchimpSyncModified()) { $data["status"] = $status; } $data["language"] = $helper->getStoreLanguageCode($storeId); $interest = $this->_getInterest($subscriber); + if (!empty($interest)) { $data['interests'] = $interest; } @@ -200,6 +228,7 @@ protected function _getInterest($subscriber) $helper = $this->getMailchimpHelper(); $interestsAvailable = $helper->getInterest($storeId); $interest = $helper->getInterestGroups(null, $subscriber->getSubscriberId(), $storeId, $interestsAvailable); + foreach ($interest as $i) { foreach ($i['category'] as $key => $value) { $rc[$value['id']] = $value['checked']; @@ -220,10 +249,12 @@ public function updateSubscriber($subscriber, $updateStatus = false) $helper = $this->getMailchimpHelper(); $storeId = $subscriber->getStoreId(); $subscriptionEnabled = $helper->isSubscriptionEnabled($storeId); + if ($subscriptionEnabled) { $listId = $helper->getGeneralList($storeId); $newStatus = $this->translateMagentoStatusToMailchimpStatus($subscriber->getStatus()); $forceStatus = ($updateStatus) ? $newStatus : null; + try { $api = $helper->getApi($storeId); } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { @@ -232,11 +263,10 @@ public function updateSubscriber($subscriber, $updateStatus = false) } $mailChimpTags = $this->_buildMailchimpTags($subscriber, $storeId); - $language = $helper->getStoreLanguageCode($storeId); $interest = $this->_getInterest($subscriber); + $emailHash = hash('md5', strtolower($subscriber->getSubscriberEmail())); - $emailHash = md5(strtolower($subscriber->getSubscriberEmail())); try { $api->lists->members->addOrUpdate( $listId, @@ -299,6 +329,7 @@ protected function _catchMailchimpSubsNotAppliedIf($e, $isAdmin, $subscriber) $helper = $this->getMailchimpHelper(); $errorMessage = $e->getFriendlyMessage(); $helper->logError($errorMessage); + if ($isAdmin) { $this->addError($errorMessage); } else { @@ -319,6 +350,7 @@ protected function _catchMailchimpSubsNotAppliedElse($e, $isAdmin, $subscriber) $helper = $this->getMailchimpHelper(); $errorMessage = $e->getFriendlyMessage(); $helper->logError($errorMessage); + if ($isAdmin) { $this->addError($errorMessage); } else { @@ -439,9 +471,10 @@ public function deleteSubscriber($subscriber) $helper = $this->getMailchimpHelper(); $storeId = $subscriber->getStoreId(); $listId = $helper->getGeneralList($storeId); + try { $api = $helper->getApi($storeId); - $emailHash = md5(strtolower($subscriber->getSubscriberEmail())); + $emailHash = hash('md5', strtolower($subscriber->getSubscriberEmail())); $api->getLists()->getMembers()->update($listId, $emailHash, null, 'unsubscribed'); } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $helper->logError($e->getMessage()); @@ -459,6 +492,7 @@ public function deleteSubscriber($subscriber) public function update($emailAddress) { $subscriber = Mage::getSingleton('newsletter/subscriber')->loadByEmail($emailAddress); + if ($subscriber->getId()) { $subscriber->setMailchimpSyncModified(1) ->save(); @@ -529,6 +563,7 @@ protected function getMailchimpDateHelper() protected function getAddressFromLastOrder($lastOrder) { $addressData = array(); + if ($lastOrder && $lastOrder->getShippingAddress()) { $addressData = $lastOrder->getShippingAddress(); } @@ -551,7 +586,7 @@ protected function getSubscriberSyncDataItem($itemId, $magentoStoreId) ->setPageSize(1); if ($collection->getSize()) { - $subscriberSyncDataItem = $collection->getFirstItem(); + $subscriberSyncDataItem = $collection->getLastItem(); } return $subscriberSyncDataItem; @@ -583,7 +618,22 @@ protected function _buildMailchimpTags($subscriber, $storeId) ->setWebsiteId($this->getWebsiteByStoreId($storeId))->load($subscriber->getCustomerId()) ); $mailChimpTags->buildMailChimpTags(); + return $mailChimpTags; } + + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Subscribers_Collection + */ + public function getEcommerceSubscribersCollection() + { + /** + * @var $collection Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Subscribers_Collection + */ + $collection = Mage::getResourceModel('mailchimp/ecommercesyncdata_subscribers_collection'); + + return $collection; + } + } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php index 4e9fc2301..c1b734d3f 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers/MailchimpTags.php @@ -588,11 +588,15 @@ protected function addCompany($customAtt, $customer, $key) protected function getLastOrderByEmail() { $lastOrder = $this->getLastOrder(); + if ($lastOrder === null) { $helper = $this->getMailchimpHelper(); - $orderCollection = $helper->getOrderCollectionByCustomerEmail($this->getSubscriber()->getSubscriberEmail()); + $orderCollection = $helper->getOrderCollectionByCustomerEmail($this->getSubscriber()->getSubscriberEmail()) + ->setOrder('created_at', 'DESC') + ->setPageSize(1); + if ($this->isNotEmptyOrderCollection($orderCollection)) { - $lastOrder = $orderCollection->setOrder('created_at', 'DESC')->getFirstItem(); + $lastOrder = $orderCollection->getLastItem(); $this->setLastOrder($lastOrder); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php b/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php index d0af86ed6..a609b95cc 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ClearEcommerce.php @@ -23,7 +23,7 @@ class Ebizmarts_MailChimp_Model_ClearEcommerce protected $_dateHelper; /** - * @var Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata_Collection + * @var Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection */ protected $_ecommerceData; @@ -297,7 +297,7 @@ public function deleteEcommerceRows($ids, $type) } /** - * @return Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata_Collection + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection */ protected function getEcommerceCollection() { diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php index d5081bb98..4bb82041b 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php @@ -21,7 +21,6 @@ class Ebizmarts_MailChimp_Model_Config const GENERAL_CHECKOUT_SUBSCRIBE = 'mailchimp/general/checkout_subscribe'; const GENERAL_MCSTOREID = 'mailchimp/general/storeid'; const GENERAL_MCISSYNCING = 'mailchimp/general/is_syicing'; - const GENERAL_ECOMMMINSYNCDATEFLAG = 'mailchimp/general/mcminsyncdateflag'; const GENERAL_SUBMINSYNCDATEFLAG = 'mailchimp/general/subminsyncdateflag'; const GENERAL_TWO_WAY_SYNC = 'mailchimp/general/webhook_active'; const GENERAL_UNSUBSCRIBE = 'mailchimp/general/webhook_delete'; @@ -81,23 +80,20 @@ class Ebizmarts_MailChimp_Model_Config const POPUP_COOKIE_TIME = 'mailchimp/emailcatcher/popup_cookie_time'; const POPUP_INSIST = 'mailchimp/emailcatcher/popup_insist'; - const ABANDONEDCART_ACTIVE = 'mailchimp/abandonedcart/active'; - const ABANDONEDCART_FIRSTDATE = 'mailchimp/abandonedcart/firstdate'; - const ABANDONEDCART_PAGE = 'mailchimp/abandonedcart/page'; - const CART_AMOUNT = 'mailchimp/abandonedcart/cart_batch_amount'; + const ABANDONEDCART_ACTIVE = 'mailchimp/abandonedcart/active'; + const ABANDONEDCART_FIRSTDATE = 'mailchimp/abandonedcart/firstdate'; + const ABANDONEDCART_PAGE = 'mailchimp/abandonedcart/page'; + const ABANDONEDCART_AMOUNT = 'mailchimp/abandonedcart/cart_batch_amount'; - const WARNING_MESSAGE = 'mailchimp/warning_message'; - const POPUP_MESSAGE = 'mailchimp/popup_message'; + const MANDRILL_APIKEY = 'mandrill/general/apikey'; + const MANDRILL_ACTIVE = 'mandrill/general/active'; + const MANDRILL_LOG = 'mandrill/general/enable_log'; - const MANDRILL_APIKEY = 'mandrill/general/apikey'; - const MANDRILL_ACTIVE = 'mandrill/general/active'; - const MANDRILL_LOG = 'mandrill/general/enable_log'; - - const IS_CUSTOMER = "CUS"; - const IS_PRODUCT = "PRO"; - const IS_ORDER = "ORD"; - const IS_QUOTE = "QUO"; - const IS_SUBSCRIBER = "SUB"; - const IS_PROMO_RULE = "PRL"; - const IS_PROMO_CODE = "PCD"; + const IS_CUSTOMER = "CUS"; + const IS_PRODUCT = "PRO"; + const IS_ORDER = "ORD"; + const IS_QUOTE = "QUO"; + const IS_SUBSCRIBER = "SUB"; + const IS_PROMO_RULE = "PRL"; + const IS_PROMO_CODE = "PCD"; } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php b/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php index 567db65dd..2c87de56d 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata.php @@ -23,4 +23,156 @@ public function _construct() parent::_construct(); $this->_init('mailchimp/ecommercesyncdata'); } + + /** + * Save entry for ecommerce_sync_data table overwriting old item if exists or creating a new one if it does not. + * + * @param $itemId + * @param $itemType + * @param $mailchimpStoreId + * @param null $syncDelta + * @param null $syncError + * @param int $syncModified + * @param null $syncDeleted + * @param null $token + * @param null $syncedFlag + * @param bool $saveOnlyIfexists + * @param null $deletedRelatedId + * @param bool $allowBatchRemoval + */ + public function saveEcommerceSyncData( + $itemId, + $itemType, + $mailchimpStoreId, + $syncDelta = null, + $syncError = null, + $syncModified = 0, + $syncDeleted = null, + $token = null, + $syncedFlag = null, + $saveOnlyIfexists = false, + $deletedRelatedId = null, + $allowBatchRemoval = true + ) { + $ecommerceSyncDataItem = $this->getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId); + + if (!$saveOnlyIfexists || $ecommerceSyncDataItem->getMailchimpSyncDelta()) { + $this->setEcommerceSyncDataItemValues( + $itemId, $itemType, $syncDelta, $syncError, $syncModified, $syncDeleted, + $token, $syncedFlag, $deletedRelatedId, $allowBatchRemoval, $ecommerceSyncDataItem + ); + + $ecommerceSyncDataItem->save(); + } + } + + /** + * Load Ecommerce Sync Data Item if exists or set the values for a new one and return it. + * + * @param $itemId + * @param $itemType + * @param $mailchimpStoreId + * @return Ebizmarts_MailChimp_Model_Ecommercesyncdata + */ + public function getEcommerceSyncDataItem($itemId, $itemType, $mailchimpStoreId) + { + $collection = $this->getCollection() + ->addFieldToFilter('related_id', array('eq' => $itemId)) + ->addFieldToFilter('type', array('eq' => $itemType)) + ->addFieldToFilter('mailchimp_store_id', array('eq' => $mailchimpStoreId)) + ->setCurPage(1) + ->setPageSize(1); + + if ($collection->getSize()) { + $ecommerceSyndDataItem = $collection->getLastItem(); + } else { + $ecommerceSyndDataItem = $this->setData("related_id", $itemId) + ->setData("type", $itemType) + ->setData("mailchimp_store_id", $mailchimpStoreId); + } + + return $ecommerceSyndDataItem; + } + + /** + * @param $itemId + * @param $itemType + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection + */ + public function getAllEcommerceSyncDataItemsPerId($itemId, $itemType) + { + $collection = $this->getCollection() + ->addFieldToFilter('related_id', array('eq' => $itemId)) + ->addFieldToFilter('type', array('eq' => $itemType)); + + return $collection; + } + + /** + * @param $itemId + * @param $itemType + * @param $syncDelta + * @param $syncError + * @param $syncModified + * @param $syncDeleted + * @param $token + * @param $syncedFlag + * @param $deletedRelatedId + * @param $allowBatchRemoval + * @param Ebizmarts_MailChimp_Model_Ecommercesyncdata $ecommerceSyncDataItem + */ + protected function setEcommerceSyncDataItemValues( + $itemId, + $itemType, + $syncDelta, + $syncError, + $syncModified, + $syncDeleted, + $token, + $syncedFlag, + $deletedRelatedId, + $allowBatchRemoval, + Ebizmarts_MailChimp_Model_Ecommercesyncdata $ecommerceSyncDataItem + ) { + if ($itemId) { + $ecommerceSyncDataItem->setData("related_id", $itemId); + } + + if ($syncDelta) { + $ecommerceSyncDataItem->setData("mailchimp_sync_delta", $syncDelta); + } elseif ($allowBatchRemoval === true) { + $ecommerceSyncDataItem->setData("batch_id", null); + } + + if ($allowBatchRemoval === -1) { + $ecommerceSyncDataItem->setData("batch_id", '-1'); + } + + if ($syncError) { + $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); + } + + //Always set modified value to 0 when saving sync delta or errors. + $ecommerceSyncDataItem->setData("mailchimp_sync_modified", $syncModified); + + if ($syncDeleted !== null) { + $ecommerceSyncDataItem->setData("mailchimp_sync_deleted", $syncDeleted); + + if ($itemType == Ebizmarts_MailChimp_Model_Config::IS_PRODUCT && $syncError == '') { + $ecommerceSyncDataItem->setData("mailchimp_sync_error", $syncError); + } + } + + if ($token) { + $ecommerceSyncDataItem->setData("mailchimp_token", $token); + } + + if ($deletedRelatedId) { + $ecommerceSyncDataItem->setData("deleted_related_id", $deletedRelatedId); + } + + if ($syncedFlag !== null) { + $ecommerceSyncDataItem->setData("mailchimp_synced_flag", $syncedFlag); + } + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata/Quote.php b/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata/Quote.php new file mode 100755 index 000000000..a3b41fb37 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Ecommercesyncdata/Quote.php @@ -0,0 +1,26 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-10-02 15:53 + * @file: Ecommercesyncdata.php + */ +class Ebizmarts_MailChimp_Model_Ecommercesyncdata_Quote extends Ebizmarts_MailChimp_Model_Ecommercesyncdata +{ + + /** + * Initialize + * + * @return void + */ + public function _construct() + { + + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php index bc73a2d0f..d65235e20 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Queue.php @@ -20,24 +20,21 @@ class Ebizmarts_MailChimp_Model_Email_Queue extends Mage_Core_Model_Email_Queue */ public function send() { - $mageMCHelper = Mage::helper('mailchimp'); - $mageMCDateHelper = Mage::helper('mailchimp/date'); - /** - * @var $collection Mage_Core_Model_Resource_Email_Queue_Collection -*/ + * @var $collection Mage_Core_Model_Resource_Email_Queue_Collection + */ $collection = Mage::getResourceModel('core/email_queue_collection') ->addOnlyForSendingFilter() ->setPageSize(self::MESSAGES_LIMIT_PER_CRON_RUN) ->setCurPage(1) ->load(); /** - * @var $message Mage_Core_Model_Email_Queue -*/ + * @var $message Mage_Core_Model_Email_Queue + */ foreach ($collection as $message) { if ($message->getId()) { if ($message->getEntityType() == 'order') { - $order = Mage::getModel('sales/order')->load($message->getEntityId()); + $order = $this->_getOrderByEntityId($message->getEntityId()); $storeId = $order->getStoreId(); } else { //If email is not an order confirmation email, it will check if Mandrill enable in default config @@ -49,21 +46,20 @@ public function send() try { $this->_sendMandrillEnabled($message, $parameters, $storeId); - $message->setProcessedAt($mageMCDateHelper->formatDate(null, 'Y-m-d H:i:s')); - $message->save(); + $this->_saveMessage($message); } catch (Exception $e) { Mage::logException($e); } } else { $parameters = new Varien_Object($message->getMessageParameters()); + if ($parameters->getReturnPathEmail() !== null) { $mailTransport = new Zend_Mail_Transport_Sendmail("-f" . $parameters->getReturnPathEmail()); Zend_Mail::setDefaultTransport($mailTransport); } $this->_sendMandrillNotEnabled($message, $parameters); - $message->setProcessedAt($mageMCDateHelper->formatDate(null, 'Y-m-d H:i:s')); - $message->save(); + $this->_saveMessage($message); } } } @@ -71,6 +67,26 @@ public function send() return $this; } + /** + * @param $entityId + * @return Mage_Core_Model_Abstract + */ + protected function _getOrderByEntityId($entityId) + { + return Mage::getModel('sales/order')->load($entityId); + } + + /** + * @param $message + */ + protected function _saveMessage($message) + { + $mageMCDateHelper = Mage::helper('mailchimp/date'); + + $message->setProcessedAt($mageMCDateHelper->formatDate(null, 'Y-m-d H:i:s')); + $message->save(); + } + /** * @param $message * @param $parameters diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php index 222f8b799..39cff3ebe 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php @@ -176,7 +176,7 @@ protected function _getEmailFrom($mail) if (isset($sender['domain'])) { $emailArray = explode('@', $fromEmail); - if (count($emailArray) > 1 && $emailArray[1] == $sender['domain']) { + if (isset($emailArray[1]) && $emailArray[1] == $sender['domain']) { $senderExists = true; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mailchimperrors.php b/app/code/community/Ebizmarts/MailChimp/Model/Mailchimperrors.php index 405d60e20..337c25066 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mailchimperrors.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Mailchimperrors.php @@ -1,4 +1,5 @@ - * @copyright Ebizmarts (http://ebizmarts.com) - * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 5/16/16 6:53 PM - * @file: Collection.php - */ - -class Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract -{ - - /** - * Set resource type - * - * @return void - */ - public function _construct() - { - parent::_construct(); - $this->_init('mailchimp/ecommercesyncdata'); - } -} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index ae82b3638..59d452917 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -14,7 +14,6 @@ class Ebizmarts_MailChimp_Model_Observer { const PRODUCT_IS_ENABLED = 1; - const PRODUCT_IS_DISABLED = 2; /** * @return Mage_Core_Model_Resource @@ -107,13 +106,14 @@ protected function getCustomerModel() /** * Handle save of System -> Configuration, section * - * @param Varien_Event_Observer $observer - * @return Varien_Event_Observer - * @throws Mage_Core_Exception + * @param Varien_Event_Observer $observer + * @return Varien_Event_Observer + * @throws Mage_Core_Exception */ public function saveConfigBefore(Varien_Event_Observer $observer) { $config = $observer->getObject(); + if ($config->getSection() == "mailchimp") { $configData = $config->getData(); $configDataChanged = false; @@ -189,9 +189,9 @@ protected function isListXorStoreInherited($configData) /** * Handle confirmation emails and subscription to Mailchimp * - * @param Varien_Event_Observer $observer - * @return Varien_Event_Observer - * @throws Mage_Core_Exception + * @param Varien_Event_Observer $observer + * @return Varien_Event_Observer + * @throws Mage_Core_Exception */ public function subscriberSaveBefore(Varien_Event_Observer $observer) { @@ -219,10 +219,10 @@ public function subscriberSaveBefore(Varien_Event_Observer $observer) /** * Handle interest groups for subscriber and allow Magento email to be sent if configured that way. * - * @param Varien_Event_Observer $observer - * @return Varien_Event_Observer - * @throws Mage_Core_Exception - * @throws Mage_Core_Model_Store_Exception + * @param Varien_Event_Observer $observer + * @return Varien_Event_Observer + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception */ public function subscriberSaveAfter(Varien_Event_Observer $observer) { @@ -347,6 +347,7 @@ public function customerSaveAfter(Varien_Event_Observer $observer) $subscriberEmail = ($origEmail) ? $origEmail : $customerEmail; $subscriber = $this->handleCustomerGroups($subscriberEmail, $params, $storeId, $customerId); $apiSubscriber = $this->makeApiSubscriber(); + if ($origEmail) { // check if customer has changed email address if ($origEmail != $customerEmail) { @@ -370,7 +371,10 @@ public function customerSaveAfter(Varien_Event_Observer $observer) if ($helper->isEcomSyncDataEnabled($storeId)) { //update mailchimp ecommerce data for that customer - $this->makeApiCustomer()->update($customerId, $storeId); + $apiCustomer = $this->makeApiCustomer(); + $apiCustomer->setMailchimpStoreId($helper->getMCStoreId($storeId)); + $apiCustomer->setMagentoStoreId($storeId); + $apiCustomer->update($customerId); } } @@ -391,7 +395,10 @@ public function customerAddressSaveBefore(Varien_Event_Observer $observer) if ($helper->isEcomSyncDataEnabled($storeId)) { //update mailchimp ecommerce data for that customer - $this->makeApiCustomer()->update($customerId, $storeId); + $apiCustomer = $this->makeApiCustomer(); + $apiCustomer->setMailchimpStoreId($helper->getMCStoreId($storeId)); + $apiCustomer->setMagentoStoreId($storeId); + $apiCustomer->update($customerId); } return $observer; @@ -417,6 +424,7 @@ public function newOrder(Varien_Event_Observer $observer) if (isset($post)) { $email = $order->getCustomerEmail(); $subscriber = $helper->loadListSubscriber($post, $email); + if ($subscriber) { if (!$subscriber->getCustomerId()) { $subscriber->setSubscriberFirstname($order->getCustomerFirstname()); @@ -430,8 +438,8 @@ public function newOrder(Varien_Event_Observer $observer) if ($ecommEnabled) { $this->removeCampaignData(); - $items = $order->getAllItems(); + foreach ($items as $item) { if ($this->isBundleItem($item) || $this->isConfigurableItem($item)) { continue; @@ -439,14 +447,19 @@ public function newOrder(Varien_Event_Observer $observer) $mailchimpStoreId = $helper->getMCStoreId($storeId); $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); + if (!$isMarkedAsDeleted) { - $this->makeApiProduct()->update($productId, $mailchimpStoreId); + $apiProducts = $this->makeApiProduct(); + $apiProducts->setMailchimpStoreId($mailchimpStoreId); + $apiProducts->setMagentoStoreId($storeId); + $apiProducts->update($productId); } } } @@ -454,6 +467,14 @@ public function newOrder(Varien_Event_Observer $observer) return $observer; } + /** + * @return Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata + */ + public function getMailchimpEcommerceSyncDataModel() + { + return Mage::getModel('mailchimp/ecommercesyncdata'); + } + /** * Catch order save before event, mark it as modified and associate the landing page to the order data. * @@ -485,11 +506,13 @@ public function saveCampaignData(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); $campaignCookie = $this->_getCampaignCookie(); + if ($campaignCookie) { $order->setMailchimpCampaignId($campaignCookie); } $landingCookie = $this->_getLandingCookie(); + if ($landingCookie && !$order->getMailchimpLandingPage()) { $order->setMailchimpLandingPage($landingCookie); } @@ -629,10 +652,10 @@ public function addColumnToSalesOrderGrid(Varien_Event_Observer $observer) public function addColumnToSalesOrderGridCollection(Varien_Event_Observer $observer) { - $helper = $this->makeHelper(); $addColumnConfig = $helper->getMonkeyInGrid(0); $ecommEnabledAnyScope = $helper->isEcomSyncDataEnabledInAnyScope(); + if ($ecommEnabledAnyScope && $addColumnConfig) { $collection = $observer->getOrderGridCollection(); $select = $collection->getSelect(); @@ -653,6 +676,7 @@ public function addColumnToSalesOrderGridCollection(Varien_Event_Observer $obser ); $select->group("main_table.entity_id"); $direction = $this->getRegistry(); + if ($direction) { $collection->addOrder('mc.id', $direction); $this->removeRegistry(); @@ -683,6 +707,7 @@ public function loadCustomerToQuote(Varien_Event_Observer $observer) $action == 'saveShippingMethod' || $action == 'saveBilling'); $emailCookie = $this->getEmailCookie(); $mcEidCookie = $this->getMcEidCookie(); + if ($emailCookie && $emailCookie != 'none' && !$onCheckout ) { $email = $this->getEmailFromPopUp($emailCookie); @@ -726,7 +751,8 @@ public function newCreditMemo(Varien_Event_Observer $observer) if ($ecomEnabled) { $mailchimpStoreId = $helper->getMCStoreId($storeId); - + $apiProduct->setMailchimpStoreId($mailchimpStoreId); + $apiProduct->setMagentoStoreId($storeId); $items = $creditMemo->getAllItems(); foreach ($items as $item) { @@ -735,14 +761,16 @@ public function newCreditMemo(Varien_Event_Observer $observer) } $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); + if (!$isMarkedAsDeleted) { - $apiProduct->update($productId, $mailchimpStoreId); + $apiProduct->update($productId); } } @@ -770,22 +798,26 @@ public function cancelCreditMemo(Varien_Event_Observer $observer) if ($ecomEnabled) { $mailchimpStoreId = $helper->getMCStoreId($storeId); - + $apiProduct->setMagentoStoreId($storeId); + $apiProduct->setMailchimpStoreId($mailchimpStoreId); $items = $creditMemo->getAllItems(); + foreach ($items as $item) { if ($this->isBundleItem($item) || $this->isConfigurableItem($item)) { continue; } $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); + if (!$isMarkedAsDeleted) { - $apiProduct->update($productId, $mailchimpStoreId); + $apiProduct->update($productId); } } @@ -812,16 +844,20 @@ public function itemCancel(Varien_Event_Observer $observer) if ($ecomEnabled) { $mailchimpStoreId = $helper->getMCStoreId($storeId); + $apiProduct->setMailchimpStoreId($mailchimpStoreId); + $apiProduct->setMagentoStoreId($storeId); $productId = $item->getProductId(); - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); + if (!$this->isBundleItem($item) && !$this->isConfigurableItem($item) && !$isMarkedAsDeleted) { - $apiProduct->update($productId, $mailchimpStoreId); + $apiProduct->update($productId); } } @@ -839,32 +875,36 @@ public function productSaveAfter(Varien_Event_Observer $observer) $product = $observer->getEvent()->getProduct(); $helper = $this->makeHelper(); $apiProduct = $this->makeApiProduct(); - $stores = $helper->getMageApp()->getStores(); + foreach ($stores as $storeId => $store) { $ecommEnabled = $helper->isEcommerceEnabled($storeId); if ($ecommEnabled) { $mailchimpStoreId = $helper->getMCStoreId($storeId); - + $apiProduct->setMailchimpStoreId($mailchimpStoreId); + $apiProduct->setMagentoStoreId($storeId); $status = $this->getCatalogProductStatusModel()->getProductStatus($product->getId(), $storeId); + if ($status[$product->getId()] == self::PRODUCT_IS_ENABLED) { - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $product->getId(), Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); $errorMessage = $dataProduct->getMailchimpSyncError(); + if ($isMarkedAsDeleted || $errorMessage == Ebizmarts_MailChimp_Model_Api_Products::PRODUCT_DISABLED_IN_MAGENTO ) { $dataProduct->delete(); } else { - $apiProduct->update($product->getId(), $mailchimpStoreId); + $apiProduct->update($product->getId()); } } else { - $apiProduct->updateDisabledProducts($product->getId(), $mailchimpStoreId); + $apiProduct->updateDisabledProducts($product->getId()); } } } @@ -886,17 +926,20 @@ public function productAttributeUpdate(Varien_Event_Observer $observer) foreach ($mailchimpStoreIdsArray as $scopeData => $mailchimpStoreId) { $scopeArray = $this->getScopeArrayFromString($scopeData); $ecommEnabled = $helper->isEcommerceEnabled($scopeArray['scope_id'], $scopeArray['scope']); + $apiProduct->setMailchimpStoreId($mailchimpStoreId); if ($ecommEnabled) { foreach ($productIds as $productId) { - $dataProduct = $helper->getEcommerceSyncDataItem( + $dataProduct = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $productId, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $mailchimpStoreId ); + $isMarkedAsDeleted = $dataProduct->getMailchimpSyncDeleted(); + if (!$isMarkedAsDeleted) { - $apiProduct->update($productId, $mailchimpStoreId); + $apiProduct->update($productId); } } } @@ -914,6 +957,7 @@ protected function getEmailFromPopUp($emailCookie) $emailCookieArr = explode('/', $emailCookie); $email = $emailCookieArr[0]; $email = str_replace(' ', '+', $email); + return $email; } @@ -930,6 +974,7 @@ protected function getEmailFromMcEid($storeId, $mcEidCookie) $listId = $helper->getGeneralList($storeId); $listMember = $mailchimpApi->lists->members->getEmailByMcEid($listId, $mcEidCookie); $email = $listMember['members'][0]['email_address']; + return $email; } @@ -943,7 +988,11 @@ protected function handleOrderUpdate($order) if ($storeId == 0) { $this->handleAdminOrderUpdate($order); } else { - $this->makeApiOrder()->update($order->getId(), $storeId); + $helper = $this->makeHelper(); + $apiOrder = $this->makeApiOrder(); + $apiOrder->setMagentoStoreId($storeId); + $apiOrder->setMailchimpStoreId($helper->getMCStoreId($storeId)); + $apiOrder->update($order->getId(), $storeId); } } @@ -971,9 +1020,11 @@ public function secondaryCouponsDelete(Varien_Event_Observer $observer) { $promoCodesApi = $this->makeApiPromoCode(); $params = $this->getRequest()->getParams(); + if (isset($params['ids']) && isset($params['id'])) { $promoRuleId = $params['id']; $promoCodeIds = $params['ids']; + foreach ($promoCodeIds as $promoCodeId) { $promoCodesApi->markAsDeleted($promoCodeId, $promoRuleId); } @@ -995,7 +1046,8 @@ public function cleanProductImagesCacheAfter(Varien_Event_Observer $observer) protected function markProductsAsModified() { - $tableName = $mailchimpTableName = $this->getCoreResource()->getTableName('mailchimp/ecommercesyncdata'); + $tableName = $mailchimpTableName = $this->getCoreResource() + ->getTableName('mailchimp/ecommercesyncdata'); $sqlQuery = "UPDATE " . $tableName . " " . "SET mailchimp_sync_modified = 1 " . "WHERE type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT . "';"; @@ -1058,6 +1110,7 @@ protected function addSuccessIfRequired($helper) $moduleController = $request->getControllerName(); $moduleControllerAction = $request->getActionName(); $fullActionName = $module . '_' . $moduleController . '_' . $moduleControllerAction; + if (strstr($fullActionName, 'Mage_Newsletter_manage_save')) { Mage::getSingleton('customer/session')->addSuccess( $helper->__('Confirmation request has been sent.') @@ -1123,10 +1176,10 @@ protected function getRequest() /** * Handle frontend customer interest groups only if is not subscribed and all admin customer groups. * - * @param $subscriberEmail - * @param $params - * @param $storeId - * @param null $customerId + * @param $subscriberEmail + * @param $params + * @param $storeId + * @param null $customerId * @return Mage_Newsletter_Model_Subscriber * @throws Mage_Core_Model_Store_Exception */ @@ -1135,10 +1188,12 @@ public function handleCustomerGroups($subscriberEmail, $params, $storeId, $custo $helper = $this->makeHelper(); $subscriberModel = $this->getSubscriberModel(); $subscriber = $subscriberModel->loadByEmail($subscriberEmail); + if ($subscriber->getId()) { $helper->saveInterestGroupData($params, $storeId, $customerId, $subscriber); } elseif (isset($params['customer_id'])) { $groups = $helper->getInterestGroupsIfAvailable($params); + if ($groups) { $helper->saveInterestGroupData($params, $storeId, $customerId); $this->getWarningMessageAdminHtmlSession($helper); @@ -1157,6 +1212,7 @@ public function handleCustomerGroups($subscriberEmail, $params, $storeId, $custo protected function getEmailCookie() { $emailCookie = Mage::getModel('core/cookie')->get('email'); + return $emailCookie; } @@ -1166,6 +1222,7 @@ protected function getEmailCookie() protected function getMcEidCookie() { $mcEidCookie = Mage::getModel('core/cookie')->get('mailchimp_email_id'); + return $mcEidCookie; } @@ -1265,5 +1322,4 @@ protected function isMailchimpSave($subscriberSource) { return $subscriberSource === Ebizmarts_MailChimp_Model_Subscriber::MAILCHIMP_SUBSCRIBE; } - } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index f4f95f02a..5b7438d22 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -80,14 +80,22 @@ public function processWebhookData() } } - $webhookRequest->setProcessed(1)->save(); + $this->_saveProcessedWebhook($webhookRequest); } } + /** + * @param $webhookRequest + */ + protected function _saveProcessedWebhook($webhookRequest) + { + $webhookRequest->setProcessed(1)->save(); + } + /** * Update customer email * - * @param array $data + * @param array $data * @return void */ protected function _updateEmail(array $data) @@ -116,7 +124,7 @@ protected function _updateEmail(array $data) /** * Add "Cleaned Emails" notification to Adminnotification Inbox * - * @param array $data + * @param array $data * @return void */ protected function _clean(array $data) @@ -137,7 +145,7 @@ protected function _clean(array $data) /** * Subscribe email to Magento list, store aware * - * @param array $data + * @param array $data * @return void */ protected function _subscribe(array $data) @@ -174,7 +182,7 @@ protected function _subscribe(array $data) /** * Unsubscribe or delete email from Magento list, store aware * - * @param array $data + * @param array $data * @return void */ protected function _unsubscribe(array $data) @@ -287,7 +295,7 @@ protected function _addSubscriberData($subscriber, $fname, $lname, $email, $list try { $subscriber->setSubscriberFirstname($fname); $subscriber->setSubscriberLastname($lname); - $md5HashEmail = md5(strtolower($email)); + $md5HashEmail = hash('md5', strtolower($email)); $member = $api->getLists()->getMembers()->get( $listId, $md5HashEmail, diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata.php similarity index 72% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata.php index 63fa7891e..952d987fd 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Ecommercesyncdata.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata.php @@ -1,4 +1,5 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 5/16/16 6:37 PM - * @file: SychBatches.php + * @date: 2019-10-02 15:53 + * @file: Ecommercesyncdata.php */ -class Ebizmarts_MailChimp_Model_Mysql4_Ecommercesyncdata extends Mage_Core_Model_Mysql4_Abstract +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata extends Mage_Core_Model_Resource_Db_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Collection.php new file mode 100755 index 000000000..4cce9b842 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Collection.php @@ -0,0 +1,107 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-10-02 15:57 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection extends + Mage_Core_Model_Resource_Db_Collection_Abstract +{ + /** + * @var int + */ + protected $_storeId; + + /** + * @var string + */ + protected $_mailchimpStoreId; + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + $this->_init('mailchimp/ecommercesyncdata'); + } + + public function getMailchimpEcommerceDataTableName() + { + return $this->getCoreResource() + ->getTableName('mailchimp/ecommercesyncdata'); + } + + /** + * @return Mage_Core_Model_Resource + */ + public function getCoreResource() + { + return Mage::getSingleton('core/resource'); + } + + /** + * @return int + */ + public function getStoreId() + { + return $this->_storeId; + } + + /** + * @param int $storeId + */ + public function setStoreId($storeId) + { + $this->_storeId = $storeId; + } + + /** + * @return string + */ + public function getMailchimpStoreId() + { + return $this->_mailchimpStoreId; + } + + /** + * @param string $mailchimpStoreId + */ + public function setMailchimpStoreId($mailchimpStoreId) + { + $this->_mailchimpStoreId = $mailchimpStoreId; + } + + /** + * @param $collection Varien_Data_Collection_Db + * @param $limit + */ + public function limitCollection($collection, $limit) + { + $collection->getSelect()->limit($limit); + } + + /** + * @param $collection Varien_Data_Collection_Db + * @param $where + * @param int null $limit + */ + public function addWhere($collection, $where = null, $limit = null) + { + if (isset($where)) { + $collection->getSelect()->where($where); + } + + if (isset($limit)) { + $collection->getSelect()->limit($limit); + } + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Customers/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Customers/Collection.php new file mode 100755 index 000000000..09ed33ba5 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Customers/Collection.php @@ -0,0 +1,41 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Customers_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_Customer_Model_Resource_Customer_Collection $preFilteredCustomersCollection + */ + public function joinLeftEcommerceSyncData($preFilteredCustomersCollection) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $joinCondition = "m4m.related_id = e.entity_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + $preFilteredCustomersCollection->getSelect()->joinLeft( + array("m4m" => $mailchimpTableName), + sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER, $this->getMailchimpStoreId()) + ); + + $preFilteredCustomersCollection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR m4m.mailchimp_sync_modified = 1"); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Orders.php new file mode 100644 index 000000000..7d190cbbd --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Orders.php @@ -0,0 +1,25 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:41 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Orders extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata +{ + public function _construct() + { + parent::_construct(); + $this->setType(Ebizmarts_MailChimp_Model_Config::IS_ORDER); + } +} + diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Orders/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Orders/Collection.php new file mode 100755 index 000000000..22c5a23de --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Orders/Collection.php @@ -0,0 +1,41 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Orders_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_Sales_Model_Resource_Order_Collection $preFilteredOrdersCollection + */ + public function joinLeftEcommerceSyncData($preFilteredOrdersCollection) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $preFilteredOrdersCollection->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = main_table.entity_id AND m4m.type = '" + . Ebizmarts_MailChimp_Model_Config::IS_ORDER + . "' AND m4m.mailchimp_store_id = '" . $this->getMailchimpStoreId() . "'", + array('m4m.*') + ); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Product.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Product.php new file mode 100644 index 000000000..d9aab3b54 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Product.php @@ -0,0 +1,25 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:41 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Product extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata +{ + public function _construct() + { + parent::_construct(); + $this->setType(Ebizmarts_MailChimp_Model_Config::IS_PRODUCT); + } +} + diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Product/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Product/Collection.php new file mode 100755 index 000000000..69eb86178 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Product/Collection.php @@ -0,0 +1,109 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Product_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_Catalog_Model_Resource_Product_Collection $preFilteredProductsCollection + */ + public function joinLeftEcommerceSyncData($preFilteredProductsCollection) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $preFilteredProductsCollection->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = e.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PRODUCT + . "' AND m4m.mailchimp_store_id = '" . $this->getMailchimpStoreId() . "'", + array('m4m.*') + ); + } + + /** + * @param $collection Mage_Catalog_Model_Resource_Product_Collection + * @param $joinCondition + */ + public function executeMailchimpDataJoin($collection, $joinCondition) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $collection->getSelect()->joinLeft( + array("m4m" => $mailchimpTableName), + sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_PRODUCT, $this->getMailchimpStoreId()), + array( + "m4m.related_id", + "m4m.type", + "m4m.mailchimp_store_id", + "m4m.mailchimp_sync_delta", + "m4m.mailchimp_sync_modified", + "m4m.mailchimp_synced_flag" + ) + ); + } + + /** + * @param $deletedProducts + */ + public function joinMailchimpSyncDataDeleted($deletedProducts, $limit = null) + { + $this->joinLeftEcommerceSyncData($deletedProducts); + $deletedProducts->getSelect()->where("m4m.mailchimp_sync_deleted = 1 AND m4m.mailchimp_sync_error = ''"); + + if (isset($limit)) { + $deletedProducts->getSelect()->limit($limit); + } + } + + public function addJoinLeft($collection, array $array, $colString) + { + $collection->getSelect()->joinLeft($array, $colString); + } + + public function resetColumns($collection, $reset, $columns) + { + $collection->getSelect()->reset($reset)->columns($columns); + } + + /** + * @param $collection Mage_Catalog_Model_Resource_Product_Collection + */ + public function joinQtyAndBackorders($collection) + { + $collection->joinField( + 'qty', + 'cataloginventory/stock_item', + 'qty', + 'product_id=entity_id', + '{{table}}.stock_id=1', + 'left' + ); + + $collection->joinField( + 'backorders', + 'cataloginventory/stock_item', + 'backorders', + 'product_id=entity_id', + '{{table}}.stock_id=1', + 'left' + ); + } + +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoCodes.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoCodes.php new file mode 100644 index 000000000..76285df1a --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoCodes.php @@ -0,0 +1,25 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:41 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Promocodes extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata +{ + public function _construct() + { + parent::_construct(); + $this->setType(Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE); + } +} + diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoCodes/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoCodes/Collection.php new file mode 100755 index 000000000..ce9c5370b --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoCodes/Collection.php @@ -0,0 +1,67 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoCodes_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_SalesRule_Model_Resource_Coupon_Collection $preFilteredPromoCodesCollection + */ + public function joinLeftEcommerceSyncData($preFilteredPromoCodesCollection, $columns = array('m4m.*')) + { + $joinCondition = "m4m.related_id = main_table.coupon_id AND m4m.type = '%s' AND m4m.mailchimp_store_id = '%s'"; + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $preFilteredPromoCodesCollection->getSelect()->joinLeft( + array("m4m" => $mailchimpTableName), + sprintf($joinCondition, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, $this->getMailchimpStoreId()), + $columns + ); + } + + /** + * @param $collection Mage_SalesRule_Model_Resource_Coupon_Collection + */ + public function addWebsiteColumn($collection) + { + $websiteTableName = $this->getCoreResource()->getTableName('salesrule/website'); + $collection->getSelect()->joinLeft( + array('website' => $websiteTableName), + 'main_table.rule_id=website.rule_id', + array('*') + ); + } + + /** + * @param $collection Mage_SalesRule_Model_Resource_Coupon_Collection + */ + public function joinPromoRuleData($collection) + { + $salesRuleName = $this->getCoreResource()->getTableName('salesrule/rule'); + $conditions = 'main_table.rule_id=salesrule.rule_id'; + $collection->getSelect()->joinLeft( + array('salesrule' => $salesRuleName), + $conditions, + array('use_auto_generation' => 'use_auto_generation') + ); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoRules/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoRules/Collection.php new file mode 100755 index 000000000..a2cc74291 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/PromoRules/Collection.php @@ -0,0 +1,40 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_PromoRules_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_SalesRule_Model_Resource_Rule_Collection $preFilteredPromoRulesCollection + */ + public function joinLeftEcommerceSyncData($preFilteredPromoRulesCollection, $columns = array('m4m.*')) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $preFilteredPromoRulesCollection->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_PROMO_RULE + . "' AND m4m.mailchimp_store_id = '" . $this->getMailchimpStoreId() . "'", + $columns + ); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Quote.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Quote.php new file mode 100644 index 000000000..5e91a2740 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Quote.php @@ -0,0 +1,25 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:41 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Quote extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata +{ + public function _construct() + { + parent::_construct(); + $this->setType(Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + } +} + diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Quote/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Quote/Collection.php new file mode 100755 index 000000000..21d18e636 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Quote/Collection.php @@ -0,0 +1,40 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Quote_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_Sales_Model_Resource_Quote_Collection $preFilteredQuotesCollection + */ + public function joinLeftEcommerceSyncData($preFilteredQuotesCollection) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $preFilteredQuotesCollection->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE + . "' AND m4m.mailchimp_store_id = '" . $this->getMailchimpStoreId() . "'", + array('m4m.*') + ); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Subscribers/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Subscribers/Collection.php new file mode 100755 index 000000000..6e9cf9dd0 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Ecommercesyncdata/Subscribers/Collection.php @@ -0,0 +1,40 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2019-11-04 17:32 + */ +class Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Subscribers_Collection extends + Ebizmarts_MailChimp_Model_Resource_Ecommercesyncdata_Collection +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + } + + /** + * @param Mage_Newsletter_Model_Resource_Subscriber_Collection $preFilteredOrdersCollection + */ + public function joinLeftEcommerceSyncData($preFilteredOrdersCollection) + { + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $preFilteredOrdersCollection->getSelect()->joinLeft( + array('m4m' => $mailchimpTableName), + "m4m.related_id = main_table.entity_id AND m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_CUSTOMER + . "' AND m4m.mailchimp_store_id = '" . $this->getMailchimpStoreId() . "'", + array('m4m.*') + ); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Interestgroup.php similarity index 90% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Interestgroup.php index fb41f3b95..e0d8cc50d 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Interestgroup.php @@ -1,4 +1,5 @@ * @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:46 PM + * @date: 2019-10-02 15:54 * @file: Interestgroup.php */ -class Ebizmarts_MailChimp_Model_Mysql4_Interestgroup extends Mage_Core_Model_Mysql4_Abstract +class Ebizmarts_MailChimp_Model_Resource_Interestgroup extends Mage_Core_Model_Resource_Db_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Interestgroup/Collection.php similarity index 73% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup/Collection.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Interestgroup/Collection.php index 2352d3cb4..3e1940b87 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup/Collection.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Interestgroup/Collection.php @@ -1,4 +1,5 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 5/16/16 6:53 PM - * @file: Collection.php + * @date: 2019-10-02 15:57 */ - -class Ebizmarts_MailChimp_Model_Mysql4_Interestgroup_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract +class Ebizmarts_MailChimp_Model_Resource_Interestgroup_Collection extends + Mage_Core_Model_Resource_Db_Collection_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Mailchimperrors.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Mailchimperrors.php similarity index 78% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Mailchimperrors.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Mailchimperrors.php index b3e31298c..1a254150d 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Mailchimperrors.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Mailchimperrors.php @@ -1,4 +1,5 @@ * @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:46 PM + * @date: 2019-10-02 15:54 * @file: Mailchimperrors.php */ -class Ebizmarts_MailChimp_Model_Mysql4_Mailchimperrors extends Mage_Core_Model_Mysql4_Abstract +class Ebizmarts_MailChimp_Model_Resource_Mailchimperrors extends Mage_Core_Model_Resource_Db_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Mailchimperrors/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Mailchimperrors/Collection.php similarity index 73% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Mailchimperrors/Collection.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Mailchimperrors/Collection.php index 0aac6a6e4..d321a1871 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Mailchimperrors/Collection.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Mailchimperrors/Collection.php @@ -1,4 +1,5 @@ * @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:48 PM - * @file: Collection.php + * @date: 2019-10-02 15:57 */ -class Ebizmarts_MailChimp_Model_Mysql4_Mailchimperrors_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract +class Ebizmarts_MailChimp_Model_Resource_Mailchimperrors_Collection extends + Mage_Core_Model_Resource_Db_Collection_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Stores.php similarity index 78% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Stores.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Stores.php index 553a66a7a..db01763e9 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Stores.php @@ -1,4 +1,5 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 3/5/18 1:36 PM + * @date: 2019-10-02 15:54 * @file: Stores.php */ -class Ebizmarts_MailChimp_Model_Mysql4_Stores extends Mage_Core_Model_Mysql4_Abstract +class Ebizmarts_MailChimp_Model_Resource_Stores extends Mage_Core_Model_Resource_Db_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Stores/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Stores/Collection.php similarity index 74% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Stores/Collection.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Stores/Collection.php index 4973c60c9..13239ecd6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Stores/Collection.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Stores/Collection.php @@ -1,4 +1,5 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 3/5/18 1:39 PM - * @file: Collection.php + * @date: 2019-10-02 15:57 */ -class Ebizmarts_MailChimp_Model_Mysql4_Stores_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract + +class Ebizmarts_MailChimp_Model_Resource_Stores_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Synchbatches.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Synchbatches.php similarity index 78% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Synchbatches.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Synchbatches.php index e2146938a..e22123394 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Synchbatches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Synchbatches.php @@ -1,4 +1,5 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 5/16/16 6:37 PM + * @date: 2019-10-02 15:54 * @file: SychBatches.php */ -class Ebizmarts_MailChimp_Model_Mysql4_SynchBatches extends Mage_Core_Model_Mysql4_Abstract +class Ebizmarts_MailChimp_Model_Resource_SynchBatches extends Mage_Core_Model_Resource_Db_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Synchbatches/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Synchbatches/Collection.php similarity index 73% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Synchbatches/Collection.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Synchbatches/Collection.php index e7cda4b3c..ac2dd2ace 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Synchbatches/Collection.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Synchbatches/Collection.php @@ -1,4 +1,5 @@ * @copyright Ebizmarts (http://ebizmarts.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) - * @date: 5/16/16 6:53 PM - * @file: Collection.php + * @date: 2019-10-02 15:58 */ - -class Ebizmarts_MailChimp_Model_Mysql4_Synchbatches_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract +class Ebizmarts_MailChimp_Model_Resource_Synchbatches_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Webhookrequest.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Webhookrequest.php similarity index 78% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Webhookrequest.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Webhookrequest.php index e4ad6fea1..4a6549751 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Webhookrequest.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Webhookrequest.php @@ -1,4 +1,5 @@ * @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:46 PM + * @date: 2019-10-02 15:56 * @file: Mailchimperrors.php */ -class Ebizmarts_MailChimp_Model_Mysql4_Webhookrequest extends Mage_Core_Model_Mysql4_Abstract +class Ebizmarts_MailChimp_Model_Resource_Webhookrequest extends Mage_Core_Model_Resource_Db_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Webhookrequest/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Webhookrequest/Collection.php similarity index 73% rename from app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Webhookrequest/Collection.php rename to app/code/community/Ebizmarts/MailChimp/Model/Resource/Webhookrequest/Collection.php index 34db39aac..f40a829eb 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Webhookrequest/Collection.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Resource/Webhookrequest/Collection.php @@ -1,4 +1,5 @@ * @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:48 PM - * @file: Collection.php + * @date: 2019-10-02 15:58 */ -class Ebizmarts_MailChimp_Model_Mysql4_Webhookrequest_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract +class Ebizmarts_MailChimp_Model_Resource_Webhookrequest_Collection extends + Mage_Core_Model_Resource_Db_Collection_Abstract { /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Stores.php index b3cf97407..7312b8914 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Stores.php @@ -1,4 +1,5 @@ getCode()==$code) { + if ($this->getCode() == $code) { $this->setStatus(self::STATUS_SUBSCRIBED) ->setIsStatusChanged(true) ->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_CONFIRMATION) diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php index d1b1d215a..60a6f56e3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Backend/Store.php @@ -16,7 +16,6 @@ class Ebizmarts_MailChimp_Model_System_Config_Backend_Store extends Mage_Core_Mo protected function _afterSave() { $helper = $this->makeHelper(); - $dateHelper = $this->makeDateHelper(); $scopeId = $this->getScopeId(); $scope = $this->getScope(); $groups = $this->getData('groups'); @@ -24,23 +23,14 @@ protected function _afterSave() $newMailchimpStoreId = (isset($groups['general']['fields']['storeid']['value'])) ? $groups['general']['fields']['storeid']['value'] : null; + $oldMailchimpStoreId = $helper->getMCStoreId($scopeId, $scope); $isSyncing = $helper->getMCIsSyncing($newMailchimpStoreId, $scopeId, $scope); - $ecommMinSyncDate = $helper->getEcommMinSyncDateFlag($newMailchimpStoreId, $scopeId, $scope); - $helper->cancelAllPendingBatches($oldMailchimpStoreId); $helper->restoreAllCanceledBatches($newMailchimpStoreId); + if ($this->isValueChanged() && $this->getValue()) { - $helper->deletePreviousConfiguredMCStoreLocalData($oldMailchimpStoreId, $scopeId, $scope); - if ($ecommMinSyncDate === null) { - $configValues = array( - array( - Ebizmarts_MailChimp_Model_Config::GENERAL_ECOMMMINSYNCDATEFLAG."_$newMailchimpStoreId", - $dateHelper->formatDate(null, "Y-m-d H:i:s") - ) - ); - $helper->saveMailchimpConfig($configValues, 0, 'default'); - } + $helper->deletePreviousConfiguredMCStoreLocalData($oldMailchimpStoreId, $scopeId, $scope); if ($isSyncing === null) { $configValues = array( 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 813f1978b..18c539e5e 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 @@ -80,8 +80,8 @@ public function __construct($params) } catch (MailChimp_Error $e) { if ($helper->isEcomSyncDataEnabled($scopeArray['scope_id'], $scopeArray['scope'])) { $message = $helper->__( - 'Looks like your Mailchimp store was deleted. Please create a new one and associate ' - . 'it in order to get your Ecommerce data synced.' + 'It seems your Mailchimp store was deleted. ' + . 'Please create a new one and associate it in order to get your Ecommerce data synced.' ); Mage::getSingleton('adminhtml/session')->addWarning($message); } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php index d1602b0e4..63e699632 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/BatchLimit.php @@ -20,9 +20,7 @@ public function toOptionArray() array('value' => 50, 'label' => Mage::helper('mailchimp')->__('50')), array('value' => 100, 'label' => Mage::helper('mailchimp')->__('100')), array('value' => 200, 'label' => Mage::helper('mailchimp')->__('200')), - array('value' => 500, 'label' => Mage::helper('mailchimp')->__('500')), - array('value' => 1000, 'label' => Mage::helper('mailchimp')->__('1000')), - array('value' => 5000, 'label' => Mage::helper('mailchimp')->__('5000')) + array('value' => 500, 'label' => Mage::helper('mailchimp')->__('500')) ); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Fieldtype.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Fieldtype.php index 00a4318e5..63842bea6 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Fieldtype.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Fieldtype.php @@ -1,4 +1,5 @@ * File : Fieldtype.php diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php index fb924a52d..a2a88086a 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php @@ -1,4 +1,5 @@ getStoreValuesForForm(false, true); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php index 96a7699b3..24d5a357c 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/OrderGrid.php @@ -1,4 +1,5 @@ self::ICON, 'label' => $helper->__('Icon for Mailchimp orders')), array('value' => self::SYNCED, 'label' => $helper->__('If orders are synced to Mailchimp')), array('value' => self::BOTH, 'label' => $helper->__('Both')) - ); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php index 5f1cca3e3..6aa9e4adf 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/Store.php @@ -56,9 +56,10 @@ public function toOptionArray() if (isset($mcStores['stores'])) { $stores[] = array('value' => '', 'label' => $helper->__('--- Select a Mailchimp Store ---')); + foreach ($mcStores['stores'] as $store) { if ($store['platform'] == 'Magento') { - if ($store['list_id']=='') { + if ($store['list_id'] == '') { continue; } @@ -68,7 +69,7 @@ public function toOptionArray() $label = $store['name'] . ' (' . $helper->__("Warning: not connected") . ')'; } - $stores[] = array('value'=> $store['id'], 'label' => $label); + $stores[] = array('value' => $store['id'], 'label' => $label); } } } else { 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 9151d5994..970b06c7a 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 @@ -38,7 +38,7 @@ public function __construct() } if ((!is_array($this->_accountDetails) - || isset($this->_accountDetails['status'])) + || isset($this->_accountDetails['status'])) && $mandillHelper->getMandrillApiKey($storeId) ) { $api = new Mandrill_Message($mandillHelper->getMandrillApiKey($storeId)); @@ -83,8 +83,8 @@ public function toOptionArray() 'Hourly Quota: %s %s', $this->_accountDetails['hourly_quota'], "the maximum number of emails Mandrill will deliver for this user each hour. " - . "Any emails beyond that will be accepted and queued for later delivery. " - . "Users with higher reputations will have higher hourly quotas" + . "Any emails beyond that will be accepted and queued for later delivery. " + . "Users with higher reputations will have higher hourly quotas" ) ), array( diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/WebhookDelete.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/WebhookDelete.php index ac9c20e4c..f6e5d538c 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/WebhookDelete.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/WebhookDelete.php @@ -1,4 +1,5 @@ getParam('scope'); $scopeId = $request->getParam('scope_id'); $success = 1; + try { $stores = $mageApp->getStores(); + if ($scopeId == 0) { foreach ($stores as $store) { $helper->resetErrors($store->getId()); @@ -51,8 +54,8 @@ public function resendEcommerceDataAction() $filters = $request->getParam('filter'); $scope = $request->getParam('scope'); $scopeId = $request->getParam('scope_id'); - $success = 0; + if (is_array($filters) && empty($filters)) { $this->addWarning($helper->__('At least one type of eCommerce data should be selected to Resend.')); $success = $helper->__('Redirecting... ') @@ -85,6 +88,7 @@ public function createMergeFieldsAction() $scopeId = $request->getParam('scope_id'); $success = 0; $subEnabled = $helper->isSubscriptionEnabled($scopeId, $scope); + if ($subEnabled) { $success = $helper->createMergeFields($scopeId, $scope); } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php index 4426ab087..6b27da40b 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php @@ -25,6 +25,7 @@ public function preDispatch() public function indexAction() { $customerId = (int)$this->getRequest()->getParam('id'); + if ($customerId) { $block = $this->getLayout() ->createBlock( @@ -99,8 +100,10 @@ public function getInfoAction() } $data = $this->getSourceAccountInfoOptions($apiKey, $mcStoreId); + foreach ($data as $key => $element) { $liElement = ''; + if ($element['value'] == Ebizmarts_MailChimp_Model_System_Config_Source_Account::SYNC_LABEL_KEY) { $liElement = $helper->getSyncFlagDataHtml($element, $liElement); $data[$key]['label'] = $liElement; @@ -268,6 +271,7 @@ protected function getApiKeyValue() { $helper = $this->getHelper(); $scopeArray = $helper->getCurrentScope(); + return $helper->getApiKey($scopeArray['scope_id'], $scopeArray['scope']); } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php index 74df0c9c4..5b508e54c 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimperrorsController.php @@ -40,6 +40,7 @@ public function downloadresponseAction() $batchId = $error->getBatchId(); $storeId = $error->getStoreId(); $mailchimpStoreId = $error->getMailchimpStoreId(); + if ($mailchimpStoreId) { $enabled = $helper->isEcomSyncDataEnabled($storeId); } else { @@ -51,6 +52,7 @@ public function downloadresponseAction() $response->setHeader('Content-disposition', 'attachment; filename=' . $batchId . '.json'); $response->setHeader('Content-type', 'application/json'); $counter = 0; + do { $counter++; $files = $apiBatches->getBatchResponse($batchId, $storeId); @@ -62,11 +64,12 @@ public function downloadresponseAction() foreach ($files as $file) { $items = $this->getFileContent($file); + foreach ($items as $item) { $fileContent[] = array( - 'status_code' => $item->status_code, - 'operation_id' => $item->operation_id, - 'response' => json_decode($item->response) + 'status_code' => $item['status_code'], + 'operation_id' => $item['operation_id'], + 'response' => json_decode($item['response']) ); } @@ -74,6 +77,7 @@ public function downloadresponseAction() } $baseDir = $apiBatches->getMagentoBaseDir(); + if ($apiBatches->batchDirExists($baseDir, $batchId)) { $apiBatches->removeBatchDir($baseDir, $batchId); } @@ -128,7 +132,9 @@ protected function getApiBatches() */ protected function getFileContent($file) { - return json_decode(file_get_contents($file)); + $fileContent = $this->getFileHelper()->read($file); + + return json_decode($fileContent, true); } /** @@ -136,6 +142,14 @@ protected function getFileContent($file) */ protected function unlink($file) { - unlink($file); + return $this->getFileHelper()->unlink($file); + } + + /** + * @return Ebizmarts_MailChimp_Helper_File + */ + protected function getFileHelper() + { + return Mage::helper('mailchimp/file'); } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php index 7a99fbdad..2543e8563 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpstoresController.php @@ -47,7 +47,6 @@ public function gridAction() protected function _initStore($idFieldName = 'id') { $this->_title($this->__('Mailchimp Stores'))->_title($this->__('Manage Mailchimp Stores')); - $storeId = (int)$this->getRequest()->getParam($idFieldName); if ($storeId) { @@ -65,8 +64,8 @@ public function editAction() $mailchimpStore = $this->loadMailchimpStore($id); $this->sessionregisterStore($mailchimpStore); $title = $id ? $this->__('Edit Store') : $this->__('New Store'); - $this->_initAction(); + $block = $this->getLayout() ->createBlock('mailchimp/adminhtml_mailchimpstores_edit') ->setData('action', $this->getUrl('*/*/save')); @@ -184,36 +183,47 @@ protected function _loadStores() continue; } - $storeData = Mage::getModel('mailchimp/stores'); - $storeData->setApikey($apiKey) - ->setStoreid($store['id']) - ->setListid($store['list_id']) - ->setName($store['name']) - ->setPlatform($store['platform']) - ->setIsSync($store['is_syncing']) - ->setEmailAddress($store['email_address']) - ->setCurrencyCode($store['currency_code']) - ->setMoneyFormat($store['money_format']) - ->setPrimaryLocale($store['primary_locale']) - ->setTimezone($store['timezone']) - ->setPhone($store['phone']) - ->setAddressAddressOne($store['address']['address1']) - ->setAddressAddressTwo($store['address']['address2']) - ->setAddressCity($store['address']['city']) - ->setAddressProvince($store['address']['province']) - ->setAddressProvinceCode($store['address']['province_code']) - ->setAddressPostalCode($store['address']['postal_code']) - ->setAddressCountry($store['address']['country']) - ->setAddressCountryCode($store['address']['country_code']) - ->setDomain($store['domain']) - ->setMcAccountName($root['account_name']) - ->setListName(key_exists('name', $list) ? $list['name'] : '') - ->save(); + $this->_saveStoreData($apiKey, $store, $root, $list); } } } } + /** + * @param $apiKey + * @param $store + * @param $root + * @param $list + */ + protected function _saveStoreData($apiKey, $store, $root, $list) + { + $storeData = Mage::getModel('mailchimp/stores'); + $storeData->setApikey($apiKey) + ->setStoreid($store['id']) + ->setListid($store['list_id']) + ->setName($store['name']) + ->setPlatform($store['platform']) + ->setIsSync($store['is_syncing']) + ->setEmailAddress($store['email_address']) + ->setCurrencyCode($store['currency_code']) + ->setMoneyFormat($store['money_format']) + ->setPrimaryLocale($store['primary_locale']) + ->setTimezone($store['timezone']) + ->setPhone($store['phone']) + ->setAddressAddressOne($store['address']['address1']) + ->setAddressAddressTwo($store['address']['address2']) + ->setAddressCity($store['address']['city']) + ->setAddressProvince($store['address']['province']) + ->setAddressProvinceCode($store['address']['province_code']) + ->setAddressPostalCode($store['address']['postal_code']) + ->setAddressCountry($store['address']['country']) + ->setAddressCountryCode($store['address']['country_code']) + ->setDomain($store['domain']) + ->setMcAccountName($root['account_name']) + ->setListName(key_exists('name', $list) ? $list['name'] : '') + ->save(); + } + public function getstoresAction() { $helper = $this->getMailchimpHelper(); @@ -332,6 +342,7 @@ protected function createAddressArray($formData) $address['postal_code'] = $formData['address_postal_code']; $address['country'] = ''; $address['country_code'] = $formData['address_country_code']; + return $address; } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php index 078c9366e..6c9ddec83 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MergevarsController.php @@ -1,4 +1,5 @@ loadLayout(); $this->renderLayout(); } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php index 35fe96fcb..d019da966 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/CartController.php @@ -18,32 +18,36 @@ class Ebizmarts_MailChimp_CartController extends Mage_Checkout_CartController public function loadquoteAction() { $params = $this->getRequest()->getParams(); + if (isset($params['id'])) { //restore the quote $quote = Mage::getModel('sales/quote')->load($params['id']); $storeId = $quote->getStoreId(); $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId($storeId); - $quoteSyncData = Mage::helper('mailchimp') + $quoteSyncData = $this->getMailchimpEcommerceSyncDataModel() ->getEcommerceSyncDataItem( $params['id'], Ebizmarts_MailChimp_Model_Config::IS_QUOTE, $mailchimpStoreId ); $url = Mage::getUrl(Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::ABANDONEDCART_PAGE, $storeId)); + if (isset($params['mc_cid'])) { - $url .= '?mc_cid='.$params['mc_cid']; + $url .= '?mc_cid=' . $params['mc_cid']; } if (!isset($params['token']) || $params['token'] != $quoteSyncData->getMailchimpToken()) { - Mage::getSingleton('customer/session')->addNotice("Your token cart is incorrect"); + Mage::getSingleton('customer/session')->addNotice($this->_("Your token cart is incorrect")); $this->getResponse() ->setRedirect($url); } else { $quote->setMailchimpAbandonedcartFlag(1); $quote->save(); + if (!$quote->getCustomerId()) { $this->_getSession()->setQuoteId($quote->getId()); $newQuote = $this->_getSession()->getQuote(); + if ($newQuote->getId() != $quote->getId()) { $newQuote = $this->_getSession()->getQuote(); $newQuote->delete(); @@ -58,11 +62,12 @@ public function loadquoteAction() $this->getResponse() ->setRedirect($url, 301); } else { - Mage::getSingleton('customer/session')->addNotice("Login to complete your order"); + Mage::getSingleton('customer/session')->addNotice($this->_("Login to complete your order")); Mage::getSingleton('customer/session')->setAfterAuthUrl($url, $storeId); $url = Mage::getUrl('customer/account/login'); + if (isset($params['mc_cid'])) { - $url .= '?mc_cid='.$params['mc_cid']; + $url .= '?mc_cid=' . $params['mc_cid']; } $this->getResponse()->setRedirect($url, 301); @@ -75,6 +80,7 @@ public function loadquoteAction() public function loadcouponAction() { $params = $this->getRequest()->getParams(); + if (isset($params['coupon_id']) && isset($params['coupon_token'])) { $helper = Mage::helper('mailchimp'); $id = $params['coupon_id']; @@ -83,20 +89,23 @@ public function loadcouponAction() $mailchimpStoreId = $helper->getMCStoreId($storeId); $url = Mage::getUrl('checkout/cart'); - $promoCodeSyncData = $helper->getEcommerceSyncDataItem( + $promoCodeSyncData = $this->getMailchimpEcommerceSyncDataModel()->getEcommerceSyncDataItem( $id, Ebizmarts_MailChimp_Model_Config::IS_PROMO_CODE, $mailchimpStoreId ); $couponId = $promoCodeSyncData->getRelatedId(); + if ($couponId && $promoCodeSyncData->getMailchimpToken() == $token) { $coupon = Mage::getModel('salesrule/coupon')->load($couponId); + if ($coupon->getId()) { $code = $coupon->getCode(); Mage::getSingleton("checkout/session")->setData("coupon_code", $code); $quote = Mage::getSingleton('checkout/cart')->getQuote(); $quote->setCouponCode($code)->save(); Mage::getSingleton('core/session')->addSuccess($this->__('Coupon was automatically applied.')); + if (!$quote->getItemsCount()) { Mage::getSingleton('core/session') ->addWarning( @@ -129,4 +138,12 @@ public function loadcouponAction() } } } + + /** + * @return mixed + */ + public function getMailchimpEcommerceSyncDataModel() + { + return Mage::getModel('mailchimp/ecommercesyncdata'); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php b/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php index 5f093c6a4..c1a15d317 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php @@ -26,6 +26,7 @@ public function indexAction() $customerId = $order->getCustomerId(); $subscriber = $this->getSubscriberModel() ->loadByEmail($customerEmail); + try { if (!$subscriber->getSubscriberId()) { $subscriber->setSubscriberEmail($customerEmail); diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php b/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php index 91e9381e3..dd743ebdf 100755 --- a/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/WebhookController.php @@ -36,12 +36,15 @@ public function indexAction() $moduleName = $request->getModuleName(); $data = $request->getPost(); $helper = $this->getHelper(); + if ($moduleName == 'monkey') { if (isset($data['data']['list_id'])) { $listId = $data['data']['list_id']; $storeIds = $helper->getMagentoStoreIdsByListId($listId); + if (!empty($storeIds)) { $storeId = $storeIds[0]; + if ($helper->isSubscriptionEnabled($storeId)) { $this->_deleteWebhook($storeId, $listId); } @@ -91,10 +94,10 @@ protected function _deleteWebhook($storeId, $listId) if (!$api) { try { - $webhooks = $api->lists->webhooks->getAll($listId); + $webhooks = $api->getLists()->getWebhooks()->getAll($listId); foreach ($webhooks['webhooks'] as $webhook) { if (strpos($webhook['url'], 'monkey/webhook') !== false) { - $api->lists->webhooks->delete($listId, $webhook['id']); + $helper->deleteWebhookFromList($api->getLists()->getWebhooks(), $listId, $webhook['id']); } } } catch (MailChimp_Error $e) { diff --git a/app/code/community/Ebizmarts/MailChimp/etc/adminhtml.xml b/app/code/community/Ebizmarts/MailChimp/etc/adminhtml.xml index cb8cc5672..74c214b4d 100644 --- a/app/code/community/Ebizmarts/MailChimp/etc/adminhtml.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/adminhtml.xml @@ -10,12 +10,17 @@ Mailchimp Errors 810 adminhtml/mailchimperrors/index - + Mailchimp Stores 820 adminhtml/mailchimpstores/index + + Mailchimp Configuration + 830 + adminhtml/system_config/edit/section/mailchimp + @@ -36,6 +41,9 @@ Mailchimp Stores + + Mailchimp Configuration + diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index 1225d8f8e..0693aa89c 100644 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -2,10 +2,10 @@ - 1.1.18 + 1.1.19 - 1.1.18 + 1.1.19 @@ -128,10 +128,10 @@ Ebizmarts_MailChimp_Model - mailchimp_mysql4 + mailchimp_resource - - Ebizmarts_MailChimp_Model_Mysql4 + + Ebizmarts_MailChimp_Model_Resource mailchimp_sync_batches
@@ -152,7 +152,7 @@ mailchimp_stores
-
+ Ebizmarts_MailChimp_Model_Subscriber 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 bfe48ab44..a38e0b464 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 @@ -31,7 +31,11 @@ $baseDir = Mage::getBaseDir(); try { - mkdir($baseDir . DS . 'var' . DS . 'mailchimp'); + /** + * @var $fileHelper Ebizmarts_MailChimp_Helper_File + */ + $fileHelper = Mage::helper('mailchimp/file'); + $fileHelper->mkDir($baseDir . DS . 'var' . DS . 'mailchimp'); } catch (Exception $e) { Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); } diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/notifications.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/notifications.phtml index 2118010a0..3f6832379 100755 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/notifications.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/notifications.phtml @@ -1,30 +1,29 @@ getMessageNotification()) : ?> -
+
escapeHtml($message) ?>
- diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/form/field/array_dropdown.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/form/field/array_dropdown.phtml index 9ab12c5c6..b9b7622c4 100644 --- a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/form/field/array_dropdown.phtml +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/system/config/form/field/array_dropdown.phtml @@ -19,7 +19,7 @@ $colspan = $colspan > 1 ? 'colspan="' . $colspan . '"' : ''; - _columns as $columnName => $column):?> + _columns as $columnName => $column): ?> quoteEscape($column['label']) ?> quoteEscape($colspan) ?>> @@ -64,7 +64,7 @@ $colspan = $colspan > 1 ? 'colspan="' . $colspan . '"' : ''; - +