Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Validate.php
Go to the documentation of this file.
1 <?php
6 declare(strict_types=1);
7 
9 
15 
16 class Validate extends Action
17 {
21  const ADMIN_RESOURCE = 'Magento_InventoryApi::source';
22 
26  private $resultJsonFactory;
27 
32  public function __construct(
33  Context $context,
34  JsonFactory $resultJsonFactory
35  ) {
36  $this->resultJsonFactory = $resultJsonFactory;
37  parent::__construct($context);
38  }
39 
43  public function execute()
44  {
45  $response = new DataObject();
46  $response->setError(false);
47 
48  $sourceCode = $this->getRequest()->getParam('sourceCode');
49  $items = $this->getRequest()->getParam('items');
50 
51  //TODO: This is simple check. Need to create separate service and add additional checks:
52  //TODO: 1. manage stock
53  //TODO: 2. sum of all qty less on equal to source available qty (for products that occur twice or more in order)
54  //TODO: 3. check total qty
55  try {
56  $itemsToShip = [];
57  $totalQty = 0;
58  foreach ($items as $item) {
59  if (empty($item['sources'])) {
60  continue;
61  }
62  foreach ($item['sources'] as $source) {
63  if ($source['sourceCode'] == $sourceCode) {
64  if ($item['isManageStock']) {
65  $qtyToCompare = (float)$source['qtyAvailable'];
66  } else {
67  $qtyToCompare = (float)$item['qtyToShip'];
68  }
69  if ((float)$source['qtyToDeduct'] > $qtyToCompare) {
70  throw new LocalizedException(
71  __('Qty of %1 should be less or equal to %2', $item['sku'], $source['qtyAvailable'])
72  );
73  }
74  $itemsToShip[$item['sku']] = ($itemsToShip[$item['sku']] ?? 0) + $source['qtyToDeduct'];
75  $totalQty += $itemsToShip[$item['sku']];
76  }
77  }
78  }
79  if ($totalQty == 0) {
80  throw new LocalizedException(
81  __('You should select one or more items to ship.')
82  );
83  }
84  } catch (LocalizedException $e) {
85  $response->setError(true);
86  $response->setMessages([$e->getMessage()]);
87  }
88 
89  return $this->resultJsonFactory->create()->setData($response);
90  }
91 }
$response
Definition: 404.php:11
$source
Definition: source.php:23
__()
Definition: __.php:13
$sourceCode
Definition: inventory.phtml:11
__construct(Context $context, JsonFactory $resultJsonFactory)
Definition: Validate.php:32
$items