Skip to content

how to get revenue using custom period or date range?

how can we get the Revenue using custom Period or Date?

below is code,

custom.php : /var/www/html/m2_new_staging/app/code/Rental/Totalrevenue/Model/Api

<?php

namespace RentalTotalrevenueModelApi;
use MagentoReportsModelResourceModelOrderCollectionFactory;
use PsrLogLoggerInterface;

class Custom
{
  protected $_collectionFactory;
  protected $logger;

  public function __construct(
    LoggerInterface $logger,
    CollectionFactory $collectionFactory
  )
  {

    $this->logger = $logger;
  }

  /**
  * @inheritdoc
  */

  public function getTotalRevenue()
  {
      //pass ID parameter as you need from store or website
      $isFilter = $this->getRequest()->getParam(
          'store'
      ) || $this->getRequest()->getParam(
          'website'
      ) || $this->getRequest()->getParam(
          'group'
      );
      $period = $this->getRequest()->getParam('period', Period::PERIOD_24_HOURS); // 1y, 2y
      / @var $collection Collection /
      $collection = $this->_collectionFactory->create()->addCreateAtPeriodFilter(
          $period
      )->calculateTotals(
          $isFilter
      );
      if ($this->getRequest()->getParam('store')) {
          $collection->addFieldToFilter('store_id', $this->getRequest()->getParam('store'));
      } else {
          if ($this->getRequest()->getParam('website')) {
              $storeIds = $this->_storeManager->getWebsite($this->getRequest()->getParam('website'))->getStoreIds();
              $collection->addFieldToFilter('store_id', ['in' => $storeIds]);
          } else {
              if ($this->getRequest()->getParam('group')) {
                  $storeIds = $this->_storeManager->getGroup($this->getRequest()->getParam('group'))->getStoreIds();
                  $collection->addFieldToFilter('store_id', ['in' => $storeIds]);
              } elseif (!$collection->isLive()) {
                  $collection->addFieldToFilter(
                      'store_id',
                      ['eq' => $this->_storeManager->getStore(Store::ADMIN_CODE)->getId()]
                  );
              }
          }
      }
      $collection->load();
      $totals = $collection->getFirstItem();
      return $totals->getRevenue();
      //return 'Total Revenue $param ' . $param;
  }
  
}

here i have code $period = $this->getRequest()->getParam(‘period’,
Period::PERIOD_24_HOURS); how to get revenue to changing period like,
today, last months, last 3 months, custom date range?

enter image description here

after searching in google, I get some idea that I need to create custom Filter for the period., but how to create that kind of custom period filter?

Like, in below code hot set Filter?

  $period = $this->getRequest()->getParam('period', Period::PERIOD_24_HOURS);