/**
  * Order Cancel
  *
  * @return void
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function execute()
 {
     $isEnabled = $this->helper->isEnabled();
     if ($isEnabled) {
         $statuses = $this->helper->getOrderStatuses();
         $olderThan = $this->helper->getOlderThan();
         $recentThan = $this->helper->getRecentThan();
         $comment = $this->helper->getComment();
         $orders = $this->orderCollectionFactory->create();
         $orders->addFieldToFilter('status', ['in' => $statuses]);
         $orders->getSelect()->where(new \Zend_Db_Expr('TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `updated_at`)) >= ' . $olderThan * 60));
         $orders->getSelect()->where(new \Zend_Db_Expr('TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `updated_at`)) <= ' . $recentThan * 60));
         $orders->getSelect()->limit(10);
         $orders->setOrder('entity_id', 'DESC');
         foreach ($orders->getItems() as $order) {
             if (!$order->canCancel()) {
                 continue;
             }
             try {
                 $order->cancel();
                 $order->addStatusHistoryComment($comment)->setIsCustomerNotified(false);
                 $order->save();
             } catch (\Exception $e) {
                 $this->logger->critical($e);
             }
         }
     }
 }
 /**
  * Push trackEcommerceOrder to tracker on checkout success page
  *
  * @param \Magento\Framework\Event\Observer $observer
  * @return \Henhed\Piwik\Observer\CheckoutSuccessObserver
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $orderIds = $observer->getEvent()->getOrderIds();
     if (!$this->_dataHelper->isTrackingEnabled() || empty($orderIds) || !is_array($orderIds)) {
         return $this;
     }
     $collection = $this->_orderCollectionFactory->create();
     $collection->addFieldToFilter('entity_id', ['in' => $orderIds]);
     // Group order items by SKU since Piwik doesn't seem to handle multiple
     // `addEcommerceItem' with the same SKU.
     $piwikItems = [];
     // Aggregate all placed orders into one since Piwik seems to only
     // register one `trackEcommerceOrder' per request. (For multishipping)
     $piwikOrder = [];
     foreach ($collection as $order) {
         /* @var $order \Magento\Sales\Model\Order */
         foreach ($order->getAllVisibleItems() as $item) {
             /* @var $item \Magento\Sales\Model\Order\Item */
             $sku = $item->getSku();
             $name = $item->getName();
             $price = (double) $item->getBasePriceInclTax();
             $qty = (double) $item->getQtyOrdered();
             if (!isset($piwikItems[$sku])) {
                 $piwikItems[$sku] = [$sku, $name, $price * $qty, $qty];
             } else {
                 // Aggregate row total instead of unit price in case there
                 // are different prices for the same SKU.
                 $piwikItems[$sku][2] += $price * $qty;
                 $piwikItems[$sku][3] += $qty;
             }
         }
         $orderId = $order->getIncrementId();
         $grandTotal = (double) $order->getBaseGrandTotal();
         $subTotal = (double) $order->getBaseSubtotalInclTax();
         $tax = (double) $order->getBaseTaxAmount();
         $shipping = (double) $order->getBaseShippingInclTax();
         $discount = abs((double) $order->getBaseDiscountAmount());
         if (empty($piwikOrder)) {
             $piwikOrder = [$orderId, $grandTotal, $subTotal, $tax, $shipping, $discount];
         } else {
             $piwikOrder[0] .= ', ' . $orderId;
             $piwikOrder[1] += $grandTotal;
             $piwikOrder[2] += $subTotal;
             $piwikOrder[3] += $tax;
             $piwikOrder[4] += $shipping;
             $piwikOrder[5] += $discount;
         }
     }
     // Push `addEcommerceItem'
     foreach ($piwikItems as $piwikItem) {
         list($sku, $name, $rowTotal, $qty) = $piwikItem;
         $this->_piwikTracker->addEcommerceItem($sku, $name, false, $qty > 0 ? $rowTotal / $qty : 0, $qty);
     }
     // Push `trackEcommerceOrder'
     if (!empty($piwikOrder)) {
         list($orderId, $grandTotal, $subTotal, $tax, $shipping, $discount) = $piwikOrder;
         $this->_piwikTracker->trackEcommerceOrder($orderId, $grandTotal, $subTotal, $tax, $shipping, $discount > 0 ? $discount : false);
     }
     return $this;
 }
 /**
  * Init customer order for display on front
  *
  * @return void
  */
 protected function initOrders()
 {
     $customerId = $this->_customerSession->getCustomerId();
     $orders = $this->_orderCollectionFactory->create()->addAttributeToFilter('customer_id', $customerId)->addAttributeToFilter('status', ['in' => $this->_orderConfig->getVisibleOnFrontStatuses()])->addAttributeToSort('created_at', 'desc')->setPage(1, 1);
     //TODO: add filter by current website
     $this->orders = $orders;
 }
Example #4
0
 /**
  * {@inheritdoc}
  */
 public function install(array $fixtures)
 {
     foreach ($fixtures as $file) {
         $fileName = $this->fixtureManager->getFixture($file);
         if (!file_exists($fileName)) {
             continue;
         }
         $rows = $this->csvReader->getData($fileName);
         $header = array_shift($rows);
         $isFirst = true;
         foreach ($rows as $row) {
             $data = [];
             foreach ($row as $key => $value) {
                 $data[$header[$key]] = $value;
             }
             $row = $data;
             if ($isFirst) {
                 $customer = $this->customerRepository->get($row['customer_email']);
                 if (!$customer->getId()) {
                     continue;
                 }
                 /** @var \Magento\Sales\Model\ResourceModel\Collection $orderCollection */
                 $orderCollection = $this->orderCollectionFactory->create();
                 $orderCollection->addFilter('customer_id', $customer->getId());
                 if ($orderCollection->count() > 0) {
                     break;
                 }
             }
             $isFirst = false;
             $orderData = $this->converter->convertRow($row);
             $this->orderProcessor->createOrder($orderData);
         }
     }
 }
Example #5
0
 /**
  * Retrieve last order on current website
  *
  * @return \Magento\Sales\Model\Order|false
  */
 public function getLastOrder()
 {
     $storeIds = $this->getQuote()->getStore()->getWebsite()->getStoreIds();
     $collection = $this->_ordersFactory->create()->addFieldToFilter('customer_id', $this->getCustomerId())->addFieldToFilter('store_id', ['in' => $storeIds])->setOrder('created_at', 'desc')->setPageSize(1)->load();
     foreach ($collection as $order) {
         return $order;
     }
     return false;
 }
Example #6
0
 /**
  * @return bool|\Magento\Sales\Model\ResourceModel\Order\Collection
  */
 public function getOrders()
 {
     if (!($customerId = $this->_customerSession->getCustomerId())) {
         return false;
     }
     if (!$this->orders) {
         $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('customer_id', $customerId)->addFieldToFilter('status', ['in' => $this->_orderConfig->getVisibleOnFrontStatuses()])->setOrder('created_at', 'desc');
     }
     return $this->orders;
 }
Example #7
0
 /**
  * Load search results
  *
  * @return $this
  */
 public function load()
 {
     $result = [];
     if (!$this->hasStart() || !$this->hasLimit() || !$this->hasQuery()) {
         $this->setResults($result);
         return $this;
     }
     $query = $this->getQuery();
     //TODO: add full name logic
     $collection = $this->_collectionFactory->create()->addAttributeToSelect('*')->addAttributeToSearchFilter([['attribute' => 'increment_id', 'like' => $query . '%'], ['attribute' => 'billing_firstname', 'like' => $query . '%'], ['attribute' => 'billing_lastname', 'like' => $query . '%'], ['attribute' => 'billing_telephone', 'like' => $query . '%'], ['attribute' => 'billing_postcode', 'like' => $query . '%'], ['attribute' => 'shipping_firstname', 'like' => $query . '%'], ['attribute' => 'shipping_lastname', 'like' => $query . '%'], ['attribute' => 'shipping_telephone', 'like' => $query . '%'], ['attribute' => 'shipping_postcode', 'like' => $query . '%']])->setCurPage($this->getStart())->setPageSize($this->getLimit())->load();
     foreach ($collection as $order) {
         $result[] = ['id' => 'order/1/' . $order->getId(), 'type' => __('Order'), 'name' => __('Order #%1', $order->getIncrementId()), 'description' => $order->getFirstname() . ' ' . $order->getLastname(), 'url' => $this->_adminhtmlData->getUrl('sales/order/view', ['order_id' => $order->getId()])];
     }
     $this->setResults($result);
     return $this;
 }
 public function setUp()
 {
     $objectManagerHelper = new ObjectManagerHelper($this);
     $this->contextMock = $this->getMock('Magento\\Backend\\App\\Action\\Context', [], [], '', false);
     $resultRedirectFactory = $this->getMock('Magento\\Backend\\Model\\View\\Result\\RedirectFactory', [], [], '', false);
     $this->responseMock = $this->getMock('Magento\\Framework\\App\\ResponseInterface', [], [], '', false);
     $this->requestMock = $this->getMockBuilder('Magento\\Framework\\App\\Request\\Http')->disableOriginalConstructor()->getMock();
     $this->objectManagerMock = $this->getMock('Magento\\Framework\\ObjectManager\\ObjectManager', [], [], '', false);
     $this->messageManagerMock = $this->getMock('Magento\\Framework\\Message\\Manager', [], [], '', false);
     $this->orderCollectionMock = $this->getMockBuilder('Magento\\Sales\\Model\\ResourceModel\\Order\\Collection')->disableOriginalConstructor()->getMock();
     $orderCollection = 'Magento\\Sales\\Model\\ResourceModel\\Order\\CollectionFactory';
     $this->orderCollectionFactoryMock = $this->getMockBuilder($orderCollection)->disableOriginalConstructor()->setMethods(['create'])->getMock();
     $this->sessionMock = $this->getMock('Magento\\Backend\\Model\\Session', ['setIsUrlNotice'], [], '', false);
     $this->actionFlagMock = $this->getMock('Magento\\Framework\\App\\ActionFlag', ['get', 'set'], [], '', false);
     $this->helperMock = $this->getMock('\\Magento\\Backend\\Helper\\Data', ['getUrl'], [], '', false);
     $this->resultRedirectMock = $this->getMock('Magento\\Backend\\Model\\View\\Result\\Redirect', [], [], '', false);
     $resultRedirectFactory->expects($this->any())->method('create')->willReturn($this->resultRedirectMock);
     $redirectMock = $this->getMockBuilder('Magento\\Backend\\Model\\View\\Result\\Redirect')->disableOriginalConstructor()->getMock();
     $resultFactoryMock = $this->getMockBuilder('Magento\\Framework\\Controller\\ResultFactory')->disableOriginalConstructor()->getMock();
     $resultFactoryMock->expects($this->any())->method('create')->with(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT)->willReturn($redirectMock);
     $this->contextMock->expects($this->once())->method('getMessageManager')->willReturn($this->messageManagerMock);
     $this->contextMock->expects($this->once())->method('getRequest')->willReturn($this->requestMock);
     $this->contextMock->expects($this->once())->method('getResponse')->willReturn($this->responseMock);
     $this->contextMock->expects($this->once())->method('getObjectManager')->willReturn($this->objectManagerMock);
     $this->contextMock->expects($this->once())->method('getSession')->willReturn($this->sessionMock);
     $this->contextMock->expects($this->once())->method('getActionFlag')->willReturn($this->actionFlagMock);
     $this->contextMock->expects($this->once())->method('getHelper')->willReturn($this->helperMock);
     $this->contextMock->expects($this->once())->method('getResultRedirectFactory')->willReturn($resultRedirectFactory);
     $this->contextMock->expects($this->any())->method('getResultFactory')->willReturn($resultFactoryMock);
     $this->filterMock = $this->getMock('Magento\\Ui\\Component\\MassAction\\Filter', [], [], '', false);
     $this->filterMock->expects($this->once())->method('getCollection')->with($this->orderCollectionMock)->willReturn($this->orderCollectionMock);
     $this->orderCollectionFactoryMock->expects($this->once())->method('create')->willReturn($this->orderCollectionMock);
     $this->massAction = $objectManagerHelper->getObject('Magento\\Sales\\Controller\\Adminhtml\\Order\\MassUnhold', ['context' => $this->contextMock, 'filter' => $this->filterMock, 'collectionFactory' => $this->orderCollectionFactoryMock]);
 }
 /**
  * Clean expired quotes (cron process)
  *
  * @return void
  */
 public function execute()
 {
     $lifetimes = $this->storesConfig->getStoresConfigByPath('sales/orders/delete_pending_after');
     foreach ($lifetimes as $storeId => $lifetime) {
         /** @var $orders \Magento\Sales\Model\ResourceModel\Order\Collection */
         $orders = $this->orderCollectionFactory->create();
         $orders->addFieldToFilter('store_id', $storeId);
         $orders->addFieldToFilter('status', Order::STATE_PENDING_PAYMENT);
         $orders->getSelect()->where(new \Zend_Db_Expr('TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `updated_at`)) >= ' . $lifetime * 60));
         try {
             $orders->walk('cancel');
             $orders->walk('save');
         } catch (\Exception $e) {
             $this->logger->error('Error cancelling deprecated orders: ' . $e->getMessage());
         }
     }
 }
 public function testConstructMethod()
 {
     $data = [];
     $customerId = 25;
     $this->customerSession->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId));
     $statuses = ['pending', 'processing', 'comlete'];
     $this->orderConfig->expects($this->once())->method('getVisibleOnFrontStatuses')->will($this->returnValue($statuses));
     $orderCollection = $this->getMock('Magento\\Sales\\Model\\ResourceModel\\Order\\Collection', ['addFieldToSelect', 'addFieldToFilter', 'setOrder'], [], '', false, false);
     $this->context->expects($this->any())->method('getPageConfig')->willReturn($this->pageConfig);
     $orderCollection->expects($this->at(0))->method('addFieldToSelect')->with($this->equalTo('*'))->will($this->returnSelf());
     $orderCollection->expects($this->at(1))->method('addFieldToFilter')->with('customer_id', $this->equalTo($customerId))->will($this->returnSelf());
     $orderCollection->expects($this->at(2))->method('addFieldToFilter')->with('status', $this->equalTo(['in' => $statuses]))->will($this->returnSelf());
     $orderCollection->expects($this->at(3))->method('setOrder')->with('created_at', 'desc')->will($this->returnSelf());
     $this->orderCollectionFactory->expects($this->atLeastOnce())->method('create')->will($this->returnValue($orderCollection));
     $this->pageConfig->expects($this->atLeastOnce())->method('getTitle')->willReturn($this->pageTitleMock);
     $this->pageTitleMock->expects($this->atLeastOnce())->method('set')->willReturnSelf();
     $this->model = new \Magento\Sales\Block\Order\History($this->context, $this->orderCollectionFactory, $this->customerSession, $this->orderConfig, $data);
     $this->assertEquals($orderCollection, $this->model->getOrders());
 }
Example #11
0
 /**
  * Retrieve related orders collection
  *
  * @return \Magento\Sales\Model\ResourceModel\Order\Collection
  */
 public function getRelatedOrders()
 {
     if ($this->_relatedOrders === null) {
         $billingAgreement = $this->_getBillingAgreementInstance();
         $billingAgreementId = $billingAgreement ? $billingAgreement->getAgreementId() : 0;
         $this->_relatedOrders = $this->_orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('customer_id', (int) $this->_customerSession->getCustomerId())->addFieldToFilter('status', ['in' => $this->_orderConfig->getVisibleOnFrontStatuses()])->setOrder('created_at', 'desc');
         $this->_agreementResource->addOrdersFilter($this->_relatedOrders, $billingAgreementId);
     }
     return $this->_relatedOrders;
 }
Example #12
0
 public function testLoadByIncrementIdAndStoreId()
 {
     $incrementId = '000000001';
     $storeId = '2';
     $this->salesOrderCollectionFactoryMock->expects($this->once())->method('create')->willReturn($this->salesOrderCollectionMock);
     $this->salesOrderCollectionMock->expects($this->any())->method('addFieldToFilter')->willReturnSelf();
     $this->salesOrderCollectionMock->expects($this->once())->method('load')->willReturnSelf();
     $this->salesOrderCollectionMock->expects($this->once())->method('getFirstItem')->willReturn($this->order);
     $this->assertSame($this->order, $this->order->loadByIncrementIdAndStoreId($incrementId, $storeId));
 }
 /**
  * Get customer last order id.
  *
  * @param \Magento\Customer\Model\Customer $customer
  *
  * @return bool|mixed
  */
 public function getCustomerLastOrderId(\Magento\Customer\Model\Customer $customer)
 {
     $storeIds = $this->storeManager->getWebsite($customer->getWebsiteId())->getStoreIds();
     $collection = $this->orderCollection->create()->addFieldToFilter('customer_id', $customer->getId())->addFieldToFilter('store_id', ['in' => $storeIds])->setPageSize(1)->setOrder('entity_id');
     if ($collection->getSize()) {
         //@codingStandardsIgnoreStart
         return $collection->getFirstItem();
         //@codingStandardsIgnoreEnd
     } else {
         return false;
     }
 }
Example #14
0
 public function testConstructMethod()
 {
     $data = [];
     $attribute = ['customer_id', 'status'];
     $customerId = 25;
     $layout = $this->getMock('Magento\\Framework\\View\\Layout', ['getBlock'], [], '', false, false);
     $this->context->expects($this->once())->method('getLayout')->will($this->returnValue($layout));
     $this->customerSession->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId));
     $statuses = ['pending', 'processing', 'complete'];
     $this->orderConfig->expects($this->once())->method('getVisibleOnFrontStatuses')->will($this->returnValue($statuses));
     $orderCollection = $this->getMock('Magento\\Sales\\Model\\ResourceModel\\Order\\Collection', ['addAttributeToSelect', 'addFieldToFilter', 'addAttributeToFilter', 'addAttributeToSort', 'setPageSize', 'load'], [], '', false, false);
     $this->orderCollectionFactory->expects($this->once())->method('create')->will($this->returnValue($orderCollection));
     $orderCollection->expects($this->at(0))->method('addAttributeToSelect')->with($this->equalTo('*'))->will($this->returnSelf());
     $orderCollection->expects($this->at(1))->method('addAttributeToFilter')->with($attribute[0], $this->equalTo($customerId))->willReturnSelf();
     $orderCollection->expects($this->at(2))->method('addAttributeToFilter')->with($attribute[1], $this->equalTo(['in' => $statuses]))->will($this->returnSelf());
     $orderCollection->expects($this->at(3))->method('addAttributeToSort')->with('created_at', 'desc')->will($this->returnSelf());
     $orderCollection->expects($this->at(4))->method('setPageSize')->with('5')->will($this->returnSelf());
     $orderCollection->expects($this->at(5))->method('load')->will($this->returnSelf());
     $this->block = new \Magento\Sales\Block\Order\Recent($this->context, $this->orderCollectionFactory, $this->customerSession, $this->orderConfig, $data);
     $this->assertEquals($orderCollection, $this->block->getOrders());
 }
Example #15
0
 /**
  * Get order collection
  *
  * @return $this
  */
 public function getOrderCollection()
 {
     $orderIds = $this->getOrderIds();
     if (empty($orderIds) || !is_array($orderIds)) {
         return;
     }
     if (!$this->_orderCollection) {
         $this->_orderCollection = $this->_salesOrderCollection->create();
         $this->_orderCollection->addFieldToFilter('entity_id', ['in' => $orderIds]);
     }
     return $this->_orderCollection;
 }
 /**
  * Total value refunded for the customer.
  *
  * @return float|int
  */
 public function getTotalRefund()
 {
     //filter by customer id
     $customerOrders = $this->orderCollection->create()->addAttributeToFilter('customer_id', $this->customer->getId());
     $totalRefunded = 0;
     //calculate total refunded
     foreach ($customerOrders as $order) {
         $refunded = $order->getTotalRefunded();
         $totalRefunded += $refunded;
     }
     return $totalRefunded;
 }
Example #17
0
 public function testInitOrders()
 {
     $customerId = 25;
     $attribute = ['customer_id', 'status'];
     $this->httpContext->expects($this->once())->method('getValue')->with($this->equalTo(Context::CONTEXT_AUTH))->will($this->returnValue(true));
     $this->customerSession->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId));
     $statuses = ['pending', 'processing', 'complete'];
     $this->orderConfig->expects($this->once())->method('getVisibleOnFrontStatuses')->will($this->returnValue($statuses));
     $this->orderCollection->expects($this->at(0))->method('addAttributeToFilter')->with($attribute[0], $this->equalTo($customerId))->will($this->returnSelf());
     $this->orderCollection->expects($this->at(1))->method('addAttributeToFilter')->with($attribute[1], $this->equalTo(['in' => $statuses]))->will($this->returnSelf());
     $this->orderCollection->expects($this->at(2))->method('addAttributeToSort')->with('created_at', 'desc')->will($this->returnSelf());
     $this->orderCollection->expects($this->at(3))->method('setPage')->with($this->equalTo(1), $this->equalTo(1))->will($this->returnSelf());
     $this->orderCollectionFactory->expects($this->atLeastOnce())->method('create')->will($this->returnValue($this->orderCollection));
     $this->createBlockObject();
     $this->assertEquals($this->orderCollection, $this->block->getOrders());
 }
Example #18
0
 /**
  * Render information about specified orders and their items
  *
  * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-options
  * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions
  * @link https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#transaction
  *
  * @return string|void
  */
 public function getOrdersTrackingCode()
 {
     $orderIds = $this->getOrderIds();
     if (empty($orderIds) || !is_array($orderIds)) {
         return;
     }
     $collection = $this->_salesOrderCollection->create();
     $collection->addFieldToFilter('entity_id', ['in' => $orderIds]);
     $result = [];
     $result[] = "ga('require', 'ec', 'ec.js');";
     foreach ($collection as $order) {
         if ($order->getIsVirtual()) {
             $address = $order->getBillingAddress();
         } else {
             $address = $order->getShippingAddress();
         }
         foreach ($order->getAllVisibleItems() as $item) {
             $result[] = sprintf("ga('ec:addProduct', {\n                        'id': '%s',\n                        'name': '%s',\n                        'price': '%s',\n                        'quantity': %s\n                    });", $this->escapeJsQuote($item->getSku()), $this->escapeJsQuote($item->getName()), $item->getBasePrice(), $item->getQtyOrdered());
         }
         $result[] = sprintf("ga('ec:setAction', 'purchase', {\n                    'id': '%s',\n                    'affiliation': '%s',\n                    'revenue': '%s',\n                    'tax': '%s',\n                    'shipping': '%s'\n                });", $order->getIncrementId(), $this->escapeJsQuote($this->_storeManager->getStore()->getFrontendName()), $order->getBaseGrandTotal(), $order->getBaseTaxAmount(), $order->getBaseShippingAmount());
         $result[] = "ga('send', 'pageview');";
     }
     return implode("\n", $result);
 }
Example #19
0
 /**
  * Get sales Order collection model populated with data
  *
  * @param array $filters
  * @return \Magento\Sales\Model\ResourceModel\Order\Collection
  */
 protected function getSalesOrderCollection(array $filters = [])
 {
     /** @var \Magento\Sales\Model\ResourceModel\Order\Collection $salesOrderCollection */
     $salesOrderCollection = $this->salesOrderCollectionFactory->create();
     foreach ($filters as $field => $condition) {
         $salesOrderCollection->addFieldToFilter($field, $condition);
     }
     return $salesOrderCollection->load();
 }
 /**
  * Save/reset the order as transactional data.
  *
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     try {
         $order = $observer->getEvent()->getOrder();
         $status = $order->getStatus();
         $storeId = $order->getStoreId();
         $store = $this->storeManager->getStore($storeId);
         $storeName = $store->getName();
         $websiteId = $store->getWebsiteId();
         $customerEmail = $order->getCustomerEmail();
         // start app emulation
         $appEmulation = $this->emulationFactory->create();
         $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);
         $emailOrder = $this->emailOrderFactory->create()->loadByOrderId($order->getEntityId(), $order->getQuoteId());
         //reimport email order
         $emailOrder->setUpdatedAt($order->getUpdatedAt())->setCreatedAt($order->getUpdatedAt())->setStoreId($storeId)->setOrderStatus($status);
         if ($emailOrder->getEmailImported() != \Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_IMPORTED) {
             $emailOrder->setEmailImported(null);
         }
         //if api is not enabled
         if (!$store->getWebsite()->getConfig(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_API_ENABLED)) {
             return $this;
         }
         // check for order status change
         $statusBefore = $this->registry->registry('sales_order_status_before');
         if ($status != $statusBefore) {
             //If order status has changed and order is already imported then set modified to 1
             if ($emailOrder->getEmailImported() == \Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_IMPORTED) {
                 $emailOrder->setModified(\Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_IMPORTED);
             }
         }
         // set back the current store
         $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
         $emailOrder->save();
         //@codingStandardsIgnoreStart
         //Status check automation enrolment
         $configStatusAutomationMap = unserialize($this->scopeConfig->getValue(\Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_AUTOMATION_STUDIO_ORDER_STATUS, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $order->getStore()));
         //@codingStandardsIgnoreEnd
         if (!empty($configStatusAutomationMap)) {
             foreach ($configStatusAutomationMap as $configMap) {
                 if ($configMap['status'] == $status) {
                     //send to automation queue
                     $this->doAutomationEnrolment(['programId' => $configMap['automation'], 'automationType' => 'order_automation_' . $status, 'email' => $customerEmail, 'order_id' => $order->getId(), 'website_id' => $websiteId, 'store_name' => $storeName]);
                 }
             }
         }
         //If customer's first order
         if ($order->getCustomerId()) {
             $orders = $this->orderCollectionFactory->create()->addFieldToFilter('customer_id', $order->getCustomerId());
             if ($orders->getSize() == 1) {
                 $automationTypeNewOrder = \Dotdigitalgroup\Email\Model\Sync\Automation::AUTOMATION_TYPE_CUSTOMER_FIRST_ORDER;
                 $programIdNewOrder = $this->helper->getAutomationIdByType('XML_PATH_CONNECTOR_AUTOMATION_STUDIO_FIRST_ORDER', $order->getWebsiteId());
                 //send to automation queue
                 $this->doAutomationEnrolment(['programId' => $programIdNewOrder, 'automationType' => $automationTypeNewOrder, 'email' => $customerEmail, 'order_id' => $order->getId(), 'website_id' => $websiteId, 'store_name' => $storeName]);
             }
         }
         //admin oder when editing the first one is canceled
         $this->registry->unregister('sales_order_status_before');
     } catch (\Exception $e) {
         throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()));
     }
     return $this;
 }
Example #21
0
 /**
  * @return void
  */
 protected function _construct()
 {
     parent::_construct();
     $orders = $this->_orderCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('customer_id', $this->_customerSession->getCustomerId())->addAttributeToFilter('status', ['in' => $this->_orderConfig->getVisibleOnFrontStatuses()])->addAttributeToSort('created_at', 'desc')->setPageSize('5')->load();
     $this->setOrders($orders);
 }