0

I am working on a custom report for bestseller products, Following is a requirement,

  1. Add Custom date range
  2. Fetch all products max limit is 500

I am not able to set custom date range & limit, Following is a sample external script code

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Reports\Model\ResourceModel\Report\Collection\Factory');
$collection = $productCollection->create('Magento\Sales\Model\ResourceModel\Report\Bestsellers\Collection');
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$collection->setPeriod('year');

Any help appreciated,

Thanks

0

Try this

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory as BestSellersCollectionFactory;



public function __construct(
    CollectionFactory $productCollectionFactory,
    DateTime $dateTime,
    BestSellersCollectionFactory $bestSellersCollectionFactory
) {
    
    $this->dateTime = $dateTime;
    $this->_bestSellersCollectionFactory = $bestSellersCollectionFactory;
    $this->_productCollectionFactory = $productCollectionFactory;
}
/**
 * get collection of best-seller products
 * @return mixed
 */
public function getProductCollection()
{
    $productIds = [];

    $currentTime = $this->dateTime->date();
    $bestSellers = $this->_bestSellersCollectionFactory->create()
        ->setPeriod('month');
    foreach ($bestSellers as $product) {
        $productIds[] = $product->getProductId();
    }
    $collection = $this->_productCollectionFactory->create()->addIdFilter($productIds);
    $collection->addMinimalPrice()
        ->addFinalPrice()
        ->addTaxPercents()
        ->addAttributeToSelect('*')
    ->addFieldToFilter('from_date', ['lteq' => $currentTime])
    ->addFieldToFilter('to_date', ['gteq' => $currentTime])
    ->setOrder('sort_order', 'ASC')
        ->addStoreFilter($this->getStoreId())->setPageSize($this->getProductsCount());
    return $collection;
}
1
  • Hello Waqar, Following is wrong, i have to set custom date range here from_date and to_date $bestSellers = $this->_bestSellersCollectionFactory->create() ->setPeriod('month'); – shyam Dec 21 '20 at 10:24

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.