Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SourceDeductionService.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
15 
20 {
24  private $sourceItemsSave;
25 
29  private $getSourceItemBySourceCodeAndSku;
30 
34  private $getStockItemConfiguration;
35 
39  private $getStockBySalesChannel;
40 
47  public function __construct(
48  SourceItemsSaveInterface $sourceItemsSave,
49  GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku,
50  GetStockItemConfigurationInterface $getStockItemConfiguration,
51  GetStockBySalesChannelInterface $getStockBySalesChannel
52  ) {
53  $this->sourceItemsSave = $sourceItemsSave;
54  $this->getSourceItemBySourceCodeAndSku = $getSourceItemBySourceCodeAndSku;
55  $this->getStockItemConfiguration = $getStockItemConfiguration;
56  $this->getStockBySalesChannel = $getStockBySalesChannel;
57  }
58 
62  public function execute(SourceDeductionRequestInterface $sourceDeductionRequest): void
63  {
64  $sourceItems = [];
65  $sourceCode = $sourceDeductionRequest->getSourceCode();
66  $salesChannel = $sourceDeductionRequest->getSalesChannel();
67 
68  $stockId = $this->getStockBySalesChannel->execute($salesChannel)->getStockId();
69  foreach ($sourceDeductionRequest->getItems() as $item) {
70  $itemSku = $item->getSku();
71  $qty = $item->getQty();
72  $stockItemConfiguration = $this->getStockItemConfiguration->execute(
73  $itemSku,
74  $stockId
75  );
76 
77  if (!$stockItemConfiguration->isManageStock()) {
78  //We don't need to Manage Stock
79  continue;
80  }
81 
82  $sourceItem = $this->getSourceItemBySourceCodeAndSku->execute($sourceCode, $itemSku);
83  if (($sourceItem->getQuantity() - $qty) >= 0) {
84  $sourceItem->setQuantity($sourceItem->getQuantity() - $qty);
86  } else {
87  throw new LocalizedException(
88  __('Not all of your products are available in the requested quantity.')
89  );
90  }
91  }
92 
93  if (!empty($sourceItems)) {
94  $this->sourceItemsSave->execute($sourceItems);
95  }
96  }
97 }
__()
Definition: __.php:13
execute(SourceDeductionRequestInterface $sourceDeductionRequest)
$sourceItems
$sourceCode
Definition: inventory.phtml:11
$sourceItemsSave
__construct(SourceItemsSaveInterface $sourceItemsSave, GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku, GetStockItemConfigurationInterface $getStockItemConfiguration, GetStockBySalesChannelInterface $getStockBySalesChannel)