You are here

class StockTransactions2 in Commerce Stock 8

The second part of a two part create stock transaction form.

Hierarchy

Expanded class hierarchy of StockTransactions2

1 string reference to 'StockTransactions2'
commerce_stock_ui.routing.yml in modules/ui/commerce_stock_ui.routing.yml
modules/ui/commerce_stock_ui.routing.yml

File

modules/ui/src/Form/StockTransactions2.php, line 15

Namespace

Drupal\commerce_stock_ui\Form
View source
class StockTransactions2 extends FormBase {

  /**
   * The product variation storage.
   *
   * @var \Drupal\commerce_product\ProductVariationStorage
   */
  protected $productVariationStorage;

  /**
   * The stock service manager.
   *
   * @var \Drupal\commerce_stock\StockServiceManager
   */
  protected $stockServiceManager;

  /**
   * The current request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Constructs a StockTransactions2 object.
   *
   * @param \Drupal\commerce_product\ProductVariationStorage $productVariationStorage
   *   The commerce product variation storage.
   * @param \Drupal\commerce_stock\StockServiceManager $stockServiceManager
   *   The stock service manager.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   */
  public function __construct(ProductVariationStorage $productVariationStorage, StockServiceManager $stockServiceManager, Request $request) {
    $this->productVariationStorage = $productVariationStorage;
    $this->stockServiceManager = $stockServiceManager;
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager')
      ->getStorage('commerce_product_variation'), $container
      ->get('commerce_stock.service_manager'), $container
      ->get('request_stack')
      ->getCurrentRequest());
  }

  /**
   * Returns the page title.
   */
  public function getTitle() {
    $variation_id = $this->request->query
      ->get('commerce_product_v_id');
    $product_variation = $this->productVariationStorage
      ->load($variation_id);
    return $this
      ->t('Create stock transaction for :product_variation', [
      ':product_variation' => $product_variation
        ->label(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'commerce_stock_transactions2';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->request->query
      ->has('commerce_product_v_id')) {
      $variation_id = $this->request->query
        ->get('commerce_product_v_id');
    }
    else {
      return $this
        ->redirect('commerce_stock_ui.stock_transactions1');
    }
    $product_variation = $this->productVariationStorage
      ->load($variation_id);
    $stockService = $this->stockServiceManager
      ->getService($product_variation);
    $locations = $stockService
      ->getStockChecker()
      ->getLocationList(TRUE);
    $location_options = [];

    /** @var \Drupal\commerce_stock\StockLocationInterface $location */
    foreach ($locations as $location) {
      $location_options[$location
        ->getId()] = $location
        ->getName();
    }
    $form['transaction_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Transaction type'),
      '#options' => [
        'receiveStock' => $this
          ->t('Receive stock'),
        'sellStock' => $this
          ->t('Sell stock'),
        'returnStock' => $this
          ->t('Return stock'),
        'moveStock' => $this
          ->t('Move stock'),
      ],
    ];
    $form['product_variation_id'] = [
      '#type' => 'value',
      '#value' => $variation_id,
    ];
    $form['source'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Source location'),
    ];
    $form['source']['source_location'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Location'),
      '#options' => $location_options,
    ];
    $form['source']['source_zone'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Zone/Bins'),
      '#description' => $this
        ->t('The location zone (bins)'),
      '#size' => 60,
      '#maxlength' => 50,
    ];
    $form['target'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Move target'),
      '#states' => [
        'visible' => [
          ':input[name="transaction_type"]' => [
            'value' => 'moveStock',
          ],
        ],
      ],
    ];
    $form['target']['target_location'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Target Location'),
      '#options' => $location_options,
    ];
    $form['target']['target_zone'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Zone/Bins'),
      '#description' => $this
        ->t('The location zone (bins)'),
      '#size' => 60,
      '#maxlength' => 50,
    ];
    $form['user'] = [
      '#type' => 'entity_autocomplete',
      '#title' => $this
        ->t('Optional user'),
      '#target_type' => 'user',
      '#selection_handler' => 'default',
      '#states' => [
        'visible' => [
          ':input[name="transaction_type"]' => [
            [
              'value' => 'sellStock',
            ],
            [
              'value' => 'returnStock',
            ],
          ],
        ],
      ],
    ];
    $form['order'] = [
      '#type' => 'entity_autocomplete',
      '#title' => $this
        ->t('Optional order number'),
      '#target_type' => 'commerce_order',
      '#selection_handler' => 'default',
      '#states' => [
        'visible' => [
          ':input[name="transaction_type"]' => [
            [
              'value' => 'sellStock',
            ],
            [
              'value' => 'returnStock',
            ],
          ],
        ],
      ],
    ];
    $form['transaction_qty'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Quantity'),
      '#default_value' => '1',
      '#step' => '0.01',
      '#required' => TRUE,
    ];
    $form['transaction_note'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Note'),
      '#description' => $this
        ->t('A note for the transaction'),
      '#maxlength' => 64,
      '#size' => 64,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * @todo: We need to check the product is managed by a stock service. Or
   * remove this override as it does nothing.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $transaction_type = $form_state
      ->getValue('transaction_type');
    $product_variation_id = $form_state
      ->getValue('product_variation_id');
    $source_location = $form_state
      ->getValue('source_location');
    $source_zone = $form_state
      ->getValue('source_zone');
    $qty = $form_state
      ->getValue('transaction_qty');
    $transaction_note = $form_state
      ->getValue('transaction_note');
    $product_variation = $this->productVariationStorage
      ->load($product_variation_id);
    if ($transaction_type == 'receiveStock') {
      $this->stockServiceManager
        ->receiveStock($product_variation, $source_location, $source_zone, $qty, NULL, $currency_code = NULL, $transaction_note);
      $this
        ->messenger()
        ->addMessage($this
        ->t('@qty has been added to "@variation_title" using a "Received Stock" transaction.', [
        '@qty' => $qty,
        '@variation_title' => $product_variation
          ->getTitle(),
      ]));
    }
    elseif ($transaction_type == 'sellStock') {
      $order_id = $form_state
        ->getValue('order');
      $user_id = $form_state
        ->getValue('user');
      $this->stockServiceManager
        ->sellStock($product_variation, $source_location, $source_zone, $qty, NULL, $currency_code = NULL, $order_id, $user_id, $transaction_note);
      $this
        ->messenger()
        ->addMessage($this
        ->t('@qty has been removed from "@variation_title" using a "Sell Stock" transaction.', [
        '@qty' => $qty,
        '@variation_title' => $product_variation
          ->getTitle(),
      ]));
    }
    elseif ($transaction_type == 'returnStock') {
      $order_id = $form_state
        ->getValue('order');
      $user_id = $form_state
        ->getValue('user');
      $this->stockServiceManager
        ->returnStock($product_variation, $source_location, $source_zone, $qty, NULL, $currency_code = NULL, $order_id, $user_id, $transaction_note);
      $this
        ->messenger()
        ->addMessage($this
        ->t('@qty has been added to "@variation_title" using a "Return Stock" transaction.', [
        '@qty' => $qty,
        '@variation_title' => $product_variation
          ->getTitle(),
      ]));
    }
    elseif ($transaction_type == 'moveStock') {
      $target_location = $form_state
        ->getValue('target_location');
      $target_zone = $form_state
        ->getValue('target_zone');
      $this->stockServiceManager
        ->moveStock($product_variation, $source_location, $target_location, $source_zone, $target_zone, $qty, NULL, $currency_code = NULL, $transaction_note);

      // Display notification for end users.
      $target_location_entity = \Drupal::entityTypeManager()
        ->getStorage('commerce_stock_location')
        ->load($target_location);
      $target_location_name = $target_location_entity
        ->getName();
      $source_location_entity = \Drupal::entityTypeManager()
        ->getStorage('commerce_stock_location')
        ->load($source_location);
      $source_location_name = $source_location_entity
        ->getName();
      $this
        ->messenger()
        ->addMessage($this
        ->t('@qty has been moved from "@source_location" to "@target_location" for "@variation_title" using a "Move Stock" transaction.', [
        '@qty' => $qty,
        '@variation_title' => $product_variation
          ->getTitle(),
        '@source_location' => $source_location_name,
        '@target_location' => $target_location_name,
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StockTransactions2::$productVariationStorage protected property The product variation storage.
StockTransactions2::$request protected property The current request.
StockTransactions2::$stockServiceManager protected property The stock service manager.
StockTransactions2::buildForm public function Form constructor. Overrides FormInterface::buildForm
StockTransactions2::create public static function Instantiates a new instance of this class. Overrides FormBase::create
StockTransactions2::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StockTransactions2::getTitle public function Returns the page title.
StockTransactions2::submitForm public function Form submission handler. Overrides FormInterface::submitForm
StockTransactions2::validateForm public function @todo: We need to check the product is managed by a stock service. Or remove this override as it does nothing. Overrides FormBase::validateForm
StockTransactions2::__construct public function Constructs a StockTransactions2 object.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.