Magento 2 Products – Remove Special Price if Special Price Date Has Expired

datemagento2productsspecial-price

I am facing issue in Magento 2.1.7

If special price date has expired for any products , i want to remove special price and special price to date and special price from date
form products, by using crons.

i have tried everything but couldn't find a way to resolve it. Any suggestion appreciated.

Thanks in advance.

Best Answer

Try following way


<?php
namespace SR\StackExchange\Cron;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Catalog\Api\ProductRepositoryInterface;

class ProcessSpecialProducts
{
    /**
     * @var ProductCollectionFactory
     */
    private $productCollectionFactory;

    /**
     * @var DateTime
     */
    private $date;

    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    /**
     * ProcessSpecialProducts constructor.
     *
     * @param ProductCollectionFactory $productCollectionFactory
     * @param ProductRepositoryInterface $productRepository
     * @param DateTime $date
     */
    public function __construct(
        ProductCollectionFactory $productCollectionFactory,
        ProductRepositoryInterface $productRepository,
        DateTime $date
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->productRepository = $productRepository;
        $this->date = $date;
    }

    public function execute()
    {
        $currentDate = $this->date->date();
        $expiredProductsCollection = $this->productCollectionFactory->create();
        $expiredProductsCollection
            ->addFieldToFilter(
                'special_to_date',
                [
                    'notnull' => 1,
                    'lteq' => $currentDate
                ]
            )
            ->addFieldToFilter(
                'special_price',
                [
                    'notnull' => 1
                ]
            );

        /** @var \Magento\Catalog\Model\Product $product */
        foreach($expiredProductsCollection as $product) {
            try {
                $product = $this->productRepository->get($product->getSku(), true);
                $product->setSpecialToDate(null);
                $product->setSpecialPrice(null);
                $product->setSpecialFromDate(null);
                $this->productRepository->save($product);
            } catch (\Exception $e){}
        }
    }
}
Related Topic