From 90894b19bd4fb86095cae5e0fbb8cab0ef5c8ed7 Mon Sep 17 00:00:00 2001 From: gonzalo Date: Tue, 21 Feb 2017 16:17:36 -0300 Subject: [PATCH] add Reset button --- Block/Adminhtml/System/Config/ResetErrors.php | 90 ++++ .../Adminhtml/Ecommerce/ResetLocalErrors.php | 46 ++ Cron/Ecommerce.php | 4 +- Helper/Data.php | 23 +- Model/Api/Order.php | 432 +++++++++++++++--- Model/Config/Backend/Monkeylist.php | 23 +- Model/Config/Source/Details.php | 18 +- Model/Logger/Logger.php | 11 +- .../ResourceModel/MailChimpSyncEcommerce.php | 2 +- Observer/Sales/Order/SaveAfter.php | 40 ++ etc/adminhtml/events.xml | 6 + etc/adminhtml/system.xml | 18 +- .../templates/system/config/reseterrors.phtml | 24 + 13 files changed, 641 insertions(+), 96 deletions(-) create mode 100644 Block/Adminhtml/System/Config/ResetErrors.php create mode 100644 Controller/Adminhtml/Ecommerce/ResetLocalErrors.php create mode 100644 Observer/Sales/Order/SaveAfter.php create mode 100644 etc/adminhtml/events.xml create mode 100644 view/adminhtml/templates/system/config/reseterrors.phtml diff --git a/Block/Adminhtml/System/Config/ResetErrors.php b/Block/Adminhtml/System/Config/ResetErrors.php new file mode 100644 index 00000000..f3d7d62d --- /dev/null +++ b/Block/Adminhtml/System/Config/ResetErrors.php @@ -0,0 +1,90 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2/20/17 3:25 PM + * @file: ResetErrors.php + */ + +namespace Ebizmarts\MailChimp\Block\Adminhtml\System\Config; + +class ResetErrors extends \Magento\Config\Block\System\Config\Form\Field +{ + /** + * @var \Ebizmarts\MailChimp\Helper\Data + */ + private $_helper; + + /** + * ResetErrors constructor. + * @param \Magento\Backend\Block\Template\Context $context + * @param \Ebizmarts\MailChimp\Helper\Data $helper + * @param array $data + */ + public function __construct( + \Magento\Backend\Block\Template\Context $context, + \Ebizmarts\MailChimp\Helper\Data $helper, + array $data=[]) + { + $this->_helper = $helper; + parent::__construct($context, $data); + } + + protected function _construct() + { + parent::_construct(); + $this->setTemplate('system/config/reseterrors.phtml'); + } + +// protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) +// { +// return $this->_toHtml(); +// } + protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) + { + $originalData = $element->getOriginalData(); + $this->addData( + [ + 'button_label' => __($originalData['button_label']), + 'button_url' => $this->getAjaxCheckUrl(), + 'html_id' => $element->getHtmlId(), + ] + ); + return $this->_toHtml(); + } + + public function getButtonHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) + { + + + $originalData = $element->getOriginalData(); + $label = $originalData['button_label']; + $this->addData([ + 'button_label' => __($label), + 'button_url' => $this->getAjaxCheckUrl(), + 'html_id' => $element->getHtmlId(), + ]); + return $this->_toHtml(); + + +// $button = $this->getLayout()->createBlock('adminhtml/widget_button') +// ->setData( +// array( +// 'id' => 'reseterrors_button', +// 'label' => $this->_helper->__('Reset Local Errors'), +// 'onclick' => 'javascript:reseterrors(); return false;' +// ) +// ); +// +// return $button->toHtml(); + } + public function getAjaxCheckUrl() + { + return $this->_urlBuilder->getUrl('mailchimp/ecommerce/ResetLocalErrors'); + } +} \ No newline at end of file diff --git a/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php b/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php new file mode 100644 index 00000000..c688e13e --- /dev/null +++ b/Controller/Adminhtml/Ecommerce/ResetLocalErrors.php @@ -0,0 +1,46 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2/21/17 5:07 PM + * @file: ResetLocalErrors.php + */ + +namespace Ebizmarts\MailChimp\Controller\Adminhtml\Ecommerce; + +use Magento\Framework\Controller\Result\JsonFactory; + +class ResetLocalErrors extends \Magento\Backend\App\Action +{ + protected $resultJsonFactory; + protected $helper; + + public function __construct( + \Magento\Backend\App\Action\Context $context, + JsonFactory $resultJsonFactory, + \Ebizmarts\MailChimp\Helper\Data $helper + ) + { + parent::__construct($context); + $this->resultJsonFactory = $resultJsonFactory; + $this->helper = $helper; + } + + public function execute() + { + $resultJson = $this->resultJsonFactory->create(); + return $resultJson->setData([ + 'valid' => (int)1, + 'message' => 'OK', + ]); + } + protected function _isAllowed() + { + return $this->_authorization->isAllowed('Magento_EncryptionKey::crypt_key'); + } +} \ No newline at end of file diff --git a/Cron/Ecommerce.php b/Cron/Ecommerce.php index 2a56e040..55aca8af 100644 --- a/Cron/Ecommerce.php +++ b/Cron/Ecommerce.php @@ -94,7 +94,6 @@ protected function _processStore($storeId) $orders = $this->_apiOrder->sendOrders($storeId); $results = array_merge($results,$orders); } - $this->_helper->log(var_export($results,true)); if (!empty($results)) { try { $batchArray['operations'] = $results; @@ -105,7 +104,8 @@ protected function _processStore($storeId) } else { $api = $this->_helper->getApi(); $batchResponse =$api->batchOperation->add($batchArray); -// $this->_helper->log(var_export($batchResponse,true)); + $this->_helper->log(var_export($results,true),null,$batchResponse['id']); + $this->_helper->log(var_export($batchResponse,true)); $this->_mailChimpSyncBatches->setStoreId($storeId); $this->_mailChimpSyncBatches->setBatchId($batchResponse['id']); $this->_mailChimpSyncBatches->setStatus($batchResponse['status']); diff --git a/Helper/Data.php b/Helper/Data.php index d52a70a2..b966201d 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -29,6 +29,7 @@ class Data extends \Magento\Framework\App\Helper\AbstractHelper const XML_PATH_ECOMMERCE_ACTIVE = 'mailchimp/ecommerce/active'; const XML_PATH_SYNC_DATE = 'mailchimp/general/mcminsyncdateflag'; const XML_ECOMMERCE_OPTIN = 'mailchimp/ecommerce/customer_optin'; + const XML_ECOMMERCE_FIRSTDATE = 'mailchimp/ecommerce/firstdate'; const ORDER_STATE_OK = 'complete'; @@ -219,10 +220,10 @@ public function getLogger() * @param $message * @param null $store */ - public function log($message, $store = null) + public function log($message, $store = null, $file = null) { if ($this->getConfigValue(self::XML_PATH_LOG, $store)) { - $this->_mlogger->mailchimpLog($message); + $this->_mlogger->mailchimpLog($message, $file); } } @@ -249,18 +250,24 @@ public function deleteStore() } } - public function createStore($listId=null) + public function getMCStoreName($storeId) + { + return $this->_storeManager->getStore($storeId)->getFrontendName(); + } + public function createStore($listId=null, $storeId) { if ($listId) { //generate store id $date = date('Y-m-d-His'); - $baseUrl = $this->_storeManager->getStore()->getBaseUrl(); - $storeId = parse_url($baseUrl, PHP_URL_HOST) . '_' . $date; - $currencyCode = $this->_storeManager->getStore()->getDefaultCurrencyCode(); + $baseUrl = $this->_storeManager->getStore($storeId)->getName(); + $mailchimpStoreId = md5(parse_url($baseUrl, PHP_URL_HOST) . '_' . $date); + $currencyCode = $this->_storeManager->getStore($storeId)->getDefaultCurrencyCode(); + $name = $this->getMCStoreName($storeId); + //create store in mailchimp try { - $this->getApi()->ecommerce->stores->add($storeId,$listId,$storeId,$currencyCode,'Magento'); - return $storeId; + $this->getApi()->ecommerce->stores->add($mailchimpStoreId,$listId,$name,$currencyCode,'Magento'); + return $mailchimpStoreId; } catch (Exception $e) { return null; diff --git a/Model/Api/Order.php b/Model/Api/Order.php index c1a65438..ec1ee422 100644 --- a/Model/Api/Order.php +++ b/Model/Api/Order.php @@ -17,6 +17,16 @@ class Order { + const BATCH_LIMIT = 50; + const PAID = 'paid'; + const PARTIALLY_PAID = 'parially_paid'; + const SHIPPED = 'shipped'; + const PARTIALLY_SHIPPED = 'parially_shipped'; + const PENDING = 'pending'; + const REFUNDED = 'refunded'; + const PARTIALLY_REFUNDED = 'partially_refunded'; + const CANCELED = 'canceled'; + const COMPLETE = 'complete'; /** * @var \Ebizmarts\MailChimp\Helper\Data */ @@ -26,9 +36,9 @@ class Order */ protected $_order; /** - * @var \Magento\Sales\Model\ResourceModel\Order\Collection + * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory */ - protected $_orderCollection; + protected $_orderCollectionFactory; /** * @var \Magento\Framework\Stdlib\DateTime\DateTime */ @@ -54,7 +64,8 @@ class Order */ protected $_productRepository; protected $_chimpSyncEcommerce; - + protected $_firstDate; + protected $_counter; protected $_batchId; @@ -73,7 +84,7 @@ class Order public function __construct( \Ebizmarts\MailChimp\Helper\Data $helper, \Magento\Sales\Model\OrderRepository $order, - \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection, + \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, \Magento\Catalog\Model\ResourceModel\Product $product, \Magento\Framework\Stdlib\DateTime\DateTime $date, \Ebizmarts\MailChimp\Model\Api\Product $apiProduct, @@ -85,7 +96,7 @@ public function __construct( { $this->_helper = $helper; $this->_order = $order; - $this->_orderCollection = $orderCollection; + $this->_orderCollectionFactory = $orderCollectionFactory; $this->_date = $date; $this->_apiProduct = $apiProduct; $this->_productRepository = $productRepository; @@ -94,23 +105,113 @@ public function __construct( $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->_counter = 0; + } + public function sendOrders($storeId) { + $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)); + + return $batchArray; + } + protected function _getCollection() + { + return $this->_orderCollectionFactory->create(); + } + protected function _getModifiedOrders($storeId) + { + $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( + ['m4m' => 'mailchimp_sync_ecommerce'], + "m4m.store_id = main_table.store_id and m4m.related_id = main_table.entity_id", + [] + ); + $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()); + /** + * @var $oneOrder \Magento\Sales\Model\Order + */ + + foreach ($collection as $item) { + try { + $error = ''; + $oneOrder = $this->_order->get($item->getEntityId()); + $productData = $this->_apiProduct->sendModifiedProduct($oneOrder, $mailchimpStoreId); + if (count($productData)) { + foreach ($productData as $p) { + $batchArray[$this->_counter] = $p; + $this->_counter++; + } + } + $orderJson = $this->GeneratePOSTPayload($oneOrder, $mailchimpStoreId); + 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]['body'] = $orderJson; + + } else { + $error = $this->_helper->__('Something went wrong when retreiving product information.'); + } + //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); + + $this->_counter++; + } catch (Exception $e) { + $this->_helper->log($e->getMessage()); + } + } + return $batchArray; } - public function sendOrders($storeId) + + private function _getNewOrders($storeId) { + $this->_helper->log(__METHOD__); + $batchArray = array(); - $collection = $this->_orderCollection; - $collection->addFieldToFilter('main_table.store_id',array('eq'=>$storeId)) - ->addFieldToFilter('main_table.state',array('eq'=>\Ebizmarts\MailChimp\Helper\Data::ORDER_STATE_OK)); + $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( ['m4m' => 'mailchimp_sync_ecommerce'], "m4m.store_id = main_table.store_id and m4m.related_id = main_table.entity_id", [] ); + $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); + $mailchimpStoreId = $this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$storeId); /** * @var $oneOrder \Magento\Sales\Model\Order */ @@ -130,7 +231,9 @@ public function sendOrders($storeId) $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); if (!empty($orderJson)) { $batchArray[$counter]['method'] = "POST"; @@ -144,16 +247,16 @@ public function sendOrders($storeId) $order->setData("mailchimp_sync_error", $error); } //update order delta + $this->_helper->log("before save ecommerce"); $chimpSyncEcommerce = $this->_getChimpSyncEcommerce($order->getStoreId(),$oneOrder->getId(),\Ebizmarts\MailChimp\Helper\Data::IS_ORDER); -// if(!$chimpSyncEcommerce) { - $chimpSyncEcommerce->setStoreId($order->getStoreId()); - $chimpSyncEcommerce->setType(\Ebizmarts\MailChimp\Helper\Data::IS_ORDER); - $chimpSyncEcommerce->setRelatedId($oneOrder->getId()); -// } + $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) @@ -168,6 +271,77 @@ 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. + * + * @param $order + * @return bool + */ + protected function _isModifiedOrder($order) + { + 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 @@ -189,6 +363,7 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI $data['lines'] = array(); //order lines + $this->_helper->log("before items"); $items = $order->getAllVisibleItems(); $itemCount = 0; /** @@ -220,83 +395,207 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI ); } } + $this->_helper->log("after items"); if (!$itemCount) { return ""; } $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 (Exception $e) { + } catch (\Mailchimp_Error $e) { $this->_helper->log($e->getMessage()); } - 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 + if (!$this->_isModifiedOrder($order)) { + if (isset($customers['total_items']) && $customers['total_items'] > 0) { + $id = $customers['customers'][0]['id']; + $data['customer'] = array( + 'id' => $id ); - $guestCustomer = $this->_apiCustomer->createGuestCustomer($guestId, $order); - $mergeFields = $this->_apiCustomer->getMergeVars($guestCustomer); - if (is_array($mergeFields)) { - $data['customer'] = array_merge($mergeFields, $data['customer']); - } } else { - $data["customer"] = array( - "id" => $order->getCustomerId(), - "email_address" => $order->getCustomerEmail(), - "opt_in_status" => $this->_apiCustomer->getOptin() - ); - } - if($order->getCustomerFirstname()) { - $data["customer"]["first_name"] = $order->getCustomerFirstname(); + if ((bool)$order->getCustomerIsGuest()) { + $guestId = "GUEST-" . $this->_helper->getDateMicrotime(); + $data["customer"] = array( + "id" => $guestId, + "email_address" => $order->getCustomerEmail(), + "opt_in_status" => false + ); + } else { + $custEmailAddr = null; + try { + $customer = $api->ecommerce->customers->get($mailchimpStoreId, $order->getCustomerId(), 'email_address'); + if (isset($customer['email_address'])) { + $custEmailAddr = $customer['email_address']; + } + } catch (\Mailchimp_Error $e) { + } + $data["customer"] = array( + "id" => ($order->getCustomerId()) ? $order->getCustomerId() : $guestId = "CUSTOMER-" . $this->_helper->getDateMicrotime(), + "email_address" => ($custEmailAddr) ? $custEmailAddr : $order->getCustomerEmail(), + "opt_in_status" => $this->_apiCustomer->getOptin() + ); + } } - if($order->getCustomerLastname()) { - $data["customer"]["last_name"] = $order->getCustomerLastname(); + } else { + if (isset($customers['customers'][0]['id'])) { + $id = $customers['customers'][0]['id']; + $data['customer'] = array( + 'id' => $id + ); } } + +// $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["customer"]["first_name"] = $order->getCustomerFirstname(); + } + if($order->getCustomerLastname()) { + $data["customer"]["last_name"] = $order->getCustomerLastname(); + } $billingAddress = $order->getBillingAddress(); $street = $billingAddress->getStreet(); - $country = $this->_countryInformation->getCountryInfo($billingAddress->getCountryId()); - $data["customer"]["address"] = array( - "address1" => $street[0], - "address2" => count($street) > 1 ? $street[1] : "", - "city" => $billingAddress->getCity(), - "province" => $billingAddress->getRegion() ? $billingAddress->getRegion() : "", - "province_code" => $billingAddress->getRegionCode() ? $billingAddress->getRegionCode() : "", - "postal_code" => $billingAddress->getPostcode(), - "country" => $country->getFullNameLocale(), - "country_code" => $country->getTwoLetterAbbreviation() - ); + $address = array(); + + if ($street[0]) { + $address["address1"] = $street[0]; + $data['billing_address']["address1"] = $street[0]; + } + + if (count($street) > 1) { + $address["address2"] = $street[1]; + $data['billing_address']["address2"] = $street[1]; + } + + if ($billingAddress->getCity()) { + $address["city"] = $billingAddress->getCity(); + $data['billing_address']["city"] = $billingAddress->getCity(); + } + + if ($billingAddress->getRegion()) { + $address["province"] = $billingAddress->getRegion(); + $data['billing_address']["province"] = $billingAddress->getRegion(); + } + + if ($billingAddress->getRegionCode()) { + $address["province_code"] = $billingAddress->getRegionCode(); + $data['billing_address']["province_code"] = $billingAddress->getRegionCode(); + } + + if ($billingAddress->getPostcode()) { + $address["postal_code"] = $billingAddress->getPostcode(); + $data['billing_address']["postal_code"] = $billingAddress->getPostcode(); + } + + if ($billingAddress->getCountry()) { + $address["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $address["country_code"] = $billingAddress->getCountry(); + $data['billing_address']["country"] = Mage::getModel('directory/country')->loadByCode($billingAddress->getCountry())->getName(); + $data['billing_address']["country_code"] = $billingAddress->getCountry(); + } + + if (count($address)) { + $data["customer"]["address"] = $address; + } + if ($billingAddress->getName()) { + $data['billing_address']['name'] = $billingAddress->getName(); + } + + $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(); } //customer orders data - $orderCollection = $this->_orderCollection + $orderCollection = $this->_getCollection() ->addFieldToFilter('state', array('eq' => 'complete')) - ->addAttributeToFilter('customer_email', array('eq' => $order->getCustomerEmail())) - ->addFieldToFilter('mailchimp_sync_delta', array('notnull' => true)) - ->addFieldToFilter('mailchimp_sync_delta', array('neq' => '')) - ->addFieldToFilter('mailchimp_sync_delta', array('gt' => $this->_helper->getMCMinSyncDateFlag())) - ->addFieldToFilter('mailchimp_sync_error', array('eq' => "")); + ->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 */ @@ -307,7 +606,7 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI $data["customer"]["orders_count"] = $totalOrders; $data["customer"]["total_spent"] = $totalAmountSpent; $jsonData = ""; - + $this->_helper->log('after foreach, before json'); //enconde to JSON try { @@ -317,6 +616,7 @@ protected function GeneratePOSTPayload(\Magento\Sales\Model\Order $order,$storeI //json encode failed $this->_helper->log("Order ".$order->getId()." json encode failed"); } + $this->_helper->log('end'); return $jsonData; } } \ No newline at end of file diff --git a/Model/Config/Backend/Monkeylist.php b/Model/Config/Backend/Monkeylist.php index f8549a54..996a8c5c 100644 --- a/Model/Config/Backend/Monkeylist.php +++ b/Model/Config/Backend/Monkeylist.php @@ -63,30 +63,31 @@ public function __construct( public function beforeSave() { + $generalData = $this->getData(); $data = $this->getData('groups'); - $this->_helper->log($data['ecommerce']); - $active = $data['ecommerce']['fields']['active']['value']; + if (isset($data['ecommerce']['fields']['active']['value'])) { + $active = $data['ecommerce']['fields']['active']['value']; + } elseif ($data['ecommerce']['fields']['active']['inherit']) { + $active = $data['ecommerce']['fields']['active']['inherit']; + } if ($active&&$this->isValueChanged()) { - if ($this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE)) { + if ($this->_helper->getConfigValue(\Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE,$generalData['scope_id'])) { $this->_helper->deleteStore(); } - $store = $this->_helper->createStore($this->getValue()); + $store = $this->_helper->createStore($this->getValue(), $generalData['scope_id']); if ($store) { $this->resourceConfig->saveConfig( \Ebizmarts\Mailchimp\Helper\Data::XML_PATH_STORE, $store, - ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - 0 + $generalData['scope'], + $generalData['scope_id'] ); $this->resourceConfig->saveConfig( \Ebizmarts\MailChimp\Helper\Data::XML_PATH_SYNC_DATE, $this->_date->gmtDate(), - ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - 0 + $generalData['scope'], + $generalData['scope_id'] ); } - - - } else { } return parent::beforeSave(); } diff --git a/Model/Config/Source/Details.php b/Model/Config/Source/Details.php index d739ccad..0defdeea 100644 --- a/Model/Config/Source/Details.php +++ b/Model/Config/Source/Details.php @@ -22,15 +22,22 @@ class Details implements \Magento\Framework\Option\ArrayInterface * @var \Ebizmarts\MailChimp\Helper\Data|null */ private $_helper = null; + /** + * @var \Magento\Framework\Message\ManagerInterface + */ + private $_message; + private $_error = ''; /** + * Details constructor. * @param \Ebizmarts\MailChimp\Helper\Data $helper - * @param \Ebizmarts\MailChimp\Model\Api $api + * @param \Magento\Framework\Message\ManagerInterface $message */ public function __construct( - \Ebizmarts\MailChimp\Helper\Data $helper + \Ebizmarts\MailChimp\Helper\Data $helper, + \Magento\Framework\Message\ManagerInterface $message ) { - + $this->_message = $message; $this->_helper = $helper; if ($this->_helper->getApiKey()) { $api = $this->_helper->getApi(); @@ -50,8 +57,9 @@ public function __construct( } else { $this->_options['store_exists'] = false; } - } catch (\Exception $e) { - $this->_helper->log($e->getMessage()); + } catch (\Mailchimp_Error $e) { + $this->_error = $e->getMessage(); + $this->_options['store_exists'] = false; } } else { $this->_options = '--- Enter your API Key ---'; diff --git a/Model/Logger/Logger.php b/Model/Logger/Logger.php index d9de5d25..ae3ed762 100644 --- a/Model/Logger/Logger.php +++ b/Model/Logger/Logger.php @@ -14,8 +14,14 @@ class Logger extends \Monolog\Logger { - public function mailchimpLog($message) + public function mailchimpLog($message,$file) { + if ($file) { + $fileName = BP. DIRECTORY_SEPARATOR . 'var' . DIRECTORY_SEPARATOR . $file .'_Request.log'; + $this->info('name of log file: ['.$fileName.']'); + $this->pushHandler(new \Monolog\Handler\StreamHandler($fileName)); + } + try { if ($message===null) { $message = "NULL"; @@ -35,5 +41,8 @@ public function mailchimpLog($message) } $message .= "\r\n"; $this->info($message); + if ($file) { + $this->popHandler(); + } } } diff --git a/Model/ResourceModel/MailChimpSyncEcommerce.php b/Model/ResourceModel/MailChimpSyncEcommerce.php index 609a664d..e126e87c 100644 --- a/Model/ResourceModel/MailChimpSyncEcommerce.php +++ b/Model/ResourceModel/MailChimpSyncEcommerce.php @@ -35,6 +35,6 @@ public function getByStoreIdType(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommer if ($data) { $chimp->setData($data); } - return $this; + return $chimp; } } \ No newline at end of file diff --git a/Observer/Sales/Order/SaveAfter.php b/Observer/Sales/Order/SaveAfter.php new file mode 100644 index 00000000..62242453 --- /dev/null +++ b/Observer/Sales/Order/SaveAfter.php @@ -0,0 +1,40 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 2/15/17 3:38 PM + * @file: SaveAfter.php + */ + +namespace Ebizmarts\MailChimp\Observer\Sales\Order; + +use Magento\Framework\Event\Observer; + +class SaveAfter implements \Magento\Framework\Event\ObserverInterface +{ + protected $_ecommerce; + /** + * SaveAfter constructor. + * @param \Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce + */ + public function __construct(\Ebizmarts\MailChimp\Model\MailChimpSyncEcommerce $ecommerce) + { + $this->_ecommerce = $ecommerce; + } + + public function execute(\Magento\Framework\Event\Observer $observer) + { + $order = $observer->getEvent()->getOrder(); + $ecom = $this->_ecommerce->getByStoreIdType($order->getStoreId(),$order->getId(),'ORD'); + if ($ecom) { + $ecom->setMailchimpSyncModified(1); + $ecom->getResource()->save($ecom); + } + + } +} \ No newline at end of file diff --git a/etc/adminhtml/events.xml b/etc/adminhtml/events.xml new file mode 100644 index 00000000..d3fa1e36 --- /dev/null +++ b/etc/adminhtml/events.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index e9b35aa0..007ecd03 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -35,11 +35,11 @@ 1 - + Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Account @@ -99,6 +99,20 @@ Magento\Config\Model\Config\Source\Yesno + + + Ebizmarts\MailChimp\Block\Adminhtml\System\Config\Date + + 1 + + + + Reset Errors + Ebizmarts\MailChimp\Block\Adminhtml\System\Config\ResetErrors + + 1 + + diff --git a/view/adminhtml/templates/system/config/reseterrors.phtml b/view/adminhtml/templates/system/config/reseterrors.phtml new file mode 100644 index 00000000..ed7c0251 --- /dev/null +++ b/view/adminhtml/templates/system/config/reseterrors.phtml @@ -0,0 +1,24 @@ + + + +escapeHtml('Reset errors')); ?> + + +
+ + +