0

Create a Magento 2 extension to implement guest order history feature.

Please implement with a new controller that takes parameter(s) to query a single order and returns a json with information about order status, total, items (sku, item_id, price) and total invoiced.

Use Itdesire as namespace and OrderController as module name. (Itdesire_OrderController)

1

app/code/Itdesire/OrderController/registration.php

 <?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Itdesire_OrderController',
    __DIR__
);

app/code/Itdesire/OrderController/etc/module.xml

    <?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Itdesire_OrderController" setup_version="1.0.0"/>
</config>

app/code/Itdesire/OrderController/etc/webapi.xml

<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/guestorder/getGuestOrderHistory/:param" method="GET">
        <service class="Itdesire\OrderController\Api\GuestorderInterface" method="getGuestOrderHistory"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

app/code/Itdesire/OrderController/etc/di.xml

    <?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Itdesire\OrderController\Api\GuestorderInterface" type="Itdesire\OrderController\Model\Guestorder" />
</config>

app/code/Itdesire/OrderController/etc/frontend/routes.xml

    <?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route frontName="ordercontroller" id="ordercontroller">
            <module name="Itdesire_OrderController"/>
        </route>
    </router>
</config>

app/code/Itdesire/OrderController/Model/Guestorder.php

<?php

namespace Itdesire\OrderController\Model;

use Itdesire\OrderController\Api\GuestorderInterface;

/**
 * Defines the implementaiton class of the calculator service contract.
 */
class Guestorder implements GuestorderInterface
{
    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    protected $orderCollectionFactory;

    /**
     * Constructor
     *     
     * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
     */
    public function __construct(
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
    ) {
        $this->orderCollectionFactory = $orderCollectionFactory;
    }

    /**
     * Return mixed.
     *
     * @api
     * @param string $param.
     * @return mixed.
     */
    public function getGuestOrderHistory($param) {
        $arrayData = $this->getJsonArrayOfGuestOrders($param);
        return $arrayData;
    }

    /**
     * get guest order collection
     *
     * @return \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    public function getGuestOrderCollection($param)
    {
        $orderCollecion = $this->orderCollectionFactory
                                ->create()
                                ->addFieldToSelect('*');

        $orderCollecion->addFieldToFilter(
                            'customer_id',
                            array(
                                'null' => true
                            )
                        );

        if ('all' !== $param){
            $orderCollecion->getSelect()->limit((int)$param);
        }

        return $orderCollecion;
    }

    /**
     * format guest order collection into array for json object
     */
    public function getJsonArrayOfGuestOrders($param)
    {
        $jsonArray = [];
        $guestOrderCollection = $this->getGuestOrderCollection($param);
        foreach($guestOrderCollection as $_collection){
            $guestOrderHistory['status'] = $_collection->getStatus();
            $guestOrderHistory['total'] = $_collection->getGrandTotal();
            $allVisibleItems = $_collection->getAllVisibleItems();
            $itemArray = [];
            $qtyInvoiced = 0;
            foreach($allVisibleItems as $_item){
                $qtyInvoiced = $qtyInvoiced + $_item->getQtyInvoiced();
                $_itemArray['sku'] = $_item->getSku();
                $_itemArray['item_id'] = $_item->getItemId();
                $_itemArray['price'] = $_item->getRowTotal();
                $_itemArray['qty_invoiced'] = $_item->getQtyInvoiced();
                $_itemArray['qty'] = $_item->getQtyOrdered();
                $itemArray[] = $_itemArray;
            }
            $guestOrderHistory['qty_invoiced'] = $qtyInvoiced;
            $guestOrderHistory['item'] = $itemArray;
            $jsonArray[] = $guestOrderHistory;
        }
        return $jsonArray;
    }
}

app/code/Itdesire/OrderController/Controller/Guestorderhistory/Index.php

<?php

namespace Itdesire\OrderController\Controller\Guestorderhistory;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    protected $orderCollectionFactory;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context  $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->orderCollectionFactory = $orderCollectionFactory;
        $this->resultJsonFactory = $resultJsonFactory;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        //return $this->resultPageFactory->create();
        $result = $this->resultJsonFactory->create();
        $jsonData = $this->getJsonArrayOfGuestOrders();
        return $result->setData($jsonData);
    }

    /**
     * get guest order collection
     *
     * @return \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    public function getGuestOrderCollection()
    {
        $orderCollecion = $this->orderCollectionFactory
                                ->create()
                                ->addFieldToSelect('*');

        $orderCollecion->addFieldToFilter(
                            'customer_id',
                            array(
                                'null' => true
                            )
                        );

        $totalGuestOrder = $this->getRequest()->getParam('total_guest_order');
        if ('all' !== $totalGuestOrder){
            $orderCollecion->getSelect()->limit((int)$totalGuestOrder);
        }

        return $orderCollecion;
    }

    /**
     * format guest order collection into array for json object
     */
    public function getJsonArrayOfGuestOrders()
    {
        $jsonArray = [];
        $guestOrderCollection = $this->getGuestOrderCollection();
        foreach($guestOrderCollection as $_collection){
            $guestOrderHistory['increment_id'] = $_collection->getIncrementId();
            $guestOrderHistory['status'] = $_collection->getStatus();
            $guestOrderHistory['total'] = $_collection->getGrandTotal();
            $allVisibleItems = $_collection->getAllVisibleItems();
            $itemArray = [];
            $qtyInvoiced = 0;
            foreach($allVisibleItems as $_item){
                $qtyInvoiced = $qtyInvoiced + $_item->getQtyInvoiced();
                $_itemArray['sku'] = $_item->getSku();
                $_itemArray['item_id'] = $_item->getItemId();
                $_itemArray['price'] = $_item->getRowTotal();
                $_itemArray['qty_invoiced'] = $_item->getQtyInvoiced();
                $_itemArray['qty'] = $_item->getQtyOrdered();
                $itemArray[] = $_itemArray;
            }
            $guestOrderHistory['qty_invoiced'] = $qtyInvoiced;
            $guestOrderHistory['item'] = $itemArray;
            $jsonArray[] = $guestOrderHistory;
        }
        return $jsonArray;
    }
}

app/code/Itdesire/OrderController/Api/GuestorderInterface.php

   <?php

namespace Itdesire\OrderController\Api;

/**
 * Defines the service contract for some simple maths functions. The purpose is
 * to demonstrate the definition of a simple web service, not that these
 * functions are really useful in practice. The function prototypes were therefore
 * selected to demonstrate different parameter and return values, not as a good
 * calculator design.
 */
interface GuestorderInterface
{
    /**
     * Return mixed.
     *
     * @api
     * @param string $param.
     * @return mixed.
     */
    public function getGuestOrderHistory($param);
}

How to Run?

### Install extension
---------------------------

1. Go to Magento 2 root folder

2. paste all code in a foler app/code/Itdesire/OrderController

3. Enter following commands to enable module:

   php bin/magento module:enable Itdesire_OrderController
   php bin/magento setup:upgrade
   php bin/magento cache:clean


### How to use
---------------------

Method 1: 
---------
params: total_guest_order --> it can be 1,2,3... ( Numbers of orders to return )
Replace http://localhost/demo/Magento-CE-2.1.4 with your URL and Just hit the url

http://localhost/demo/Magento-CE-2.1.4/index.php/ordercontroller/guestorderhistory?total_guest_order=1


Method 2:
---------
Cut and paste run.php file to your magento root and replace "localhost/demo/Magento-CE-2.1.4" as per your magento directory path and execute run.php file using browser.
  • Can you explain what is the purpose of adding Api/GuestorderInterface.php here? – Magento Learner Aug 7 '18 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.