You are here

class CommerceTurnoverSensorPlugin in Monitoring 8

Monitors commerce order turnover stats.

Based on SensorEntityDatabaseAggregator using commerce_order table.

Plugin annotation


@SensorPlugin(
  id = "commerce_turnover",
  label = @Translation("Commerce order turnover"),
  description = @Translation("Monitors how much money was earned with commerce orders."),
  provider = "commerce_order",
  addable = TRUE
)

Hierarchy

Expanded class hierarchy of CommerceTurnoverSensorPlugin

File

src/Plugin/monitoring/SensorPlugin/CommerceTurnoverSensorPlugin.php, line 30

Namespace

Drupal\monitoring\Plugin\monitoring\SensorPlugin
View source
class CommerceTurnoverSensorPlugin extends ContentEntityAggregatorSensorPlugin {

  /**
   * The commerce currency formatter.
   *
   * @var \CommerceGuys\Intl\Formatter\CurrencyFormatterInterface
   */
  protected $currencyFormatter;

  /**
   * The current store service.
   *
   * @var \Drupal\commerce_store\CurrentStoreInterface
   */
  protected $currentStore;

  /**
   * The workflow manager.
   *
   * @var \Drupal\state_machine\WorkflowManagerInterface
   */
  protected $workflowManager;

  /**
   * Date formatter.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected $dateFormatter;

  /**
   * {@inheritdoc}
   */
  public function __construct(SensorConfig $sensor_config, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, CurrencyFormatterInterface $currency_formatter, CurrentStoreInterface $current_store, WorkflowManagerInterface $workflow_manager, DateFormatterInterface $date_formatter) {
    parent::__construct($sensor_config, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager);
    $this->currencyFormatter = $currency_formatter;
    $this->currentStore = $current_store;
    $this->workflowManager = $workflow_manager;
    $this->dateFormatter = $date_formatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, SensorConfig $sensor_config, $plugin_id, $plugin_definition) {
    return new static($sensor_config, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('entity_field.manager'), $container
      ->get('commerce_price.currency_formatter'), $container
      ->get('commerce_store.current_store'), $container
      ->get('plugin.manager.workflow'), $container
      ->get('date.formatter'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityQueryAggregate() {
    $query = parent::getEntityQueryAggregate();
    $query
      ->aggregate('total_price.number', 'SUM');
    $query
      ->condition('total_price.currency_code', $this->sensorConfig
      ->getSetting('commerce_order_currency'));
    if ($paid_states = array_filter($this->sensorConfig
      ->getSetting('commerce_order_paid_states'))) {
      $query
        ->condition('state', $paid_states, 'IN');
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function runSensor(SensorResultInterface $result) {
    parent::runSensor($result);
    $query_result = $this
      ->getEntityQueryAggregate()
      ->execute();
    $currency_code = $this->sensorConfig
      ->getSetting('commerce_order_currency');
    $sensor_value = NULL;
    if (!empty($query_result)) {
      $query_result = reset($query_result);
      if (is_numeric($query_result['total_pricenumber_sum'])) {
        $sensor_value = $query_result['total_pricenumber_sum'];
        $result
          ->setMessage('@formatted_value in @time_interval', [
          '@formatted_value' => $this->currencyFormatter
            ->format($sensor_value, $currency_code),
          '@time_interval' => $this->dateFormatter
            ->formatInterval($this->sensorConfig
            ->getTimeIntervalValue()),
        ]);
      }
    }
    $result
      ->setValue($sensor_value);
  }

  /**
   * Adds additional settings to the sensor configuration form.
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['commerce_order_paid_states'] = [
      '#type' => 'checkboxes',
      '#title' => t('"Paid" order states'),
      '#description' => t('Select order states in which the order is considered to be paid.'),
      '#options' => $this
        ->getOrderStates(),
      '#default_value' => $this->sensorConfig
        ->getSetting('commerce_order_paid_states'),
    ];
    $currencies = $this->entityTypeManager
      ->getStorage('commerce_currency')
      ->loadMultiple();
    $current_store = $this->currentStore
      ->getStore();
    $default_currency = $current_store
      ->getDefaultCurrency();
    foreach ($currencies as $currency_code => $currency) {
      $currencies[$currency_code] = $currency
        ->getName();
    }
    $selected_currency = $this->sensorConfig
      ->getSetting('commerce_order_currency') ?: '';
    if (empty($selected_currency) && $default_currency instanceof CurrencyInterface) {
      $selected_currency = $default_currency
        ->getCurrencyCode();
    }
    $form['commerce_order_currency'] = [
      '#type' => 'select',
      '#title' => t('Currency'),
      '#description' => t('Select which currency the orders are using.'),
      '#options' => $currencies,
      '#default_value' => $selected_currency,
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * Gets all order states from all workflows.
   *
   * @return array
   *   An array of order states or empty array if no states found.
   */
  protected function getOrderStates() {
    $states = [];
    foreach ($this->workflowManager
      ->getDefinitions() as $workflow) {
      if ($workflow['group'] == 'commerce_order') {
        foreach ($workflow['states'] as $key => $state) {
          $states[$key] = $state['label'];
        }
      }
    }
    return $states;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CommerceTurnoverSensorPlugin::$currencyFormatter protected property The commerce currency formatter.
CommerceTurnoverSensorPlugin::$currentStore protected property The current store service.
CommerceTurnoverSensorPlugin::$dateFormatter protected property Date formatter.
CommerceTurnoverSensorPlugin::$workflowManager protected property The workflow manager.
CommerceTurnoverSensorPlugin::buildConfigurationForm public function Adds additional settings to the sensor configuration form. Overrides ContentEntityAggregatorSensorPlugin::buildConfigurationForm
CommerceTurnoverSensorPlugin::create public static function Creates an instance of the sensor with config. Overrides ContentEntityAggregatorSensorPlugin::create
CommerceTurnoverSensorPlugin::getEntityQueryAggregate protected function Builds the entity aggregate query. Overrides ContentEntityAggregatorSensorPlugin::getEntityQueryAggregate
CommerceTurnoverSensorPlugin::getOrderStates protected function Gets all order states from all workflows.
CommerceTurnoverSensorPlugin::runSensor public function Runs the sensor, updating $sensor_result. Overrides ContentEntityAggregatorSensorPlugin::runSensor
CommerceTurnoverSensorPlugin::__construct public function Instantiates a sensor object. Overrides ContentEntityAggregatorSensorPlugin::__construct
ContentEntityAggregatorSensorPlugin::$aggregateField protected property Local variable to store the field that is used as aggregate.
ContentEntityAggregatorSensorPlugin::$configurableEntityType protected property Allows plugins to control if the entity type can be configured. 1
ContentEntityAggregatorSensorPlugin::$entityFieldManager protected property The entity field manager.
ContentEntityAggregatorSensorPlugin::$entityTypeManager protected property Local variable to store \Drupal::entityTypeManger().
ContentEntityAggregatorSensorPlugin::addAggregate protected function Add aggregation to the query.
ContentEntityAggregatorSensorPlugin::addConditionSubmit public function Adds sensor to entity when 'Add another condition' button is pressed.
ContentEntityAggregatorSensorPlugin::addFieldSubmit public function Adds sensor to entity when 'Add another field' button is pressed.
ContentEntityAggregatorSensorPlugin::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides SensorPluginBase::calculateDependencies
ContentEntityAggregatorSensorPlugin::conditionsReplace public function Returns the updated 'conditions' fieldset for replacement by ajax.
ContentEntityAggregatorSensorPlugin::fieldsReplace public function Returns the updated 'verbose_fields' fieldset for replacement by ajax.
ContentEntityAggregatorSensorPlugin::getDefaultConfiguration public function Default configuration for a sensor. Overrides DatabaseAggregatorSensorPluginBase::getDefaultConfiguration 1
ContentEntityAggregatorSensorPlugin::getEntityQuery protected function Builds the entity query for verbose output.
ContentEntityAggregatorSensorPlugin::resultVerbose public function Provide additional info about sensor call. Overrides ExtendedInfoSensorPluginInterface::resultVerbose
ContentEntityAggregatorSensorPlugin::submitConfigurationForm public function Form submission handler. Overrides DatabaseAggregatorSensorPluginBase::submitConfigurationForm
ContentEntityAggregatorSensorPlugin::validateConfigurationForm public function Form validation handler. Overrides SensorPluginBase::validateConfigurationForm
ContentEntityAggregatorSensorPlugin::verboseResultUnaggregated public function Adds unaggregated verbose output to the render array $output.
DatabaseAggregatorSensorPluginBase::$configurableTimestampField protected property Allows plugins to control if a timestamp field can be configured. 2
DatabaseAggregatorSensorPluginBase::$configurableValueType protected property Allows plugins to control if the value type can be configured. Overrides SensorPluginBase::$configurableValueType
DatabaseAggregatorSensorPluginBase::getConditions protected function Gets conditions to be used in the select query.
DatabaseAggregatorSensorPluginBase::getTimeIntervalField protected function Gets the time field.
DatabaseAggregatorSensorPluginBase::getTimeIntervalOptions protected function Returns time interval options.
DatabaseAggregatorSensorPluginBase::getTimeIntervalValue protected function Gets the time interval value.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
SensorPluginBase::$pluginDefinition protected property The plugin implementation definition.
SensorPluginBase::$pluginId protected property The plugin_id.
SensorPluginBase::$sensorConfig protected property Current sensor config object.
SensorPluginBase::$services protected property
SensorPluginBase::addService public function Service setter. Overrides SensorPluginInterface::addService
SensorPluginBase::getConfigurableValueType public function Configurable value type. Overrides SensorPluginInterface::getConfigurableValueType
SensorPluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
SensorPluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
SensorPluginBase::getSensorId public function Gets sensor name (not the label). Overrides SensorPluginInterface::getSensorId
SensorPluginBase::getService public function @todo: Replace with injection Overrides SensorPluginInterface::getService
SensorPluginBase::isEnabled public function Determines if sensor is enabled. Overrides SensorPluginInterface::isEnabled
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.