/** * 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; }
/** * 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; }
/** * 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); } } } }
/** * {@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); } } }
/** * 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; }
/** * @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; }
/** * 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; }
/** * 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()); } } }
/** * 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; }
/** * 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; }
/** * 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; } }
/** * 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); }
/** * 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(); }
/** * @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); }
/** * 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; }