Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Protected Member Functions | Protected Attributes
Collection Class Reference
Inheritance diagram for Collection:
Collection AbstractCollection OrderSearchResultInterface Collection SearchResultsInterface AbstractCollection AbstractDb SourceProviderInterface Collection ArrayInterface CollectionDataSourceInterface OptionSourceInterface ArgumentInterface Collection Collection Collection

Public Member Functions

 __construct (\Magento\Framework\Data\Collection\EntityFactory $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot $entitySnapshot, \Magento\Framework\DB\Helper $coreResourceHelper, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\Sales\Model\Order\Config $orderConfig, \Magento\Sales\Model\ResourceModel\Report\OrderFactory $reportOrderFactory, \Magento\Framework\DB\Adapter\AdapterInterface $connection=null, \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource=null)
 
 checkIsLive ($range)
 
 isLive ()
 
 prepareSummary ($range, $customStart, $customEnd, $isFilter=0)
 
 getDateRange ($range, $customStart, $customEnd, $returnObjects=false)
 
 addItemCountExpr ()
 
 calculateTotals ($isFilter=0)
 
 calculateSales ($isFilter=0)
 
 setDateRange ($fromDate, $toDate)
 
 setStoreIds ($storeIds)
 
 groupByCustomer ()
 
 joinCustomerName ($alias='name')
 
 addOrdersCount ()
 
 addRevenueToSelect ($convertCurrency=false)
 
 addSumAvgTotals ($storeId=0)
 
 orderByTotalAmount ($dir=self::SORT_ORDER_DESC)
 
 orderByOrdersCount ($dir=self::SORT_ORDER_DESC)
 
 orderByCustomerRegistration ($dir=self::SORT_ORDER_DESC)
 
 orderByCreatedAt ($dir=self::SORT_ORDER_DESC)
 
 getSelectCountSql ()
 
 addCreateAtPeriodFilter ($period)
 
- Public Member Functions inherited from Collection
 __construct (\Magento\Framework\Data\Collection\EntityFactory $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot $entitySnapshot, \Magento\Framework\DB\Helper $coreResourceHelper, \Magento\Framework\DB\Adapter\AdapterInterface $connection=null, \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource=null)
 
 addItemCountExpr ()
 
 getSelectCountSql ()
 
 addAddressFields ()
 
 addFieldToSearchFilter ($field, $condition=null)
 
 addAttributeToSearchFilter ($attributes, $condition=null)
 
 addBillingAgreementsFilter ($agreements)
 
- Public Member Functions inherited from AbstractCollection
 setSelectCountSql (\Magento\Framework\DB\Select $countSelect)
 
 getSelectCountSql ()
 
 addAttributeToSelect ($attribute)
 
 addAttributeToFilter ($attribute, $condition=null)
 
 addAttributeToSort ($attribute, $dir='asc')
 
 setPage ($pageNum, $pageSize)
 
 getAllIds ($limit=null, $offset=null)
 
 getSearchCriteria ()
 
 setSearchCriteria (\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria=null)
 
 getTotalCount ()
 
 setTotalCount ($totalCount)
 
 setItems (array $items=null)
 
- Public Member Functions inherited from Collection
 __construct (\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, Snapshot $entitySnapshot, \Magento\Framework\DB\Adapter\AdapterInterface $connection=null, \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource=null)
 
 fetchItem ()
 
- Public Member Functions inherited from AbstractCollection
 __construct (\Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Framework\DB\Adapter\AdapterInterface $connection=null, \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource=null)
 
 getMainTable ()
 
 setMainTable ($table)
 
 getSelect ()
 
 addFieldToSelect ($field, $alias=null)
 
 addExpressionFieldToSelect ($alias, $expression, $fields)
 
 removeFieldFromSelect ($field, $isAlias=false)
 
 removeAllFieldsFromSelect ()
 
 setModel ($model)
 
 getModelName ()
 
 setResourceModel ($model)
 
 getResourceModelName ()
 
 getResource ()
 
 getTable ($table)
 
 getAllIds ()
 
 join ($table, $cond, $cols=' *')
 
 setResetItemsDataChanged ($flag)
 
 resetItemsDataChanged ()
 
 save ()
 
 __sleep ()
 
 __wakeup ()
 
- Public Member Functions inherited from AbstractDb
 __construct (EntityFactoryInterface $entityFactory, Logger $logger, FetchStrategyInterface $fetchStrategy, \Magento\Framework\DB\Adapter\AdapterInterface $connection=null)
 
 getResource ()
 
 addBindParam ($name, $value)
 
 getIdFieldName ()
 
 setConnection (\Magento\Framework\DB\Adapter\AdapterInterface $conn)
 
 getSelect ()
 
 getConnection ()
 
 getSize ()
 
 getSelectCountSql ()
 
 getSelectSql ($stringMode=false)
 
 setOrder ($field, $direction=self::SORT_ORDER_DESC)
 
 addOrder ($field, $direction=self::SORT_ORDER_DESC)
 
 unshiftOrder ($field, $direction=self::SORT_ORDER_DESC)
 
 addFieldToFilter ($field, $condition=null)
 
 distinct ($flag)
 
 load ($printQuery=false, $logQuery=false)
 
 loadWithFilter ($printQuery=false, $logQuery=false)
 
 fetchItem ()
 
 getData ()
 
 resetData ()
 
 loadData ($printQuery=false, $logQuery=false)
 
 printLogQuery ($printQuery=false, $logQuery=false, $sql=null)
 
 addFilterToMap ($filter, $alias, $group='fields')
 
 __clone ()
 
 joinExtensionAttribute (JoinDataInterface $join, JoinProcessorInterface $extensionAttributesJoinProcessor)
 
 getItemObjectClass ()
 
 __sleep ()
 
 __wakeup ()
 
- Public Member Functions inherited from Collection
 __construct (EntityFactoryInterface $entityFactory)
 
 addFilter ($field, $value, $type='and')
 
 addFieldToFilter ($field, $condition)
 
 getFilter ($field)
 
 isLoaded ()
 
 getCurPage ($displacement=0)
 
 getLastPageNumber ()
 
 getPageSize ()
 
 getSize ()
 
 getFirstItem ()
 
 getLastItem ()
 
 getItems ()
 
 getColumnValues ($colName)
 
 getItemsByColumnValue ($column, $value)
 
 getItemByColumnValue ($column, $value)
 
 addItem (\Magento\Framework\DataObject $item)
 
 getAllIds ()
 
 removeItemByKey ($key)
 
 removeAllItems ()
 
 clear ()
 
 walk ($callback, array $args=[])
 
 each ($objMethod, $args=[])
 
 setDataToAll ($key, $value=null)
 
 setCurPage ($page)
 
 setPageSize ($size)
 
 setOrder ($field, $direction=self::SORT_ORDER_DESC)
 
 setItemObjectClass ($className)
 
 getNewEmptyItem ()
 
 distinct ($flag)
 
 loadData ($printQuery=false, $logQuery=false)
 
 load ($printQuery=false, $logQuery=false)
 
 loadWithFilter ($printQuery=false, $logQuery=false)
 
 toXml ()
 
 toArray ($arrRequiredFields=[])
 
 toOptionArray ()
 
 toOptionHash ()
 
 getItemById ($idValue)
 
 getIterator ()
 
 count ()
 
 getFlag ($flag)
 
 setFlag ($flag, $value=null)
 
 hasFlag ($flag)
 
 __sleep ()
 
 __wakeup ()
 
- Public Member Functions inherited from SourceProviderInterface
 getIdFieldName ()
 
 addFieldToFilter ($attribute, $condition=null)
 
- Public Member Functions inherited from OrderSearchResultInterface
 getItems ()
 
 setItems (array $items=null)
 
- Public Member Functions inherited from SearchResultsInterface
 getSearchCriteria ()
 
 setSearchCriteria (\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria)
 
 getTotalCount ()
 
 setTotalCount ($totalCount)
 

Protected Member Functions

 _getSalesAmountExpression ()
 
 _prepareSummaryLive ($range, $customStart, $customEnd, $isFilter=0)
 
 _prepareSummaryAggregated ($range, $customStart, $customEnd)
 
 _getRangeExpression ($range)
 
 _getRangeExpressionForAttribute ($range, $attribute)
 
 _getTZRangeOffsetExpression ($range, $attribute, $from=null, $to=null)
 
 _getTZRangeExpressionForAttribute ($range, $attribute, $tzFrom='+00:00', $tzTo=null)
 
 _calculateTotalsLive ($isFilter=0)
 
 _calculateTotalsAggregated ($isFilter=0)
 
 getTotalsExpression ( $storeId, $baseSubtotalRefunded, $baseSubtotalCanceled, $baseDiscountCanceled)
 
 _initInitialFieldsToSelect ()
 
- Protected Member Functions inherited from Collection
 _construct ()
 
 _getAllIdsSelect ($limit=null, $offset=null)
 
 _addAddressFields ()
 
- Protected Member Functions inherited from AbstractCollection
 _attributeToField ($attribute)
 
 _getAllIdsSelect ($limit=null, $offset=null)
 
- Protected Member Functions inherited from Collection
 beforeAddLoadedItem (\Magento\Framework\DataObject $item)
 
- Protected Member Functions inherited from AbstractCollection
 _construct ()
 
 _initSelect ()
 
 _initSelectFields ()
 
 _getInitialFieldsToSelect ()
 
 _initInitialFieldsToSelect ()
 
 _init ($model, $resourceModel)
 
 _beforeLoad ()
 
 _afterLoad ()
 
- Protected Member Functions inherited from AbstractDb
 _setIdFieldName ($fieldName)
 
 _getItemId (\Magento\Framework\DataObject $item)
 
 _renderFilters ()
 
 _renderFiltersBefore ()
 
 _translateCondition ($field, $condition)
 
 _getMappedField ($field)
 
 _getMapper ()
 
 _getConditionSql ($fieldName, $condition)
 
 _getConditionFieldName ($fieldName)
 
 _renderOrders ()
 
 _renderLimit ()
 
 _beforeLoad ()
 
 beforeAddLoadedItem (\Magento\Framework\DataObject $item)
 
 _toOptionArray ($valueField=null, $labelField='name', $additional=[])
 
 _toOptionHash ($valueField=null, $labelField='name')
 
 _afterLoadData ()
 
 _afterLoad ()
 
 _logQuery ($sql)
 
 _reset ()
 
 _fetchAll (Select $select)
 
 _initSelect ()
 
- Protected Member Functions inherited from Collection
 _setIsLoaded ($flag=true)
 
 _addItem ($item)
 
 _getItemId (\Magento\Framework\DataObject $item)
 
 _renderFilters ()
 
 _renderOrders ()
 
 _renderLimit ()
 
 _toOptionArray ($valueField='id', $labelField='name', $additional=[])
 
 _toOptionHash ($valueField='id', $labelField='name')
 

Protected Attributes

 $_isLive = false
 
 $_salesAmountExpression
 
 $_scopeConfig
 
 $_storeManager
 
 $_localeDate
 
 $_orderConfig
 
 $_reportOrderFactory
 
- Protected Attributes inherited from Collection
 $_idFieldName = 'entity_id'
 
 $_eventPrefix = 'sales_order_collection'
 
 $_eventObject = 'order_collection'
 
 $_coreResourceHelper
 
- Protected Attributes inherited from AbstractCollection
 $_countSelect
 
 $searchCriteria
 
- Protected Attributes inherited from Collection
 $entitySnapshot
 
- Protected Attributes inherited from AbstractCollection
 $_model
 
 $_resourceModel
 
 $_resource
 
 $_fieldsToSelect = null
 
 $_initialFieldsToSelect = null
 
 $_fieldsToSelectChanged = false
 
 $_joinedTables = []
 
 $_mainTable = null
 
 $_resetItemsDataChanged = false
 
 $_eventPrefix = ''
 
 $_eventObject = ''
 
 $_eventManager = null
 
- Protected Attributes inherited from AbstractDb
 $_conn
 
 $_select
 
 $_idFieldName
 
 $_bindParams = []
 
 $_data = null
 
 $_map = null
 
 $_fetchStmt = null
 
 $_isOrdersRendered = false
 
 $_logger
 
 $extensionAttributesJoinProcessor
 
- Protected Attributes inherited from Collection
 $_items = []
 
 $_itemObjectClass = \Magento\Framework\DataObject::class
 
 $_orders = []
 
 $_filters = []
 
 $_isFiltersRendered = false
 
 $_curPage = 1
 
 $_pageSize = false
 
 $_totalRecords
 
 $_isCollectionLoaded
 
 $_flags = []
 
 $_entityFactory
 

Additional Inherited Members

- Data Fields inherited from Collection
const SORT_ORDER_ASC = 'ASC'
 
const SORT_ORDER_DESC = 'DESC'
 

Detailed Description

Reports orders collection

Author
Magento Core Team core@.nosp@m.mage.nosp@m.ntoco.nosp@m.mmer.nosp@m.ce.co.nosp@m.m @SuppressWarnings(PHPMD.CouplingBetweenObjects) @api
Since
100.0.2

Definition at line 19 of file Collection.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Framework\Data\Collection\EntityFactory  $entityFactory,
\Psr\Log\LoggerInterface  $logger,
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface  $fetchStrategy,
\Magento\Framework\Event\ManagerInterface  $eventManager,
\Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot  $entitySnapshot,
\Magento\Framework\DB\Helper  $coreResourceHelper,
\Magento\Framework\App\Config\ScopeConfigInterface  $scopeConfig,
\Magento\Store\Model\StoreManagerInterface  $storeManager,
\Magento\Framework\Stdlib\DateTime\TimezoneInterface  $localeDate,
\Magento\Sales\Model\Order\Config  $orderConfig,
\Magento\Sales\Model\ResourceModel\Report\OrderFactory  $reportOrderFactory,
\Magento\Framework\DB\Adapter\AdapterInterface  $connection = null,
\Magento\Framework\Model\ResourceModel\Db\AbstractDb  $resource = null 
)

Constructor

Parameters
\Magento\Framework\Data\Collection\EntityFactory$entityFactory
\Psr\Log\LoggerInterface$logger
\Magento\Framework\Data\Collection\Db\FetchStrategyInterface$fetchStrategy
\Magento\Framework\Event\ManagerInterface$eventManager
\Magento\Framework\Model\ResourceModel\Db\VersionControl\Snapshot$entitySnapshot
\Magento\Framework\DB\Helper$coreResourceHelper
\Magento\Framework\App\Config\ScopeConfigInterface$scopeConfig
\Magento\Store\Model\StoreManagerInterface$storeManager
\Magento\Framework\Stdlib\DateTime\TimezoneInterface$localeDate
\Magento\Sales\Model\Order\Config$orderConfig
\Magento\Sales\Model\ResourceModel\Report\OrderFactory$reportOrderFactory
null$connection
\Magento\Framework\Model\ResourceModel\Db\AbstractDb$resource@SuppressWarnings(PHPMD.ExcessiveParameterList)

Definition at line 89 of file Collection.php.

103  {
104  parent::__construct(
105  $entityFactory,
106  $logger,
107  $fetchStrategy,
108  $eventManager,
110  $coreResourceHelper,
111  $connection,
112  $resource
113  );
114  $this->_scopeConfig = $scopeConfig;
115  $this->_storeManager = $storeManager;
116  $this->_localeDate = $localeDate;
117  $this->_orderConfig = $orderConfig;
118  $this->_reportOrderFactory = $reportOrderFactory;
119  }
$storeManager
$resource
Definition: bulk.php:12
$logger
$connection
Definition: bulk.php:13

Member Function Documentation

◆ _calculateTotalsAggregated()

_calculateTotalsAggregated (   $isFilter = 0)
protected

Calculate totals aggregated report

Parameters
int$isFilter
Returns
$this @SuppressWarnings(PHPMD.UnusedFormalParameter)

Definition at line 564 of file Collection.php.

565  {
566  $this->setMainTable('sales_order_aggregated_created');
567  $this->removeAllFieldsFromSelect();
568 
569  $this->getSelect()->columns(
570  [
571  'revenue' => 'SUM(main_table.total_revenue_amount)',
572  'tax' => 'SUM(main_table.total_tax_amount_actual)',
573  'shipping' => 'SUM(main_table.total_shipping_amount_actual)',
574  'quantity' => 'SUM(orders_count)',
575  ]
576  );
577 
578  $statuses = $this->_orderConfig->getStateStatuses(\Magento\Sales\Model\Order::STATE_CANCELED);
579 
580  if (empty($statuses)) {
581  $statuses = [0];
582  }
583 
584  $this->getSelect()->where('main_table.order_status NOT IN(?)', $statuses);
585 
586  return $this;
587  }

◆ _calculateTotalsLive()

_calculateTotalsLive (   $isFilter = 0)
protected

Calculate totals live report

Parameters
int$isFilter
Returns
$this

Definition at line 512 of file Collection.php.

513  {
514  $this->setMainTable('sales_order');
515  $this->removeAllFieldsFromSelect();
516 
517  $connection = $this->getConnection();
518 
519  $baseTaxInvoiced = $connection->getIfNullSql('main_table.base_tax_invoiced', 0);
520  $baseTaxRefunded = $connection->getIfNullSql('main_table.base_tax_refunded', 0);
521  $baseShippingInvoiced = $connection->getIfNullSql('main_table.base_shipping_invoiced', 0);
522  $baseShippingRefunded = $connection->getIfNullSql('main_table.base_shipping_refunded', 0);
523 
524  $revenueExp = $this->_getSalesAmountExpression();
525  $taxExp = sprintf('%s - %s', $baseTaxInvoiced, $baseTaxRefunded);
526  $shippingExp = sprintf('%s - %s', $baseShippingInvoiced, $baseShippingRefunded);
527 
528  if ($isFilter == 0) {
529  $rateExp = $connection->getIfNullSql('main_table.base_to_global_rate', 0);
530  $this->getSelect()->columns(
531  [
532  'revenue' => new \Zend_Db_Expr(sprintf('SUM((%s) * %s)', $revenueExp, $rateExp)),
533  'tax' => new \Zend_Db_Expr(sprintf('SUM((%s) * %s)', $taxExp, $rateExp)),
534  'shipping' => new \Zend_Db_Expr(sprintf('SUM((%s) * %s)', $shippingExp, $rateExp)),
535  ]
536  );
537  } else {
538  $this->getSelect()->columns(
539  [
540  'revenue' => new \Zend_Db_Expr(sprintf('SUM(%s)', $revenueExp)),
541  'tax' => new \Zend_Db_Expr(sprintf('SUM(%s)', $taxExp)),
542  'shipping' => new \Zend_Db_Expr(sprintf('SUM(%s)', $shippingExp)),
543  ]
544  );
545  }
546 
547  $this->getSelect()->columns(
548  ['quantity' => 'COUNT(main_table.entity_id)']
549  )->where(
550  'main_table.state NOT IN (?)',
551  [\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, \Magento\Sales\Model\Order::STATE_NEW]
552  );
553 
554  return $this;
555  }
$connection
Definition: bulk.php:13

◆ _getRangeExpression()

_getRangeExpression (   $range)
protected

Get range expression

Parameters
string$range
Returns
\Zend_Db_Expr

Definition at line 319 of file Collection.php.

320  {
321  switch ($range) {
322  case '24h':
323  $expression = $this->getConnection()->getConcatSql(
324  [
325  $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d %H:'),
326  $this->getConnection()->quote('00'),
327  ]
328  );
329  break;
330  case '7d':
331  case '1m':
332  $expression = $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m-%d');
333  break;
334  case '1y':
335  case '2y':
336  case 'custom':
337  default:
338  $expression = $this->getConnection()->getDateFormatSql('{{attribute}}', '%Y-%m');
339  break;
340  }
341 
342  return $expression;
343  }

◆ _getRangeExpressionForAttribute()

_getRangeExpressionForAttribute (   $range,
  $attribute 
)
protected

Retrieve range expression adapted for attribute

Parameters
string$range
string$attribute
Returns
string

Definition at line 352 of file Collection.php.

353  {
354  $expression = $this->_getRangeExpression($range);
355  return str_replace('{{attribute}}', $this->getConnection()->quoteIdentifier($attribute), $expression);
356  }

◆ _getSalesAmountExpression()

_getSalesAmountExpression ( )
protected

Get sales amount expression

Returns
string

Definition at line 174 of file Collection.php.

175  {
176  if (null === $this->_salesAmountExpression) {
177  $connection = $this->getConnection();
178  $expressionTransferObject = new \Magento\Framework\DataObject(
179  [
180  'expression' => '%s - %s - %s - (%s - %s - %s)',
181  'arguments' => [
182  $connection->getIfNullSql('main_table.base_total_invoiced', 0),
183  $connection->getIfNullSql('main_table.base_tax_invoiced', 0),
184  $connection->getIfNullSql('main_table.base_shipping_invoiced', 0),
185  $connection->getIfNullSql('main_table.base_total_refunded', 0),
186  $connection->getIfNullSql('main_table.base_tax_refunded', 0),
187  $connection->getIfNullSql('main_table.base_shipping_refunded', 0),
188  ],
189  ]
190  );
191 
192  $this->_eventManager->dispatch(
193  'sales_prepare_amount_expression',
194  ['collection' => $this, 'expression_object' => $expressionTransferObject]
195  );
196  $this->_salesAmountExpression = vsprintf(
197  $expressionTransferObject->getExpression(),
198  $expressionTransferObject->getArguments()
199  );
200  }
201 
203  }
$connection
Definition: bulk.php:13

◆ _getTZRangeExpressionForAttribute()

_getTZRangeExpressionForAttribute (   $range,
  $attribute,
  $tzFrom = '+00:00',
  $tzTo = null 
)
protected

Retrieve range expression with timezone conversion adapted for attribute

Parameters
string$range
string$attribute
string$tzFrom
string$tzTo
Returns
string @SuppressWarnings(PHPMD.UnusedFormalParameter)

Definition at line 386 of file Collection.php.

386  :00', $tzTo = null)
387  {
388  if (null == $tzTo) {
389  $tzTo = $this->_localeDate->scopeDate()->format('P');
390  }
391  $connection = $this->getConnection();
392  $expression = $this->_getRangeExpression($range);
393  $attribute = $connection->quoteIdentifier($attribute);
394  $periodExpr = $connection->getDateAddSql(
395  $attribute,
396  $tzTo,
397  \Magento\Framework\DB\Adapter\AdapterInterface::INTERVAL_HOUR
398  );
399 
400  return str_replace('{{attribute}}', $periodExpr, $expression);
401  }

◆ _getTZRangeOffsetExpression()

_getTZRangeOffsetExpression (   $range,
  $attribute,
  $from = null,
  $to = null 
)
protected

Retrieve query for attribute with timezone conversion

Parameters
string$range
string$attribute
string | null$from
string | null$to
Returns
string

Definition at line 367 of file Collection.php.

368  {
369  return str_replace(
370  '{{attribute}}',
371  $this->_reportOrderFactory->create()->getStoreTZOffsetQuery($this->getMainTable(), $attribute, $from, $to),
372  $this->_getRangeExpression($range)
373  );
374  }

◆ _initInitialFieldsToSelect()

_initInitialFieldsToSelect ( )
protected

Initialize initial fields to select

Returns
$this @codeCoverageIgnore

Definition at line 906 of file Collection.php.

907  {
908  // No fields should be initialized
909  return $this;
910  }

◆ _prepareSummaryAggregated()

_prepareSummaryAggregated (   $range,
  $customStart,
  $customEnd 
)
protected

Prepare report summary from aggregated data

Parameters
string$range
string | null$customStart
string | null$customEnd
Returns
$this

Reset all columns, because result will group only by 'created_at' field

Definition at line 275 of file Collection.php.

276  {
277  $this->setMainTable('sales_order_aggregated_created');
281  $this->getSelect()->reset(\Magento\Framework\DB\Select::COLUMNS);
282  $rangePeriod = $this->_getRangeExpressionForAttribute($range, 'main_table.period');
283 
284  $tableName = $this->getConnection()->quoteIdentifier('main_table.period');
285  $rangePeriodAggregateStmt = str_replace($tableName, "MIN({$tableName})", $rangePeriod);
286 
287  $this->getSelect()->columns(
288  [
289  'revenue' => 'SUM(main_table.total_revenue_amount)',
290  'quantity' => 'SUM(main_table.orders_count)',
291  'range' => $rangePeriodAggregateStmt,
292  ]
293  )->order(
294  'range'
295  )->group(
296  $rangePeriod
297  );
298 
299  $this->getSelect()->where(
300  $this->_getConditionSql('main_table.period', $this->getDateRange($range, $customStart, $customEnd))
301  );
302 
303  $statuses = $this->_orderConfig->getStateStatuses(\Magento\Sales\Model\Order::STATE_CANCELED);
304 
305  if (empty($statuses)) {
306  $statuses = [0];
307  }
308  $this->addFieldToFilter('main_table.order_status', ['nin' => $statuses]);
309 
310  return $this;
311  }
$tableName
Definition: trigger.php:13
const COLUMNS
Definition: Select.php:48
getDateRange($range, $customStart, $customEnd, $returnObjects=false)
Definition: Collection.php:413

◆ _prepareSummaryLive()

_prepareSummaryLive (   $range,
  $customStart,
  $customEnd,
  $isFilter = 0 
)
protected

Prepare report summary from live data

Parameters
string$range
mixed$customStart
mixed$customEnd
int$isFilter
Returns
$this

Reset all columns, because result will group only by 'created_at' field

Definition at line 214 of file Collection.php.

215  {
216  $this->setMainTable('sales_order');
217  $connection = $this->getConnection();
218 
222  $this->getSelect()->reset(\Magento\Framework\DB\Select::COLUMNS);
223 
224  $expression = $this->_getSalesAmountExpression();
225  if ($isFilter == 0) {
226  $this->getSelect()->columns(
227  [
228  'revenue' => new \Zend_Db_Expr(
229  sprintf(
230  'SUM((%s) * %s)',
231  $expression,
232  $connection->getIfNullSql('main_table.base_to_global_rate', 0)
233  )
234  ),
235  ]
236  );
237  } else {
238  $this->getSelect()->columns(['revenue' => new \Zend_Db_Expr(sprintf('SUM(%s)', $expression))]);
239  }
240 
241  $dateRange = $this->getDateRange($range, $customStart, $customEnd);
242 
243  $tzRangeOffsetExpression = $this->_getTZRangeOffsetExpression(
244  $range,
245  'created_at',
246  $dateRange['from'],
247  $dateRange['to']
248  );
249 
250  $this->getSelect()->columns(
251  ['quantity' => 'COUNT(main_table.entity_id)', 'range' => $tzRangeOffsetExpression]
252  )->where(
253  'main_table.state NOT IN (?)',
254  [\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, \Magento\Sales\Model\Order::STATE_NEW]
255  )->order(
256  'range',
257  \Magento\Framework\DB\Select::SQL_ASC
258  )->group(
259  $tzRangeOffsetExpression
260  );
261 
262  $this->addFieldToFilter('created_at', $dateRange);
263 
264  return $this;
265  }
_getTZRangeOffsetExpression($range, $attribute, $from=null, $to=null)
Definition: Collection.php:367
const COLUMNS
Definition: Select.php:48
getDateRange($range, $customStart, $customEnd, $returnObjects=false)
Definition: Collection.php:413
$connection
Definition: bulk.php:13
const SQL_ASC
Definition: Select.php:81

◆ addCreateAtPeriodFilter()

addCreateAtPeriodFilter (   $period)

Add period filter by created_at attribute

Parameters
string$period
Returns
$this

Definition at line 918 of file Collection.php.

919  {
920  list($from, $to) = $this->getDateRange($period, 0, 0, true);
921 
922  $this->checkIsLive($period);
923 
924  if ($this->isLive()) {
925  $fieldToFilter = 'created_at';
926  } else {
927  $fieldToFilter = 'period';
928  }
929 
930  $this->addFieldToFilter(
931  $fieldToFilter,
932  [
933  'from' => $from->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT),
934  'to' => $to->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT)
935  ]
936  );
937 
938  return $this;
939  }
getDateRange($range, $customStart, $customEnd, $returnObjects=false)
Definition: Collection.php:413

◆ addItemCountExpr()

addItemCountExpr ( )

Add item count expression

Returns
$this

Definition at line 483 of file Collection.php.

484  {
485  $this->getSelect()->columns(['items_count' => 'total_item_count'], 'main_table');
486  return $this;
487  }

◆ addOrdersCount()

addOrdersCount ( )

Add Order count field to select

Returns
$this

Definition at line 757 of file Collection.php.

758  {
759  $this->addFieldToFilter('state', ['neq' => \Magento\Sales\Model\Order::STATE_CANCELED]);
760  $this->getSelect()->columns(['orders_count' => 'COUNT(main_table.entity_id)']);
761 
762  return $this;
763  }

◆ addRevenueToSelect()

addRevenueToSelect (   $convertCurrency = false)

Add revenue

Parameters
bool$convertCurrency
Returns
$this

Definition at line 771 of file Collection.php.

772  {
773  $expr = $this->getTotalsExpression(
774  !$convertCurrency,
775  $this->getConnection()->getIfNullSql('main_table.base_subtotal_refunded', 0),
776  $this->getConnection()->getIfNullSql('main_table.base_subtotal_canceled', 0),
777  $this->getConnection()->getIfNullSql('main_table.base_discount_canceled', 0)
778  );
779  $this->getSelect()->columns(['revenue' => $expr]);
780 
781  return $this;
782  }
getTotalsExpression( $storeId, $baseSubtotalRefunded, $baseSubtotalCanceled, $baseDiscountCanceled)
Definition: Collection.php:820

◆ addSumAvgTotals()

addSumAvgTotals (   $storeId = 0)

Add summary average totals

Parameters
int$storeId
Returns
$this

calculate average and total amount

Definition at line 790 of file Collection.php.

791  {
795  $expr = $this->getTotalsExpression(
796  $storeId,
797  $this->getConnection()->getIfNullSql('main_table.base_subtotal_refunded', 0),
798  $this->getConnection()->getIfNullSql('main_table.base_subtotal_canceled', 0),
799  $this->getConnection()->getIfNullSql('main_table.base_discount_canceled', 0)
800  );
801 
802  $this->getSelect()->columns(
803  ['orders_avg_amount' => "AVG({$expr})"]
804  )->columns(
805  ['orders_sum_amount' => "SUM({$expr})"]
806  );
807 
808  return $this;
809  }
getTotalsExpression( $storeId, $baseSubtotalRefunded, $baseSubtotalCanceled, $baseDiscountCanceled)
Definition: Collection.php:820

◆ calculateSales()

calculateSales (   $isFilter = 0)

Calculate lifitime sales

Parameters
int$isFilter
Returns
$this

Definition at line 595 of file Collection.php.

596  {
597  $statuses = $this->_orderConfig->getStateStatuses(\Magento\Sales\Model\Order::STATE_CANCELED);
598 
599  if (empty($statuses)) {
600  $statuses = [0];
601  }
602  $connection = $this->getConnection();
603 
604  if ($this->_scopeConfig->getValue(
605  'sales/dashboard/use_aggregated_data',
606  \Magento\Store\Model\ScopeInterface::SCOPE_STORE
607  )
608  ) {
609  $this->setMainTable('sales_order_aggregated_created');
610  $this->removeAllFieldsFromSelect();
611  $averageExpr = $connection->getCheckSql(
612  'SUM(main_table.orders_count) > 0',
613  'SUM(main_table.total_revenue_amount)/SUM(main_table.orders_count)',
614  0
615  );
616  $this->getSelect()->columns(
617  ['lifetime' => 'SUM(main_table.total_revenue_amount)', 'average' => $averageExpr]
618  );
619 
620  if (!$isFilter) {
621  $this->addFieldToFilter(
622  'store_id',
623  ['eq' => $this->_storeManager->getStore(\Magento\Store\Model\Store::ADMIN_CODE)->getId()]
624  );
625  }
626  $this->getSelect()->where('main_table.order_status NOT IN(?)', $statuses);
627  } else {
628  $this->setMainTable('sales_order');
629  $this->removeAllFieldsFromSelect();
630 
631  $expr = $this->_getSalesAmountExpression();
632 
633  if ($isFilter == 0) {
634  $expr = '(' . $expr . ') * main_table.base_to_global_rate';
635  }
636 
637  $this->getSelect()->columns(
638  ['lifetime' => "SUM({$expr})", 'average' => "AVG({$expr})"]
639  )->where(
640  'main_table.status NOT IN(?)',
641  $statuses
642  )->where(
643  'main_table.state NOT IN(?)',
644  [\Magento\Sales\Model\Order::STATE_NEW, \Magento\Sales\Model\Order::STATE_PENDING_PAYMENT]
645  );
646  }
647  return $this;
648  }
$connection
Definition: bulk.php:13

◆ calculateTotals()

calculateTotals (   $isFilter = 0)

Calculate totals report

Parameters
int$isFilter
Returns
$this

Definition at line 495 of file Collection.php.

496  {
497  if ($this->isLive()) {
498  $this->_calculateTotalsLive($isFilter);
499  } else {
500  $this->_calculateTotalsAggregated($isFilter);
501  }
502 
503  return $this;
504  }

◆ checkIsLive()

checkIsLive (   $range)

Check range for live mode

Parameters
string$range
Returns
$this @SuppressWarnings(PHPMD.UnusedFormalParameter)

Definition at line 128 of file Collection.php.

129  {
130  $this->_isLive = (bool)(!$this->_scopeConfig->getValue(
131  'sales/dashboard/use_aggregated_data',
132  \Magento\Store\Model\ScopeInterface::SCOPE_STORE
133  ));
134  return $this;
135  }

◆ getDateRange()

getDateRange (   $range,
  $customStart,
  $customEnd,
  $returnObjects = false 
)

Calculate From and To dates (or times) by given period

Parameters
string$range
string$customStart
string$customEnd
bool$returnObjects
Returns
array @SuppressWarnings(PHPMD.CyclomaticComplexity)

Definition at line 413 of file Collection.php.

414  {
415  $dateEnd = new \DateTime();
416  $dateStart = new \DateTime();
417 
418  // go to the end of a day
419  $dateEnd->setTime(23, 59, 59);
420 
421  $dateStart->setTime(0, 0, 0);
422 
423  switch ($range) {
424  case '24h':
425  $dateEnd = new \DateTime();
426  $dateEnd->modify('+1 hour');
427  $dateStart = clone $dateEnd;
428  $dateStart->modify('-1 day');
429  break;
430 
431  case '7d':
432  // substract 6 days we need to include
433  // only today and not hte last one from range
434  $dateStart->modify('-6 days');
435  break;
436 
437  case '1m':
438  $dateStart->setDate(
439  $dateStart->format('Y'),
440  $dateStart->format('m'),
441  $this->_scopeConfig->getValue(
442  'reports/dashboard/mtd_start',
443  \Magento\Store\Model\ScopeInterface::SCOPE_STORE
444  )
445  );
446  break;
447 
448  case 'custom':
449  $dateStart = $customStart ? $customStart : $dateEnd;
450  $dateEnd = $customEnd ? $customEnd : $dateEnd;
451  break;
452 
453  case '1y':
454  case '2y':
455  $startMonthDay = explode(
456  ',',
457  $this->_scopeConfig->getValue(
458  'reports/dashboard/ytd_start',
459  \Magento\Store\Model\ScopeInterface::SCOPE_STORE
460  )
461  );
462  $startMonth = isset($startMonthDay[0]) ? (int)$startMonthDay[0] : 1;
463  $startDay = isset($startMonthDay[1]) ? (int)$startMonthDay[1] : 1;
464  $dateStart->setDate($dateStart->format('Y'), $startMonth, $startDay);
465  if ($range == '2y') {
466  $dateStart->modify('-1 year');
467  }
468  break;
469  }
470 
471  if ($returnObjects) {
472  return [$dateStart, $dateEnd];
473  } else {
474  return ['from' => $dateStart, 'to' => $dateEnd, 'datetime' => true];
475  }
476  }

◆ getSelectCountSql()

getSelectCountSql ( )

Get select count sql

Returns
Select

Definition at line 886 of file Collection.php.

887  {
888  $countSelect = clone $this->getSelect();
889  $countSelect->reset(\Magento\Framework\DB\Select::ORDER);
890  $countSelect->reset(\Magento\Framework\DB\Select::LIMIT_COUNT);
891  $countSelect->reset(\Magento\Framework\DB\Select::LIMIT_OFFSET);
892  $countSelect->reset(\Magento\Framework\DB\Select::COLUMNS);
893  $countSelect->reset(\Magento\Framework\DB\Select::GROUP);
894  $countSelect->reset(\Magento\Framework\DB\Select::HAVING);
895  $countSelect->columns("COUNT(DISTINCT main_table.entity_id)");
896 
897  return $countSelect;
898  }
const HAVING
Definition: Select.php:53
const ORDER
Definition: Select.php:54
const COLUMNS
Definition: Select.php:48
const LIMIT_OFFSET
Definition: Select.php:56
const GROUP
Definition: Select.php:52
const LIMIT_COUNT
Definition: Select.php:55

◆ getTotalsExpression()

getTotalsExpression (   $storeId,
  $baseSubtotalRefunded,
  $baseSubtotalCanceled,
  $baseDiscountCanceled 
)
protected

Get SQL expression for totals

Parameters
int$storeId
string$baseSubtotalRefunded
string$baseSubtotalCanceled
string$baseDiscountCanceled
Returns
string

Definition at line 820 of file Collection.php.

825  {
826  $template = ($storeId != 0)
827  ? '(main_table.base_subtotal - %2$s - %1$s - ABS(main_table.base_discount_amount) - %3$s)'
828  : '((main_table.base_subtotal - %1$s - %2$s - ABS(main_table.base_discount_amount) - %3$s) '
829  . ' * main_table.base_to_global_rate)';
830  return sprintf($template, $baseSubtotalRefunded, $baseSubtotalCanceled, $baseDiscountCanceled);
831  }
$template
Definition: export.php:12

◆ groupByCustomer()

groupByCustomer ( )

Add group By customer attribute

Returns
$this

Definition at line 732 of file Collection.php.

733  {
734  $this->getSelect()->where('main_table.customer_id IS NOT NULL')->group('main_table.customer_id');
735  return $this;
736  }

◆ isLive()

isLive ( )

Retrieve is live flag for rep

Returns
bool @codeCoverageIgnore

Definition at line 143 of file Collection.php.

◆ joinCustomerName()

joinCustomerName (   $alias = 'name')

Join Customer Name (concat)

Parameters
string$alias
Returns
$this

Definition at line 744 of file Collection.php.

745  {
746  $fields = ['main_table.customer_firstname', 'main_table.customer_lastname'];
747  $fieldConcat = $this->getConnection()->getConcatSql($fields, ' ');
748  $this->getSelect()->columns([$alias => $fieldConcat]);
749  return $this;
750  }
$fields
Definition: details.phtml:14
if(!trim($html)) $alias
Definition: details.phtml:20

◆ orderByCreatedAt()

orderByCreatedAt (   $dir = self::SORT_ORDER_DESC)

Sort order by order created_at date

Parameters
string$dir
Returns
$this

Definition at line 875 of file Collection.php.

876  {
877  $this->setOrder('created_at', $dir);
878  return $this;
879  }
setOrder($field, $direction=self::SORT_ORDER_DESC)
Definition: AbstractDb.php:274

◆ orderByCustomerRegistration()

orderByCustomerRegistration (   $dir = self::SORT_ORDER_DESC)

Order by customer registration

Parameters
string$dir
Returns
$this

Definition at line 863 of file Collection.php.

864  {
865  $this->setOrder('customer_id', $dir);
866  return $this;
867  }
setOrder($field, $direction=self::SORT_ORDER_DESC)
Definition: AbstractDb.php:274

◆ orderByOrdersCount()

orderByOrdersCount (   $dir = self::SORT_ORDER_DESC)

Order by orders count

Parameters
string$dir
Returns
$this

Definition at line 851 of file Collection.php.

852  {
853  $this->getSelect()->order('orders_count ' . $dir);
854  return $this;
855  }

◆ orderByTotalAmount()

orderByTotalAmount (   $dir = self::SORT_ORDER_DESC)

Sort order by total amount

Parameters
string$dir
Returns
$this

Definition at line 839 of file Collection.php.

840  {
841  $this->getSelect()->order('orders_sum_amount ' . $dir);
842  return $this;
843  }

◆ prepareSummary()

prepareSummary (   $range,
  $customStart,
  $customEnd,
  $isFilter = 0 
)

Prepare report summary

Parameters
string$range
mixed$customStart
mixed$customEnd
int$isFilter
Returns
$this

Definition at line 157 of file Collection.php.

158  {
159  $this->checkIsLive($range);
160  if ($this->_isLive) {
161  $this->_prepareSummaryLive($range, $customStart, $customEnd, $isFilter);
162  } else {
163  $this->_prepareSummaryAggregated($range, $customStart, $customEnd, $isFilter);
164  }
165 
166  return $this;
167  }
_prepareSummaryAggregated($range, $customStart, $customEnd)
Definition: Collection.php:275
_prepareSummaryLive($range, $customStart, $customEnd, $isFilter=0)
Definition: Collection.php:214

◆ setDateRange()

setDateRange (   $fromDate,
  $toDate 
)

Set date range

Parameters
string$fromDate
string$toDate
Returns
$this

Definition at line 657 of file Collection.php.

658  {
659  $this->_reset()->addFieldToFilter(
660  'created_at',
661  ['from' => $fromDate, 'to' => $toDate]
662  )->addFieldToFilter(
663  'state',
664  ['neq' => \Magento\Sales\Model\Order::STATE_CANCELED]
665  )->getSelect()->columns(
666  ['orders' => 'COUNT(DISTINCT(main_table.entity_id))']
667  )->group(
668  'entity_id'
669  );
670 
671  $this->getSelect()->columns(['items' => 'SUM(main_table.total_qty_ordered)']);
672 
673  return $this;
674  }

◆ setStoreIds()

setStoreIds (   $storeIds)

Set store filter collection

Parameters
int[]$storeIds
Returns
$this

Definition at line 682 of file Collection.php.

683  {
684  $connection = $this->getConnection();
685  $baseSubtotalInvoiced = $connection->getIfNullSql('main_table.base_subtotal_invoiced', 0);
686  $baseDiscountRefunded = $connection->getIfNullSql('main_table.base_discount_refunded', 0);
687  $baseSubtotalRefunded = $connection->getIfNullSql('main_table.base_subtotal_refunded', 0);
688  $baseDiscountInvoiced = $connection->getIfNullSql('main_table.base_discount_invoiced', 0);
689  $baseTotalInvocedCost = $connection->getIfNullSql('main_table.base_total_invoiced_cost', 0);
690  if ($storeIds) {
691  $this->getSelect()->columns(
692  [
693  'subtotal' => 'SUM(main_table.base_subtotal)',
694  'tax' => 'SUM(main_table.base_tax_amount)',
695  'shipping' => 'SUM(main_table.base_shipping_amount)',
696  'discount' => 'SUM(main_table.base_discount_amount)',
697  'total' => 'SUM(main_table.base_grand_total)',
698  'invoiced' => 'SUM(main_table.base_total_paid)',
699  'refunded' => 'SUM(main_table.base_total_refunded)',
700  'profit' => "SUM({$baseSubtotalInvoiced}) " .
701  "+ SUM({$baseDiscountRefunded}) - SUM({$baseSubtotalRefunded}) " .
702  "- SUM({$baseDiscountInvoiced}) - SUM({$baseTotalInvocedCost})",
703  ]
704  );
705  } else {
706  $this->getSelect()->columns(
707  [
708  'subtotal' => 'SUM(main_table.base_subtotal * main_table.base_to_global_rate)',
709  'tax' => 'SUM(main_table.base_tax_amount * main_table.base_to_global_rate)',
710  'shipping' => 'SUM(main_table.base_shipping_amount * main_table.base_to_global_rate)',
711  'discount' => 'SUM(main_table.base_discount_amount * main_table.base_to_global_rate)',
712  'total' => 'SUM(main_table.base_grand_total * main_table.base_to_global_rate)',
713  'invoiced' => 'SUM(main_table.base_total_paid * main_table.base_to_global_rate)',
714  'refunded' => 'SUM(main_table.base_total_refunded * main_table.base_to_global_rate)',
715  'profit' => "SUM({$baseSubtotalInvoiced} * main_table.base_to_global_rate) " .
716  "+ SUM({$baseDiscountRefunded} * main_table.base_to_global_rate) " .
717  "- SUM({$baseSubtotalRefunded} * main_table.base_to_global_rate) " .
718  "- SUM({$baseDiscountInvoiced} * main_table.base_to_global_rate) " .
719  "- SUM({$baseTotalInvocedCost} * main_table.base_to_global_rate)",
720  ]
721  );
722  }
723 
724  return $this;
725  }
$connection
Definition: bulk.php:13

Field Documentation

◆ $_isLive

$_isLive = false
protected

Definition at line 26 of file Collection.php.

◆ $_localeDate

$_localeDate
protected

Definition at line 54 of file Collection.php.

◆ $_orderConfig

$_orderConfig
protected

Definition at line 61 of file Collection.php.

◆ $_reportOrderFactory

$_reportOrderFactory
protected

Definition at line 68 of file Collection.php.

◆ $_salesAmountExpression

$_salesAmountExpression
protected

Definition at line 33 of file Collection.php.

◆ $_scopeConfig

$_scopeConfig
protected

Definition at line 40 of file Collection.php.

◆ $_storeManager

$_storeManager
protected

Definition at line 47 of file Collection.php.


The documentation for this class was generated from the following file: