diff --git a/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php b/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php index c688e13e..b9de815b 100644 --- a/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php +++ b/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php @@ -14,6 +14,8 @@ namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce; use Magento\Framework\Controller\Result\JsonFactory; +use Magento\Framework\Exception\ValidatorException; +use Symfony\Component\Config\Definition\Exception\Exception; class ResetLocalErrors extends \Magento\Backend\App\Action { @@ -33,10 +35,18 @@ public function __construct( public function execute() { + $valid = 1; + $message = ''; $resultJson = $this->resultJsonFactory->create(); + try { + $this->helper->resetErrors(); + } catch(ValidatorException $e) { + $valid = 0; + $message = $e->getMessage(); + } return $resultJson->setData([ - 'valid' => (int)1, - 'message' => 'OK', + 'valid' => (int)$valid, + 'message' => $message, ]); } protected function _isAllowed() diff --git a/Cron/Ecommerce.php b/Cron/Ecommerce.php index 55aca8af..14033243 100644 --- a/Cron/Ecommerce.php +++ b/Cron/Ecommerce.php @@ -38,6 +38,10 @@ class Ecommerce * @var \Ebizmarts\MailChimp\Model\Api\Order */ private $_apiOrder; + /** + * @var \Ebizmarts\MailChimp\Model\Api\Cart + */ + private $_apiCart; /** * @var \Ebizmarts\MailChimp\Model\MailChimpSyncBatches */ @@ -50,6 +54,8 @@ class Ecommerce * @param \Ebizmarts\MailChimp\Model\Api\Product $apiProduct * @param \Ebizmarts\MailChimp\Model\Api\Result $apiResult * @param \Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer + * @param \Ebizmarts\MailChimp\Model\Api\Order $apiOrder + * @param \Ebizmarts\MailChimp\Model\Api\Cart $apiCart * @param \Ebizmarts\MailChimp\Model\MailChimpSyncBatches $mailChimpSyncBatches */ public function __construct( @@ -59,6 +65,7 @@ public function __construct( \Ebizmarts\MailChimp\Model\Api\Result $apiResult, \Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer, \Ebizmarts\MailChimp\Model\Api\Order $apiOrder, + \Ebizmarts\MailChimp\Model\Api\Cart $apiCart, \Ebizmarts\MailChimp\Model\MailChimpSyncBatches $mailChimpSyncBatches ) { @@ -69,10 +76,12 @@ public function __construct( $this->_apiResult = $apiResult; $this->_apiCustomer = $apiCustomer; $this->_apiOrder = $apiOrder; + $this->_apiCart = $apiCart; } public function execute() { + $this->_helper->log(__METHOD__); foreach($this->_storeManager->getStores() as $storeId => $val) { $this->_storeManager->setCurrentStore($storeId); @@ -85,14 +94,17 @@ public function execute() protected function _processStore($storeId) { + $this->_helper->log(__METHOD__); $batchArray = array(); $results = array(); - if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ECOMMERCE_ACTIVE)) { + if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ECOMMERCE_ACTIVE,$storeId)) { $results = $this->_apiProduct->_sendProducts($storeId); $customers = $this->_apiCustomer->sendCustomers($storeId); $results = array_merge($results,$customers); $orders = $this->_apiOrder->sendOrders($storeId); $results = array_merge($results,$orders); + $carts = $this->_apiCart->createBatchJson($storeId); + $results= array_merge($results,$carts); } if (!empty($results)) { try { @@ -104,7 +116,7 @@ protected function _processStore($storeId) } else { $api = $this->_helper->getApi(); $batchResponse =$api->batchOperation->add($batchArray); - $this->_helper->log(var_export($results,true),null,$batchResponse['id']); + $this->_helper->log($results,null,$batchResponse['id']); $this->_helper->log(var_export($batchResponse,true)); $this->_mailChimpSyncBatches->setStoreId($storeId); $this->_mailChimpSyncBatches->setBatchId($batchResponse['id']); diff --git a/Helper/Data.php b/Helper/Data.php index b966201d..1a2038f9 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -11,9 +11,8 @@ namespace Ebizmarts\MailChimp\Helper; -use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\Exception\ValidatorException; use Magento\Store\Model\Store; -use Magento\Framework\App\Config\ScopeConfigInterface; use Symfony\Component\Config\Definition\Exception\Exception; class Data extends \Magento\Framework\App\Helper\AbstractHelper @@ -30,6 +29,9 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper const XML_PATH_SYNC_DATE = 'mailchimp/general/mcminsyncdateflag'; const XML_ECOMMERCE_OPTIN = 'mailchimp/ecommerce/customer_optin'; const XML_ECOMMERCE_FIRSTDATE = 'mailchimp/ecommerce/firstdate'; + const XML_ABANDONEDCART_ACTIVE = 'mailchimp/abandonedcart/active'; + const XML_ABANDONEDCART_FIRSTDATE = 'mailchimp/abandonedcart/firstdate'; + const ORDER_STATE_OK = 'complete'; @@ -78,6 +80,18 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper * @var \Magento\Customer\Model\ResourceModel\Customer\CustomerRepository */ private $_customer; + /** + * @var \Ebizmarts\MailChimp\Model\MailChimpErrors + */ + private $_mailChimpErrors; + /** + * @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerceFactory + */ + private $_mailChimpSyncEcommerce; + /** + * @var \Magento\Catalog\Model\ResourceModel\Product\Collection + */ + private $_productCollection; /** * Data constructor. @@ -89,6 +103,9 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper * @param \Magento\Framework\Module\ModuleList\Loader $loader * @param \Mailchimp $api * @param \Magento\Customer\Model\ResourceModel\CustomerRepository $customer + * @param \Ebizmarts\MailChimp\Model\MailChimpErrors $mailChimpErrors + * @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerceFactory $mailChimpSyncEcommerce + * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection */ public function __construct( \Magento\Framework\App\Helper\Context $context, @@ -98,7 +115,10 @@ public function __construct( \Magento\Framework\App\State $state, \Magento\Framework\Module\ModuleList\Loader $loader, \Mailchimp $api, - \Magento\Customer\Model\ResourceModel\CustomerRepository $customer + \Magento\Customer\Model\ResourceModel\CustomerRepository $customer, + \Ebizmarts\MailChimp\Model\MailChimpErrors $mailChimpErrors, + \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerceFactory $mailChimpSyncEcommerce, + \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection ) { $this->_storeManager = $storeManager; @@ -110,6 +130,9 @@ public function __construct( $this->_loader = $loader; $this->_api = $api; $this->_customer = $customer; + $this->_mailChimpErrors = $mailChimpErrors; + $this->_mailChimpSyncEcommerce = $mailChimpSyncEcommerce; + $this->_productCollection = $productCollection; parent::__construct($context); } @@ -442,5 +465,58 @@ public function getDateMicrotime() $date = date('Y-m-d-H-i-s') . '-' . $msecArray[1]; return $date; } + public function resetErrors() + { + try { + // clean the errors table + $connection = $this->_mailChimpErrors->getResource()->getConnection(); + $tableName = $this->_mailChimpErrors->getResource()->getMainTable(); + $connection->truncateTable($tableName); + // clean the syncecommerce table with errors + $connection = $this->_mailChimpSyncEcommerce->getResource()->getConnection(); + $tableName = $this->_mailChimpSyncEcommerce->getResource()->getMainTable(); + $connection->delete($tableName,['mailchimp_sync_error is not null']); + // clean the errors in eav for products +// $productCollection = $this->_productCollection; +// $productCollection->addAttributeToFilter( +// array( +// array('attribute' => 'mailchimp_sync_error', 'neq' => '') +// ), '', 'left' +// ); +// foreach ($productCollection as $product) { +// $product->setData("mailchimp_sync_delta", null); +// $product->setData("mailchimp_sync_error", ''); +// $resource = $product->getResource(); +// $resource->saveAttribute($product, 'mailchimp_sync_delta'); +// $resource->saveAttribute($product, 'mailchimp_sync_error'); +// } + // clean the error in eav for customers + } catch(\Zend_Db_Exception $e) { + throw new ValidatorException(__($e->getMessage())); + } + } + public function resetEcommerce() + { + $this->resetErrors(); + } + public function saveEcommerceData($storeId, $entityId , $date, $error, $modified, $type, $deleted = 0, $token = null) + { + $chimpSyncEcommerce = $this->getChimpSyncEcommerce($storeId,$entityId,$type); + $chimpSyncEcommerce->setMailchimpStoreId($storeId); + $chimpSyncEcommerce->setType($type); + $chimpSyncEcommerce->setRelatedId($entityId); + $chimpSyncEcommerce->setMailchimpSyncModified($modified); + $chimpSyncEcommerce->setMailchimpSyncDelta($date); + $chimpSyncEcommerce->setMailchimpSyncError($error); + $chimpSyncEcommerce->setMailchimpSyncDeleted($deleted); + $chimpSyncEcommerce->setMailchimpToken($token); + $chimpSyncEcommerce->getResource()->save($chimpSyncEcommerce); + } + public function getChimpSyncEcommerce($storeId,$id,$type) + { + $chimp = $this->_mailChimpSyncEcommerce->create(); + return $chimp->getByStoreIdType($storeId,$id,$type); + } + } diff --git a/Model/Api/Cart.php b/Model/Api/Cart.php new file mode 100644 index 00000000..d04f43a6 --- /dev/null +++ b/Model/Api/Cart.php @@ -0,0 +1,628 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 3/7/17 12:42 PM + * @file: Cart.php + */ +namespace Ebizmarts\MailChimp\Model\Api; + +use Symfony\Component\Config\Definition\Exception\Exception; + +class Cart +{ + + const BATCH_LIMIT = 100; + + protected $_firstDate; + protected $_counter; + protected $_batchId; + protected $_api = null; + protected $_token = null; + + /** + * @var \Ebizmarts\MailChimp\Helper\Data + */ + protected $_helper; + /** + * @var \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory + */ + protected $_quoteCollection; + /** + * @var \Magento\Framework\Stdlib\DateTime\DateTime + */ + protected $_date; + /** + * @var \Magento\Customer\Model\CustomerFactory + */ + protected $_customerFactory; + /** + * @var Product + */ + protected $_apiProduct; + /** + * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory + */ + protected $_orderCollectionFactory; + /** + * @var Customer + */ + protected $_apiCustomer; + /** + * @var \Magento\Directory\Api\CountryInformationAcquirerInterface + */ + protected $_countryInformation; + /** + * @var \Magento\Framework\Url + */ + protected $_urlHelper; + + /** + * Cart constructor. + * @param \Ebizmarts\MailChimp\Helper\Data $helper + * @param \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteColletcion + * @param \Magento\Framework\Stdlib\DateTime\DateTime $date + * @param \Magento\Customer\Model\CustomerFactory $customerFactory + * @param Product $apiProduct + * @param Customer $apiCustomer + * @param \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation + * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory + * @param \Magento\Framework\Url $urlHelper + */ + public function __construct( + \Ebizmarts\MailChimp\Helper\Data $helper, + \Magento\Quote\Model\ResourceModel\Quote\CollectionFactory $quoteColletcion, + \Magento\Framework\Stdlib\DateTime\DateTime $date, + \Magento\Customer\Model\CustomerFactory $customerFactory, + \Ebizmarts\MailChimp\Model\Api\Product $apiProduct, + \Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer, + \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation, + \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, + \Magento\Framework\Url $urlHelper + ) + { + $this->_helper = $helper; + $this->_quoteCollection = $quoteColletcion; + $this->_date = $date; + $this->_customerFactory = $customerFactory; + $this->_apiProduct = $apiProduct; + $this->_apiCustomer = $apiCustomer; + $this->_orderCollectionFactory = $orderCollectionFactory; + $this->_countryInformation = $countryInformation; + $this->_urlHelper = $urlHelper; + } + + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + public function createBatchJson($magentoStoreId) + { + $this->_helper->log(__METHOD__); + $allCarts = array(); + if (!$this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_ACTIVE,$magentoStoreId)) { + return $allCarts; + } + + $this->_firstDate = $this->_helper->getConfigValue( + \Ebizmarts\MailChimp\Helper\Data::XML_ABANDONEDCART_FIRSTDATE, + $magentoStoreId + ); + $this->_counter = 0; + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE,$magentoStoreId); + + $date = $this->_helper->getDateMicrotime(); + $this->_batchId = 'storeid-' . $magentoStoreId . '_' . \Ebizmarts\MailChimp\Helper\Data::IS_QUOTE.'_'.$date; + // get all the carts converted in orders (must be deleted on mailchimp) + $allCarts = array_merge($allCarts, $this->_getConvertedQuotes($mailchimpStoreId, $magentoStoreId)); + // get all the carts modified but not converted in orders + $allCarts = array_merge($allCarts, $this->_getModifiedQuotes($mailchimpStoreId, $magentoStoreId)); + // get new carts + $allCarts = array_merge($allCarts, $this->_getNewQuotes($mailchimpStoreId, $magentoStoreId)); + return $allCarts; + } + + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) + { + $this->_helper->log(__METHOD__); + $allCarts = array(); + $convertedCarts = $this->_getQuoteCollection(); + // get only the converted quotes + $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( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $convertedCarts->getSelect()->where("m4m.mailchimp_sync_deleted = 0"); + // limit the collection + $convertedCarts->getSelect()->limit(self::BATCH_LIMIT); + $this->_helper->log((string)$convertedCarts->getSelect()); + /** + * @var $cart \Magento\Quote\Model\Quote + */ + 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); + /** + * @var $cartForEmail \Magento\Quote\Model\Quote + */ + foreach ($allCartsForEmail as $cartForEmail) { + $alreadySentCartId = $cartForEmail->getEntityId(); + if ($alreadySentCartId != $cartId) { + $allCarts[$this->_counter]['method'] = 'DELETE'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; + $allCarts[$this->_counter]['body'] = ''; + $this->_updateQuote($mailchimpStoreId, $alreadySentCartId, $this->_date->gmtDate(), "", 0,1); + $this->_counter += 1; + } + } + + $allCartsForEmail->clear(); + $allCarts[$this->_counter]['method'] = 'DELETE'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; + $allCarts[$this->_counter]['body'] = ''; + $this->_updateQuote($mailchimpStoreId, $cartId, $this->_date->gmtDate(), "", 0,1); + $this->_counter += 1; + } + + return $allCarts; + } + + /** + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) + { + $this->_helper->log(__METHOD__); + $allCarts = array(); + $modifiedCarts = $this->_getQuoteCollection(); + // select carts with no orders + $modifiedCarts->addFieldToFilter('is_active', array('eq'=>1)); + // 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( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $modifiedCarts->getSelect()->where("m4m.mailchimp_sync_modified = 1 AND m4m.mailchimp_sync_deleted = 0". + " AND m4m.mailchimp_sync_delta < main_table.updated_at"); + // limit the collection + $modifiedCarts->getSelect()->limit(self::BATCH_LIMIT); + $this->_helper->log((string)$modifiedCarts->getSelect()); + /** + * @var $cart \Magento\Quote\Model\Quote + */ + foreach ($modifiedCarts as $cart) { + $cartId = $cart->getEntityId(); + $allCarts[$this->_counter]['method'] = 'DELETE'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; + $allCarts[$this->_counter]['body'] = ''; + $this->_counter += 1; + /** + * @var $customer \Magento\Customer\Model\Customer + */ +// $customer = Mage::getModel("customer/customer"); +// $customer->setWebsiteId(Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId()); +// $customer->loadByEmail($cart->getCustomerEmail()); + $customer = $this->_customerFactory->create(); + $customer->setWebsiteId(); + $customer->loadByEmail($cart->getCustomerEmail()); + + if ($customer->getEmail() != $cart->getCustomerEmail()) { + $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + /** + * @var $cartForEmail \Magento\Quote\Model\Quote + */ + foreach ($allCartsForEmail as $cartForEmail) { + $alreadySentCartId = $cartForEmail->getEntityId(); + if($alreadySentCartId != $cartId) { + $allCarts[$this->_counter]['method'] = 'DELETE'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; + $allCarts[$this->_counter]['body'] = ''; + $this->_updateQuote($mailchimpStoreId, $alreadySentCartId, $this->_date->gmtDate(), null, null, 1); + $this->_counter += 1; + } + } + + $allCartsForEmail->clear(); + } + // avoid carts abandoned as guests when customer email associated to a registered customer. + if (!$cart->getCustomerId() && $customer->getEmail()==$cart->getCustomerEmail()) { + $this->_updateQuote($mailchimpStoreId, $cartId, $this->_date->gmtDate()); + continue; + } + + // send the products that not already sent + $productData = $this->_apiProduct->sendQuoteModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId); + if (count($productData)) { + foreach($productData as $p) { + $allCarts[$this->_counter] = $p; + $this->_counter += 1; + } + } + + if (count($cart->getAllVisibleItems())) { + $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); + if ($cartJson!="") { + $allCarts[$this->_counter]['method'] = 'POST'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; + $allCarts[$this->_counter]['body'] = $cartJson; + $this->_counter += 1; + } + } + + $this->_updateQuote($mailchimpStoreId, $cartId, $this->_date->gmtDate()); + } + + return $allCarts; + } + + /** + * @param $mailchimpStoreId + * @return array + */ + protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) + { + $this->_helper->log(__METHOD__); + $allCarts = array(); + $newCarts = $this->_getQuoteCollection(); + $newCarts->addFieldToFilter('is_active', array('eq'=>1)); + $newCarts->addFieldToFilter('customer_email', array('notnull'=>true)); + $newCarts->addFieldToFilter('items_count', array('gt'=>0)); + // select carts for the current Magento store id + $newCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + // filter by first date if exists. + if ($this->_firstDate) { + $newCarts->addFieldToFilter('created_at', array('gt' => $this->_firstDate)); + } + //join with mailchimp_ecommerce_sync_data table to filter by sync data. + $newCarts->getSelect()->joinLeft( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.related_id = main_table.entity_id and m4m.type = '" . \Ebizmarts\MailChimp\Helper\Data::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $newCarts->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); + // limit the collection + $newCarts->getSelect()->limit(self::BATCH_LIMIT); + $this->_helper->log((string)$newCarts->getSelect()); + /** + * @var $cart \Magento\Quote\Model\Quote + */ + foreach ($newCarts as $cart) { + $this->_helper->log('each cart'); + $cartId = $cart->getEntityId(); + $orderCollection = $this->_getOrderCollection(); + $orderCollection->addFieldToFilter('main_table.customer_email', array('eq' => $cart->getCustomerEmail())) + ->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. + $this->_helper->log((string)$orderCollection->getSelect()); + if (!count($cart->getAllVisibleItems()) || $orderCollection->getSize()) { + $this->_helper->log("cart is empty, leave"); + $this->_updateQuote($mailchimpStoreId, $cartId, $this->_date->gmtDate()); + continue; + } + $this->_helper->log('before get the customer by email'); + $customer = $this->_customerFactory->create(); + $customer->setWebsiteId($magentoStoreId); + $customer->loadByEmail($cart->getCustomerEmail()); + $this->_helper->log('after get customer by email'); + + if ($customer->getEmail() != $cart->getCustomerEmail()) { + $this->_helper->log('not same email'); + $this->_helper->log('before get all carts'); + $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + foreach ($allCartsForEmail as $cartForEmail) { + $alreadySentCartId = $cartForEmail->getEntityId(); + $allCarts[$this->_counter]['method'] = 'DELETE'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; + $allCarts[$this->_counter]['body'] = ''; + $this->_updateQuote($mailchimpStoreId, $alreadySentCartId, $this->_date->gmtDate(), null, null, 1); + $this->_counter += 1; + } + + $allCartsForEmail->clear(); + } + + // don't send the carts for guest customers who are registered + if (!$cart->getCustomerId()&&$customer->getEmail()==$cart->getCustomerEmail()) { + $this->_updateQuote($mailchimpStoreId, $cartId, $this->_date->gmtDate()); + continue; + } + + // send the products that not already sent + $this->_helper->log('before send modified products'); + $productData = $this->_apiProduct->sendQuoteModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId); + if (count($productData)) { + foreach($productData as $p) { + $allCarts[$this->_counter] = $p; + $this->_counter += 1; + } + } + $this->_helper->log('after send modified products'); + + $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); + if ($cartJson!="") { + $allCarts[$this->_counter]['method'] = 'POST'; + $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; + $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; + $allCarts[$this->_counter]['body'] = $cartJson; + $this->_updateQuote($mailchimpStoreId, $cartId, $this->_date->gmtDate()); + $this->_counter += 1; + } + } + + return $allCarts; + } + + /** + * Get all existing carts in the current store view for a given email address. + * + * @param $email + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return object + */ + protected function _getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) + { + $this->_helper->log(__METHOD__); + $allCartsForEmail = $this->_getQuoteCollection(); + $allCartsForEmail->addFieldToFilter('is_active', array('eq' => 1)); + $allCartsForEmail->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + $allCartsForEmail->addFieldToFilter('customer_email', array('eq' => $email)); + $allCartsForEmail->getSelect()->joinLeft( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_QUOTE."' + AND m4m.mailchimp_store_id = '" . $mailchimpStoreId . "'", + ['m4m.*'] + ); + // be sure that the quotes are already in mailchimp and not deleted + $allCartsForEmail->getSelect()->where("m4m.mailchimp_sync_deleted = 0"); + $this->_helper->log((string)$allCartsForEmail->getSelect()); + return $allCartsForEmail; + } + + /** + * @param $cart + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return string + */ + protected function _makeCart(\Magento\Quote\Model\Quote $cart, $mailchimpStoreId, $magentoStoreId) + { + $this->_helper->log(__METHOD__); + $this->_token = null; + $campaignId = $cart->getMailchimpCampaignId(); + $oneCart = array(); + $oneCart['id'] = $cart->getEntityId(); + $this->_helper->log('before get customer'); + $oneCart['customer'] = $this->_getCustomer($cart, $mailchimpStoreId, $magentoStoreId); + if ($campaignId) { + $oneCart['campaign_id'] = $campaignId; + } + $this->_helper->log('after get customer'); + + $oneCart['checkout_url'] = $this->_getCheckoutUrl($cart); + $oneCart['currency_code'] = $cart->getQuoteCurrencyCode(); + $oneCart['order_total'] = $cart->getGrandTotal(); + $oneCart['tax_total'] = 0; + $lines = array(); + // get all items on the cart + $items = $cart->getAllVisibleItems(); + $itemCount = 0; + /** + * @var $item \Magento\Quote\Model\Quote\Item + */ + foreach ($items as $item) { + $line = array(); + if ($item->getProductType()=='bundle'||$item->getProductType()=='grouped') { + continue; + } + + if ($item->getProductType()==\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) { + $variant = null; + if ($item->getOptionByCode('simple_product')) { + $variant = $item->getOptionByCode('simple_product')->getProduct(); + } + + if (!$variant) { + continue; + } + + $variantId = $variant->getId(); + } else { + $variantId = $item->getProductId(); + } + + //id can not be 0 so we add 1 to $itemCount before setting the id. + $itemCount++; + $line['id'] = (string)$itemCount; + $line['product_id'] = $item->getProductId(); + $line['product_variant_id'] = $variantId; + $line['quantity'] = (int)$item->getQty(); + $line['price'] = $item->getPrice(); + $lines[] = $line; + } + + $jsonData = ""; + if ($itemCount) { + $oneCart['lines'] = $lines; + //enconde to JSON + try { + $jsonData = json_encode($oneCart); + } catch (Exception $e) { + //json encode failed + $this->_helper->log("Carts " . $cart->getId() . " json encode failed"); + } + } + + return $jsonData; + } + /** + * @param \Magento\Quote\Model\Quote $cart + * @return string + */ + protected function _getCheckoutUrl(\Magento\Quote\Model\Quote $cart) + { + $token = md5(rand(0, 9999999)); + $url = $this->_urlHelper->getUrl( + 'mailchimp/cart/loadquote', array( + 'id' => $cart->getId(), + 'token' => $token, + '_nosid' => true, + '_secure' => true + ) + ); + $this->_token = $token; + return $url; + } + protected function _getCustomer(\Magento\Quote\Model\Quote $cart,$mailchimpStoreId, $magentoStoreId) + { + $api = $this->_helper->getApi($magentoStoreId); + $customers = array(); + try { + $customers = $api->ecommerce->customers->getByEmail($mailchimpStoreId, $cart->getCustomerEmail()); + } catch (\Mailchimp_Error $e) { + $this->_helper->log($e->getMessage()); + } + + if (isset($customers['total_items']) && $customers['total_items'] > 0) { + $customer = array( + 'id' => $customers['customers'][0]['id'] + ); + } else { + if (!$cart->getCustomerId()) { + $date = $this->_helper->getDateMicrotime(); + $customer = array( + "id" => "GUEST-" . $date, + "email_address" => $cart->getCustomerEmail(), + "opt_in_status" => false + ); + } else { + $customer = array( + "id" => $cart->getCustomerId(), + "email_address" => $cart->getCustomerEmail(), + "opt_in_status" => $this->_apiCustomer->getOptin($magentoStoreId) + ); + } + } + + $firstName = $cart->getCustomerFirstname(); + if ($firstName) { + $customer["first_name"] = $firstName; + } + + $lastName = $cart->getCustomerLastname(); + if ($lastName) { + $customer["last_name"] = $lastName; + } + + $billingAddress = $cart->getBillingAddress(); + if ($billingAddress) { + $street = $billingAddress->getStreet(); + $address = array(); + if ($street[0]) { + $address['address1'] = $street[0]; + } + + if (count($street) > 1) { + $address['address1'] = $street[1]; + } + + if ($billingAddress->getCity()) { + $address['city'] = $billingAddress->getCity(); + } + + if ($billingAddress->getRegion()) { + $address['province'] = $billingAddress->getRegion(); + } + + if ($billingAddress->getRegionCode()) { + $address['province_code'] = $billingAddress->getRegionCode(); + } + + if ($billingAddress->getPostcode()) { + $address['postal_code'] = $billingAddress->getPostcode(); + } + + if ($billingAddress->getCountryId()) { + $country = $this->_countryInformation->getCountryInfo($billingAddress->getCountryId()); + $countryName = $country->getFullNameLocale(); + $address['shipping_address']['country'] = $countryName; + $address['shipping_address']['country_code'] = $country->getTwoLetterAbbreviation(); + } + + if (count($address)) { + $customer['address'] = $address; + } + } + + //company +// if ($billingAddress->getCompany()) { +// $customer["company"] = $billingAddress->getCompany(); +// } + + return $customer; + } + + /** + * @return \Magento\Quote\Model\ResourceModel\Quote\Collection + */ + protected function _getQuoteCollection() + { + return $this->_quoteCollection->create(); + } + + /** + * @return \Magento\Sales\Model\ResourceModel\Order\Collection + */ + protected function _getOrderCollection() + { + return $this->_orderCollectionFactory->create(); + } + + /** + * @param $storeId + * @param $entityId + * @param $sync_delta + * @param $sync_error + * @param $sync_modified + * @param $sync_deleted + */ + protected function _updateQuote($storeId, $entityId, $sync_delta, $sync_error='', $sync_modified=0, $sync_deleted=0) + { + $this->_helper->log(__METHOD__); + $this->_helper->saveEcommerceData($storeId, $entityId, $sync_delta, $sync_error, $sync_modified, + \Ebizmarts\MailChimp\Helper\Data::IS_QUOTE, $sync_deleted, $this->_token); + } +} \ No newline at end of file diff --git a/Model/Api/Customer.php b/Model/Api/Customer.php index 2fe61dc6..368cc42e 100644 --- a/Model/Api/Customer.php +++ b/Model/Api/Customer.php @@ -18,20 +18,17 @@ class Customer { + const MAX = 100; /** * @var \Ebizmarts\MailChimp\Helper\Data */ protected $_helper; /** - * @var \Magento\Customer\Api\CustomerRepositoryInterface - */ - protected $_customerRepository; - /** - * @var \Magento\Customer\Model\ResourceModel\Customer\Collection + * @var \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory */ protected $_collection; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Collection + * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory */ protected $_orderCollection; /** @@ -43,7 +40,7 @@ class Customer */ protected $_countryInformation; /** - * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory + * @var \Magento\Customer\Model\CustomerFactory */ protected $_customerFactory; protected $_address; @@ -56,25 +53,24 @@ class Customer /** * Customer constructor. * @param \Ebizmarts\MailChimp\Helper\Data $helper - * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository - * @param \Magento\Customer\Model\ResourceModel\Customer\Collection $collection - * @param \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection + * @param \Magento\Customer\Model\CustomerFactory $customerFactory + * @param \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $collection + * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollection * @param \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation + * @param \Magento\Customer\Model\Address $address * @param \Magento\Framework\Stdlib\DateTime\DateTime $date */ public function __construct( \Ebizmarts\MailChimp\Helper\Data $helper, - \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, - \Magento\Customer\Api\Data\CustomerInterfaceFactory $customerFactory, - \Magento\Customer\Model\ResourceModel\Customer\Collection $collection, - \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection, + \Magento\Customer\Model\CustomerFactory $customerFactory, + \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $collection, + \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollection, \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation, \Magento\Customer\Model\Address $address, \Magento\Framework\Stdlib\DateTime\DateTime $date ) { $this->_helper = $helper; - $this->_customerRepository = $customerRepository; $this->_collection = $collection; $this->_orderCollection = $orderCollection; $this->_date = $date; @@ -85,28 +81,35 @@ public function __construct( } public function sendCustomers($storeId) { - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE); - $collection = $this->_collection; - $collection->addAttributeToFilter( - array( - array('attribute' => 'mailchimp_sync_delta', 'null' => true), - array('attribute' => 'mailchimp_sync_delta', 'eq' => ''), - array('attribute' => 'mailchimp_sync_delta', 'lt' => $this->_helper->getMCMinSyncDateFlag()), - array('attribute' => 'mailchimp_sync_modified', 'eq'=> 1) - ), '', 'left' - ) - ->addAttributeToFilter('store_id',array('eq'=>$storeId)); + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE,$storeId); + $collection = $this->_collection->create(); + $collection->addFieldToFilter('store_id',array('eq'=>$storeId)); + $collection->getSelect()->joinLeft( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.related_id = e.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER. + "' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'", + ['m4m.*'] + ); + $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null ". + "OR (m4m.mailchimp_sync_delta > '".$this->_helper->getMCMinSyncDateFlag(). + "' and m4m.mailchimp_sync_modified = 1)"); + $collection->getSelect()->limit(self::MAX); + $this->_helper->log((string)$collection->getSelect()); $counter = 0; $customerArray = array(); foreach($collection as $item) { - $customer = $this->_customerRepository->getById($item->getId()); + $this->_helper->log('process each customer'); + $customer = $this->_customerFactory->create(); + $customer->getResource()->load($customer,$item->getId()); + + +// $item->getId()); $data = $this->_buildCustomerData($customer); $customerJson = ''; try { - $this->_helper->log('before json'); $customerJson = json_encode($data); } catch(Exception $e) { $this->_helper->log('Customer: '.$customer->getId().' json encode failed'); @@ -118,12 +121,7 @@ public function sendCustomers($storeId) $customerArray[$counter]['body'] = $customerJson; //update customers delta - $customer->setCustomAttribute("mailchimp_sync_delta",$this->_date->gmtDate()); - //$customer->setData("mailchimp_sync_delta",$this->_date->gmtDate()); - $customer->setCustomAttribute("mailchimp_sync_error", ""); - $customer->setCustomAttribute("mailchimp_sync_modified", 0); - $this->_customerRepository->save($customer); -// $customer->save($customer); + $this->_updateCustomer($mailchimpStoreId, $customer->getId(), $this->_date->gmtDate(), '', 0); } $counter++; @@ -135,68 +133,84 @@ public function sendCustomers($storeId) * @param \Magento\Customer\Model\Customer $customer * @return array */ - protected function _buildCustomerData(\Magento\Customer\Api\Data\CustomerInterface $customer) + protected function _buildCustomerData(\Magento\Customer\Model\Customer $customer) { + $this->_helper->log(__METHOD__); $point = 0; $data = array(); - $data['id'] = $customer->getId(); - $data['email_address'] = $customer->getEmail(); - $data['first_name'] = $customer->getFirstName(); - $data['last_name'] = $customer->getLastName(); - $data['opt_in_status'] = $this->getOptin(); + $data["id"] = $customer->getId(); + $data["email_address"] = $customer->getEmail() ? $customer->getEmail() : ''; + $data["first_name"] = $customer->getFirstname() ? $customer->getFirstname() : ''; + $data["last_name"] = $customer->getLastname() ? $customer->getLastname() : ''; + $data["opt_in_status"] = $this->getOptin(); // customer order data - $orderCollection = $this->_orderCollection; - $orderCollection->addFieldToFilter('state', 'complete') + $orderCollection = $this->_orderCollection->create(); + $orderCollection->addFieldToFilter('state', array( + array('neq',\Magento\Sales\Model\Order::STATE_CANCELED), + array('neq',\Magento\Sales\Model\Order::STATE_CLOSED))) ->addAttributeToFilter('customer_id', array('eq' => $customer->getId())); + $this->_helper->log((string)$orderCollection->getSelect()); $totalOrders = 0; $totalAmountSpent = 0; /** - * @var $order \Magento\Sales\Model\Order + * @var $customerOrder \Magento\Sales\Model\Order */ - foreach($orderCollection as $order) { + foreach($orderCollection as $customerOrder) { $totalOrders++; - $totalAmountSpent += $order->getGrandTotal(); + $totalAmountSpent += $customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded() + - $customerOrder->getTotalCanceled(); } $data['orders_count'] = $totalOrders; $data['total_spent'] = $totalAmountSpent; - foreach($customer->getAddresses() as $address) { - /** - * @var $address \Magento\Customer\Model\Address - */ - if (!array_key_exists('address',$data)) { + $address = $customer->getDefaultBillingAddress(); + $this->_helper->log('after get billing address'); + if($address) { + $customerAddress = array(); + if ($street = $address->getStreet()) { $street = $address->getStreet(); + if ($street[0]) { + $customerAddress["address1"] = $street[0]; + } + if (count($street) > 1) { + $customerAddress["address2"] = $street[1]; + } + } + $this->_helper->log('after street'); + if ($address->getCity()) { + $customerAddress["city"] = $address->getCity(); + } + $this->_helper->log('after city'); + if ($address->getRegion()) { + $customerAddress["province"] = $address->getRegion(); + } + $this->_helper->log('after region'); + if ($address->getRegionCode()) { + $customerAddress["province_code"] = $address->getRegionCode(); + } + $this->_helper->log('after region code'); + if ($address->getPostcode()) { + $customerAddress["postal_code"] = $address->getPostcode(); + } + $this->_helper->log('after post code'); + if ($address->getCountry()) { $country = $this->_countryInformation->getCountryInfo($address->getCountryId()); -// $this->_helper->log('country name'.$point++); $countryName = $country->getFullNameLocale(); -// $this->_helper->log('region '.$point++); -// //$regionModel = $address->getRegionModel($address->getRegionId()); -// $this->_helper->log($address->getRegion()); -// $this->_helper->log('region code '.$point++); -// $this->_helper->log($address->getRegionCode()); -// $this->_helper->log('postcode '.$point++); -// $this->_helper->log($address->getPostcode()); - $data['address'] = array( - "address1" => $street[0] ? $street[0] : "", - "address2" => count($street)>1 ? $street[1] : "", - "city" => $address->getCity() ? $address->getCity() : "", -// "province" => $address->getRegion() ? $address->getRegion() : "", -// "province_code" => $address->getRegionCode() ? $address->getRegionCode() : "", - "postal_code" => $address->getPostcode(), - "country" => $countryName, - "country_code" => $country->getTwoLetterAbbreviation() - ); -// $this->_helper->log('before getcompany'); + $customerAddress["country"] = $countryName; + $customerAddress["country_code"] = $country->getTwoLetterAbbreviation(); + } + $this->_helper->log('after country'); + if (count($customerAddress)) { + $data["address"] = $customerAddress; + } + //company // if ($address->getCompany()) { // $data["company"] = $address->getCompany(); // } - break; - } - } -// $this->_helper->log('antes del mergeVar'); -// $mergeFields = $this->getMergeVars($customer); -// if (is_array($mergeFields)) { -// $data = array_merge($mergeFields, $data); +// break; +// } // } + } + $this->_helper->log('before return'); return $data; } @@ -225,12 +239,18 @@ public function createGuestCustomer($guestId, $order) { return $guestCustomer; } - public function getOptin() { - if ($this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_ECOMMERCE_OPTIN, 0)) { + public function getOptin($storeId = 0) { + if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_ECOMMERCE_OPTIN, $storeId)) { $optin = true; } else { $optin = false; } return $optin; } + protected function _updateCustomer($storeId, $entityId, $sync_delta, $sync_error, $sync_modified) + { + $this->_helper->saveEcommerceData($storeId, $entityId, $sync_delta, $sync_error, $sync_modified, + \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER); + } + } \ No newline at end of file diff --git a/Model/Api/Order.php b/Model/Api/Order.php index ec1ee422..bce442d4 100644 --- a/Model/Api/Order.php +++ b/Model/Api/Order.php @@ -27,6 +27,9 @@ class Order const PARTIALLY_REFUNDED = 'partially_refunded'; const CANCELED = 'canceled'; const COMPLETE = 'complete'; + + protected $_api = null; + /** * @var \Ebizmarts\MailChimp\Helper\Data */ @@ -60,9 +63,13 @@ class Order */ protected $_countryInformation; /** - * @var \Magento\Catalog\Model\ProductRepository + * @var \Magento\Catalog\Model\ProductFactory + */ + protected $_productFactory; + /** + * @var \Magento\Framework\Url */ - protected $_productRepository; + protected $_urlHelper; protected $_chimpSyncEcommerce; protected $_firstDate; protected $_counter; @@ -73,14 +80,15 @@ class Order * Order constructor. * @param \Ebizmarts\MailChimp\Helper\Data $helper * @param \Magento\Sales\Model\OrderRepository $order - * @param \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection + * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory * @param \Magento\Catalog\Model\ResourceModel\Product $product * @param \Magento\Framework\Stdlib\DateTime\DateTime $date * @param Product $apiProduct * @param Customer $apiCustomer + * @param \Magento\Catalog\Model\ProductFactory $productFactory * @param \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation + * @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce */ - public function __construct( \Ebizmarts\MailChimp\Helper\Data $helper, \Magento\Sales\Model\OrderRepository $order, @@ -89,9 +97,10 @@ public function __construct( \Magento\Framework\Stdlib\DateTime\DateTime $date, \Ebizmarts\MailChimp\Model\Api\Product $apiProduct, \Ebizmarts\MailChimp\Model\Api\Customer $apiCustomer, - \Magento\Catalog\Model\ProductRepository $productRepository, + \Magento\Catalog\Model\ProductFactory $productFactory, \Magento\Directory\Api\CountryInformationAcquirerInterface $countryInformation, - \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce + \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce, + \Magento\Framework\Url $urlHelper ) { $this->_helper = $helper; @@ -99,23 +108,33 @@ public function __construct( $this->_orderCollectionFactory = $orderCollectionFactory; $this->_date = $date; $this->_apiProduct = $apiProduct; - $this->_productRepository = $productRepository; + $this->_productFactory = $productFactory; $this->_product = $product; $this->_apiCustomer = $apiCustomer; $this->_countryInformation = $countryInformation; $this->_chimpSyncEcommerce = $chimpSyncEcommerce; $this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_ORDER. '_' . $this->_date->gmtTimestamp(); - $this->_firstDate = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_ECOMMERCE_FIRSTDATE); + $this->_firstDate = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_ECOMMERCE_FIRSTDATE); $this->_counter = 0; + $this->_urlHelper = $urlHelper; } - public function sendOrders($storeId) { + + /** + * Set the request for orders to be created on MailChimp + * + * @param $mailchimpStoreId + * @param $magentoStoreId + * @return array + */ + public function sendOrders($magentoStoreId) + { + $this->_helper->log(__METHOD__); $batchArray = array(); - //$mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE); - // get all the carts modified but not converted in orders - $batchArray = array_merge($batchArray, $this->_getModifiedOrders($storeId)); - // get new carts - $batchArray = array_merge($batchArray, $this->_getNewOrders($storeId)); + // get all the orders modified + $batchArray = array_merge($batchArray, $this->_getModifiedOrders($magentoStoreId)); + // get new orders + $batchArray = array_merge($batchArray, $this->_getNewOrders($magentoStoreId)); return $batchArray; } @@ -123,268 +142,212 @@ protected function _getCollection() { return $this->_orderCollectionFactory->create(); } - protected function _getModifiedOrders($storeId) + protected function _getModifiedOrders($magentoStoreId) { $this->_helper->log(__METHOD__); - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$storeId); $batchArray = array(); - $collection = $this->_getCollection(); - //create missing products first - $collection->addAttributeToSelect('entity_id'); - $collection->addFieldToFilter('main_table.store_id',array('eq'=>$storeId)); - $collection->getSelect()->joinLeft( + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE,$magentoStoreId); + $modifiedOrders = $this->_getCollection(); + // 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( ['m4m' => 'mailchimp_sync_ecommerce'], - "m4m.store_id = main_table.store_id and m4m.related_id = main_table.entity_id", - [] + "m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_ORDER. + "' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'", + ['m4m.*'] ); - $collection->getSelect()->where("m4m.mailchimp_sync_delta > '".$this->_helper->getMCMinSyncDateFlag(). - "' and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_ORDER."' and m4m.mailchimp_sync_modified = 1"); - if($this->_firstDate) { - $collection->addFieldToFilter('created_at',array('from' => $this->_firstDate)); - } - $collection->getSelect()->limit(self::BATCH_LIMIT); - $this->_helper->log((string)$collection->getSelect()); + // be sure that the order are already in mailchimp and not deleted + $modifiedOrders->getSelect()->where("m4m.mailchimp_sync_modified = 1 AND m4m.mailchimp_store_id = '".$mailchimpStoreId."'"); + // limit the collection + $modifiedOrders->getSelect()->limit(self::BATCH_LIMIT); + $this->_helper->log((string)$modifiedOrders->getSelect()); /** - * @var $oneOrder \Magento\Sales\Model\Order + * @var $order \Magento\Sales\Model\Order */ - - foreach ($collection as $item) { + foreach ($modifiedOrders as $item) { + $this->_helper->log('inside the foreach'); try { $error = ''; - $oneOrder = $this->_order->get($item->getEntityId()); - $productData = $this->_apiProduct->sendModifiedProduct($oneOrder, $mailchimpStoreId); + $orderId = $item->getEntityId(); + $order = $this->_order->get($orderId); + //create missing products first + $productData = $this->_apiProduct->sendModifiedProduct($order, $mailchimpStoreId); if (count($productData)) { foreach ($productData as $p) { $batchArray[$this->_counter] = $p; $this->_counter++; } } - $orderJson = $this->GeneratePOSTPayload($oneOrder, $mailchimpStoreId); + + $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId, true); if (!empty($orderJson)) { $batchArray[$this->_counter]['method'] = "PATCH"; - $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $oneOrder->getEntityId(); - $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $oneOrder->getEntityId(); + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders/' . $orderId; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; $batchArray[$this->_counter]['body'] = $orderJson; - } else { $error = $this->_helper->__('Something went wrong when retreiving product information.'); + $this->_updateOrder($mailchimpStoreId, $orderId, $this->_date->gmtDate(), $error, 0); + continue; } - //update order delta - $chimpSyncEcommerce = $this->_getChimpSyncEcommerce($oneOrder->getStoreId(),$oneOrder->getId(),\Ebizmarts\MailChimp\Helper\Data::IS_ORDER); - $chimpSyncEcommerce->setStoreId($oneOrder->getStoreId()); - $chimpSyncEcommerce->setType(\Ebizmarts\MailChimp\Helper\Data::IS_ORDER); - $chimpSyncEcommerce->setRelatedId($oneOrder->getId()); - $chimpSyncEcommerce->setMailchimpSyncModified(0); - $chimpSyncEcommerce->setMailchimpSyncDelta($this->_date->gmtDate()); - $chimpSyncEcommerce->setMailchimpSyncError($error); - $chimpSyncEcommerce->getResource()->save($chimpSyncEcommerce); + //update order delta + $this->_updateOrder($mailchimpStoreId, $orderId, $this->_date->gmtDate(), $error, 0); $this->_counter++; } catch (Exception $e) { $this->_helper->log($e->getMessage()); } } + return $batchArray; } - private function _getNewOrders($storeId) + protected function _getNewOrders($magentoStoreId) { $this->_helper->log(__METHOD__); - $batchArray = array(); - $collection = $this->_getCollection(); - $this->_helper->log((string)$collection->getSelect()); - $this->_helper->log("step 1"); - $collection->addFieldToFilter('main_table.store_id',array('eq'=>$storeId)); -// ->addFieldToFilter('main_table.state',array('eq'=>\Ebizmarts\MailChimp\Helper\Data::ORDER_STATE_OK)); - $this->_helper->log((string)$collection->getSelect()); - $this->_helper->log("step 2"); - $collection->getSelect()->joinLeft( + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE,$magentoStoreId); + $newOrders = $this->_getCollection(); + // select carts for the current Magento store id + $newOrders->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); + // filter by first date if exists. + if ($this->_firstDate) { + $newOrders->addFieldToFilter('created_at', array('gt' => $this->_firstDate)); + } + $newOrders->getSelect()->joinLeft( ['m4m' => 'mailchimp_sync_ecommerce'], - "m4m.store_id = main_table.store_id and m4m.related_id = main_table.entity_id", - [] + "m4m.related_id = main_table.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_ORDER. + "' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'", + ['m4m.*'] ); - $this->_helper->log((string)$collection->getSelect()); - $this->_helper->log("step 3"); - $collection->getSelect()->where("m4m.mailchimp_sync_delta is null or (m4m.mailchimp_sync_delta < '". - $this->_helper->getMCMinSyncDateFlag()."' and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_ORDER."')"); - $this->_helper->log((string)$collection->getSelect()); - $this->_helper->log("step 4"); - $counter = 0; - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$storeId); + // be sure that the quote are not in mailchimp + $newOrders->getSelect()->where("m4m.mailchimp_sync_delta IS NULL"); + // limit the collection + $newOrders->getSelect()->limit(self::BATCH_LIMIT); + $this->_helper->log((string)$newOrders->getSelect()); /** - * @var $oneOrder \Magento\Sales\Model\Order + * @var $order \Magento\Sales\Model\Order */ - foreach ($collection as $oneOrder) - { + foreach ($newOrders as $item) { + $this->_helper->log('inside foreach'); try { - /** - * @var $order \Magento\Sales\Model\Order - */ - $order = $this->_order->get($oneOrder->getId()); - - $order->getResource()->save($order); - $productData = $this->_apiProduct->sendModifiedProduct($order,$mailchimpStoreId); + $error = ''; + $this->_helper->log('before get id'); + $orderId = $item->getEntityId(); + $this->_helper->log('before get the order'); + $order = $this->_order->get($orderId);; + //create missing products first + $this->_helper->log('before send products'); + $productData = $this->_apiProduct->sendModifiedProduct($order, $mailchimpStoreId); if (count($productData)) { foreach ($productData as $p) { - $batchArray[$counter] = $p; - $counter++; + $batchArray[$this->_counter] = $p; + $this->_counter++; } } - $this->_helper->log("before GeneratePOSTPayload"); - $orderJson = $this->GeneratePOSTPayload($order, $storeId); - $this->_helper->log("after GeneratePOSTPayload"); - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$storeId); + $this->_helper->log('before generate order post'); + $orderJson = $this->GeneratePOSTPayload($order, $mailchimpStoreId, $magentoStoreId); if (!empty($orderJson)) { - $batchArray[$counter]['method'] = "POST"; - $batchArray[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; - $batchArray[$counter]['operation_id'] = $this->_batchId . '_' . $order->getEntityId(); - $batchArray[$counter]['body'] = $orderJson; - + $batchArray[$this->_counter]['method'] = "POST"; + $batchArray[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/orders'; + $batchArray[$this->_counter]['operation_id'] = $this->_batchId . '_' . $orderId; + $batchArray[$this->_counter]['body'] = $orderJson; } else { $error = $this->_helper->__('Something went wrong when retreiving product information.'); - $this->_helper->log($error); - $order->setData("mailchimp_sync_error", $error); + $this->_updateOrder($mailchimpStoreId, $orderId, $this->_date->gmtDate(), $error, 0); } + //update order delta - $this->_helper->log("before save ecommerce"); - $chimpSyncEcommerce = $this->_getChimpSyncEcommerce($order->getStoreId(),$oneOrder->getId(),\Ebizmarts\MailChimp\Helper\Data::IS_ORDER); - $chimpSyncEcommerce->setStoreId($order->getStoreId()); - $chimpSyncEcommerce->setType(\Ebizmarts\MailChimp\Helper\Data::IS_ORDER); - $chimpSyncEcommerce->setRelatedId($oneOrder->getId()); - $chimpSyncEcommerce->setMailchimpSyncModified(0); - $chimpSyncEcommerce->setMailchimpSyncDelta($this->_date->gmtDate()); - $chimpSyncEcommerce->setMailchimpSyncError(''); - $chimpSyncEcommerce->getResource()->save($chimpSyncEcommerce); - $this->_helper->log("after save ecommerce"); - $counter++; - } - catch (Exception $e) - { - $this->_helper->log('Order '.$oneOrder->getId().' fails '.$e->getMessage()); + $this->_updateOrder($mailchimpStoreId, $orderId, $this->_date->gmtDate(), $error, 0); + $this->_counter++; + } catch (Exception $e) { + $this->_helper->log($e->getMessage()); } } + return $batchArray; } - private function _getChimpSyncEcommerce($storeId,$id,$type) - { - $chimp = $this->_chimpSyncEcommerce->getByStoreIdType($storeId,$id,$type); - return $chimp; - } + /** - * Return true if order has been already sent to MailChimp and has been modified afterwards. + * Set all the data for each order to be sent * * @param $order - * @return bool + * @param $mailchimpStoreId + * @param $magentoStoreId + * @param $isModifiedOrder + * @return string */ - protected function _isModifiedOrder($order) + protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order, $mailchimpStoreId, $magentoStoreId, $isModifiedOrder = false) { - return ($order->getMailchimpSyncModified() && $order->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag()); - } - - protected function _getMailChimpStatus(\Magento\Sales\Model\Order $order) - { - $mailChimpFinancialStatus = null; - $mailChimpFulfillmentStatus = null; - $totalItemsOrdered = $order->getData('total_qty_ordered'); - $shippedItemAmount = 0; - $invoicedItemAmount = 0; - $refundedItemAmount = 0; - $mailChimpStatus = array(); - /** - * @var $item \Magento\Sales\Model\Order\Item - */ - - foreach ($order->getAllVisibleItems() as $item){ - $shippedItemAmount += $item->getQtyShipped(); - $invoicedItemAmount += $item->getQtyInvoiced(); - $refundedItemAmount += $item->getQtyRefunded(); - } - if ($shippedItemAmount > 0) { - if ($totalItemsOrdered > $shippedItemAmount) { - $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED; - } else { - $mailChimpFulfillmentStatus = self::SHIPPED; - } - } - if ($refundedItemAmount > 0) { - if ($totalItemsOrdered > $refundedItemAmount) { - $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED; - } else { - $mailChimpFinancialStatus = self::REFUNDED; - } - } - if ($invoicedItemAmount > 0) { - if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) { - if ($totalItemsOrdered > $invoicedItemAmount) { - $mailChimpFinancialStatus = self::PARTIALLY_PAID; - } else { - $mailChimpFinancialStatus = self::PAID; - } - } - - } - - if (!$mailChimpFinancialStatus && $order->getState() == \Magento\Sales\Model\Order::STATE_CANCELED) { - $mailChimpFinancialStatus = self::CANCELED; - } - - if (!$mailChimpFinancialStatus) { - $mailChimpFinancialStatus = self::PENDING; - } - - if ($mailChimpFinancialStatus) { - $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus; - } - if ($mailChimpFulfillmentStatus) { - $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus; - } - return $mailChimpStatus; - } - - /** - * @param \Magento\Sales\Model\Order $order - * @param $storeId - * @return array - */ - protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeId) - { - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$storeId); + $this->_helper->log(__METHOD__); $data = array(); $data['id'] = $order->getEntityId(); if ($order->getMailchimpCampaignId()) { $data['campaign_id'] = $order->getMailchimpCampaignId(); } + + if ($order->getMailchimpLandingPage()) { + $data['landing_site'] = $order->getMailchimpLandingPage(); + } + $this->_helper->log('before charge currency'); $data['currency_code'] = $order->getOrderCurrencyCode(); $data['order_total'] = $order->getGrandTotal(); $data['tax_total'] = $order->getTaxAmount(); + $data['discount_total'] = abs($order->getDiscountAmount()); $data['shipping_total'] = $order->getShippingAmount(); + $statusArray = $this->_getMailChimpStatus($order); + $this->_helper->log('before charge status'); + if (isset($statusArray['financial_status'])) { + $data['financial_status'] = $statusArray['financial_status']; + } + + if (isset($statusArray['fulfillment_status'])) { + $data['fulfillment_status'] = $statusArray['fulfillment_status']; + } + $data['processed_at_foreign'] = $order->getCreatedAt(); + $data['updated_at_foreign'] = $order->getUpdatedAt(); + if ($order->getState() == \Magento\Sales\Model\Order::STATE_CANCELED) { + $orderCancelDate = null; + $commentCollection = $order->getStatusHistoryCollection(); + /** + * @var $comment \Magento\Sales\Model\Order\Status\History + */ + foreach ($commentCollection as $comment) { + if ($comment->getStatus() === \Magento\Sales\Model\Order::STATE_CANCELED) { + $orderCancelDate = $comment->getCreatedAt(); + } + } + + if ($orderCancelDate) { + $data['cancelled_at_foreign'] = $orderCancelDate; + } + } + $data['lines'] = array(); //order lines - $this->_helper->log("before items"); $items = $order->getAllVisibleItems(); + $this->_helper->log('before processing items'); $itemCount = 0; /** * @var $item \Magento\Sales\Model\Order\Item */ foreach ($items as $item) { - - if ($item->getProductType()==\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) { + $productSyncData = $this->_helper->getChimpSyncEcommerce($mailchimpStoreId, $item->getProductId(), + \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT); + if ($item->getProductType() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) { $options = $item->getProductOptions(); $sku = $options['simple_sku']; - $variant = $this->_productRepository->get($sku); + $variant = $this->_productFactory->create()->getIdBySku($sku); + if (!$variant) { + continue; + } } else { - $sku = $item->getSku(); $variant = $item->getProductId(); } - - // load the product and check if the product was already sent to mailchimp - $this->_product = $this->_productRepository->get($sku); - $syncDelta = $this->_product->getMailchimpSyncDelta(); - $syncError = $this->_product->getMailchimpSyncError(); - if ($syncDelta&&!$syncError) { + if ($productSyncData->getMailchimpSyncDelta() && $productSyncData->getMailchimpSyncError() == 0) { $itemCount++; $data["lines"][] = array( "id" => (string)$itemCount, @@ -392,26 +355,28 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI "product_variant_id" => $variant, "quantity" => (int)$item->getQtyOrdered(), "price" => $item->getPrice(), + "discount" => abs($item->getDiscountAmount()) ); } } - $this->_helper->log("after items"); - if (!$itemCount) { + unset($data['lines']); return ""; } + + //customer data + $this->_helper->log('before get the customer'); + $api = $this->_helper->getApi(); - $this->_helper->log("before get customer from mailchimp"); $customers = array(); try { - $this->_helper->log($order->getCustomerEmail()); - $this->_helper->log($mailchimpStoreId); $customers = $api->ecommerce->customers->getByEmail($mailchimpStoreId, $order->getCustomerEmail()); } catch (\Mailchimp_Error $e) { $this->_helper->log($e->getMessage()); } + $this->_helper->log('after get the customer'); - if (!$this->_isModifiedOrder($order)) { + if (!$isModifiedOrder) { if (isset($customers['total_items']) && $customers['total_items'] > 0) { $id = $customers['customers'][0]['id']; $data['customer'] = array( @@ -434,10 +399,11 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI } } catch (\Mailchimp_Error $e) { } + $data["customer"] = array( "id" => ($order->getCustomerId()) ? $order->getCustomerId() : $guestId = "CUSTOMER-" . $this->_helper->getDateMicrotime(), "email_address" => ($custEmailAddr) ? $custEmailAddr : $order->getCustomerEmail(), - "opt_in_status" => $this->_apiCustomer->getOptin() + "opt_in_status" => $this->_apiCustomer->getOptin($magentoStoreId) ); } } @@ -449,56 +415,21 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI ); } } +// $store = Mage::getModel('core/store')->load($magentoStoreId); + $this->_helper->log('before charge customer data'); - -// $this->_helper->log("after get customer from mailchimp"); -// $this->_helper->log($customers); -// if (isset($customers['total_items']) && $customers['total_items'] > 0) { -// $id = $customers['customers'][0]['id']; -// $data['customer'] = array( -// 'id' => $id -// ); -// $guestCustomer = $this->_apiCustomer->createGuestCustomer($id, $order); -// $mergeFields = $this->_apiCustomer->getMergeVars($guestCustomer); -// if (is_array($mergeFields)) { -// $data['customer'] = array_merge($mergeFields, $data['customer']); -// } -// } else { -// if ((bool)$order->getCustomerIsGuest()) { -// $guestId = "GUEST-" . $this->_helper->getDateMicrotime(); -// $data["customer"] = array( -// "id" => $guestId, -// "email_address" => $order->getCustomerEmail(), -// "opt_in_status" => false -// ); -// $this->_helper->log('before createGuestCustomer'); -// $guestCustomer = $this->_apiCustomer->createGuestCustomer($guestId, $order); -// $this->_helper->log('after createGuestCustomer before getMergeVars'); -// $mergeFields = $this->_apiCustomer->getMergeVars($guestCustomer); -// $this->_helper->log('after getMergeVars'); -// if (is_array($mergeFields)) { -// $data['customer'] = array_merge($mergeFields, $data['customer']); -// } -// } else { -// $data["customer"] = array( -// "id" => $order->getCustomerId(), -// "email_address" => $order->getCustomerEmail(), -// "opt_in_status" => $this->_apiCustomer->getOptin() -// ); -// } -// if($order->getCustomerFirstname()) { -// $data["customer"]["first_name"] = $order->getCustomerFirstname(); -// } -// if($order->getCustomerLastname()) { -// $data["customer"]["last_name"] = $order->getCustomerLastname(); -// } -// } -// $this->_helper->log('after customer, before billing'); - - if($order->getCustomerFirstname()) { + $data['order_url'] = $this->_urlHelper->getUrl( + 'sales/order/view/', array( + 'order_id' => $order->getId(), + '_nosid' => true, + '_secure' => true + ) + ); + if ($order->getCustomerFirstname()) { $data["customer"]["first_name"] = $order->getCustomerFirstname(); } - if($order->getCustomerLastname()) { + + if ($order->getCustomerLastname()) { $data["customer"]["last_name"] = $order->getCustomerLastname(); } $billingAddress = $order->getBillingAddress(); @@ -536,87 +467,197 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI } if ($billingAddress->getCountry()) { - $address["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); - $address["country_code"] = $billingAddress->getCountry(); - $data['billing_address']["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); - $data['billing_address']["country_code"] = $billingAddress->getCountry(); + $country = $this->_countryInformation->getCountryInfo($billingAddress->getCountryId()); + $countryName = $country->getFullNameLocale(); + $address["country"] =$data['billing_address']['country'] = $countryName; + $address["country_code"] = $data['billing_address']['country_code'] = $country->getTwoLetterAbbreviation(); } - if (count($address)) { $data["customer"]["address"] = $address; } + if ($billingAddress->getName()) { $data['billing_address']['name'] = $billingAddress->getName(); } - $shippingAddress = $order->getShippingAddress(); - $street = $shippingAddress->getStreet(); - if ($shippingAddress->getName()) { - $data['shipping_address']['name'] = $shippingAddress->getName(); - } - if (isset($street[0]) && $street[0]) { - $data['shipping_address']['address1'] = $street[0]; - } - if (isset($street[1]) && $street[1]) { - $data['shipping_address']['address2'] = $street[1]; - } - if ($shippingAddress->getCity()) { - $data['shipping_address']['city'] = $shippingAddress->getCity(); - } - if ($shippingAddress->getRegion()) { - $data['shipping_address']['province'] = $shippingAddress->getRegion(); - } - if ($shippingAddress->getRegionCode()) { - $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); - } - if ($shippingAddress->getPostcode()) { - $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); - } - if ($shippingAddress->getCountry()) { - $data['shipping_address']['country'] = Mage::getModel('directory/country')->loadByCode($shippingAddress->getCountry())->getName(); - $data['shipping_address']['country_code'] = $shippingAddress->getCountry(); - } - //company if ($billingAddress->getCompany()) { $data["customer"]["company"] = $billingAddress->getCompany(); $data["billing_address"]["company"] = $billingAddress->getCompany(); } - if ($shippingAddress->getCompamy()) { - $data["shipping_address"]["company"] = $billingAddress->getCompany(); + $shippingAddress = $order->getShippingAddress(); + if ($shippingAddress) { + $street = $shippingAddress->getStreet(); + if ($shippingAddress->getName()) { + $data['shipping_address']['name'] = $shippingAddress->getName(); + } + + if (isset($street[0]) && $street[0]) { + $data['shipping_address']['address1'] = $street[0]; + } + + if (isset($street[1]) && $street[1]) { + $data['shipping_address']['address2'] = $street[1]; + } + + if ($shippingAddress->getCity()) { + $data['shipping_address']['city'] = $shippingAddress->getCity(); + } + + if ($shippingAddress->getRegion()) { + $data['shipping_address']['province'] = $shippingAddress->getRegion(); + } + + if ($shippingAddress->getRegionCode()) { + $data['shipping_address']['province_code'] = $shippingAddress->getRegionCode(); + } + + if ($shippingAddress->getPostcode()) { + $data['shipping_address']['postal_code'] = $shippingAddress->getPostcode(); + } + + if ($shippingAddress->getCountryId()) { + $country = $this->_countryInformation->getCountryInfo($shippingAddress->getCountryId()); + $countryName = $country->getFullNameLocale(); + $data['shipping_address']['country'] = $countryName; + $data['shipping_address']['country_code'] = $country->getTwoLetterAbbreviation(); + } + +// if ($shippingAddress->getCompamy()) { +// $data["shipping_address"]["company"] = $shippingAddress->getCompany(); +// } } //customer orders data - $orderCollection = $this->_getCollection() - ->addFieldToFilter('state', array('eq' => 'complete')) + $this->_helper->log('before charge totals'); + + $orderCollection = $this->_orderCollectionFactory->create(); + $orderCollection->addFieldToFilter('state', array( + array('neq',\Magento\Sales\Model\Order::STATE_CANCELED), + array('neq',\Magento\Sales\Model\Order::STATE_CLOSED))) ->addAttributeToFilter('customer_email', array('eq' => $order->getCustomerEmail())); - if($this->_firstDate) { - $orderCollection->addFieldToFilter('created_at', array('from' => $this->_firstDate)); - } $totalOrders = 1; $totalAmountSpent = (int)$order->getGrandTotal(); - $this->_helper->log('after collection, before foreach'); /** - * @var $orderAlreadySent \Magento\Sales\Model\Order + * @var $customerOrder \Magento\Sales\Model\Order */ - foreach ($orderCollection as $orderAlreadySent) { + foreach ($orderCollection as $customerOrder) { $totalOrders++; - $totalAmountSpent += (int)$orderAlreadySent->getGrandTotal(); + $totalAmountSpent += $customerOrder->getGrandTotal() - $customerOrder->getTotalRefunded() + - $customerOrder->getTotalCanceled(); } + $data["customer"]["orders_count"] = $totalOrders; $data["customer"]["total_spent"] = $totalAmountSpent; $jsonData = ""; - $this->_helper->log('after foreach, before json'); + //enconde to JSON try { - $jsonData = json_encode($data); - } catch (Exception $e) { //json encode failed - $this->_helper->log("Order ".$order->getId()." json encode failed"); + $this->_helper->log("Order " . $order->getEntityId() . " json encode failed"); } - $this->_helper->log('end'); + return $jsonData; } + + protected function _getMailChimpStatus(\Magento\Sales\Model\Order $order) + { + $this->_helper->log(__METHOD__); + $mailChimpFinancialStatus = null; + $mailChimpFulfillmentStatus = null; + $totalItemsOrdered = $order->getData('total_qty_ordered'); + $shippedItemAmount = 0; + $invoicedItemAmount = 0; + $refundedItemAmount = 0; + $mailChimpStatus = array(); + /** + * @var $item \Magento\Sales\Model\Order\Item + */ + foreach ($order->getAllVisibleItems() as $item) { + $shippedItemAmount += $item->getQtyShipped(); + $invoicedItemAmount += $item->getQtyInvoiced(); + $refundedItemAmount += $item->getQtyRefunded(); + } + + if ($shippedItemAmount > 0) { + if ($totalItemsOrdered > $shippedItemAmount) { + $mailChimpFulfillmentStatus = self::PARTIALLY_SHIPPED; + } else { + $mailChimpFulfillmentStatus = self::SHIPPED; + } + } + + if ($refundedItemAmount > 0) { + if ($totalItemsOrdered > $refundedItemAmount) { + $mailChimpFinancialStatus = self::PARTIALLY_REFUNDED; + } else { + $mailChimpFinancialStatus = self::REFUNDED; + } + } + + if ($invoicedItemAmount > 0) { + if ($refundedItemAmount == 0 || $refundedItemAmount != $invoicedItemAmount) { + if ($totalItemsOrdered > $invoicedItemAmount) { + $mailChimpFinancialStatus = self::PARTIALLY_PAID; + } else { + $mailChimpFinancialStatus = self::PAID; + } + } + } + + if (!$mailChimpFinancialStatus && $order->getState() == \Magento\Sales\Model\Order::STATE_CANCELED) { + $mailChimpFinancialStatus = self::CANCELED; + } + + if (!$mailChimpFinancialStatus) { + $mailChimpFinancialStatus = self::PENDING; + } + + if ($mailChimpFinancialStatus) { + $mailChimpStatus['financial_status'] = $mailChimpFinancialStatus; + } + + if ($mailChimpFulfillmentStatus) { + $mailChimpStatus['fulfillment_status'] = $mailChimpFulfillmentStatus; + } + + return $mailChimpStatus; + } + +// public function update($order, $magentoStoreId) +// { +// if (Mage::helper('mailchimp')->isEcomSyncDataEnabled('stores', $magentoStoreId)) { +// $mailchimpStoreId = Mage::helper('mailchimp')->getMCStoreId('stores', $magentoStoreId); +// $orderSyncData = Mage::helper('mailchimp')->getEcommerceSyncDataItem($order->getId(), Ebizmarts_MailChimp_Model_Config::IS_ORDER, $mailchimpStoreId); +// if ($orderSyncData->getMailchimpSyncDelta() > Mage::helper('mailchimp')->getMCMinSyncDateFlag('stores', $magentoStoreId)) { +// $orderSyncData->setData("mailchimp_sync_error", "") +// ->setData("mailchimp_sync_modified", 1) +// ->save(); +// } +// } +// } + +// /** +// * Get Api Object +// * +// * @param $magentoStoreId +// * @return Ebizmarts_Mailchimp|null +// */ +// protected function _getApi($magentoStoreId) +// { +// if (!$this->_api) { +// $this->_api = Mage::helper('mailchimp')->getApi('stores', $magentoStoreId); +// } +// +// return $this->_api; +// } + + protected function _updateOrder($storeId, $entityId, $sync_delta, $sync_error, $sync_modified) + { + $this->_helper->log(__METHOD__); + $this->_helper->saveEcommerceData($storeId, $entityId, $sync_delta, $sync_error, $sync_modified, + \Ebizmarts\MailChimp\Helper\Data::IS_ORDER); + } } \ No newline at end of file diff --git a/Model/Api/Product.php b/Model/Api/Product.php index b3f68953..44d60bd0 100644 --- a/Model/Api/Product.php +++ b/Model/Api/Product.php @@ -50,25 +50,31 @@ class Product * @var string */ protected $_batchId; + /** + * @var \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce + */ + protected $_chimpSyncEcommerce; /** * Product constructor. - * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection + * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection * @param \Magento\Catalog\Model\ProductRepository $productRepository * @param \Magento\Framework\Stdlib\DateTime\DateTime $date * @param \Ebizmarts\MailChimp\Helper\Data $helper * @param \Magento\Catalog\Helper\Image $imageHelper * @param \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository * @param \Magento\Catalog\Model\CategoryRepository $categoryRepository + * @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce */ public function __construct( - \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection, + \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection, \Magento\Catalog\Model\ProductRepository $productRepository, \Magento\Framework\Stdlib\DateTime\DateTime $date, \Ebizmarts\MailChimp\Helper\Data $helper, \Magento\Catalog\Helper\Image $imageHelper, \Magento\CatalogInventory\Model\Stock\StockItemRepository $stockItemRepository, - \Magento\Catalog\Model\CategoryRepository $categoryRepository + \Magento\Catalog\Model\CategoryRepository $categoryRepository, + \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $chimpSyncEcommerce ) { $this->_productRepository = $productRepository; @@ -78,40 +84,37 @@ public function __construct( $this->_imageHelper = $imageHelper; $this->_stockItemRepository = $stockItemRepository; $this->_categoryRepository = $categoryRepository; + $this->_chimpSyncEcommerce = $chimpSyncEcommerce; $this->_batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT. '_' . $this->_date->gmtTimestamp(); } public function _sendProducts($storeId) { $batchArray = array(); $counter = 0; - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE); - $collection = $this->_productCollection; + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE,$storeId); + $collection = $this->_getCollection(); $collection->setStoreId($storeId); - $collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) - ->addAttributeToFilter( - array( - array('attribute'=>'mailchimp_sync_delta','null'=>true), - array('attribute'=>'mailchimp_sync_delta','lt'=>$this->_helper->getMCMinSyncDateFlag()), - array('attribute'=>'mailchimp_sync_modified', 'eq'=>1) - ), '', 'left' - ); + $collection->getSelect()->joinLeft( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.related_id = e.entity_id and m4m.type = '".\Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT. + "' and m4m.mailchimp_store_id = '".$mailchimpStoreId."'", + ['m4m.*'] + ); + $collection->getSelect()->where("m4m.mailchimp_sync_delta IS null OR (m4m.mailchimp_sync_delta > '".$this->_helper->getMCMinSyncDateFlag(). + "' and m4m.mailchimp_sync_modified = 1)"); $collection->getSelect()->limit(self::MAX); + $this->_helper->log((string)$collection->getSelect()); foreach($collection as $item) { /** * @var $product \Magento\Catalog\Model\Product */ $product = $this->_productRepository->get($item->getSku()); - if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() && - $product->getMailchimpSyncDelta() > $this->_helper->getMCMinSyncDateFlag()) { - $product->setData("mailchimp_sync_error", ""); - $product->setData('mailchimp_sync_modified', 0); - $product->setData("mailchimp_sync_modified", $this->_date->gmtDate()); - $product->setHasDataChanges(true); -// $product->getResource()->save($product); - $product->getResource()->saveAttribute($product,'mailchimp_sync_error'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); +// $productSyncData = $this->_chimpSyncEcommerce->getByStoreIdType($mailchimpStoreId,$product->getId(), +// \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT); + if ($item->getMailchimpSyncModified() && $item->getMailchimpSyncDelta() && + $item->getMailchimpSyncDelta() > $this->_helper->getMCMinSyncDateFlag()) { + $this->_updateProduct($mailchimpStoreId,$product->getId(),$this->_date->gmtDate(),"",0); continue; } else { $data = $this->_buildNewProductRequest($product, $mailchimpStoreId); @@ -121,27 +124,21 @@ public function _sendProducts($storeId) $counter++; //update product delta - $product->setData("mailchimp_sync_delta", $this->_date->gmtDate()); - $product->setData("mailchimp_sync_error", ""); - $product->setData('mailchimp_sync_modified', 0); - $product->setHasDataChanges(true); - $product->getResource()->save($product); - $product->getResource()->saveAttribute($product,'mailchimp_sync_error'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); + $this->_updateProduct($mailchimpStoreId,$product->getId(),$this->_date->gmtDate(),"",0); } else { - $product->setData("mailchimp_sync_delta", $this->_date->gmtDate()); - $product->setData("mailchimp_sync_error", "This product type is not supported on MailChimp."); - $product->setData('mailchimp_sync_modified', 0); - $product->setHasDataChanges(true); - $product->getResource()->save($product); - $product->getResource()->saveAttribute($product,'mailchimp_sync_error'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); + $this->_updateProduct($mailchimpStoreId,$product->getId(),$this->_date->gmtDate(), + "This product type is not supported on MailChimp.",0); } } return $batchArray; + } + /** + * @return \Magento\Catalog\Model\ResourceModel\Product\Collection + */ + protected function _getCollection() + { + return $this->_productCollection->create(); } protected function _buildNewProductRequest(\Magento\Catalog\Model\Product $product, $mailchimpStoreId) { @@ -186,10 +183,51 @@ protected function _buildNewProductRequest(\Magento\Catalog\Model\Product $produ $data['body'] = $body; return $data; } - protected function _buildOldProductRequest($product, $mailchimpStoreId) + protected function _buildOldProductRequest(\Magento\Catalog\Model\Product $product, $batchId, $mailchimpStoreId) { - return ""; - } + $operations = array(); + if ($product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE || + $product->getTypeId() == \Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL || + $product->getTypeId() == "downloadable") { + $data = $this->_buildProductData($product); + + $parentIds = $product->getTypeInstance()->getParentIdsByChild($product->getId()); + //$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($product->getId()); + + if (empty($parentIds)) { + $parentIds = array($product->getId()); + } + + //add or update variant + foreach ($parentIds as $parentId) { + $variendata = array(); + $variendata["id"] = $data["id"]; + $variendata["title"] = $data["title"]; + $variendata["url"] = $data["url"]; + $variendata["sku"] = $data["sku"]; + $variendata["price"] = $data["price"]; + $variendata["inventory_quantity"] = $data["inventory_quantity"]; + $variendata["image_url"] = $data["image_url"]; + $variendata["backorders"] = $data["backorders"]; + $variendata["visibility"] = $data["visibility"]; + $productdata = array(); + $productdata['method'] = "PUT"; + $productdata['path'] = "/ecommerce/stores/" . $mailchimpStoreId . "/products/".$parentId.'/variants/'.$data['id']; + $productdata['operation_id'] = $batchId . '_' . $parentId; + try { + $body = json_encode($variendata); + } catch (Exception $e) { + //json encode failed + $this->_helper->log("Product " . $product->getId() . " json encode failed"); + continue; + } + + $productdata['body'] = $body; + $operations[] = $productdata; + } + } + + return $operations; } protected function _buildProductData(\Magento\Catalog\Model\Product $product, $isVarient = true, $variants = null) { $data = array(); @@ -239,37 +277,92 @@ protected function _buildProductData(\Magento\Catalog\Model\Product $product, $ return $data; } + /** + * @param \Magento\Sales\Model\Order $order + * @param $mailchimpStoreId + * @return array + * @throws \Magento\Framework\Exception\NoSuchEntityException + */ public function sendModifiedProduct(\Magento\Sales\Model\Order $order,$mailchimpStoreId) { + $this->_helper->log(__METHOD__); $data = array(); $batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT . '_' . $this->_date->gmtTimestamp(); $items = $order->getAllVisibleItems(); foreach ($items as $item) { + $this->_helper->log($item->getProductId()); + //@todo get from the store not the default + $product = $this->_productRepository->getById($item->getProductId()); + $productSyncData = $this->_chimpSyncEcommerce->getByStoreIdType($mailchimpStoreId,$product->getId(), + \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT); + + if ($product->getId()!=$item->getProductId()||$product->getTypeId()=='bundle'||$product->getTypeId()=='grouped') { + $this->_helper->log('continue is bundle/grouped'); + continue; + } + + if ($productSyncData->getMailchimpSyncModified() && + $productSyncData->getMailchimpSyncDelta() > $this->_helper->getMCMinSyncDateFlag()) { + $this->_helper->log('is an old product'); + $data[] = $this->_buildOldProductRequest($product,$batchId); + $this->_updateProduct($mailchimpStoreId, $product->getId(), $this->_date->gmtDate(),'',0); + } elseif (!$productSyncData->getMailchimpSyncDelta() || + $productSyncData->getMailchimpSyncDelta() < $this->_helper->getMCMinSyncDateFlag()) { + $this->_helper->log('is a new product'); + $data[] = $this->_buildNewProductRequest($product, $mailchimpStoreId); + $this->_updateProduct($mailchimpStoreId, $product->getId(), $this->_date->gmtDate(),'',0); + } + } + return $data; + } + + public function sendQuoteModifiedProduct(\Magento\Quote\Model\Quote $quote,$mailchimpStoreId) + { + $this->_helper->log(__METHOD__); + $data = array(); + $batchId = \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT . '_' . $this->_date->gmtTimestamp(); + $items = $quote->getAllVisibleItems(); + /** + * @var $item \Magento\Quote\Model\Quote\Item + */ + foreach ($items as $item) + { + $this->_helper->log($item->getProductId()); + //@todo get from the store not the default $product = $this->_productRepository->getById($item->getProductId()); + $productSyncData = $this->_chimpSyncEcommerce->getByStoreIdType($mailchimpStoreId,$product->getId(), + \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT); + if ($product->getId()!=$item->getProductId()||$product->getTypeId()=='bundle'||$product->getTypeId()=='grouped') { + $this->_helper->log('continue is bundle/grouped'); continue; } - if ($product->getMailchimpSyncModified() && $product->getMailchimpSyncDelta() > $this->_helper->getMCMinSyncDateFlag()) { - $data[] = $this->_buildOldProductRequest($product, $mailchimpStoreId); - $this->_updateProduct($product); - } elseif (!$product->getMailchimpSyncDelta() || $product->getMailchimpSyncDelta() < $this->_helper->getMCMinSyncDateFlag()) { + if ($productSyncData->getMailchimpSyncModified() && + $productSyncData->getMailchimpSyncDelta() > $this->_helper->getMCMinSyncDateFlag()) { + $this->_helper->log('is an old product'); + $data[] = $this->_buildOldProductRequest($product,$batchId); + $this->_updateProduct($mailchimpStoreId, $product->getId(), $this->_date->gmtDate(),'',0); + } elseif (!$productSyncData->getMailchimpSyncDelta() || + $productSyncData->getMailchimpSyncDelta() < $this->_helper->getMCMinSyncDateFlag()) { + $this->_helper->log('is a new product'); $data[] = $this->_buildNewProductRequest($product, $mailchimpStoreId); - $this->_updateProduct($product); + $this->_updateProduct($mailchimpStoreId, $product->getId(), $this->_date->gmtDate(),'',0); } } return $data; } - protected function _updateProduct($product) + /** + * @param $storeId + * @param $entityId + * @param $sync_delta + * @param $sync_error + * @param $sync_modified + */ + protected function _updateProduct($storeId, $entityId, $sync_delta, $sync_error, $sync_modified) { - $product->setData("mailchimp_sync_delta", $this->_date->gmtDate()); - $product->setData("mailchimp_sync_error", ""); - $product->setData('mailchimp_sync_modified', 0); - $product->setHasDataChanges(true); - $product->getResource()->save($product); - $product->getResource()->saveAttribute($product,'mailchimp_sync_error'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); - $product->getResource()->saveAttribute($product,'mailchimp_sync_modified'); + $this->_helper->saveEcommerceData($storeId, $entityId, $sync_delta, $sync_error, $sync_modified, + \Ebizmarts\MailChimp\Helper\Data::IS_PRODUCT); } } \ No newline at end of file diff --git a/Model/Api/Result.php b/Model/Api/Result.php index 9a1da7bd..a600830b 100644 --- a/Model/Api/Result.php +++ b/Model/Api/Result.php @@ -188,8 +188,7 @@ protected function processEachResponseFile($files, $batchId) case \Ebizmarts\MailChimp\Helper\Data::IS_CUSTOMER: $c = $this->_customerRepository->getById($id); if ($c->getId() == $id) { - $c->setCustomAttribute("mailchimp_sync_error", $error); - //$c->setMailchimpUpdateObserverRan(true); +// $c->setCustomAttribute("mailchimp_sync_error", $error); $this->_customerRepository->save($c); } else { $this->_helper->log("Error: customer " . $id . " not found"); diff --git a/Model/Config/Backend/Monkeylist.php b/Model/Config/Backend/Monkeylist.php index 996a8c5c..a9cfb59b 100644 --- a/Model/Config/Backend/Monkeylist.php +++ b/Model/Config/Backend/Monkeylist.php @@ -71,13 +71,13 @@ public function beforeSave() $active = $data['ecommerce']['fields']['active']['inherit']; } if ($active&&$this->isValueChanged()) { - if ($this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$generalData['scope_id'])) { + if ($this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE,$generalData['scope_id'])) { $this->_helper->deleteStore(); } $store = $this->_helper->createStore($this->getValue(), $generalData['scope_id']); if ($store) { $this->resourceConfig->saveConfig( - \Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE, $store, + \Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE, $store, $generalData['scope'], $generalData['scope_id'] ); diff --git a/Model/Config/Source/Details.php b/Model/Config/Source/Details.php index 0defdeea..f1f376ba 100644 --- a/Model/Config/Source/Details.php +++ b/Model/Config/Source/Details.php @@ -43,7 +43,7 @@ public function __construct( $api = $this->_helper->getApi(); try { $this->_options = $api->root->info(); - $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE); + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_STORE); if ($mailchimpStoreId && $this->_helper->getConfigValue(\Ebizmarts\MailChimp\Helper\Data::XML_PATH_ECOMMERCE_ACTIVE)) { $this->_options['store_exists'] = true; $totalCustomers = $api->ecommerce->customers->getAll($mailchimpStoreId, 'total_items'); diff --git a/Model/Logger/Logger.php b/Model/Logger/Logger.php index ae3ed762..3d3fe72f 100644 --- a/Model/Logger/Logger.php +++ b/Model/Logger/Logger.php @@ -17,8 +17,7 @@ class Logger extends \Monolog\Logger public function mailchimpLog($message,$file) { if ($file) { - $fileName = BP. DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . $file .'_Request.log'; - $this->info('name of log file: ['.$fileName.']'); + $fileName = BP. DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'log'. DIRECTORY_SEPARATOR.$file .'_Request.log'; $this->pushHandler(new \Monolog\Handler\StreamHandler($fileName)); } diff --git a/Model/MailChimpSyncEcommerceFactory.php b/Model/MailChimpSyncEcommerceFactory.php new file mode 100644 index 00000000..28aa996b --- /dev/null +++ b/Model/MailChimpSyncEcommerceFactory.php @@ -0,0 +1,43 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2/28/17 7:24 PM + * @file: MailChimpSyncEcommerceFactory.php + */ + +namespace Ebizmarts\MailChimp\Model; + +class MailChimpSyncEcommerceFactory +{ + + protected $_objectManager; + protected $_instanceName; + + /** + * MailChimpSyncEcommerceFactory constructor. + * @param \Magento\Framework\ObjectManagerInterface $objectManager + * @param string $instanceName + */ + public function __construct( + \Magento\Framework\ObjectManagerInterface $objectManager, + $instanceName = '\\Ebizmarts\MailChimp\\Model\\MailChimpSyncEcommerce') + { + $this->_objectManager = $objectManager; + $this->_instanceName = $instanceName; + } + + /** + * @param array $data + * @return \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce + */ + public function create(array $data = array()) + { + return $this->_objectManager->create($this->_instanceName, $data); + } +} \ No newline at end of file diff --git a/Model/ResourceModel/MailChimpSyncEcommerce.php b/Model/ResourceModel/MailChimpSyncEcommerce.php index e126e87c..94ce66ec 100644 --- a/Model/ResourceModel/MailChimpSyncEcommerce.php +++ b/Model/ResourceModel/MailChimpSyncEcommerce.php @@ -29,7 +29,7 @@ public function getByStoreIdType(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommer $select = $connection->select()->from( $this->getTable('mailchimp_sync_ecommerce') )->where( - 'store_id = :store_id AND type = :type AND related_id = :related_id' + 'mailchimp_store_id = :store_id AND type = :type AND related_id = :related_id' ); $data = $connection->fetchRow($select, $bind); if ($data) { diff --git a/Setup/InstallData.php b/Setup/InstallData.php index 6625df9e..60898938 100644 --- a/Setup/InstallData.php +++ b/Setup/InstallData.php @@ -18,100 +18,12 @@ use Magento\Framework\Setup\InstallDataInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\ModuleDataSetupInterface; -use Magento\Catalog\Model\Product\Type; -use Magento\ConfigurableProduct\Model\Product\Type\Configurable; class InstallData implements InstallDataInterface { - /** - * @var EavSetupFactory - */ - private $eavSetupFactory; - - public function __construct(EavSetupFactory $eavSetupFactory) - { - $this->eavSetupFactory = $eavSetupFactory; - } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { - $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); - - $eavSetup->addAttribute( - \Magento\Catalog\Model\Product::ENTITY, - 'mailchimp_sync_modified', - [ - 'type' => 'int', - 'backend' => '', - 'frontend' => '', - 'label' => '', - 'input' => '', - 'class' => '', - 'source' => '', - 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, - 'visible' => false, - 'required' => false, - 'user_defined' => false, - 'default' => '0', - 'searchable' => false, - 'filterable' => false, - 'comparable' => false, - 'visible_on_front' => false, - 'used_in_product_listing' => false, - 'unique' => false, - 'apply_to' => implode(',',[Type::TYPE_SIMPLE,Type::TYPE_VIRTUAL,'downloadable',Configurable::TYPE_CODE]) - ] - ); - - $eavSetup->addAttribute( - \Magento\Catalog\Model\Product::ENTITY, - 'mailchimp_sync_delta', - [ - 'type' => 'datetime', - 'backend' => '', - 'frontend' => '', - 'label' => '', - 'input' => '', - 'class' => '', - 'source' => '', - 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, - 'visible' => false, - 'required' => false, - 'user_defined' => false, - 'default' => '', - 'searchable' => false, - 'filterable' => false, - 'comparable' => false, - 'visible_on_front' => false, - 'used_in_product_listing' => false, - 'unique' => false, - 'apply_to' => implode(',',[Type::TYPE_SIMPLE,Type::TYPE_VIRTUAL,'downloadable',Configurable::TYPE_CODE]) - ] - ); - $eavSetup->addAttribute( - \Magento\Catalog\Model\Product::ENTITY, - 'mailchimp_sync_error', - [ - 'type' => 'varchar', - 'backend' => '', - 'frontend' => '', - 'label' => '', - 'input' => '', - 'class' => '', - 'source' => '', - 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE, - 'visible' => false, - 'required' => false, - 'user_defined' => false, - 'default' => '', - 'searchable' => false, - 'filterable' => false, - 'comparable' => false, - 'visible_on_front' => false, - 'used_in_product_listing' => false, - 'unique' => false, - 'apply_to' => implode(',',[Type::TYPE_SIMPLE,Type::TYPE_VIRTUAL,'downloadable',Configurable::TYPE_CODE]) - ] - ); + return; } } \ No newline at end of file diff --git a/Setup/InstallSchema.php b/Setup/InstallSchema.php index 654a0f4d..a6ad21c6 100644 --- a/Setup/InstallSchema.php +++ b/Setup/InstallSchema.php @@ -36,7 +36,7 @@ public function install(SchemaSetupInterface $setup, ModuleContextInterface $con $installer->startSetup(); $connection = $installer->getConnection(); - $table = $connection + $table = $installer->getConnection() ->newTable($installer->getTable('mailchimp_sync_batches')) ->addColumn( 'id', @@ -117,6 +117,74 @@ public function install(SchemaSetupInterface $setup, ModuleContextInterface $con $installer->getConnection()->createTable($table); + + $table = $installer->getConnection() + ->newTable($installer->getTable('mailchimp_sync_ecommerce')) + ->addColumn( + 'id', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], + 'Id' + ) + ->addColumn( + 'mailchimp_store_id', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 50, + ['unsigned' => true, 'nullable' => false], + 'Store Id' + ) + ->addColumn( + 'type', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 24, + [], + 'Type of register' + ) + ->addColumn( + 'related_id', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + [], + 'Id of the related entity' + ) + ->addColumn( + 'mailchimp_sync_modified', + \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, + null, + [], + 'If the entity was modified' + ) + ->addColumn( + 'mailchimp_sync_delta', + \Magento\Framework\DB\Ddl\Table::TYPE_DATETIME, + null, + [], + 'Sync Delta' + )->addColumn( + 'mailchimp_sync_error', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 128, + [], + 'Error on synchronization' + )->addColumn( + 'mailchimp_sync_deleted', + \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, + null, + [], + 'If the object was deleted in mailchimp' + )->addColumn( + 'mailchimp_token', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 32, + [], + 'Quote token' + ) + + ; + + $installer->getConnection()->createTable($table); + $connection->addColumn( $installer->getTable('newsletter_subscriber'), 'mailchimp_id', @@ -129,7 +197,9 @@ public function install(SchemaSetupInterface $setup, ModuleContextInterface $con $path = $this->_helper->getBaseDir() . DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . 'Mailchimp'; try { - mkdir($path); + if (!is_dir($path)) { + mkdir($path); + } } catch(Exception $e) { $this->_helper->log($e->getMessage()); } diff --git a/Setup/UpgradeData.php b/Setup/UpgradeData.php index 27c380b7..ba294044 100644 --- a/Setup/UpgradeData.php +++ b/Setup/UpgradeData.php @@ -20,60 +20,12 @@ class UpgradeData implements UpgradeDataInterface { - /** - * @var EavSetupFactory - */ - private $eavSetupFactory; - public function __construct(EavSetupFactory $eavSetupFactory) - { - $this->eavSetupFactory = $eavSetupFactory; - } +// public function __construct(EavSetupFactory $eavSetupFactory) +// { +// $this->eavSetupFactory = $eavSetupFactory; +// } public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { - $setup->startSetup(); - if ($context->getVersion() - && version_compare($context->getVersion(), '0.0.2') < 0 - ) { - $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); - $eavSetup->addAttribute( - \Magento\Customer\Model\Customer::ENTITY, - 'mailchimp_sync_modified', - [ - 'type' => 'int', - 'label' => 'Mailchimp Sync Modified', - 'input' => null, - 'required' => false, - 'sort_order' => 150, - 'visible' => false, - 'system' => false, ] - ); - $eavSetup->addAttribute( - \Magento\Customer\Model\Customer::ENTITY, - 'mailchimp_sync_delta', - [ - 'type' => 'datetime', - 'label' => 'Mailchimp Sync Delta', - 'input' => null, - 'required' => false, - 'sort_order' => 151, - 'visible' => false, - 'system' => false, ] - ); - $eavSetup->addAttribute( - \Magento\Customer\Model\Customer::ENTITY, - 'mailchimp_sync_error', - [ - 'type' => 'varchar', - 'label' => 'Mailchimp Sync Error', - 'input' => null, - 'required' => false, - 'sort_order' => 152, - 'visible' => false, - 'system' => false, ] - ); - - } - $setup->endSetup(); } -} \ No newline at end of file +} diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index d37933df..1b4113be 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -22,67 +22,5 @@ class UpgradeSchema implements UpgradeSchemaInterface */ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { - $setup->startSetup(); - $connection = $setup->getConnection(); - if ($context->getVersion() - && version_compare($context->getVersion(), '0.0.3') < 0 - ) { - - $table = $connection - ->newTable($setup->getTable('mailchimp_sync_ecommerce')) - ->addColumn( - 'id', - \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, - null, - ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], - 'Id' - ) - ->addColumn( - 'store_id', - \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, - 50, - ['unsigned' => true, 'nullable' => false], - 'Store Id' - ) - ->addColumn( - 'type', - \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, - 24, - [], - 'Type of register' - ) - ->addColumn( - 'related_id', - \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, - null, - [], - 'Id of the related entity' - ) - ->addColumn( - 'mailchimp_sync_modified', - \Magento\Framework\DB\Ddl\Table::TYPE_BOOLEAN, - null, - [], - 'If the entity was modified' - ) - ->addColumn( - 'mailchimp_sync_delta', - \Magento\Framework\DB\Ddl\Table::TYPE_DATETIME, - null, - [], - 'Sync Delta' - )->addColumn( - 'mailchimp_sync_error', - \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, - 128, - [], - 'Error on synchronization' - ) - ; - - $setup->getConnection()->createTable($table); - } - - $setup->endSetup(); } } \ No newline at end of file diff --git a/composer.json b/composer.json index d0431d5f..32fa1b7a 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ }, "description": "Connect MailChimp with Magento", "type": "magento2-module", - "version": "0.0.4", + "version": "1.0.0", "authors": [ { "name": "Ebizmarts Corp", diff --git a/etc/di.xml b/etc/di.xml index 045c5973..d06cda6b 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -37,10 +37,7 @@ - - - \ No newline at end of file diff --git a/etc/module.xml b/etc/module.xml index ffb67f17..f1ec7eb1 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -11,7 +11,7 @@ */ --> - + diff --git a/view/adminhtml/templates/system/config/reseterrors.phtml b/view/adminhtml/templates/system/config/reseterrors.phtml index ed7c0251..d6382fbb 100644 --- a/view/adminhtml/templates/system/config/reseterrors.phtml +++ b/view/adminhtml/templates/system/config/reseterrors.phtml @@ -4,7 +4,15 @@ jQuery.ajax({ url: 'getAjaxCheckUrl() ?>', data: {form_key: window.FORM_KEY}, - type: 'POST' + type: 'POST', + success: function(data){ + if(data.valid==0) { + alert('Error: '+data.message); + } + else if(data.valid==1) { + alert('Errors cleaned'); + } + } }).done(function(a) { console.log(a); });