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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogInventory\Model\ResourceModel;
use Magento\CatalogInventory\Api\StockConfigurationInterface;
use Magento\Store\Model\StoreManagerInterface;
/**
* Stock resource model
*/
class Stock extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb implements QtyCounterInterface
{
/**
* @var StockConfigurationInterface
*/
protected $stockConfiguration;
/**
* Is initialized configuration flag
*
* @var bool
*/
protected $_isConfig;
/**
* Manage Stock flag
*
* @var bool
*/
protected $_isConfigManageStock;
/**
* Backorders
*
* @var bool
*/
protected $_isConfigBackorders;
/**
* Minimum quantity allowed in shopping card
*
* @var int
*/
protected $_configMinQty;
/**
* Product types that could have quantities
*
* @var array
*/
protected $_configTypeIds;
/**
* Notify for quantity below _configNotifyStockQty value
*
* @var int
*/
protected $_configNotifyStockQty;
/**
* Core store config
*
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime
*/
protected $dateTime;
/**
* @var StoreManagerInterface
* @deprecated 100.1.0
*/
protected $storeManager;
/**
* @param \Magento\Framework\Model\ResourceModel\Db\Context $context
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
* @param StockConfigurationInterface $stockConfiguration
* @param StoreManagerInterface $storeManager
* @param string $connectionName
*/
public function __construct(
\Magento\Framework\Model\ResourceModel\Db\Context $context,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Stdlib\DateTime\DateTime $dateTime,
StockConfigurationInterface $stockConfiguration,
StoreManagerInterface $storeManager,
$connectionName = null
) {
parent::__construct($context, $connectionName);
$this->_scopeConfig = $scopeConfig;
$this->dateTime = $dateTime;
$this->stockConfiguration = $stockConfiguration;
$this->storeManager = $storeManager;
}
/**
* Define main table and initialize connection
*
* @return void
*/
protected function _construct()
{
$this->_init('cataloginventory_stock', 'stock_id');
}
/**
* Lock Stock Item records.
*
* @param int[] $productIds
* @param int $websiteId
* @return array
*/
public function lockProductsStock(array $productIds, $websiteId)
{
if (empty($productIds)) {
return [];
}
$itemTable = $this->getTable('cataloginventory_stock_item');
$select = $this->getConnection()->select()->from(['si' => $itemTable])
->where('website_id = ?', $websiteId)
->where('product_id IN(?)', $productIds)
->forUpdate(true);
$productTable = $this->getTable('catalog_product_entity');
$selectProducts = $this->getConnection()->select()->from(['p' => $productTable], [])
->where('entity_id IN (?)', $productIds)
->columns(
[
'product_id' => 'entity_id',
'type_id' => 'type_id',
]
);
$items = [];
foreach ($this->getConnection()->query($select)->fetchAll() as $si) {
$items[$si['product_id']] = $si;
}
foreach ($this->getConnection()->fetchAll($selectProducts) as $p) {
$items[$p['product_id']]['type_id'] = $p['type_id'];
}
return $items;
}
/**
* {@inheritdoc}
*/
public function correctItemsQty(array $items, $websiteId, $operator)
{
if (empty($items)) {
return;
}
$connection = $this->getConnection();
$conditions = [];
foreach ($items as $productId => $qty) {
$case = $connection->quoteInto('?', $productId);
$result = $connection->quoteInto("qty{$operator}?", $qty);
$conditions[$case] = $result;
}
$value = $connection->getCaseSql('product_id', $conditions, 'qty');
$where = ['product_id IN (?)' => array_keys($items), 'website_id = ?' => $websiteId];
$connection->beginTransaction();
$connection->update($this->getTable('cataloginventory_stock_item'), ['qty' => $value], $where);
$connection->commit();
}
/**
* Load some inventory configuration settings
*
* @return void
*/
protected function _initConfig()
{
if (!$this->_isConfig) {
$configMap = [
'_isConfigManageStock' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_MANAGE_STOCK,
'_isConfigBackorders' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_BACKORDERS,
'_configMinQty' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_MIN_QTY,
'_configNotifyStockQty' => \Magento\CatalogInventory\Model\Configuration::XML_PATH_NOTIFY_STOCK_QTY,
];
foreach ($configMap as $field => $const) {
$this->{$field} = (int) $this->_scopeConfig->getValue(
$const,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
$this->_isConfig = true;
$this->_configTypeIds = array_keys($this->stockConfiguration->getIsQtyTypeIds(true));
}
}
/**
* Set items out of stock basing on their quantities and config settings
*
* @deprecated 100.2.5
* @see \Magento\CatalogInventory\Model\ResourceModel\Stock\Item::updateSetOutOfStock
* @param string|int $website
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @return void
*/
public function updateSetOutOfStock($website = null)
{
$websiteId = $this->stockConfiguration->getDefaultScopeId();
$this->_initConfig();
$connection = $this->getConnection();
$values = ['is_in_stock' => 0, 'stock_status_changed_auto' => 1];
$select = $connection->select()->from($this->getTable('catalog_product_entity'), 'entity_id')
->where('type_id IN(?)', $this->_configTypeIds);
$where = sprintf(
'website_id = %1$d' .
' AND is_in_stock = 1' .
' AND ((use_config_manage_stock = 1 AND 1 = %2$d) OR (use_config_manage_stock = 0 AND manage_stock = 1))' .
' AND ((use_config_backorders = 1 AND %3$d = %4$d) OR (use_config_backorders = 0 AND backorders = %3$d))' .
' AND ((use_config_min_qty = 1 AND qty <= %5$d) OR (use_config_min_qty = 0 AND qty <= min_qty))' .
' AND product_id IN (%6$s)',
$websiteId,
$this->_isConfigManageStock,
\Magento\CatalogInventory\Model\Stock::BACKORDERS_NO,
$this->_isConfigBackorders,
$this->_configMinQty,
$select->assemble()
);
$connection->update($this->getTable('cataloginventory_stock_item'), $values, $where);
}
/**
* Set items in stock basing on their quantities and config settings
*
* @deprecated 100.2.5
* @see \Magento\CatalogInventory\Model\ResourceModel\Stock\Item::updateSetInStock
* @param int|string $website
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @return void
*/
public function updateSetInStock($website)
{
$websiteId = $this->stockConfiguration->getDefaultScopeId();
$this->_initConfig();
$connection = $this->getConnection();
$values = ['is_in_stock' => 1];
$select = $connection->select()->from($this->getTable('catalog_product_entity'), 'entity_id')
->where('type_id IN(?)', $this->_configTypeIds);
$where = sprintf(
'website_id = %1$d' .
' AND is_in_stock = 0' .
' AND stock_status_changed_auto = 1' .
' AND ((use_config_manage_stock = 1 AND 1 = %2$d) OR (use_config_manage_stock = 0 AND manage_stock = 1))' .
' AND ((use_config_min_qty = 1 AND qty > %3$d) OR (use_config_min_qty = 0 AND qty > min_qty))' .
' AND product_id IN (%4$s)',
$websiteId,
$this->_isConfigManageStock,
$this->_configMinQty,
$select->assemble()
);
$connection->update($this->getTable('cataloginventory_stock_item'), $values, $where);
}
/**
* Update items low stock date basing on their quantities and config settings
*
* @deprecated 100.2.5
* @see \Magento\CatalogInventory\Model\ResourceModel\Stock\Item::updateLowStockDate
* @param int|string $website
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @return void
*/
public function updateLowStockDate($website)
{
$websiteId = $this->stockConfiguration->getDefaultScopeId();
$this->_initConfig();
$connection = $this->getConnection();
$condition = $connection->quoteInto(
'(use_config_notify_stock_qty = 1 AND qty < ?)',
$this->_configNotifyStockQty
) . ' OR (use_config_notify_stock_qty = 0 AND qty < notify_stock_qty)';
$currentDbTime = $connection->quoteInto('?', $this->dateTime->gmtDate());
$conditionalDate = $connection->getCheckSql($condition, $currentDbTime, 'NULL');
$value = ['low_stock_date' => new \Zend_Db_Expr($conditionalDate)];
$select = $connection->select()->from($this->getTable('catalog_product_entity'), 'entity_id')
->where('type_id IN(?)', $this->_configTypeIds);
$where = sprintf(
'website_id = %1$d' .
' AND ((use_config_manage_stock = 1 AND 1 = %2$d) OR (use_config_manage_stock = 0 AND manage_stock = 1))' .
' AND product_id IN (%3$s)',
$websiteId,
$this->_isConfigManageStock,
$select->assemble()
);
$connection->update($this->getTable('cataloginventory_stock_item'), $value, $where);
}
/**
* Add low stock filter to product collection
*
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
* @param array $fields
* @return $this
*/
public function addLowStockFilter(\Magento\Catalog\Model\ResourceModel\Product\Collection $collection, $fields)
{
$this->_initConfig();
$connection = $collection->getSelect()->getConnection();
$qtyIf = $connection->getCheckSql(
'invtr.use_config_notify_stock_qty > 0',
$this->_configNotifyStockQty,
'invtr.notify_stock_qty'
);
$conditions = [
[
$connection->prepareSqlCondition('invtr.use_config_manage_stock', 1),
$connection->prepareSqlCondition($this->_isConfigManageStock, 1),
$connection->prepareSqlCondition('invtr.qty', ['lt' => $qtyIf]),
],
[
$connection->prepareSqlCondition('invtr.use_config_manage_stock', 0),
$connection->prepareSqlCondition('invtr.manage_stock', 1)
],
];
$where = [];
foreach ($conditions as $k => $part) {
$where[$k] = join(' ' . \Magento\Framework\DB\Select::SQL_AND . ' ', $part);
}
$where = $connection->prepareSqlCondition(
'invtr.low_stock_date',
['notnull' => true]
) . ' ' . \Magento\Framework\DB\Select::SQL_AND . ' ((' . join(
') ' . \Magento\Framework\DB\Select::SQL_OR . ' (',
$where
) . '))';
$collection->joinTable(
['invtr' => 'cataloginventory_stock_item'],
'product_id = entity_id',
$fields,
$where
);
return $this;
}
}