You are here

private function StockLevel::createTransaction in Commerce Stock 8

Internal method to create transactions.

1 call to StockLevel::createTransaction()
StockLevel::postSave in modules/field/src/Plugin/Field/FieldType/StockLevel.php
Defines custom post-save behavior for field values.

File

modules/field/src/Plugin/Field/FieldType/StockLevel.php, line 143

Class

StockLevel
Plugin implementation of the 'commerce_stock_field' field type.

Namespace

Drupal\commerce_stock_field\Plugin\Field\FieldType

Code

private function createTransaction(EntityInterface $entity, array $values) {

  // To prevent multiple stock transactions, we need to track the processing.
  static $processed = [];

  // This is essential to prevent triggering of multiple transactions.
  if (isset($processed[$entity
    ->getEntityTypeId() . $entity
    ->id()])) {
    return;
  }
  $processed[$entity
    ->getEntityTypeId() . $entity
    ->id()] = TRUE;
  $stockServiceManager = \Drupal::service('commerce_stock.service_manager');
  $transaction_qty = empty($values['adjustment']) ? 0 : $values['adjustment'];

  // Some basic validation and type coercion.
  $transaction_qty = filter_var((double) $transaction_qty, FILTER_VALIDATE_FLOAT);
  if ($transaction_qty) {
    $transaction_type = $transaction_qty > 0 ? StockTransactionsInterface::STOCK_IN : StockTransactionsInterface::STOCK_OUT;

    // @todo Add zone and location to form.

    /** @var \Drupal\commerce_stock\StockLocationInterface $location */
    $location = $stockServiceManager
      ->getTransactionLocation($this
      ->getContext($entity), $entity, $transaction_qty);
    if (empty($location)) {

      // If we have no location, something isn't properly configured.
      throw new \RuntimeException('The StockServiceManager didn\'t return a location. Make sure your store is set up correctly?');
    }
    $zone = empty($values['zone']) ? '' : $values['zone'];
    $unit_cost = NULL;
    if (isset($values['unit_cost']['amount'])) {
      $unit_cost = filter_var((double) $values['unit_cost']['amount'], FILTER_VALIDATE_FLOAT);
      $unit_cost ?: NULL;
    }
    $currency_code = empty($values['unit_cost']['currency_code']) ? NULL : $values['unit_cost']['currency_code'];
    $transaction_note = empty($values['stock_transaction_note']) ? '' : $values['stock_transaction_note'];
    $metadata = [
      'data' => [
        'message' => $transaction_note,
      ],
    ];
    if (!empty($values['user_id'])) {
      $metadata['related_uid'] = $values['user_id'];
    }
    else {
      $metadata['related_uid'] = \Drupal::currentUser()
        ->id();
    }
    $stockServiceManager
      ->createTransaction($entity, $location
      ->getId(), $zone, $transaction_qty, (double) $unit_cost, $currency_code, $transaction_type, $metadata);
  }
}