diff --git a/app/code/Magento/Inventory/Model/ResourceModel/SourceItem/DeleteMultiple.php b/app/code/Magento/Inventory/Model/ResourceModel/SourceItem/DeleteMultiple.php new file mode 100644 index 000000000000..f52f8f57491a --- /dev/null +++ b/app/code/Magento/Inventory/Model/ResourceModel/SourceItem/DeleteMultiple.php @@ -0,0 +1,59 @@ +resourceConnection = $resourceConnection; + } + + /** + * Multiple delete source items + * + * @param SourceItemInterface[] $sourceItems + * @return void + */ + public function execute(array $sourceItems) + { + if (!count($sourceItems)) { + return; + } + + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(SourceItemResourceModel::TABLE_NAME_SOURCE_ITEM); + + $skuList = []; + foreach ($sourceItems as $sourceItem) { + $skuList[] = $sourceItem->getSku(); + } + + $whereCond = [ + $connection->quoteInto(SourceItemInterface::SKU . ' IN(?)', array_unique($skuList)) + ]; + + $connection->delete($tableName, $whereCond); + } +} diff --git a/app/code/Magento/Inventory/Model/SourceItem/Command/SourceItemsDelete.php b/app/code/Magento/Inventory/Model/SourceItem/Command/SourceItemsDelete.php new file mode 100644 index 000000000000..d74ad888dfdb --- /dev/null +++ b/app/code/Magento/Inventory/Model/SourceItem/Command/SourceItemsDelete.php @@ -0,0 +1,58 @@ +deleteMultiple = $deleteMultiple; + $this->logger = $logger; + } + + /** + * @inheritdoc + */ + public function execute(array $sourceItems) + { + if (empty($sourceItems)) { + throw new InputException(__('Input data is empty')); + } + try { + $this->deleteMultiple->execute($sourceItems); + } catch (\Exception $e) { + $this->logger->error($e->getMessage()); + throw new CouldNotDeleteException(__('Could not delete Source Item'), $e); + } + } +} diff --git a/app/code/Magento/Inventory/Test/Integration/Model/ResourceModel/SourceItem/DeleteMultipleTest.php b/app/code/Magento/Inventory/Test/Integration/Model/ResourceModel/SourceItem/DeleteMultipleTest.php new file mode 100644 index 000000000000..c02de3f64756 --- /dev/null +++ b/app/code/Magento/Inventory/Test/Integration/Model/ResourceModel/SourceItem/DeleteMultipleTest.php @@ -0,0 +1,63 @@ +deleteModel = Bootstrap::getObjectManager()->create(DeleteMultiple::class); + $this->sourceItemRepository = Bootstrap::getObjectManager()->create(SourceItemRepositoryInterface::class); + $this->searchCriteriaBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + */ + public function testDeleteMultipleWithEmptySourceItems() + { + $expectedCount = count($this->getSourceItems()); + + $this->deleteModel->execute([]); + + $this->assertCount($expectedCount, $this->getSourceItems()); + } + + /** + * @return \Magento\InventoryApi\Api\Data\SourceItemInterface[] + */ + private function getSourceItems(): array + { + $searchCriteria = $this->searchCriteriaBuilder->create(); + return $this->sourceItemRepository->getList($searchCriteria)->getItems(); + } +} diff --git a/app/code/Magento/Inventory/etc/di.xml b/app/code/Magento/Inventory/etc/di.xml index cc3a20ee7a61..36dd518d251e 100644 --- a/app/code/Magento/Inventory/etc/di.xml +++ b/app/code/Magento/Inventory/etc/di.xml @@ -33,6 +33,7 @@ + diff --git a/app/code/Magento/InventoryApi/Api/SourceItemsDeleteInterface.php b/app/code/Magento/InventoryApi/Api/SourceItemsDeleteInterface.php new file mode 100644 index 000000000000..1b1157bffa90 --- /dev/null +++ b/app/code/Magento/InventoryApi/Api/SourceItemsDeleteInterface.php @@ -0,0 +1,29 @@ +" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/InventoryImportExport/LICENSE_AFL.txt b/app/code/Magento/InventoryImportExport/LICENSE_AFL.txt new file mode 100644 index 000000000000..f39d641b18a1 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/InventoryImportExport/Model/Export/AttributeCollectionProvider.php b/app/code/Magento/InventoryImportExport/Model/Export/AttributeCollectionProvider.php new file mode 100644 index 000000000000..a65e620515e2 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/AttributeCollectionProvider.php @@ -0,0 +1,87 @@ +collection = $collectionFactory->create(Collection::class); + $this->attributeFactory = $attributeFactory; + } + + /** + * @return Collection + * @throws \Exception + */ + public function get(): Collection + { + if (count($this->collection) === 0) { + /** @var \Magento\Eav\Model\Entity\Attribute $sourceIdAttribute */ + $sourceIdAttribute = $this->attributeFactory->create(); + $sourceIdAttribute->setId(SourceItemInterface::SOURCE_ID); + $sourceIdAttribute->setDefaultFrontendLabel(SourceItemInterface::SOURCE_ID); + $sourceIdAttribute->setAttributeCode(SourceItemInterface::SOURCE_ID); + $sourceIdAttribute->setBackendType('int'); + $this->collection->addItem($sourceIdAttribute); + + /** @var \Magento\Eav\Model\Entity\Attribute $skuAttribute */ + $skuAttribute = $this->attributeFactory->create(); + $skuAttribute->setId(SourceItemInterface::SKU); + $skuAttribute->setBackendType('varchar'); + $skuAttribute->setDefaultFrontendLabel(SourceItemInterface::SKU); + $skuAttribute->setAttributeCode(SourceItemInterface::SKU); + $this->collection->addItem($skuAttribute); + + /** @var \Magento\Eav\Model\Entity\Attribute $statusIdAttribute */ + $statusIdAttribute = $this->attributeFactory->create(); + $statusIdAttribute->setId(SourceItemInterface::STATUS); + $statusIdAttribute->setDefaultFrontendLabel(SourceItemInterface::STATUS); + $statusIdAttribute->setAttributeCode(SourceItemInterface::STATUS); + $statusIdAttribute->setBackendType('int'); + $statusIdAttribute->setFrontendInput('select'); + $statusIdAttribute->setSourceModel(StockStatus::class); + $this->collection->addItem($statusIdAttribute); + + /** @var \Magento\Eav\Model\Entity\Attribute $quantityAttribute */ + $quantityAttribute = $this->attributeFactory->create(); + $quantityAttribute->setId(SourceItemInterface::QUANTITY); + $quantityAttribute->setBackendType('decimal'); + $quantityAttribute->setDefaultFrontendLabel(SourceItemInterface::QUANTITY); + $quantityAttribute->setAttributeCode(SourceItemInterface::QUANTITY); + $this->collection->addItem($quantityAttribute); + } + + return $this->collection; + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/ColumnProvider.php b/app/code/Magento/InventoryImportExport/Model/Export/ColumnProvider.php new file mode 100644 index 000000000000..1592f80edabf --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/ColumnProvider.php @@ -0,0 +1,50 @@ +getItems() as $item) { + $columns[] = $item->getData('id'); + } + + if (!isset($filters[Export::FILTER_ELEMENT_SKIP])) { + return $columns; + } + + // remove the skipped from columns + $skippedAttributes = array_flip($filters[Export::FILTER_ELEMENT_SKIP]); + foreach ($columns as $key => $value) { + if (array_key_exists($value, $skippedAttributes) === true) { + unset($columns[$key]); + } + } + + return $columns; + } + + /** + * @inheritdoc + */ + public function getColumns(AttributeCollection $attributeCollection, array $filters): array + { + return $this->getHeaders($attributeCollection, $filters); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/ColumnProviderInterface.php b/app/code/Magento/InventoryImportExport/Model/Export/ColumnProviderInterface.php new file mode 100644 index 000000000000..864029e2c784 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/ColumnProviderInterface.php @@ -0,0 +1,33 @@ +addFieldToFilter($columnName, ['from' => $from]); + } + + if (is_numeric($to) && !empty($to)) { + $collection->addFieldToFilter($columnName, ['to' => $to]); + } + + return; + } + + $collection->addFieldToFilter($columnName, ['eq' => $value]); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/Filter/VarcharFilter.php b/app/code/Magento/InventoryImportExport/Model/Export/Filter/VarcharFilter.php new file mode 100644 index 000000000000..e23ad36639c9 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/Filter/VarcharFilter.php @@ -0,0 +1,27 @@ +addFieldToFilter($columnName, ['like' => '%' . $value . '%']); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/FilterProcessorAggregator.php b/app/code/Magento/InventoryImportExport/Model/Export/FilterProcessorAggregator.php new file mode 100644 index 000000000000..a7e999f4ef77 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/FilterProcessorAggregator.php @@ -0,0 +1,58 @@ + FilterProcessorInterface::class] + )); + } + } + + $this->handler = $handler; + } + + /** + * @param string $type + * @param Collection $collection + * @param string $columnName + * @param string|array $value + * @throws LocalizedException + */ + public function process($type, Collection $collection, $columnName, $value) + { + if (!isset($this->handler[$type])) { + throw new LocalizedException(__( + 'No filter processor for "%type" given.', + ['type' => $type] + )); + } + $this->handler[$type]->process($collection, $columnName, $value); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/FilterProcessorInterface.php b/app/code/Magento/InventoryImportExport/Model/Export/FilterProcessorInterface.php new file mode 100644 index 000000000000..a2081ede8441 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/FilterProcessorInterface.php @@ -0,0 +1,27 @@ +sourceItemStatus = $sourceItemStatus; + } + + /** + * Retrieve All options + * + * @return array + */ + public function getAllOptions() + { + return $this->sourceItemStatus->toOptionArray(); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/SourceItemCollectionFactory.php b/app/code/Magento/InventoryImportExport/Model/Export/SourceItemCollectionFactory.php new file mode 100644 index 000000000000..154b6ed4d1c6 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/SourceItemCollectionFactory.php @@ -0,0 +1,100 @@ +objectManager = $objectManager; + $this->filterProcessor = $filterProcessor; + $this->columnProvider = $columnProvider; + } + + /** + * @param AttributeCollection $attributeCollection + * @param array $filters + * @return Collection + * @throws LocalizedException + */ + public function create(AttributeCollection $attributeCollection, array $filters): Collection + { + /** @var Collection $collection */ + $collection = $this->objectManager->create(Collection::class); + $collection->addFieldToSelect($this->columnProvider->getColumns($attributeCollection, $filters)); + + foreach ($this->retrieveFilterData($filters) as $columnName => $value) { + $attributeDefinition = $attributeCollection->getItemById($columnName); + if (!$attributeDefinition) { + throw new LocalizedException(__( + 'Given column name "%columnName" is not present in collection.', + ['columnName' => $columnName] + )); + } + + $type = $attributeDefinition->getData('backend_type'); + if (!$type) { + throw new LocalizedException(__( + 'There is no backend type specified for column "%columnName".', + ['columnName' => $columnName] + )); + } + + $this->filterProcessor->process($type, $collection, $columnName, $value); + } + + return $collection; + } + + /** + * @param array $filters + * @return array + */ + private function retrieveFilterData(array $filters) + { + return array_filter( + $filters[Export::FILTER_ELEMENT_GROUP] ?? [], + function ($value) { + return $value !== ''; + } + ); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Export/SourceItemCollectionFactoryInterface.php b/app/code/Magento/InventoryImportExport/Model/Export/SourceItemCollectionFactoryInterface.php new file mode 100644 index 000000000000..a65bedfeb0e9 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Export/SourceItemCollectionFactoryInterface.php @@ -0,0 +1,27 @@ +attributeCollectionProvider = $attributeCollectionProvider; + $this->sourceItemCollectionFactory = $sourceItemCollectionFactory; + $this->columnProvider = $columnProvider; + parent::__construct($scopeConfig, $storeManager, $collectionFactory, $resourceColFactory, $data); + } + + /** + * @inheritdoc + * @throws \Exception + */ + public function getAttributeCollection() + { + return $this->attributeCollectionProvider->get(); + } + + /** + * @inheritdoc + * @throws Exception + */ + public function export() + { + $writer = $this->getWriter(); + $writer->setHeaderCols($this->_getHeaderColumns()); + + /** @var SourceItemCollection $collection */ + $collection = $this->sourceItemCollectionFactory->create( + $this->getAttributeCollection(), + $this->_parameters + ); + + foreach ($collection->getData() as $data) { + unset($data[SourceItem::ID_FIELD_NAME]); + $writer->writeRow($data); + } + + return $writer->getContents(); + } + + /** + * @inheritdoc + * @throws Exception + */ + protected function _getHeaderColumns() + { + return $this->columnProvider->getHeaders($this->getAttributeCollection(), $this->_parameters); + } + + /** + * @inheritdoc + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function exportItem($item) + { + // will not implement this method as it is legacy interface + } + + /** + * @inheritdoc + */ + public function getEntityTypeCode() + { + return 'stock_sources'; + } + + /** + * @inheritdoc + */ + protected function _getEntityCollection() + { + // will not implement this method as it is legacy interface + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Command/Append.php b/app/code/Magento/InventoryImportExport/Model/Import/Command/Append.php new file mode 100644 index 000000000000..48eec176810f --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Command/Append.php @@ -0,0 +1,48 @@ +sourceItemConvert = $sourceItemConvert; + $this->sourceItemsSave = $sourceItemsSave; + } + + /** + * @inheritdoc + */ + public function execute(array $bunch) + { + $sourceItems = $this->sourceItemConvert->convert($bunch); + $this->sourceItemsSave->execute($sourceItems); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Command/CommandInterface.php b/app/code/Magento/InventoryImportExport/Model/Import/Command/CommandInterface.php new file mode 100644 index 000000000000..7c53e7c42922 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Command/CommandInterface.php @@ -0,0 +1,24 @@ +sourceItemConvert = $sourceItemConvert; + $this->sourceItemsDelete = $sourceItemsDelete; + } + + /** + * @inheritdoc + */ + public function execute(array $bunch) + { + $sourceItems = $this->sourceItemConvert->convert($bunch); + $this->sourceItemsDelete->execute($sourceItems); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Command/Replace.php b/app/code/Magento/InventoryImportExport/Model/Import/Command/Replace.php new file mode 100644 index 000000000000..43f4fd8b519a --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Command/Replace.php @@ -0,0 +1,58 @@ +sourceItemConvert = $sourceItemConvert; + $this->sourceItemsSave = $sourceItemsSave; + $this->sourceItemsDelete = $sourceItemsDelete; + } + + /** + * @inheritdoc + */ + public function execute(array $bunch) + { + $sourceItems = $this->sourceItemConvert->convert($bunch); + $this->sourceItemsDelete->execute($sourceItems); + $this->sourceItemsSave->execute($sourceItems); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Serializer/Json.php b/app/code/Magento/InventoryImportExport/Model/Import/Serializer/Json.php new file mode 100644 index 000000000000..37bbae397a35 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Serializer/Json.php @@ -0,0 +1,83 @@ +serializer = $serializer; + } + + /** + * Encode the mixed $valueToEncode into the JSON format + * + * @deprecated 100.2.0 @see \Magento\Framework\Serialize\Serializer\Json + * @param mixed $valueToEncode + * @return string + * @throws \InvalidArgumentException + */ + public function jsonEncode($valueToEncode) + { + return $this->serialize($valueToEncode); + } + + /** + * Decodes the given $encodedValue string which is + * encoded in the JSON format + * + * @deprecated 100.2.0 @see \Magento\Framework\Serialize\Serializer\Json + * @param string $encodedValue + * @return mixed + * @throws \InvalidArgumentException + */ + public function jsonDecode($encodedValue) + { + return $this->unserialize($encodedValue); + } + + /** + * Serialize data into string + * + * @param string|int|float|bool|array|null $data + * @return string|bool + * @throws \InvalidArgumentException + * @since 100.2.0 + */ + public function serialize($data) + { + return $this->serializer->serialize($data); + } + + /** + * Unserialize the given string + * + * @param string $string + * @return string|int|float|bool|array|null + * @throws \InvalidArgumentException + * @since 100.2.0 + */ + public function unserialize($string) + { + return $this->serializer->unserialize($string); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/SourceItemConvert.php b/app/code/Magento/InventoryImportExport/Model/Import/SourceItemConvert.php new file mode 100644 index 000000000000..b00bbd23a80b --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/SourceItemConvert.php @@ -0,0 +1,54 @@ +sourceItemFactory = $sourceItemFactory; + } + + /** + * Converts a data in sourceItem list. + * @param array $bunch + * @return SourceItemInterface[] + */ + public function convert(array $bunch): array + { + $sourceItems = []; + foreach ($bunch as $rowData) { + /** @var SourceItemInterface $sourceItem */ + $sourceItem = $this->sourceItemFactory->create(); + $sourceItem->setSourceId($rowData[Sources::COL_SOURCE]); + $sourceItem->setSku($rowData[Sources::COL_SKU]); + $sourceItem->setQuantity($rowData[Sources::COL_QTY]); + + $status = (int)$rowData[Sources::COL_QTY] > 0; + if (isset($rowData[Sources::COL_STATUS])) { + $status = (int)$rowData[Sources::COL_STATUS]; + } + $sourceItem->setStatus($status); + + $sourceItems[] = $sourceItem; + } + + return $sourceItems; + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Sources.php b/app/code/Magento/InventoryImportExport/Model/Import/Sources.php new file mode 100644 index 000000000000..06e820ed76f0 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Sources.php @@ -0,0 +1,145 @@ +jsonHelper = $jsonHelper; + $this->errorAggregator = $errorAggregator; + $this->_resourceHelper = $resourceHelper; + $this->_importExportData = $dataHelper; + $this->_dataSourceModel = $importData; + $this->validator = $validator; + + foreach ($commands as $command) { + if (!$command instanceof CommandInterface) { + throw new LocalizedException( + __('Source Import Commands must implement %interface.', ['interface' => CommandInterface::class]) + ); + } + } + $this->commands = $commands; + } + + /** + * Import data rows. + * @return boolean + * @throws LocalizedException + */ + protected function _importData() + { + $command = $this->getCommandByBehavior($this->getBehavior()); + while ($bunch = $this->_dataSourceModel->getNextBunch()) { + $command->execute($bunch); + } + + return true; + } + + /** + * @param string $behavior + * @return CommandInterface + * @throws LocalizedException + */ + private function getCommandByBehavior($behavior) + { + if (!isset($this->commands[$behavior])) { + throw new LocalizedException( + __('There is no command registered for behavior "%behavior".', ['behavior' => $behavior]) + ); + } + + return $this->commands[$behavior]; + } + + /** + * EAV entity type code getter. + * + * @return string + */ + public function getEntityTypeCode() + { + return 'stock_sources'; + } + + /** + * Validate data row. + * + * @param array $rowData + * @param int $rowNum + * @return boolean + */ + public function validateRow(array $rowData, $rowNum) + { + $result = $this->validator->validate($rowData, $rowNum); + if ($result->isValid()) { + return true; + } + + foreach ($result->getErrors() as $error) { + $this->addRowError($error, $rowNum); + } + + return false; + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Validator/QtyValidator.php b/app/code/Magento/InventoryImportExport/Model/Import/Validator/QtyValidator.php new file mode 100644 index 000000000000..5a5ca3ee6881 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Validator/QtyValidator.php @@ -0,0 +1,46 @@ +validationResultFactory = $validationResultFactory; + } + + /** + * @inheritdoc + */ + public function validate(array $rowData, int $rowNumber) + { + $errors = []; + + if (!isset($rowData[Sources::COL_QTY])) { + $errors[] = __('Missing required column "%column"', ['column' => Sources::COL_QTY]); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Validator/SkuValidator.php b/app/code/Magento/InventoryImportExport/Model/Import/Validator/SkuValidator.php new file mode 100644 index 000000000000..db7c06d52ffb --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Validator/SkuValidator.php @@ -0,0 +1,46 @@ +validationResultFactory = $validationResultFactory; + } + + /** + * @inheritdoc + */ + public function validate(array $rowData, int $rowNumber) + { + $errors = []; + + if (!isset($rowData[Sources::COL_SKU])) { + $errors[] = __('Missing required column "%column"', ['column' => Sources::COL_SKU]); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Validator/SourceValidator.php b/app/code/Magento/InventoryImportExport/Model/Import/Validator/SourceValidator.php new file mode 100644 index 000000000000..94e6f3b8c9fb --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Validator/SourceValidator.php @@ -0,0 +1,87 @@ +validationResultFactory = $validationResultFactory; + $this->sourceRepository = $sourceRepository; + $this->loadSourceIds(); + } + + /** + * @inheritdoc + */ + public function validate(array $rowData, int $rowNumber) + { + $errors = []; + + if (!isset($rowData[Sources::COL_SOURCE])) { + $errors[] = __('Missing required column "%column"', ['column' => Sources::COL_SOURCE]); + } elseif (!$this->isExistingSource($rowData[Sources::COL_SOURCE])) { + $errors[] = __('Source id "%id" does not exists', ['id' => $rowData[Sources::COL_SOURCE]]); + } + + return $this->validationResultFactory->create(['errors' => $errors]); + } + + /** + * Returns exits already the source in sources. + * + * @param int $sourceId + * @return bool + */ + private function isExistingSource($sourceId): bool + { + return isset($this->sourceIds[$sourceId]); + } + + /** + * Loads all existing source ids + * + * @return void + */ + private function loadSourceIds() + { + $sources = $this->sourceRepository->getList(); + foreach ($sources->getItems() as $source) { + $sourceId = $source->getSourceId(); + $this->sourceIds[$sourceId] = $sourceId; + } + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Validator/ValidatorChain.php b/app/code/Magento/InventoryImportExport/Model/Import/Validator/ValidatorChain.php new file mode 100644 index 000000000000..595badc05b11 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Validator/ValidatorChain.php @@ -0,0 +1,66 @@ +validationResultFactory = $validationResultFactory; + + foreach ($validators as $validator) { + if (!$validator instanceof ValidatorInterface) { + throw new LocalizedException( + __('Row Validator must implement %interface.', ['interface' => ValidatorInterface::class]) + ); + } + } + $this->validators = $validators; + } + + /** + * @inheritdoc + */ + public function validate(array $rowData, int $rowNumber) + { + /* the inner empty array covers cases when no loops were made */ + $errors = [[]]; + foreach ($this->validators as $validator) { + $validationResult = $validator->validate($rowData, $rowNumber); + + if (!$validationResult->isValid()) { + $errors[] = $validationResult->getErrors(); + } + } + + return $this->validationResultFactory->create(['errors' => array_merge(...$errors)]); + } +} diff --git a/app/code/Magento/InventoryImportExport/Model/Import/Validator/ValidatorInterface.php b/app/code/Magento/InventoryImportExport/Model/Import/Validator/ValidatorInterface.php new file mode 100644 index 000000000000..b64c44d43ef2 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Model/Import/Validator/ValidatorInterface.php @@ -0,0 +1,25 @@ +getBootstrap()->getApplication()->getTempDir(); + $this->exportFilePath = implode(DIRECTORY_SEPARATOR, [ + $sandboxDir, + 'var', + uniqid('test-export_', false) . '.csv' + ]); + + $this->exporter = Bootstrap::getObjectManager()->create(Sources::class); + $this->exporter->setWriter(Bootstrap::getObjectManager()->create( + Csv::class, + ['destination' => $this->exportFilePath] + )); + } + + protected function tearDown() + { + unlink($this->exportFilePath); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testExportWithoutAnyFiltering() + { + $this->exporter->setParameters([]); + $this->exporter->export(); + + $this->assertEquals( + file_get_contents(implode(DIRECTORY_SEPARATOR, [__DIR__, '_files', 'export_full.csv'])), + file_get_contents($this->exportFilePath) + ); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testExportWithSkuFilter() + { + $this->exporter->setParameters([ + Export::FILTER_ELEMENT_GROUP => [ + 'sku' => 'SKU-1' + ] + ]); + $this->exporter->export(); + + $this->assertEquals( + file_get_contents(implode(DIRECTORY_SEPARATOR, [__DIR__, '_files', 'export_filtered_by_sku.csv'])), + file_get_contents($this->exportFilePath) + ); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testExportWithSkuFilterByLikeQuery() + { + $this->exporter->setParameters([ + Export::FILTER_ELEMENT_GROUP => [ + 'sku' => 'U-1' + ] + ]); + $this->exporter->export(); + + $this->assertEquals( + file_get_contents(implode(DIRECTORY_SEPARATOR, [__DIR__, '_files', 'export_filtered_by_sku.csv'])), + file_get_contents($this->exportFilePath) + ); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testExportWithSourceFilter() + { + $this->exporter->setParameters([ + Export::FILTER_ELEMENT_GROUP => [ + 'source_id' => [ + 22, + 62 + ] + ] + ]); + $this->exporter->export(); + + $this->assertEquals( + file_get_contents(implode(DIRECTORY_SEPARATOR, [__DIR__, '_files', 'export_filtered_by_source.csv'])), + file_get_contents($this->exportFilePath) + ); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testExportFilteredWithoutStatusColumn() + { + $this->exporter->setParameters([ + Export::FILTER_ELEMENT_GROUP => [ + 'sku' => 'SKU-1', + 'status' => 1 + ], + Export::FILTER_ELEMENT_SKIP => [ + 'status' + ] + ]); + $this->exporter->export(); + + $this->assertEquals( + file_get_contents(implode(DIRECTORY_SEPARATOR, [ + __DIR__, + '_files', + 'export_filtered_without_status_column.csv' + ])), + file_get_contents($this->exportFilePath) + ); + } +} diff --git a/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_by_sku.csv b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_by_sku.csv new file mode 100644 index 000000000000..449aeb78494e --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_by_sku.csv @@ -0,0 +1,5 @@ +source_id,sku,status,quantity +10,SKU-1,1,5.5000 +20,SKU-1,1,3.0000 +30,SKU-1,0,10.0000 +40,SKU-1,1,10.0000 diff --git a/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_by_source.csv b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_by_source.csv new file mode 100644 index 000000000000..752c4c8699a2 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_by_source.csv @@ -0,0 +1,4 @@ +source_id,sku,status,quantity +30,SKU-1,0,10.0000 +40,SKU-1,1,10.0000 +50,SKU-2,1,5.0000 diff --git a/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_without_status_column.csv b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_without_status_column.csv new file mode 100644 index 000000000000..89cb0643b37c --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_filtered_without_status_column.csv @@ -0,0 +1,4 @@ +source_id,sku,quantity +10,SKU-1,5.5000 +20,SKU-1,3.0000 +40,SKU-1,10.0000 diff --git a/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_full.csv b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_full.csv new file mode 100644 index 000000000000..aca33a8fff41 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Export/_files/export_full.csv @@ -0,0 +1,6 @@ +source_id,sku,status,quantity +10,SKU-1,1,5.5000 +20,SKU-1,1,3.0000 +30,SKU-1,0,10.0000 +40,SKU-1,1,10.0000 +50,SKU-2,1,5.0000 diff --git a/app/code/Magento/InventoryImportExport/Test/Integration/Model/Import/SourcesTest.php b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Import/SourcesTest.php new file mode 100644 index 000000000000..e8ed795b0dbf --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Test/Integration/Model/Import/SourcesTest.php @@ -0,0 +1,253 @@ +importDataMock = $this->getMockBuilder(ImportData::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->importer = Bootstrap::getObjectManager()->create(Sources::class, [ + 'importData' => $this->importDataMock + ]); + + $this->sourceItemRepository = Bootstrap::getObjectManager()->create(SourceItemRepositoryInterface::class); + $this->searchCriteriaBuilder = Bootstrap::getObjectManager()->create(SearchCriteriaBuilder::class); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + */ + public function testValidateRowExpectsInvalidRow() + { + $rowData = $this->buildRowDataArray(880, 'SKU-55', 33, 1); + $result = $this->importer->validateRow($rowData, 2); + $this->assertNotTrue($result, 'Expect result FALSE as given source ID is not present in database.'); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + */ + public function testValidateRowExpectsValidRow() + { + $rowData = $this->buildRowDataArray(20, 'SKU-55', 33, 1); + $result = $this->importer->validateRow($rowData, 2); + $this->assertTrue($result, 'Expect result TRUE as given data is valid.'); + } + + /** + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testImportDataWithWrongBehavior() + { + $this->importer->setParameters([ + 'behavior' => 'WrongBehavior' + ]); + + $bunch = [ + $this->buildRowDataArray(10, 'SKU-1', 6.88, 1) + ]; + $this->importDataMock->expects($this->any()) + ->method('getNextBunch') + ->will($this->onConsecutiveCalls($bunch, false)); + + $this->importer->importData(); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testImportDataWithAppendBehavior() + { + $this->importer->setParameters([ + 'behavior' => Import::BEHAVIOR_APPEND + ]); + + $searchCriteria = $this->searchCriteriaBuilder->create(); + $sourceItems = $this->sourceItemRepository->getList($searchCriteria); + $beforeImportData = $this->buildDataArray($sourceItems->getItems()); + + $bunch = [ + $this->buildRowDataArray(10, 'SKU-1', 6.8800, 1), + $this->buildRowDataArray(20, 'SKU-1', 5.0000, 1), + $this->buildRowDataArray(50, 'SKU-2', 15, 1), + $this->buildRowDataArray(10, 'SKU-2', 33, 1), + ]; + $this->importDataMock->expects($this->any()) + ->method('getNextBunch') + ->will($this->onConsecutiveCalls($bunch, false)); + + $this->importer->importData(); + + $sourceItems = $this->sourceItemRepository->getList($searchCriteria); + $expectedData = $this->updateDataArrayByBunch($beforeImportData, $bunch); + $afterImportData = $this->buildDataArray($sourceItems->getItems()); + + $this->assertEquals($expectedData, $afterImportData); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testImportDataWithDelteBehavior() + { + $this->importer->setParameters([ + 'behavior' => Import::BEHAVIOR_DELETE + ]); + + $searchCriteria = $this->searchCriteriaBuilder->create(); + + $bunch = [ + $this->buildRowDataArray(10, 'SKU-1', 6.88, 1), + $this->buildRowDataArray(20, 'SKU-1', 5, 1), + ]; + $this->importDataMock->expects($this->any()) + ->method('getNextBunch') + ->will($this->onConsecutiveCalls($bunch, false)); + + $this->importer->importData(); + + $sourceItems = $this->sourceItemRepository->getList($searchCriteria); + $afterImportData = $this->buildDataArray($sourceItems->getItems()); + + $this->assertArrayNotHasKey('10-SKU-1', $afterImportData); + $this->assertArrayNotHasKey('20-SKU-1', $afterImportData); + } + + /** + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/products.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/sources.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stocks.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/source_items.php + * @magentoDataFixture ../../../../app/code/Magento/InventoryApi/Test/_files/stock_source_link.php + */ + public function testImportDataWithReplaceBehavior() + { + /** @see \Magento\InventoryImportExport\Model\Import\Command\Replace::execute */ + $this->importer->setParameters([ + 'behavior' => Import::BEHAVIOR_REPLACE + ]); + + $bunch = [ + $this->buildRowDataArray(20, 'SKU-1', 5, 1), + $this->buildRowDataArray(50, 'SKU-2', 15, 1), + ]; + $this->importDataMock->expects($this->any()) + ->method('getNextBunch') + ->will($this->onConsecutiveCalls($bunch, false)); + + $this->importer->importData(); + + $searchCriteria = $this->searchCriteriaBuilder->create(); + + $sourceItems = $this->sourceItemRepository->getList($searchCriteria); + $afterImportData = $this->buildDataArray($sourceItems->getItems()); + + $this->assertArrayHasKey('20-SKU-1', $afterImportData); + $this->assertArrayHasKey('50-SKU-2', $afterImportData); + $this->assertCount(2, $afterImportData); + } + + /** + * @param int $sourceID + * @param string $sku + * @param int $qty + * @param int $status + * @return array + */ + private function buildRowDataArray($sourceID, $sku, $qty, $status) + { + return [ + Sources::COL_SOURCE => $sourceID, + Sources::COL_SKU => $sku, + Sources::COL_QTY => $qty, + Sources::COL_STATUS => $status, + ]; + } + + /** + * @param SourceItemInterface[] $sourceItems + * @return array + */ + private function buildDataArray(array $sourceItems) + { + $comparableArray = []; + foreach ($sourceItems as $sourceItem) { + $key = sprintf('%s-%s', $sourceItem->getSourceId(), $sourceItem->getSku()); + $comparableArray[$key] = $this->buildRowDataArray( + $sourceItem->getSourceId(), + $sourceItem->getSku(), + $sourceItem->getQuantity(), + $sourceItem->getStatus() + ); + } + return $comparableArray; + } + + /** + * @param array $data + * @param array $bunch + * @return array + */ + private function updateDataArrayByBunch(array $data, array $bunch) + { + foreach ($bunch as $bunchData) { + $key = sprintf('%s-%s', $bunchData[Sources::COL_SOURCE], $bunchData[Sources::COL_SKU]); + $data[$key] = $this->buildRowDataArray( + $bunchData[Sources::COL_SOURCE], + $bunchData[Sources::COL_SKU], + number_format($bunchData[Sources::COL_QTY], 4), + $bunchData[Sources::COL_STATUS] + ); + } + return $data; + } +} diff --git a/app/code/Magento/InventoryImportExport/Test/Unit/Model/ValidatorChainTest.php b/app/code/Magento/InventoryImportExport/Test/Unit/Model/ValidatorChainTest.php new file mode 100644 index 000000000000..8879965813fa --- /dev/null +++ b/app/code/Magento/InventoryImportExport/Test/Unit/Model/ValidatorChainTest.php @@ -0,0 +1,125 @@ +validationResultFactory = $this->getMockBuilder(ValidationResultFactory::class)->getMock(); + $this->qtyValidator = $this->getMockBuilder(ValidatorInterface::class)->getMock(); + $this->skuValidator = $this->getMockBuilder(ValidatorInterface::class)->getMock(); + } + + public function testValidateWithOutValidators() + { + $emptyValidatorResult = $this->createMock(\Magento\Framework\Validation\ValidationResult::class); + $this->validationResultFactory->expects($this->once()) + ->method('create') + ->with(['errors' =>[]]) + ->willReturn($emptyValidatorResult); + + $this->validatorChain = (new ObjectManager($this))->getObject( + ValidatorChain::class, + [ + 'validationResultFactory' => $this->validationResultFactory, + 'validators' => [] + ] + ); + + $result = $this->validatorChain->validate([], 1); + $this->assertEquals($emptyValidatorResult, $result); + } + + public function testValidateWithOutErros() + { + $emptyValidatorResult = $this->createMock(\Magento\Framework\Validation\ValidationResult::class); + $emptyValidatorResult->expects($this->once())->method('isValid') + ->willReturn(true); + + $this->validationResultFactory->expects($this->once()) + ->method('create') + ->with(['errors' => []]) + ->willReturn($emptyValidatorResult); + + $this->qtyValidator->method('validate') + ->willReturn($emptyValidatorResult); + + $this->validatorChain = (new ObjectManager($this))->getObject( + ValidatorChain::class, + [ + 'validationResultFactory' => $this->validationResultFactory, + 'validators' => [$this->qtyValidator] + ] + ); + + $result = $this->validatorChain->validate([], 1); + $this->assertEquals($emptyValidatorResult, $result); + } + + public function testValidateWithErros() + { + $validatorResult = $this->createMock(\Magento\Framework\Validation\ValidationResult::class); + + $validatorResult->expects($this->once())->method('isValid') + ->willReturn(false); + + $validatorResult->expects($this->once()) + ->method('getErrors') + ->willReturn(['Qty can not negative', 'Additional error']); + + $this->qtyValidator->expects($this->once())->method('validate') + ->willReturn($validatorResult); + + $this->validationResultFactory->expects($this->once()) + ->method('create') + ->with(['errors' => ['Qty can not negative', 'Additional error']]) + ->willReturn($validatorResult); + + $this->validatorChain = (new ObjectManager($this))->getObject( + ValidatorChain::class, + [ + 'validationResultFactory' => $this->validationResultFactory, + 'validators' => [$this->qtyValidator] + ] + ); + + $result = $this->validatorChain->validate([-1], 1); + $this->assertEquals($validatorResult, $result); + } +} diff --git a/app/code/Magento/InventoryImportExport/composer.json b/app/code/Magento/InventoryImportExport/composer.json new file mode 100644 index 000000000000..1f266a415fa6 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/composer.json @@ -0,0 +1,28 @@ +{ + "name": "magento/module-inventory-import-export", + "description": "N/A", + "require": { + "php": "7.0.2|7.0.4|~7.0.6|~7.1.0", + "magento/framework": "100.2.*", + "magento/module-inventory-api": "100.0.*", + "magento/module-backend": "100.2.*", + "magento/module-catalog": "100.2.*", + "magento/module-directory": "100.2.*", + "magento/module-shipping": "100.2.*", + "magento/module-ui": "100.2.*" + }, + "type": "magento2-module", + "version": "100.0.0-dev", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\InventoryImportExport\\": "" + } + } +} diff --git a/app/code/Magento/InventoryImportExport/etc/di.xml b/app/code/Magento/InventoryImportExport/etc/di.xml new file mode 100644 index 000000000000..9fca572cce16 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/etc/di.xml @@ -0,0 +1,44 @@ + + + + + + + + Magento\InventoryImportExport\Model\Import\Validator\SkuValidator + Magento\InventoryImportExport\Model\Import\Validator\SourceValidator + Magento\InventoryImportExport\Model\Import\Validator\QtyValidator + + + + + + Magento\InventoryImportExport\Model\Import\Serializer\Json + Magento\InventoryImportExport\Model\Import\Validator\ValidatorChain + + Magento\InventoryImportExport\Model\Import\Command\Delete + Magento\InventoryImportExport\Model\Import\Command\Append + Magento\InventoryImportExport\Model\Import\Command\Replace + + + + + + + + + + + Magento\InventoryImportExport\Model\Export\Filter\IntFilter + + Magento\InventoryImportExport\Model\Export\Filter\IntFilter + Magento\InventoryImportExport\Model\Export\Filter\VarcharFilter + + + + diff --git a/app/code/Magento/InventoryImportExport/etc/export.xml b/app/code/Magento/InventoryImportExport/etc/export.xml new file mode 100644 index 000000000000..da4f062e5c3f --- /dev/null +++ b/app/code/Magento/InventoryImportExport/etc/export.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/InventoryImportExport/etc/import.xml b/app/code/Magento/InventoryImportExport/etc/import.xml new file mode 100644 index 000000000000..283b4dce0a5b --- /dev/null +++ b/app/code/Magento/InventoryImportExport/etc/import.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/InventoryImportExport/etc/module.xml b/app/code/Magento/InventoryImportExport/etc/module.xml new file mode 100644 index 000000000000..56c03395b1d4 --- /dev/null +++ b/app/code/Magento/InventoryImportExport/etc/module.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/InventoryImportExport/registration.php b/app/code/Magento/InventoryImportExport/registration.php new file mode 100644 index 000000000000..9b2496816f1a --- /dev/null +++ b/app/code/Magento/InventoryImportExport/registration.php @@ -0,0 +1,11 @@ +