You are here

function _commerce_reports_stock_calculate_dataset in Commerce Reporting 7.3

Same name and namespace in other branches
  1. 7.4 modules/stock/commerce_reports_stock.module \_commerce_reports_stock_calculate_dataset()

Calculate all the stock reports data (weekly sales, monthly sales, lifetime)

3 calls to _commerce_reports_stock_calculate_dataset()
commerce_reports_stock_handler_field_monthlysales::query in modules/stock/includes/views/handlers/commerce_reports_stock_handler_field_monthlysales.inc
Called to add the field to a query.
commerce_reports_stock_handler_field_stocklifetime::query in modules/stock/includes/views/handlers/commerce_reports_stock_handler_field_stocklifetime.inc
Called to add the field to a query.
commerce_reports_stock_handler_field_weeklysales::query in modules/stock/includes/views/handlers/commerce_reports_stock_handler_field_weeklysales.inc
Called to add the field to a query.

File

modules/stock/commerce_reports_stock.module, line 25
This module provides advanced stock reporting for Drupal Commerce.

Code

function _commerce_reports_stock_calculate_dataset() {
  $products = commerce_product_load_multiple(array(), array(
    'status' => 1,
  ));
  $start = variable_get('commerce_reports_stock_historyperiod', '3 months ago');
  $start = strtotime($start);
  $weekly_sales = _commerce_reports_stock_api_sales('W', $start);
  $monthly_sales = _commerce_reports_stock_api_sales('M', $start);
  $data = array();
  $lifetimes = array();
  $instock = array();
  foreach ($products as $product) {
    $sku = $product->sku;
    $stock = isset($product->commerce_stock[LANGUAGE_NONE][0]['value']) ? (int) $product->commerce_stock[LANGUAGE_NONE][0]['value'] : FALSE;
    $weekly_burn = isset($weekly_sales[$sku]) ? _commerce_reports_stock_calculate_average_sales($weekly_sales[$sku]) : 0;
    $monthly_burn = isset($monthly_sales[$sku]) ? _commerce_reports_stock_calculate_average_sales($monthly_sales[$sku]) : 0;
    $lifetime = _commerce_reports_stock_calculate_lifetime($stock, $weekly_burn);
    $lifetimes[] = $lifetime;
    $instock[] = (bool) $stock;
    $data[$sku] = array(
      'sku' => $sku,
      'stock' => $stock,
      'weeklysales' => sprintf('%0.1f', $weekly_burn),
      'monthlysales' => sprintf('%0.1f', $monthly_burn),
      'lifetime' => $lifetime,
    );
  }
  array_multisort($instock, SORT_NUMERIC, $lifetimes, SORT_NUMERIC, $data);
  return $data;
}