Domanda

how do I check the user order status is completed in a custom module?

È stato utile?

Soluzione

You can check it easly using customer id (you can get it using instance customer session) for example. First of all you will need to add Magento\Sales\Model\ResourceModel\Order\CollectionFactory to your class constructor argument (automatic di) and then just use filters for the collection instace to filter by customer id and order status (all needed data saves in one table sales_order) Example:

namespace JohnnySk\SalesCheck\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Sales\Model\ResourceModel\Order\{
    CollectionFactory,
    Collection
};
use Magento\Sales\Model\Order;

class Check extends AbstractHelper 
{
    /**
     * @var Magento\Sales\Model\ResourceModel\Order\CollectionFactory
     */
    protected $orderCollectionFactory;

    /**
     * @param CollectionFactory
     */
    public function __construct(
        CollectionFactory $orderCollectionFactory
    ) {
        $this->orderCollectionFactory = $orderCollectionFactory;
    }

    /**
     * Retrieve Collection of completed orders by customer id
     *
     * @param int $customerId
     * @return Collection
     */    
    public function getCompletedOrdersByCustomerId($customerId)
    {
        $orderCollectionInstance = $this->orderCollectionFactory->create()
            ->addFieldToFilter('customer_id', $customerId)
            ->addFieldToFilter('status', Order::STATE_COMPLETE);

        return $orderCollectionInstance;
    }
}

Here I provided example of custom helper class which you can use anywhere in code of your custom module. Helper's method getCompletedOrdersByCustomerId will provide a collection for you, which you also can use as you need, if current customer (which id you will provide as a param for current method) has a completed orders - you will have items in collection, if not - you will not have items (you can check using getSize method)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top