Validate.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\InventoryShippingAdminUi\Controller\Adminhtml\SourceSelection;
  8. use Magento\Backend\App\Action;
  9. use Magento\Backend\App\Action\Context;
  10. use Magento\Framework\Controller\Result\JsonFactory;
  11. use Magento\Framework\DataObject;
  12. use Magento\Framework\Exception\LocalizedException;
  13. class Validate extends Action
  14. {
  15. /**
  16. * @see _isAllowed()
  17. */
  18. const ADMIN_RESOURCE = 'Magento_InventoryApi::source';
  19. /**
  20. * @var JsonFactory
  21. */
  22. private $resultJsonFactory;
  23. /**
  24. * @param Context $context
  25. * @param JsonFactory $resultJsonFactory
  26. */
  27. public function __construct(
  28. Context $context,
  29. JsonFactory $resultJsonFactory
  30. ) {
  31. $this->resultJsonFactory = $resultJsonFactory;
  32. parent::__construct($context);
  33. }
  34. /**
  35. * @inheritdoc
  36. */
  37. public function execute()
  38. {
  39. $response = new DataObject();
  40. $response->setError(false);
  41. $sourceCode = $this->getRequest()->getParam('sourceCode');
  42. $items = $this->getRequest()->getParam('items');
  43. //TODO: This is simple check. Need to create separate service and add additional checks:
  44. //TODO: 1. manage stock
  45. //TODO: 2. sum of all qty less on equal to source available qty (for products that occur twice or more in order)
  46. //TODO: 3. check total qty
  47. try {
  48. $itemsToShip = [];
  49. $totalQty = 0;
  50. foreach ($items as $item) {
  51. if (empty($item['sources'])) {
  52. continue;
  53. }
  54. foreach ($item['sources'] as $source) {
  55. if ($source['sourceCode'] == $sourceCode) {
  56. if ($item['isManageStock']) {
  57. $qtyToCompare = (float)$source['qtyAvailable'];
  58. } else {
  59. $qtyToCompare = (float)$item['qtyToShip'];
  60. }
  61. if ((float)$source['qtyToDeduct'] > $qtyToCompare) {
  62. throw new LocalizedException(
  63. __('Qty of %1 should be less or equal to %2', $item['sku'], $source['qtyAvailable'])
  64. );
  65. }
  66. $itemsToShip[$item['sku']] = ($itemsToShip[$item['sku']] ?? 0) + $source['qtyToDeduct'];
  67. $totalQty += $itemsToShip[$item['sku']];
  68. }
  69. }
  70. }
  71. if ($totalQty == 0) {
  72. throw new LocalizedException(
  73. __('You should select one or more items to ship.')
  74. );
  75. }
  76. } catch (LocalizedException $e) {
  77. $response->setError(true);
  78. $response->setMessages([$e->getMessage()]);
  79. }
  80. return $this->resultJsonFactory->create()->setData($response);
  81. }
  82. }