/**
  * @param \Magento\Framework\Event\Observer $observer
  *
  * @return $this
  */
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $creditmemo = $observer->getEvent()->getCreditmemo();
     $storeId = $creditmemo->getStoreId();
     $order = $creditmemo->getOrder();
     $orderId = $order->getEntityId();
     $quoteId = $order->getQuoteId();
     try {
         /*
          * Reimport transactional data.
          */
         $emailOrder = $this->emailOrderFactory->create()->loadByOrderId($orderId, $quoteId, $storeId);
         if (!$emailOrder->getId()) {
             $this->helper->log('ERROR Creditmemmo Order not found :' . $orderId . ', quote id : ' . $quoteId . ', store id ' . $storeId);
             return $this;
         }
         $emailOrder->setEmailImported(\Dotdigitalgroup\Email\Model\Contact::EMAIL_CONTACT_NOT_IMPORTED)->save();
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $this;
 }
 /**
  * Get all orders to import.
  *
  * @param            $website
  * @param int        $limit
  * @param bool|false $modified
  *
  * @return array
  *
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function getConnectorOrders($website, $limit = 100, $modified = false)
 {
     $orders = [];
     $storeIds = $website->getStoreIds();
     $orderModel = $this->orderFactory->create();
     if (empty($storeIds)) {
         return [];
     }
     $orderStatuses = $this->helper->getConfigSelectedStatus($website);
     //any statuses found
     if ($orderStatuses) {
         if ($modified) {
             $orderCollection = $orderModel->getOrdersToImport($storeIds, $limit, $orderStatuses, true);
         } else {
             $orderCollection = $orderModel->getOrdersToImport($storeIds, $limit, $orderStatuses);
         }
     } else {
         return [];
     }
     try {
         //email_order order ids
         $orderIds = $orderCollection->getColumnValues('order_id');
         //get the order collection
         $salesOrderCollection = $this->salesOrderFactory->create()->getCollection()->addFieldToFilter('entity_id', ['in' => $orderIds]);
         foreach ($salesOrderCollection as $order) {
             $storeId = $order->getStoreId();
             $websiteId = $this->storeManager->getStore($storeId)->getWebsiteId();
             /**
              * Add guest to contacts table.
              */
             if ($order->getCustomerIsGuest() && $order->getCustomerEmail()) {
                 //add guest to the list
                 $this->guests[] = ['email' => $order->getCustomerEmail(), 'website_id' => $websiteId, 'store_id' => $storeId, 'is_guest' => 1];
             }
             if ($order->getId()) {
                 $connectorOrder = $this->connectorOrderFactory->create();
                 $connectorOrder->setOrderData($order);
                 $orders[] = $connectorOrder;
             }
             if ($modified) {
                 $this->orderIdsForSingleSync[] = $order->getId();
             } else {
                 $this->orderIds[] = $order->getId();
             }
         }
     } catch (\Exception $e) {
         $this->helper->debug((string) $e, []);
     }
     return $orders;
 }
 /**
  * @return \Magento\Backend\Model\View\Result\Redirect
  */
 public function execute()
 {
     $ids = $this->getRequest()->getParam('selected');
     if (!is_array($ids)) {
         $this->messageManager->addErrorMessage(__('Please select orders.'));
     } else {
         try {
             //@codingStandardsIgnoreStart
             foreach ($ids as $id) {
                 $model = $this->order->create()->setEmailOrderId($id);
                 $model->delete();
             }
             //@codingStandardsIgnoreEnd
             $this->messageManager->addSuccessMessage(__('Total of %1 record(s) were deleted.', count($ids)));
         } catch (\Exception $e) {
             $this->messageManager->addErrorMessage($e->getMessage());
         }
     }
     /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
     $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
     $resultRedirect->setPath('*/*/');
     return $resultRedirect;
 }
 /**
  * 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;
 }