1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\InventorySourceDeductionApi\Model;
use Magento\InventoryApi\Api\SourceItemsSaveInterface;
use Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface;
use Magento\InventorySalesApi\Api\GetStockBySalesChannelInterface;
use Magento\InventorySalesApi\Api\StockResolverInterface;
use Magento\Framework\Exception\LocalizedException;
/**
* @inheritdoc
*/
class SourceDeductionService implements SourceDeductionServiceInterface
{
/**
* @var SourceItemsSaveInterface
*/
private $sourceItemsSave;
/**
* @var GetSourceItemBySourceCodeAndSku
*/
private $getSourceItemBySourceCodeAndSku;
/**
* @var GetStockItemConfigurationInterface
*/
private $getStockItemConfiguration;
/**
* @var GetStockBySalesChannelInterface
*/
private $getStockBySalesChannel;
/**
* @param SourceItemsSaveInterface $sourceItemsSave
* @param GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku
* @param GetStockItemConfigurationInterface $getStockItemConfiguration
* @param GetStockBySalesChannelInterface $getStockBySalesChannel
*/
public function __construct(
SourceItemsSaveInterface $sourceItemsSave,
GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku,
GetStockItemConfigurationInterface $getStockItemConfiguration,
GetStockBySalesChannelInterface $getStockBySalesChannel
) {
$this->sourceItemsSave = $sourceItemsSave;
$this->getSourceItemBySourceCodeAndSku = $getSourceItemBySourceCodeAndSku;
$this->getStockItemConfiguration = $getStockItemConfiguration;
$this->getStockBySalesChannel = $getStockBySalesChannel;
}
/**
* @inheritdoc
*/
public function execute(SourceDeductionRequestInterface $sourceDeductionRequest): void
{
$sourceItems = [];
$sourceCode = $sourceDeductionRequest->getSourceCode();
$salesChannel = $sourceDeductionRequest->getSalesChannel();
$stockId = $this->getStockBySalesChannel->execute($salesChannel)->getStockId();
foreach ($sourceDeductionRequest->getItems() as $item) {
$itemSku = $item->getSku();
$qty = $item->getQty();
$stockItemConfiguration = $this->getStockItemConfiguration->execute(
$itemSku,
$stockId
);
if (!$stockItemConfiguration->isManageStock()) {
//We don't need to Manage Stock
continue;
}
$sourceItem = $this->getSourceItemBySourceCodeAndSku->execute($sourceCode, $itemSku);
if (($sourceItem->getQuantity() - $qty) >= 0) {
$sourceItem->setQuantity($sourceItem->getQuantity() - $qty);
$sourceItems[] = $sourceItem;
} else {
throw new LocalizedException(
__('Not all of your products are available in the requested quantity.')
);
}
}
if (!empty($sourceItems)) {
$this->sourceItemsSave->execute($sourceItems);
}
}
}