diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Console/Command/ImportGeoNamesCommand.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Console/Command/ImportGeoNamesCommand.php new file mode 100644 index 000000000000..879804c79615 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Console/Command/ImportGeoNamesCommand.php @@ -0,0 +1,81 @@ +importGeoNames = $importGeoNames; + } + + /** + * @inheritdoc + */ + protected function configure() + { + $this->setName('inventory-geonames:import') + ->setDescription('Download and import geo names for source selection algorithm') + ->setDefinition([ + new InputArgument( + self::COUNTRIES, + InputArgument::IS_ARRAY | InputArgument::REQUIRED, + 'List of country codes to import' + ) + ]); + + parent::configure(); + } + + /** + * @inheritdoc + */ + protected function execute(InputInterface $input, OutputInterface $output) + { + $countries = $input->getArgument(self::COUNTRIES); + + foreach ($countries as $country) { + $output->write('Importing ' . $country . ': '); + try { + $this->importGeoNames->execute($country); + $output->writeln('OK'); + } catch (\Exception $e) { + $output->writeln($e->getMessage()); + } + } + + $output->writeln('Done.'); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/LICENSE.txt b/app/code/Magento/InventoryDistanceBasedSourceSelection/LICENSE.txt new file mode 100644 index 000000000000..49525fd99da9 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software 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 Open Software 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, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software 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 (C) 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 "Open Software License" or "OSL" 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. \ No newline at end of file diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/LICENSE_AFL.txt b/app/code/Magento/InventoryDistanceBasedSourceSelection/LICENSE_AFL.txt new file mode 100644 index 000000000000..f39d641b18a1 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/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/InventoryDistanceBasedSourceSelection/Model/Algorithms/DistanceBasedAlgorithm.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Algorithms/DistanceBasedAlgorithm.php new file mode 100644 index 000000000000..9b833a9e4f6c --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Algorithms/DistanceBasedAlgorithm.php @@ -0,0 +1,124 @@ +getSourcesAssignedToStockOrderedByPriority = $getSourcesAssignedToStockOrderedByPriority; + $this->getDefaultSortedSourcesResult = $getDefaultSortedSourcesResult; + $this->getDistanceFromSourceToAddress = $getDistanceFromSourceToAddress; + } + + /** + * @inheritdoc + * @throws LocalizedException + */ + public function execute(InventoryRequestInterface $inventoryRequest): SourceSelectionResultInterface + { + $destinationAddress = $inventoryRequest->getExtensionAttributes()->getDestinationAddress(); + if ($destinationAddress === null) { + throw new LocalizedException(__('No destination address was provided in the request')); + } + + $stockId = $inventoryRequest->getStockId(); + $sortedSources = $this->getEnabledSourcesOrderedByDistanceByStockId( + $stockId, + $destinationAddress + ); + + return $this->getDefaultSortedSourcesResult->execute($inventoryRequest, $sortedSources); + } + + /** + * Get enabled sources ordered by priority by $stockId + * + * @param int $stockId + * @param AddressInterface $address + * @return array + * + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\LocalizedException + */ + private function getEnabledSourcesOrderedByDistanceByStockId( + int $stockId, + AddressInterface $address + ): array { + // We keep priority order as computational base + $sources = $this->getSourcesAssignedToStockOrderedByPriority->execute($stockId); + $sources = array_filter($sources, function (SourceInterface $source) { + return $source->isEnabled(); + }); + + $distanceBySourceCode = $sortSources = $sourcesWithoutDistance = []; + foreach ($sources as $source) { + try { + $distanceBySourceCode[$source->getSourceCode()] = $this->getDistanceFromSourceToAddress->execute( + $source, + $address + ); + $sortSources[] = $source; + } catch (LocalizedException $e) { + $sourcesWithoutDistance[] = $source; + } + } + + // Sort sources by distance + uasort( + $sortSources, + function (SourceInterface $a, SourceInterface $b) use ($distanceBySourceCode) { + $distanceFromA = $distanceBySourceCode[$a->getSourceCode()]; + $distanceFromB = $distanceBySourceCode[$b->getSourceCode()]; + + return ($distanceFromA < $distanceFromB) ? -1 : 1; + } + ); + + return array_merge($sortSources, $sourcesWithoutDistance); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToComponentsString.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToComponentsString.php new file mode 100644 index 000000000000..b03ad341edf3 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToComponentsString.php @@ -0,0 +1,28 @@ +getCountry(), +// 'postal_code:' . $address->getPostcode(), + 'locality:' . $address->getCity(), + ]); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToQueryString.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToQueryString.php new file mode 100644 index 000000000000..1ac5dd46a3ee --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToQueryString.php @@ -0,0 +1,27 @@ +getStreetAddress() . ', ' . + $address->getPostcode() . ' ' . + $address->getCity(); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToString.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToString.php new file mode 100644 index 000000000000..e6f5908e0f98 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/AddressToString.php @@ -0,0 +1,30 @@ +getStreetAddress(), + $address->getPostcode(), + $address->getCity(), + $address->getRegion(), + $address->getCountry(), + ]); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/LatLngToQueryString.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/LatLngToQueryString.php new file mode 100644 index 000000000000..a7e3ec929d01 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/Convert/LatLngToQueryString.php @@ -0,0 +1,24 @@ +getLat() . ',' . $latLng->getLng(); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GetDistanceFromSourceToAddress.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GetDistanceFromSourceToAddress.php new file mode 100644 index 000000000000..40aad7326a53 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GetDistanceFromSourceToAddress.php @@ -0,0 +1,66 @@ +getLatLngFromSource = $getLatLngFromSource; + $this->getLatLngFromAddress = $getLatLngFromAddress; + $this->getDistance = $getDistance; + } + + /** + * Get distance from source to address + * + * @param SourceInterface $source + * @param AddressInterface $address + * @return float + */ + public function execute(SourceInterface $source, AddressInterface $address): float + { + return $this->getDistance->execute( + $this->getLatLngFromSource->execute($source), + $this->getLatLngFromAddress->execute($address) + ); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GetLatLngFromSource.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GetLatLngFromSource.php new file mode 100644 index 000000000000..36539ffc38ca --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GetLatLngFromSource.php @@ -0,0 +1,78 @@ +addressInterfaceFactory = $addressInterfaceFactory; + $this->getLatLngFromAddress = $getLatLngFromAddress; + $this->latLngInterfaceFactory = $latLngInterfaceFactory; + } + + /** + * Get latitude and longitude from source + * + * @param SourceInterface $source + * @return LatLngInterface + */ + public function execute(SourceInterface $source): LatLngInterface + { + if (!$source->getLatitude() || !$source->getLongitude()) { + $sourceAddress = $this->addressInterfaceFactory->create([ + 'country' => $source->getCountryId() ?? '', + 'postcode' => $source->getPostcode() ?? '', + 'streetAddress' => $source->getStreet() ?? '', + 'region' => $source->getRegion() ?? '', + 'city' => $source->getCity() ?? '' + ]); + + return $this->getLatLngFromAddress->execute($sourceAddress); + } + + return $this->latLngInterfaceFactory->create([ + 'lat' => (float) $source->getLatitude(), + 'lng' => (float) $source->getLongitude() + ]); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetApiKey.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetApiKey.php new file mode 100644 index 000000000000..c2275c597404 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetApiKey.php @@ -0,0 +1,51 @@ +scopeConfig = $scopeConfig; + } + + /** + * Get distance between two points + * + * @return string + * @throws LocalizedException + */ + public function execute(): string + { + $apiKey = trim((string) $this->scopeConfig->getValue(self::XML_PATH_API_KEY)); + if (!$apiKey) { + throw new LocalizedException(__('Google API key is not defined')); + } + + return $apiKey; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetDistance.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetDistance.php new file mode 100644 index 000000000000..05468361a5c3 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetDistance.php @@ -0,0 +1,130 @@ +client = $client; + $this->json = $json; + $this->getApiKey = $getApiKey; + $this->scopeConfig = $scopeConfig; + $this->latLngToQueryString = $latLngToQueryString; + } + + /** + * @inheritdoc + * @throws LocalizedException + */ + public function execute(LatLngInterface $source, LatLngInterface $destination): float + { + $sourceString = $this->latLngToQueryString->execute($source); + $destinationString = $this->latLngToQueryString->execute($destination); + + $key = $sourceString . '|' . $destinationString; + + if (!isset($this->distanceCache[$key])) { + $queryString = http_build_query([ + 'key' => $this->getApiKey->execute(), + 'origins' => $sourceString, + 'destinations' => $destinationString, + 'mode' => $this->scopeConfig->getValue(self::XML_PATH_MODE), + ]); + + $this->client->get(self::GOOGLE_ENDPOINT . '?' . $queryString); + if ($this->client->getStatus() !== 200) { + throw new LocalizedException(__('Unable to connect google API for distance matrix')); + } + + $res = $this->json->unserialize($this->client->getBody()); + + if ($res['status'] !== 'OK' + || $res['rows'][0]['elements'][0]['status'] === self::ZERO_RESULT_RESPONSE + ) { + throw new LocalizedException( + __( + 'Unable to get distance between %1 and %2', + $sourceString, + $destinationString + ) + ); + } + + $element = $res['rows'][0]['elements'][0]; + + if ($this->scopeConfig->getValue(self::XML_PATH_VALUE) === 'time') { + $this->distanceCache[$key] = (float)$element['duration']['value']; + } else { + $this->distanceCache[$key] = (float)$element['distance']['value']; + } + } + + return $this->distanceCache[$key]; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetLatLngFromAddress.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetLatLngFromAddress.php new file mode 100644 index 000000000000..6b95c3b6674e --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/GoogleMap/GetLatLngFromAddress.php @@ -0,0 +1,132 @@ +client = $client; + $this->latLngInterfaceFactory = $latLngInterfaceFactory; + $this->json = $json; + $this->getApiKey = $getApiKey; + $this->addressToComponentsString = $addressToComponentsString; + $this->addressToString = $addressToString; + $this->addressToQueryString = $addressToQueryString; + } + + /** + * @inheritdoc + * @throws LocalizedException + */ + public function execute(AddressInterface $address): LatLngInterface + { + $cacheKey = $addressString = $this->addressToString->execute($address); + + if (!isset($this->latLngCache[$cacheKey])) { + $queryString = http_build_query([ + 'key' => $this->getApiKey->execute(), + 'components' => $this->addressToComponentsString->execute($address), + 'address' => $this->addressToQueryString->execute($address), + ]); + + $this->client->get(self::GOOGLE_ENDPOINT . '?' . $queryString); + if ($this->client->getStatus() !== 200) { + throw new LocalizedException(__('Unable to connect google API for geocoding')); + } + + $res = $this->json->unserialize($this->client->getBody()); + + if ($res['status'] !== 'OK') { + throw new LocalizedException(__('Unable to geocode address %1', $addressString)); + } + + $location = $res['results'][0]['geometry']['location']; + $this->latLngCache[$cacheKey] = $this->latLngInterfaceFactory->create([ + 'lat' => (float)$location['lat'], + 'lng' => (float)$location['lng'], + ]); + } + + return $this->latLngCache[$cacheKey]; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/Offline/GetDistance.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/Offline/GetDistance.php new file mode 100644 index 000000000000..d6fd23e2065a --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/Offline/GetDistance.php @@ -0,0 +1,39 @@ +getLat()); + $lonFrom = deg2rad($source->getLng()); + $latTo = deg2rad($destination->getLat()); + $lonTo = deg2rad($destination->getLng()); + + $latDelta = $latTo - $latFrom; + $lonDelta = $lonTo - $lonFrom; + + $angle = 2 * asin(sqrt((sin($latDelta / 2) ** 2) + + cos($latFrom) * cos($latTo) * (sin($lonDelta / 2) ** 2))); + + return $angle * (float) self::EARTH_RADIUS_KM; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/Offline/GetLatLngFromAddress.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/Offline/GetLatLngFromAddress.php new file mode 100644 index 000000000000..b875b31f30fe --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/DistanceProvider/Offline/GetLatLngFromAddress.php @@ -0,0 +1,76 @@ +getGeoNameDataByAddress = $getGeoNameDataByAddress; + $this->latLngInterfaceFactory = $latLngInterfaceFactory; + $this->addressToString = $addressToString; + } + + /** + * @inheritdoc + * @throws LocalizedException + */ + public function execute(AddressInterface $address): LatLngInterface + { + $cacheKey = $this->addressToString->execute($address); + if (!isset($this->latLngCache[$cacheKey])) { + $geoNameData = $this->getGeoNameDataByAddress->execute($address); + + $this->latLngCache[$cacheKey] = $this->latLngInterfaceFactory->create([ + 'lat' => (float)$geoNameData['latitude'], + 'lng' => (float)$geoNameData['longitude'], + ]); + } + + return $this->latLngCache[$cacheKey]; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/GetDistanceProviderCode.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/GetDistanceProviderCode.php new file mode 100644 index 000000000000..e3639c483564 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/GetDistanceProviderCode.php @@ -0,0 +1,44 @@ +scopeConfig = $scopeConfig; + } + + /** + * @inheritdoc + */ + public function execute(): string + { + return $this->scopeConfig->getValue(self::XML_PATH_DEFAULT_DISTANCE_PROVIDER); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ImportGeoNames.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ImportGeoNames.php new file mode 100644 index 000000000000..498e1fe72e9b --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ImportGeoNames.php @@ -0,0 +1,171 @@ +client = $client; + $this->file = $file; + $this->filesystem = $filesystem; + $this->updateGeoNames = $updateGeoNames; + $this->geoNamesBaseUrl = $geoNamesBaseUrl; + } + + /** + * Download a country + * + * @param string $countryCode + * @return string + * @throws \Magento\Framework\Exception\FileSystemException + */ + private function downloadCountry(string $countryCode): string + { + $countryZipFile = $this->geoNamesBaseUrl . $countryCode. '.zip'; + $this->client->get($countryZipFile); + + $varDir = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); + $exportPath = $varDir->getAbsolutePath('geonames'); + $this->file->mkdir($exportPath, 0770, true); + + $destinationFile = $exportPath . '/' . $countryCode. '.zip'; + $this->file->write($destinationFile, $this->client->getBody()); + + return $destinationFile; + } + + /** + * In memory extract ZIP file to string + * + * @param string $zipFile + * @param string $countryCode + * @return string + * @throws LocalizedException + */ + private function unpackZipFile(string $zipFile, string $countryCode): string + { + $zipArchive = new \ZipArchive(); + $res = $zipArchive->open($zipFile); + if ($res !== true) { + throw new LocalizedException(__('Cannot download country')); + } + + $resource = $zipArchive->getStream($countryCode . '.txt'); + + $contents = ''; + while (!feof($resource)) { + $contents .= fread($resource, 1024); + } + + return $contents; + } + + /** + * Import TSV file + * + * @param string $tsvContent + * @param string $countryCode + * @return int + */ + private function importTsv(string $tsvContent, string $countryCode): int + { + $lines = preg_split('/[\r\n]+/', $tsvContent); + + $geoNames = []; + foreach ($lines as $line) { + $parts = explode("\t", $line); + if (count($parts) < 10) { + continue; + } + + $geoNames[] = [ + 'country_code' => $countryCode, + 'postcode' => $parts[1], + 'city' => $parts[2], + 'region' => $parts[3], + 'province' => $parts[6], + 'latitude' => (float) $parts[9], + 'longitude' => (float) $parts[10], + ]; + } + + $this->updateGeoNames->execute($geoNames, $countryCode); + return count($geoNames); + } + + /** + * Import geonames and return the amount of items + * + * @param string $countryCode + * @return int + * @throws LocalizedException + * @throws \Magento\Framework\Exception\FileSystemException + */ + public function execute(string $countryCode): int + { + $countryCode = strtoupper(preg_replace('/\W/', '', $countryCode)); + if (!$countryCode) { + throw new LocalizedException(__('Undefined country code')); + } + + $zipFile = $this->downloadCountry($countryCode); + $tsvFile = $this->unpackZipFile($zipFile, $countryCode); + + return $this->importTsv($tsvFile, $countryCode); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/LatLng.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/LatLng.php new file mode 100644 index 000000000000..86755b27e11c --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/LatLng.php @@ -0,0 +1,54 @@ +lat = $lat; + $this->lng = $lng; + } + + /** + * @inheritdoc + */ + public function getLat(): float + { + return $this->lat; + } + + /** + * @inheritdoc + */ + public function getLng(): float + { + return $this->lng; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ResourceModel/GetGeoNameDataByAddress.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ResourceModel/GetGeoNameDataByAddress.php new file mode 100644 index 000000000000..66b310200fe5 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ResourceModel/GetGeoNameDataByAddress.php @@ -0,0 +1,88 @@ +resourceConnection = $resourceConnection; + $this->addressToString = $addressToString; + } + + /** + * Return geonames information using a fallback mechanism + * + * @param AddressInterface $address + * @return array + * @throws NoSuchEntityException + */ + public function execute(AddressInterface $address): array + { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName('inventory_geoname'); + + $qry = $connection->select()->from($tableName) + ->where('country_code = ?', $address->getCountry()) + ->where('postcode = ?', $address->getPostcode()) + ->limit(1); + + $row = $connection->fetchRow($qry); + if (!$row) { + $qry = $connection->select()->from($tableName) + ->where('country_code = ?', $address->getCountry()) + ->where('city = ?', $address->getCity()) + ->limit(1); + + $row = $connection->fetchRow($qry); + } + + if (!$row) { + $qry = $connection->select()->from($tableName) + ->where('country_code = ?', $address->getCountry()) + ->where('region = ?', $address->getRegion()) + ->limit(1); + + $row = $connection->fetchRow($qry); + } + + if (!$row) { + throw new NoSuchEntityException( + __('Unknown geoname for %1', $this->addressToString->execute($address)) + ); + } + + return $row; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ResourceModel/UpdateGeoNames.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ResourceModel/UpdateGeoNames.php new file mode 100644 index 000000000000..fabc2c852c24 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Model/ResourceModel/UpdateGeoNames.php @@ -0,0 +1,47 @@ +resourceConnection = $resourceConnection; + } + + /** + * Update country geo names + * + * @param array $geoNames + * @param string $countryCode + */ + public function execute(array $geoNames, string $countryCode): void + { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName('inventory_geoname'); + + $connection->beginTransaction(); + $connection->delete($tableName, $connection->quoteInto('country_code = ?', $countryCode)); + $connection->insertMultiple($tableName, $geoNames); + $connection->commit(); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/Plugin/FillSourceLatitudeAndLongitude.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/Plugin/FillSourceLatitudeAndLongitude.php new file mode 100644 index 000000000000..ffbda77eb729 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/Plugin/FillSourceLatitudeAndLongitude.php @@ -0,0 +1,63 @@ +getLatLngFromSource = $getLatLngFromSource; + } + + /** + * Calculate latitude and longitude using google map if api key is defined + * + * @param SourceRepositoryInterface $subject + * @param SourceInterface $source + * @return array + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function beforeSave( + SourceRepositoryInterface $subject, + SourceInterface $source + ): array { + if (!$source->getLatitude() && !$source->getLongitude()) { + try { + $latLng = $this->getLatLngFromSource->execute($source); + + $source->setLatitude($latLng->getLat()); + $source->setLongitude($latLng->getLng()); + } catch (\Exception $e) { + unset($e); // Silently fail geo coding + } + } + + return [$source]; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/README.md b/app/code/Magento/InventoryDistanceBasedSourceSelection/README.md new file mode 100644 index 000000000000..4b87af183267 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/README.md @@ -0,0 +1,16 @@ +# InventoryDistanceBasedSourceSelection module + +The `InventoryDistanceBasedSourceSelection` module implements logic for distance based source selection + +This module is part of the new inventory infrastructure. The +[Inventory Management overview](https://devdocs.magento.com/guides/v2.3/inventory/index.html) +describes the MSI (Multi-Source Inventory) project in more detail. + +## Installation details + +This module is installed as part of Magento Open Source. + +## Extension points and service contracts + +All public interfaces related to this module are located in the `InventoryDistanceBasedSourceSelectionApi` module. +Use the interfaces defined in `InventoryDistanceBasedSourceSelectionApi` to extend this module. diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/composer.json b/app/code/Magento/InventoryDistanceBasedSourceSelection/composer.json new file mode 100644 index 000000000000..75238bb167a0 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/composer.json @@ -0,0 +1,25 @@ +{ + "name": "magento/module-inventory-distance-based-source-selection", + "description": "N/A", + "require": { + "php": "~7.1.3||~7.2.0", + "magento/framework": "*", + "magento/module-inventory-distance-based-source-selection-api": "*", + "magento/module-inventory-source-selection-api": "*", + "magento/module-inventory-api": "*", + "magento/module-config": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\InventoryDistanceBasedSourceSelection\\": "" + } + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/config.xml b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/config.xml new file mode 100644 index 000000000000..502d642dfc9c --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/config.xml @@ -0,0 +1,22 @@ + + + + + + + google + + + driving + distance + + + + + diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/db_schema.xml b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/db_schema.xml new file mode 100644 index 000000000000..aada1c01836a --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/db_schema.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + +
+
diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/db_schema_whitelist.json b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/db_schema_whitelist.json new file mode 100644 index 000000000000..f6abc16afada --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/db_schema_whitelist.json @@ -0,0 +1,14 @@ +{ + "inventory_geoname": { + "column": { + "country_code": true, + "zip_code": true, + "city": true, + "region": true, + "province": true, + "latitude": true, + "longitude": true, + "postcode": true + } + } +} \ No newline at end of file diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/di.xml b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/di.xml new file mode 100644 index 000000000000..62afa6d97a53 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/di.xml @@ -0,0 +1,82 @@ + + + + + + + + + + Magento\InventoryDistanceBasedSourceSelection\Model\Algorithms\DistanceBasedAlgorithm + + + + + + + + + distance + Distance Priority + Algorithm which provides Source Selections based on shipping address distance from the source + + + + + + + + + Magento\InventoryDistanceBasedSourceSelection\Model\DistanceProvider\GoogleMap\GetDistance + Magento\InventoryDistanceBasedSourceSelection\Model\DistanceProvider\Offline\GetDistance + + + + + + + Magento\InventoryDistanceBasedSourceSelection\Model\DistanceProvider\GoogleMap\GetLatLngFromAddress + Magento\InventoryDistanceBasedSourceSelection\Model\DistanceProvider\Offline\GetLatLngFromAddress + + + + + + + + + + + + 1 + + + 1 + + + + + + + http://download.geonames.org/export/zip/ + + + + + + + Magento\InventoryDistanceBasedSourceSelection\Console\Command\ImportGeoNamesCommand + + + + diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/module.xml b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/module.xml new file mode 100644 index 000000000000..66e06b486b13 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/etc/module.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelection/registration.php b/app/code/Magento/InventoryDistanceBasedSourceSelection/registration.php new file mode 100644 index 000000000000..8dbb10b56dcb --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelection/registration.php @@ -0,0 +1,12 @@ +" 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/InventoryDistanceBasedSourceSelectionAdminUi/LICENSE_AFL.txt b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/LICENSE_AFL.txt new file mode 100644 index 000000000000..f39d641b18a1 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/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/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/DistanceProvider.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/DistanceProvider.php new file mode 100644 index 000000000000..2e96eb44a935 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/DistanceProvider.php @@ -0,0 +1,65 @@ +distanceProviderDescriptions = $distanceProviderDescriptions; + } + + /** + * Options getter + * + * @return array + */ + public function toOptionArray() + { + $res = []; + foreach ($this->distanceProviderDescriptions as $code => $description) { + $res [] = [ + 'value' => $code, + 'label' => $description + ]; + } + + return $res; + } + + /** + * Get options in "key-value" format + * + * @return array + */ + public function toArray() + { + $options = $this->toOptionArray(); + $return = []; + + foreach ($options as $option) { + $return[$option['value']] = $option['label']; + } + + return $return; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/GoogleDistanceProvider/Mode.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/GoogleDistanceProvider/Mode.php new file mode 100644 index 000000000000..f56ae3cf2239 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/GoogleDistanceProvider/Mode.php @@ -0,0 +1,48 @@ + self::MODE_DRIVING, 'label' => __('Driving')], + ['value' => self::MODE_WALKING, 'label' => __('Walking')], + ['value' => self::MODE_BICYCLING, 'label' => __('Bicycling')] + ]; + } + + /** + * Get options in "key-value" format + * + * @return array + */ + public function toArray() + { + $options = $this->toOptionArray(); + $return = []; + + foreach ($options as $option) { + $return[$option['value']] = $option['label']; + } + + return $return; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/GoogleDistanceProvider/Value.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/GoogleDistanceProvider/Value.php new file mode 100644 index 000000000000..692fc2add084 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/Model/Config/Source/GoogleDistanceProvider/Value.php @@ -0,0 +1,46 @@ + self::MODE_DISTANCE, 'label' => __('Distance')], + ['value' => self::MODE_TIME, 'label' => __('Time to destination')], + ]; + } + + /** + * Get options in "key-value" format + * + * @return array + */ + public function toArray() + { + $options = $this->toOptionArray(); + $return = []; + + foreach ($options as $option) { + $return[$option['value']] = $option['label']; + } + + return $return; + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/README.md b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/README.md new file mode 100644 index 000000000000..7a81830e093b --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/README.md @@ -0,0 +1,16 @@ +# InventoryDistanceBasedSourceSelectionAdminUi module + +The `InventoryDistanceBasedSourceSelectionAdminUi` module extends Magento's admin UI with source selection based on distance functionality. + +This module is part of the new inventory infrastructure. The +[Inventory Management overview](https://devdocs.magento.com/guides/v2.3/inventory/index.html) +describes the MSI (Multi-Source Inventory) project in more detail. + +## Installation details + +This module is installed as part of Magento Open Source. It may be disabled if the Inventory Management UI +is provided by a 3rd-party system or if you run a headless version of Magento. + +## Extension points and service contracts + +There are no extension points or service contracts for this module. diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/composer.json b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/composer.json new file mode 100644 index 000000000000..46f7b3ce2b89 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/composer.json @@ -0,0 +1,21 @@ +{ + "name": "magento/module-inventory-distance-based-source-selection-admin-ui", + "description": "N/A", + "require": { + "php": "~7.1.3||~7.2.0", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\InventoryDistanceBasedSourceSelectionAdminUi\\": "" + } + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/adminhtml/di.xml b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/adminhtml/di.xml new file mode 100644 index 000000000000..c0b8b5ad766e --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/adminhtml/di.xml @@ -0,0 +1,19 @@ + + + + + + + + Google MAP + Offline calculation + + + + diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/adminhtml/system.xml b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/adminhtml/system.xml new file mode 100755 index 000000000000..795b3e5519e0 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/adminhtml/system.xml @@ -0,0 +1,44 @@ + + + + + +
+ + + + + Magento\InventoryDistanceBasedSourceSelectionAdminUi\Model\Config\Source\DistanceProvider + + + + + + + Geocoding API and Distance Matrix API must enabled in your Google API key to support this feature. + + + Magento\InventoryDistanceBasedSourceSelectionAdminUi\Model\Config\Source\GoogleDistanceProvider\Mode + + + + Magento\InventoryDistanceBasedSourceSelectionAdminUi\Model\Config\Source\GoogleDistanceProvider\Value + + + + +
+
+
diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/module.xml b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/module.xml new file mode 100644 index 000000000000..bf4528632f1b --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/etc/module.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/registration.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/registration.php new file mode 100644 index 000000000000..401f7a93aa52 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionAdminUi/registration.php @@ -0,0 +1,12 @@ +" 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/InventoryDistanceBasedSourceSelectionApi/LICENSE_AFL.txt b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/LICENSE_AFL.txt new file mode 100644 index 000000000000..f39d641b18a1 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/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/InventoryDistanceBasedSourceSelectionApi/Model/GetDistance.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/Model/GetDistance.php new file mode 100644 index 000000000000..843310711f32 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/Model/GetDistance.php @@ -0,0 +1,70 @@ + $provider) { + if (!($provider instanceof GetDistanceInterface)) { + throw new \InvalidArgumentException( + 'LatLng provider ' . $providerCode . ' must implement ' . GetDistanceInterface::class + ); + } + } + + $this->providers = $providers; + $this->getDistanceProviderCode = $getDistanceProviderCode; + } + + /** + * @inheritdoc + * @throws NoSuchDistanceProviderException + */ + public function execute(LatLngInterface $source, LatLngInterface $destination): float + { + $code = $this->getDistanceProviderCode->execute(); + if (!isset($this->providers[$code])) { + throw new NoSuchDistanceProviderException( + __('No such distance provider: %1', $code) + ); + } + + return $this->providers[$code]->execute($source, $destination); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/Model/GetLatLngFromAddress.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/Model/GetLatLngFromAddress.php new file mode 100644 index 000000000000..185189b0ea96 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/Model/GetLatLngFromAddress.php @@ -0,0 +1,71 @@ + $provider) { + if (!($provider instanceof GetLatLngFromAddressInterface)) { + throw new \InvalidArgumentException( + 'LatLng provider ' . $providerCode . ' must implement ' . GetLatLngFromAddressInterface::class + ); + } + } + + $this->providers = $providers; + $this->getDistanceProviderCode = $getDistanceProviderCode; + } + + /** + * @inheritdoc + * @throws NoSuchLatLngFromAddressProviderException + */ + public function execute(AddressInterface $address): LatLngInterface + { + $code = $this->getDistanceProviderCode->execute(); + if (!isset($this->providers[$code])) { + throw new NoSuchLatLngFromAddressProviderException( + __('No such latitude and longitude from address provider: %1', $code) + ); + } + + return $this->providers[$code]->execute($address); + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/README.md b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/README.md new file mode 100644 index 000000000000..e9d085896154 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/README.md @@ -0,0 +1,24 @@ +# InventoryDistanceBasedSourceSelectionApi module + +The `InventoryDistanceBasedSourceSelectionApi` module provides service contracts for distance based source selection algorithm. + +This module is part of the new inventory infrastructure. The +[Inventory Management overview](https://devdocs.magento.com/guides/v2.3/inventory/index.html) +describes the MSI (Multi-Source Inventory) project in more detail. + +## Installation details + +This module is installed as part of Magento Open Source. + +## Extensibility + +The `InventoryDistanceBasedSourceSelectionApi` module contains extension points and APIs that 3rd-party developers +can use to provide custom distance based source selection algorithms. + +### Public APIs + +Public APIs are defined in the `Api` and `Api/Data` directories. + +### REST endpoints + +The `etc/webapi.xml` file defines endpoints for managing distance based algorithms. diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/composer.json b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/composer.json new file mode 100644 index 000000000000..fe027de3d297 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/composer.json @@ -0,0 +1,22 @@ +{ + "name": "magento/module-inventory-distance-based-source-selection-api", + "description": "N/A", + "require": { + "php": "~7.1.3||~7.2.0", + "magento/framework": "*", + "magento/module-inventory-source-selection-api": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\InventoryDistanceBasedSourceSelectionApi\\": "" + } + } +} diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/di.xml b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/di.xml new file mode 100644 index 000000000000..071dc4f3cabf --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/di.xml @@ -0,0 +1,15 @@ + + + + + + + diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/module.xml b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/module.xml new file mode 100644 index 000000000000..c44438af7b00 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/module.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/webapi.xml b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/webapi.xml new file mode 100644 index 000000000000..a7ace0b66fd0 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/etc/webapi.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/registration.php b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/registration.php new file mode 100644 index 000000000000..280350dc59e6 --- /dev/null +++ b/app/code/Magento/InventoryDistanceBasedSourceSelectionApi/registration.php @@ -0,0 +1,12 @@ +itemRequestFactory = $itemRequestFactory; - $this->inventoryRequestFactory = $inventoryRequestFactory; - $this->stockByWebsiteIdResolver = $stockByWebsiteIdResolver; $this->getDefaultSourceSelectionAlgorithmCode = $getDefaultSourceSelectionAlgorithmCode; $this->sourceSelectionService = $sourceSelectionService; $this->getSkuFromOrderItem = $getSkuFromOrderItem; + $this->getInventoryRequestFromOrder = $getInventoryRequestFromOrder ?: + ObjectManager::getInstance()->get(GetInventoryRequestFromOrder::class); } /** + * Get source selection result from invoice + * * @param InvoiceInterface $invoice * @return SourceSelectionResultInterface */ public function execute(InvoiceInterface $invoice): SourceSelectionResultInterface { + /** @var OrderInterface $order */ $order = $invoice->getOrder(); - $websiteId = $order->getStore()->getWebsiteId(); - $stockId = (int)$this->stockByWebsiteIdResolver->execute((int)$websiteId)->getStockId(); - - /** @var InventoryRequestInterface $inventoryRequest */ - $inventoryRequest = $this->inventoryRequestFactory->create([ - 'stockId' => $stockId, - 'items' => $this->getSelectionRequestItems($invoice->getItems()) - ]); + $inventoryRequest = $this->getInventoryRequestFromOrder->execute( + (int) $order->getEntityId(), + $this->getSelectionRequestItems($invoice->getItems()) + ); $selectionAlgorithmCode = $this->getDefaultSourceSelectionAlgorithmCode->execute(); return $this->sourceSelectionService->execute($inventoryRequest, $selectionAlgorithmCode); } /** - * @param InvoiceItemInterface[]|iterable $invoiceItems + * Get selection request items + * + * @param InvoiceItemInterface[]|Traversable $invoiceItems * @return array */ private function getSelectionRequestItems(iterable $invoiceItems): array @@ -126,16 +127,18 @@ private function getSelectionRequestItems(iterable $invoiceItems): array } /** + * Cast qty value + * * @param OrderItemInterface $item * @param string|int|float $qty - * @return float|int + * @return float */ - private function castQty(OrderItemInterface $item, $qty) + private function castQty(OrderItemInterface $item, $qty): float { if ($item->getIsQtyDecimal()) { - $qty = (double)$qty; + $qty = (float) $qty; } else { - $qty = (int)$qty; + $qty = (int) $qty; } return $qty > 0 ? $qty : 0; diff --git a/app/code/Magento/InventoryShipping/etc/db_schema.xml b/app/code/Magento/InventoryShipping/etc/db_schema.xml index ee67213b69ae..addcdf2b6d21 100644 --- a/app/code/Magento/InventoryShipping/etc/db_schema.xml +++ b/app/code/Magento/InventoryShipping/etc/db_schema.xml @@ -8,8 +8,8 @@ - - + + diff --git a/app/code/Magento/InventoryShipping/etc/di.xml b/app/code/Magento/InventoryShipping/etc/di.xml index d19203b41a40..bf575600c911 100644 --- a/app/code/Magento/InventoryShipping/etc/di.xml +++ b/app/code/Magento/InventoryShipping/etc/di.xml @@ -21,6 +21,14 @@ + + + + + + + + diff --git a/app/code/Magento/InventoryShippingAdminUi/Controller/Adminhtml/SourceSelection/ProcessAlgorithm.php b/app/code/Magento/InventoryShippingAdminUi/Controller/Adminhtml/SourceSelection/ProcessAlgorithm.php index ee832fd338b8..43f1b12ca80a 100644 --- a/app/code/Magento/InventoryShippingAdminUi/Controller/Adminhtml/SourceSelection/ProcessAlgorithm.php +++ b/app/code/Magento/InventoryShippingAdminUi/Controller/Adminhtml/SourceSelection/ProcessAlgorithm.php @@ -10,40 +10,28 @@ use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Backend\Model\View\Result\Page; +use Magento\Framework\App\Action\HttpPostActionInterface; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; -use Magento\InventorySalesApi\Model\StockByWebsiteIdResolverInterface; -use Magento\InventorySourceSelectionApi\Api\Data\ItemRequestInterfaceFactory; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\InventorySourceSelectionApi\Api\Data\InventoryRequestInterfaceFactory; +use Magento\InventorySourceSelectionApi\Api\Data\ItemRequestInterfaceFactory; use Magento\InventorySourceSelectionApi\Api\SourceSelectionServiceInterface; use Magento\InventorySourceSelectionApi\Api\GetDefaultSourceSelectionAlgorithmCodeInterface; use Magento\InventoryApi\Api\SourceRepositoryInterface; +use Magento\InventorySourceSelectionApi\Model\GetInventoryRequestFromOrder; /** * ProcessAlgorithm Controller */ -class ProcessAlgorithm extends Action +class ProcessAlgorithm extends Action implements HttpPostActionInterface { /** * @see _isAllowed() */ const ADMIN_RESOURCE = 'Magento_InventoryApi::source'; - /** - * @var StockByWebsiteIdResolverInterface - */ - private $stockByWebsiteIdResolver; - - /** - * @var ItemRequestInterfaceFactory - */ - private $itemRequestFactory; - - /** - * @var InventoryRequestInterfaceFactory - */ - private $inventoryRequestFactory; - /** * @var SourceSelectionServiceInterface */ @@ -59,40 +47,75 @@ class ProcessAlgorithm extends Action */ private $sourceRepository; + /** + * @var ItemRequestInterfaceFactory + */ + private $itemRequestFactory; + /** * @var array */ private $sources = []; /** + * @var GetInventoryRequestFromOrder + */ + private $getInventoryRequestFromOrder; + + /** + * ProcessAlgorithm constructor. + * * @param Context $context - * @param StockByWebsiteIdResolverInterface $stockByWebsiteIdResolver + * @param null $stockByWebsiteIdResolver @deprecated * @param ItemRequestInterfaceFactory $itemRequestFactory - * @param InventoryRequestInterfaceFactory $inventoryRequestFactory + * @param null $inventoryRequestFactory @deprecated * @param SourceSelectionServiceInterface $sourceSelectionService * @param GetDefaultSourceSelectionAlgorithmCodeInterface $getDefaultSourceSelectionAlgorithmCode * @param SourceRepositoryInterface $sourceRepository + * @param GetInventoryRequestFromOrder|null $getInventoryRequestFromOrder + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __construct( Context $context, - StockByWebsiteIdResolverInterface $stockByWebsiteIdResolver, + $stockByWebsiteIdResolver, ItemRequestInterfaceFactory $itemRequestFactory, - InventoryRequestInterfaceFactory $inventoryRequestFactory, + $inventoryRequestFactory, SourceSelectionServiceInterface $sourceSelectionService, GetDefaultSourceSelectionAlgorithmCodeInterface $getDefaultSourceSelectionAlgorithmCode, - SourceRepositoryInterface $sourceRepository + SourceRepositoryInterface $sourceRepository, + GetInventoryRequestFromOrder $getInventoryRequestFromOrder = null ) { parent::__construct($context); - $this->stockByWebsiteIdResolver = $stockByWebsiteIdResolver; - $this->itemRequestFactory = $itemRequestFactory; - $this->inventoryRequestFactory = $inventoryRequestFactory; $this->sourceSelectionService = $sourceSelectionService; $this->getDefaultSourceSelectionAlgorithmCode = $getDefaultSourceSelectionAlgorithmCode; $this->sourceRepository = $sourceRepository; + $this->itemRequestFactory = $itemRequestFactory; + $this->getInventoryRequestFromOrder = $getInventoryRequestFromOrder ?: + ObjectManager::getInstance()->get(GetInventoryRequestFromOrder::class); + } + + /** + * Get request items + * + * @param array $requestData + * @return array + */ + private function getRequestItems(array $requestData): array + { + $requestItems = []; + foreach ($requestData as $data) { + $requestItems[] = $this->itemRequestFactory->create([ + 'sku' => $data['sku'], + 'qty' => $data['qty'] + ]); + } + + return $requestItems; } /** * @inheritdoc + * @throws NoSuchEntityException */ public function execute(): ResultInterface { @@ -100,28 +123,15 @@ public function execute(): ResultInterface $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $request = $this->getRequest(); $postRequest = $request->getPost()->toArray(); + $orderId = (int) $postRequest['orderId']; - if ($request->isPost() && !empty($postRequest['requestData'])) { + if (!empty($postRequest['requestData'])) { $requestData = $postRequest['requestData']; $defaultCode = $this->getDefaultSourceSelectionAlgorithmCode->execute(); $algorithmCode = !empty($postRequest['algorithmCode']) ? $postRequest['algorithmCode'] : $defaultCode; + $requestItems = $this->getRequestItems($requestData); - //TODO: maybe need to add exception when websiteId empty - $websiteId = $postRequest['websiteId'] ?? 1; - $stockId = (int)$this->stockByWebsiteIdResolver->execute((int)$websiteId)->getStockId(); - - $result = $requestItems = []; - foreach ($requestData as $data) { - $requestItems[] = $this->itemRequestFactory->create([ - 'sku' => $data['sku'], - 'qty' => $data['qty'] - ]); - } - $inventoryRequest = $this->inventoryRequestFactory->create([ - 'stockId' => $stockId, - 'items' => $requestItems - ]); - + $inventoryRequest = $this->getInventoryRequestFromOrder->execute($orderId, $requestItems); $sourceSelectionResult = $this->sourceSelectionService->execute($inventoryRequest, $algorithmCode); foreach ($requestData as $data) { @@ -155,7 +165,7 @@ public function execute(): ResultInterface * * @param string $sourceCode * @return mixed - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ public function getSourceName(string $sourceCode): string { diff --git a/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByOrderIdSkuAndQty.php b/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByOrderIdSkuAndQty.php new file mode 100644 index 000000000000..358820e9f2f4 --- /dev/null +++ b/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByOrderIdSkuAndQty.php @@ -0,0 +1,128 @@ +itemRequestFactory = $itemRequestFactory; + $this->sourceSelectionService = $sourceSelectionService; + $this->getDefaultSourceSelectionAlgorithmCode = $getDefaultSourceSelectionAlgorithmCode; + $this->sourceRepository = $sourceRepository; + $this->getInventoryRequestFromOrder = $getInventoryRequestFromOrder; + } + + /** + * Get sources by order id sku and qty + * + * @param int $orderId + * @param string $sku + * @param float $qty + * @return array + * @throws NoSuchEntityException + * @SuppressWarnings(PHPMD.LongVariable) + */ + public function execute(int $orderId, string $sku, float $qty): array + { + $algorithmCode = $this->getDefaultSourceSelectionAlgorithmCode->execute(); + + $requestItem = $this->itemRequestFactory->create([ + 'sku' => $sku, + 'qty' => $qty + ]); + + $inventoryRequest = $this->getInventoryRequestFromOrder->execute($orderId, [$requestItem]); + $sourceSelectionResult = $this->sourceSelectionService->execute( + $inventoryRequest, + $algorithmCode + ); + + $result = []; + foreach ($sourceSelectionResult->getSourceSelectionItems() as $item) { + $sourceCode = $item->getSourceCode(); + $result[] = [ + 'sourceName' => $this->getSourceName($sourceCode), + 'sourceCode' => $sourceCode, + 'qtyAvailable' => $item->getQtyAvailable(), + 'qtyToDeduct' => $item->getQtyToDeduct() + ]; + } + + return $result; + } + + /** + * Get source name by code + * + * @param string $sourceCode + * @return mixed + * @throws NoSuchEntityException + */ + private function getSourceName(string $sourceCode): string + { + if (!isset($this->sources[$sourceCode])) { + $this->sources[$sourceCode] = $this->sourceRepository->get($sourceCode)->getName(); + } + + return $this->sources[$sourceCode]; + } +} diff --git a/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByStockIdSkuAndQty.php b/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByStockIdSkuAndQty.php index 4c7c0c44c91a..f0a29c69875b 100644 --- a/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByStockIdSkuAndQty.php +++ b/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/GetSourcesByStockIdSkuAndQty.php @@ -7,12 +7,18 @@ namespace Magento\InventoryShippingAdminUi\Ui\DataProvider; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\InventorySourceSelectionApi\Api\Data\ItemRequestInterfaceFactory; use Magento\InventorySourceSelectionApi\Api\Data\InventoryRequestInterfaceFactory; use Magento\InventorySourceSelectionApi\Api\SourceSelectionServiceInterface; use Magento\InventorySourceSelectionApi\Api\GetDefaultSourceSelectionAlgorithmCodeInterface; use Magento\InventoryApi\Api\SourceRepositoryInterface; +/** + * Class GetSourcesByStockIdSkuAndQty + * @package Magento\InventoryShippingAdminUi\Ui\DataProvider + * @deprecated (see \Magento\InventoryShippingAdminUi\Ui\DataProvider\GetSourcesByOrderIdStockIdSkuAndQty) + */ class GetSourcesByStockIdSkuAndQty { /** @@ -46,11 +52,14 @@ class GetSourcesByStockIdSkuAndQty private $sources = []; /** + * GetSourcesByStockIdSkuAndQty constructor. + * * @param ItemRequestInterfaceFactory $itemRequestFactory * @param InventoryRequestInterfaceFactory $inventoryRequestFactory * @param SourceSelectionServiceInterface $sourceSelectionService * @param GetDefaultSourceSelectionAlgorithmCodeInterface $getDefaultSourceSelectionAlgorithmCode * @param SourceRepositoryInterface $sourceRepository + * @SuppressWarnings(PHPMD.LongVariable) */ public function __construct( ItemRequestInterfaceFactory $itemRequestFactory, @@ -71,7 +80,8 @@ public function __construct( * @param string $sku * @param float $qty * @return array - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException + * @SuppressWarnings(PHPMD.LongVariable) */ public function execute(int $stockId, string $sku, float $qty): array { @@ -108,7 +118,7 @@ public function execute(int $stockId, string $sku, float $qty): array * * @param string $sourceCode * @return mixed - * @throws \Magento\Framework\Exception\NoSuchEntityException + * @throws NoSuchEntityException */ private function getSourceName(string $sourceCode): string { diff --git a/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/SourceSelectionDataProvider.php b/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/SourceSelectionDataProvider.php index afad5774bb95..3fa61c959ce4 100644 --- a/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/SourceSelectionDataProvider.php +++ b/app/code/Magento/InventoryShippingAdminUi/Ui/DataProvider/SourceSelectionDataProvider.php @@ -8,6 +8,7 @@ namespace Magento\InventoryShippingAdminUi\Ui\DataProvider; use Magento\Framework\Api\Filter; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Model\OrderRepository; @@ -16,7 +17,6 @@ use Magento\InventorySalesApi\Model\StockByWebsiteIdResolverInterface; use Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface; use Magento\Framework\App\RequestInterface; -use Magento\InventoryShippingAdminUi\Ui\DataProvider\GetSourcesByStockIdSkuAndQty; use Magento\InventorySalesApi\Model\GetSkuFromOrderItemInterface; class SourceSelectionDataProvider extends AbstractDataProvider @@ -31,21 +31,11 @@ class SourceSelectionDataProvider extends AbstractDataProvider */ private $orderRepository; - /** - * @var StockByWebsiteIdResolverInterface - */ - private $stockByWebsiteIdResolver; - /** * @var GetStockItemConfigurationInterface */ private $getStockItemConfiguration; - /** - * @var GetSourcesByStockIdSkuAndQty - */ - private $getSourcesByStockIdSkuAndQty; - /** * @var GetSkuFromOrderItemInterface */ @@ -56,6 +46,16 @@ class SourceSelectionDataProvider extends AbstractDataProvider */ private $sources = []; + /** + * @var GetSourcesByOrderIdSkuAndQty + */ + private $getSourcesByOrderIdSkuAndQty; + + /** + * @var StockByWebsiteIdResolverInterface + */ + private $stockByWebsiteIdResolver; + /** * @param string $name * @param string $primaryFieldName @@ -64,11 +64,14 @@ class SourceSelectionDataProvider extends AbstractDataProvider * @param OrderRepository $orderRepository * @param StockByWebsiteIdResolverInterface $stockByWebsiteIdResolver * @param GetStockItemConfigurationInterface $getStockItemConfiguration - * @param GetSourcesByStockIdSkuAndQty $getSourcesByStockIdSkuAndQty + * @param null $getSourcesByStockIdSkuAndQty @deprecated * @param GetSkuFromOrderItemInterface $getSkuFromOrderItem + * @param GetSourcesByOrderIdSkuAndQty $getSourcesByOrderIdSkuAndQty * @param array $meta * @param array $data * @SuppressWarnings(PHPMD.ExcessiveParameterList) + * @SuppressWarnings(PHPMD.LongVariable) + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __construct( $name, @@ -78,8 +81,9 @@ public function __construct( OrderRepository $orderRepository, StockByWebsiteIdResolverInterface $stockByWebsiteIdResolver, GetStockItemConfigurationInterface $getStockItemConfiguration, - GetSourcesByStockIdSkuAndQty $getSourcesByStockIdSkuAndQty, + $getSourcesByStockIdSkuAndQty, GetSkuFromOrderItemInterface $getSkuFromOrderItem, + GetSourcesByOrderIdSkuAndQty $getSourcesByOrderIdSkuAndQty = null, array $meta = [], array $data = [] ) { @@ -88,8 +92,9 @@ public function __construct( $this->orderRepository = $orderRepository; $this->stockByWebsiteIdResolver = $stockByWebsiteIdResolver; $this->getStockItemConfiguration = $getStockItemConfiguration; - $this->getSourcesByStockIdSkuAndQty = $getSourcesByStockIdSkuAndQty; $this->getSkuFromOrderItem = $getSkuFromOrderItem; + $this->getSourcesByOrderIdSkuAndQty = $getSourcesByOrderIdSkuAndQty ?: + ObjectManager::getInstance()->get(GetSourcesByOrderIdSkuAndQty::class); } /** @@ -110,7 +115,7 @@ public function addFilter(Filter $filter) public function getData() { $data = []; - $orderId = $this->request->getParam('order_id'); + $orderId = (int) $this->request->getParam('order_id'); /** @var \Magento\Sales\Model\Order $order */ $order = $this->orderRepository->get($orderId); $websiteId = $order->getStore()->getWebsiteId(); @@ -132,7 +137,7 @@ public function getData() 'sku' => $sku, 'product' => $this->getProductName($orderItem), 'qtyToShip' => $qty, - 'sources' => $this->getSources($stockId, $sku, $qty), + 'sources' => $this->getSources($orderId, $sku, $qty), 'isManageStock' => $this->isManageStock($sku, $stockId) ]; } @@ -149,15 +154,17 @@ public function getData() } /** - * @param int $stockId + * Get sources + * + * @param int $orderId * @param string $sku * @param float $qty * @return array * @throws NoSuchEntityException */ - private function getSources(int $stockId, string $sku, float $qty): array + private function getSources(int $orderId, string $sku, float $qty): array { - $sources = $this->getSourcesByStockIdSkuAndQty->execute($stockId, $sku, $qty); + $sources = $this->getSourcesByOrderIdSkuAndQty->execute($orderId, $sku, $qty); foreach ($sources as $source) { $this->sources[$source['sourceCode']] = $source['sourceName']; } diff --git a/app/code/Magento/InventoryShippingAdminUi/etc/adminhtml/di.xml b/app/code/Magento/InventoryShippingAdminUi/etc/adminhtml/di.xml index 132a0bbd2689..f2d41f52f6a9 100644 --- a/app/code/Magento/InventoryShippingAdminUi/etc/adminhtml/di.xml +++ b/app/code/Magento/InventoryShippingAdminUi/etc/adminhtml/di.xml @@ -23,4 +23,18 @@ + + + + + + + + + + + + + + diff --git a/app/code/Magento/InventoryShippingAdminUi/view/adminhtml/web/js/form/form.js b/app/code/Magento/InventoryShippingAdminUi/view/adminhtml/web/js/form/form.js index 6c4b4951b58a..50943b159222 100644 --- a/app/code/Magento/InventoryShippingAdminUi/view/adminhtml/web/js/form/form.js +++ b/app/code/Magento/InventoryShippingAdminUi/view/adminhtml/web/js/form/form.js @@ -34,6 +34,7 @@ define([ }); }); + data.orderId = formData['order_id']; data.websiteId = formData.websiteId; data = utils.serialize(utils.filterFormData(data)); data['form_key'] = window.FORM_KEY; diff --git a/app/code/Magento/InventorySourceSelection/Model/Address.php b/app/code/Magento/InventorySourceSelection/Model/Address.php new file mode 100644 index 000000000000..0673e10aae58 --- /dev/null +++ b/app/code/Magento/InventorySourceSelection/Model/Address.php @@ -0,0 +1,104 @@ +country = $country; + $this->postcode = $postcode; + $this->streetAddress = $streetAddress; + $this->region = $region; + $this->city = $city; + } + + /** + * @inheritdoc + */ + public function getCountry(): string + { + return $this->country; + } + + /** + * @inheritdoc + */ + public function getPostcode(): string + { + return $this->postcode; + } + + /** + * @inheritdoc + */ + public function getStreetAddress(): string + { + return $this->streetAddress; + } + + /** + * @inheritdoc + */ + public function getRegion(): string + { + return $this->region; + } + + /** + * @inheritdoc + */ + public function getCity(): string + { + return $this->city; + } +} diff --git a/app/code/Magento/InventorySourceSelection/Model/Algorithms/PriorityBasedAlgorithm.php b/app/code/Magento/InventorySourceSelection/Model/Algorithms/PriorityBasedAlgorithm.php index ce81ece7d26a..013b32c0c3a4 100644 --- a/app/code/Magento/InventorySourceSelection/Model/Algorithms/PriorityBasedAlgorithm.php +++ b/app/code/Magento/InventorySourceSelection/Model/Algorithms/PriorityBasedAlgorithm.php @@ -7,16 +7,17 @@ namespace Magento\InventorySourceSelection\Model\Algorithms; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\InventoryApi\Api\GetSourcesAssignedToStockOrderedByPriorityInterface; use Magento\InventoryApi\Api\Data\SourceInterface; -use Magento\InventoryApi\Api\Data\SourceItemInterface; use Magento\InventoryApi\Api\SourceItemRepositoryInterface; +use Magento\InventorySourceSelectionApi\Model\Algorithms\Result\GetDefaultSortedSourcesResult; use Magento\InventorySourceSelectionApi\Api\Data\InventoryRequestInterface; -use Magento\InventorySourceSelectionApi\Api\Data\SourceSelectionResultInterface; use Magento\InventorySourceSelectionApi\Api\Data\SourceSelectionItemInterfaceFactory; +use Magento\InventorySourceSelectionApi\Api\Data\SourceSelectionResultInterface; use Magento\InventorySourceSelectionApi\Api\Data\SourceSelectionResultInterfaceFactory; use Magento\InventorySourceSelectionApi\Model\SourceSelectionInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; +use Magento\Framework\App\ObjectManager; /** * {@inheritdoc} @@ -30,112 +31,46 @@ class PriorityBasedAlgorithm implements SourceSelectionInterface private $getSourcesAssignedToStockOrderedByPriority; /** - * @var SourceSelectionItemInterfaceFactory - */ - private $sourceSelectionItemFactory; - - /** - * @var SourceSelectionResultInterfaceFactory - */ - private $sourceSelectionResultFactory; - - /** - * @var SearchCriteriaBuilder + * @var GetDefaultSortedSourcesResult */ - private $searchCriteriaBuilder; - - /** - * @var SourceItemRepositoryInterface - */ - private $sourceItemRepository; + private $getDefaultSortedSourcesResult; /** + * PriorityBasedAlgorithm constructor. + * * @param GetSourcesAssignedToStockOrderedByPriorityInterface $getSourcesAssignedToStockOrderedByPriority * @param SourceSelectionItemInterfaceFactory $sourceSelectionItemFactory * @param SourceSelectionResultInterfaceFactory $sourceSelectionResultFactory * @param SearchCriteriaBuilder $searchCriteriaBuilder * @param SourceItemRepositoryInterface $sourceItemRepository + * @param GetDefaultSortedSourcesResult $getDefaultSortedSourcesResult + * @SuppressWarnings(PHPMD.LongVariable) + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function __construct( GetSourcesAssignedToStockOrderedByPriorityInterface $getSourcesAssignedToStockOrderedByPriority, SourceSelectionItemInterfaceFactory $sourceSelectionItemFactory, SourceSelectionResultInterfaceFactory $sourceSelectionResultFactory, SearchCriteriaBuilder $searchCriteriaBuilder, - SourceItemRepositoryInterface $sourceItemRepository + SourceItemRepositoryInterface $sourceItemRepository, + GetDefaultSortedSourcesResult $getDefaultSortedSourcesResult = null ) { $this->getSourcesAssignedToStockOrderedByPriority = $getSourcesAssignedToStockOrderedByPriority; - $this->sourceSelectionItemFactory = $sourceSelectionItemFactory; - $this->sourceSelectionResultFactory = $sourceSelectionResultFactory; - $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->sourceItemRepository = $sourceItemRepository; + $this->getDefaultSortedSourcesResult = $getDefaultSortedSourcesResult ?: + ObjectManager::getInstance()->get(GetDefaultSortedSourcesResult::class); } /** * @inheritdoc + * @throws \Magento\Framework\Exception\InputException + * @throws \Magento\Framework\Exception\LocalizedException */ public function execute(InventoryRequestInterface $inventoryRequest): SourceSelectionResultInterface { - $isShippable = true; $stockId = $inventoryRequest->getStockId(); - $sources = $this->getEnabledSourcesOrderedByPriorityByStockId($stockId); - $sourceItemSelections = []; - - foreach ($inventoryRequest->getItems() as $item) { - $itemSku = $item->getSku(); - $qtyToDeliver = $item->getQty(); - foreach ($sources as $source) { - $sourceItem = $this->getSourceItemBySourceCodeAndSku($source->getSourceCode(), $itemSku); - if (null === $sourceItem) { - continue; - } - - if ($sourceItem->getStatus() != SourceItemInterface::STATUS_IN_STOCK) { - continue; - } - - $sourceItemQty = $sourceItem->getQuantity(); - $qtyToDeduct = min($sourceItemQty, $qtyToDeliver); + $sortedSources = $this->getEnabledSourcesOrderedByPriorityByStockId($stockId); - // check if source has some qty of SKU, so it's possible to take them into account - if ($this->isZero((float)$sourceItemQty)) { - continue; - } - - $sourceItemSelections[] = $this->sourceSelectionItemFactory->create([ - 'sourceCode' => $sourceItem->getSourceCode(), - 'sku' => $itemSku, - 'qtyToDeduct' => $qtyToDeduct, - 'qtyAvailable' => $sourceItemQty - ]); - - $qtyToDeliver -= $qtyToDeduct; - } - - // if we go throw all sources from the stock and there is still some qty to delivery, - // then it doesn't have enough items to delivery - if (!$this->isZero($qtyToDeliver)) { - $isShippable = false; - } - } - - return $this->sourceSelectionResultFactory->create( - [ - 'sourceItemSelections' => $sourceItemSelections, - 'isShippable' => $isShippable - ] - ); - } - - /** - * Compare float number with some epsilon - * - * @param float $floatNumber - * - * @return bool - */ - private function isZero(float $floatNumber): bool - { - return $floatNumber < 0.0000001; + return $this->getDefaultSortedSourcesResult->execute($inventoryRequest, $sortedSources); } /** @@ -155,22 +90,4 @@ private function getEnabledSourcesOrderedByPriorityByStockId(int $stockId): arra }); return $sources; } - - /** - * Returns source item from specific source by given SKU. Return null if source item is not found - * - * @param string $sourceCode - * @param string $sku - * @return SourceItemInterface|null - */ - private function getSourceItemBySourceCodeAndSku(string $sourceCode, string $sku) - { - $searchCriteria = $this->searchCriteriaBuilder - ->addFilter(SourceItemInterface::SOURCE_CODE, $sourceCode) - ->addFilter(SourceItemInterface::SKU, $sku) - ->create(); - $sourceItemsResult = $this->sourceItemRepository->getList($searchCriteria); - - return $sourceItemsResult->getTotalCount() > 0 ? current($sourceItemsResult->getItems()) : null; - } } diff --git a/app/code/Magento/InventorySourceSelection/etc/di.xml b/app/code/Magento/InventorySourceSelection/etc/di.xml index 41f4ee815c89..30e7d66b5149 100644 --- a/app/code/Magento/InventorySourceSelection/etc/di.xml +++ b/app/code/Magento/InventorySourceSelection/etc/di.xml @@ -5,19 +5,30 @@ * See COPYING.txt for license details. */ --> - - - - - - - - - + + + + + + + + + + - Magento\InventorySourceSelection\Model\Algorithms\PriorityBasedAlgorithm + Magento\InventorySourceSelection\Model\Algorithms\PriorityBasedAlgorithm + diff --git a/app/code/Magento/InventorySourceSelection/etc/extension_attributes.xml b/app/code/Magento/InventorySourceSelection/etc/extension_attributes.xml new file mode 100644 index 000000000000..ce95758d4b39 --- /dev/null +++ b/app/code/Magento/InventorySourceSelection/etc/extension_attributes.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/app/code/Magento/InventorySourceSelectionApi/Api/Data/AddressInterface.php b/app/code/Magento/InventorySourceSelectionApi/Api/Data/AddressInterface.php new file mode 100644 index 000000000000..fea3be369f0b --- /dev/null +++ b/app/code/Magento/InventorySourceSelectionApi/Api/Data/AddressInterface.php @@ -0,0 +1,51 @@ +sourceSelectionItemFactory = $sourceSelectionItemFactory; + $this->sourceSelectionResultFactory = $sourceSelectionResultFactory; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->sourceItemRepository = $sourceItemRepository; + } + + /** + * Compare float number with some epsilon + * + * @param float $floatNumber + * + * @return bool + */ + private function isZero(float $floatNumber): bool + { + return $floatNumber < 0.0000001; + } + + /** + * Returns source item from specific source by given SKU. Return null if source item is not found + * + * @param string $sourceCode + * @param string $sku + * @return SourceItemInterface|null + */ + private function getSourceItemBySourceCodeAndSku(string $sourceCode, string $sku): ?SourceItemInterface + { + $searchCriteria = $this->searchCriteriaBuilder + ->addFilter(SourceItemInterface::SOURCE_CODE, $sourceCode) + ->addFilter(SourceItemInterface::SKU, $sku) + ->create(); + $sourceItemsResult = $this->sourceItemRepository->getList($searchCriteria); + + return $sourceItemsResult->getTotalCount() > 0 ? current($sourceItemsResult->getItems()) : null; + } + + /** + * Generate default result for priority based algorithms + * + * @param InventoryRequestInterface $inventoryRequest + * @param SourceInterface[] $sortedSources + * @return SourceSelectionResultInterface + */ + public function execute( + InventoryRequestInterface $inventoryRequest, + array $sortedSources + ): SourceSelectionResultInterface { + $isShippable = true; + $sourceItemSelections = []; + + //TODO from performance perspective it's better to switch these foreaches and make the inner one + //TODO which loops over sources to be outermost and iterate over inventory request items inside + foreach ($inventoryRequest->getItems() as $item) { + $itemSku = $item->getSku(); + $qtyToDeliver = $item->getQty(); + + foreach ($sortedSources as $source) { + $sourceItem = $this->getSourceItemBySourceCodeAndSku($source->getSourceCode(), $itemSku); + if (null === $sourceItem) { + continue; + } + + if ($sourceItem->getStatus() !== SourceItemInterface::STATUS_IN_STOCK) { + continue; + } + + $sourceItemQty = $sourceItem->getQuantity(); + $qtyToDeduct = min($sourceItemQty, $qtyToDeliver); + + // check if source has some qty of SKU, so it's possible to take them into account + if ($this->isZero((float)$sourceItemQty)) { + continue; + } + + $sourceItemSelections[] = $this->sourceSelectionItemFactory->create([ + 'sourceCode' => $sourceItem->getSourceCode(), + 'sku' => $itemSku, + 'qtyToDeduct' => $qtyToDeduct, + 'qtyAvailable' => $sourceItemQty + ]); + + $qtyToDeliver -= $qtyToDeduct; + } + + // if we go through all sources from the stock and there is still some qty to delivery, + // then it doesn't have enough items to delivery + if (!$this->isZero($qtyToDeliver)) { + $isShippable = false; + } + } + + return $this->sourceSelectionResultFactory->create( + [ + 'sourceItemSelections' => $sourceItemSelections, + 'isShippable' => $isShippable + ] + ); + } +} diff --git a/app/code/Magento/InventorySourceSelectionApi/Model/GetInventoryRequestFromOrder.php b/app/code/Magento/InventorySourceSelectionApi/Model/GetInventoryRequestFromOrder.php new file mode 100644 index 000000000000..f713f5e56a65 --- /dev/null +++ b/app/code/Magento/InventorySourceSelectionApi/Model/GetInventoryRequestFromOrder.php @@ -0,0 +1,133 @@ +inventoryRequestFactory = $inventoryRequestFactory; + $this->inventoryRequestExtensionFactory = $inventoryRequestExtensionFactory; + $this->orderRepository = $orderRepository; + $this->addressInterfaceFactory = $addressInterfaceFactory; + $this->storeManager = $storeManager; + $this->stockByWebsiteIdResolver = $stockByWebsiteIdResolver; + } + + /** + * Build inventory request based on Order Id and provided request items + * + * @param int $orderId + * @param array $requestItems + */ + public function execute(int $orderId, array $requestItems): InventoryRequestInterface + { + /** @var OrderInterface $order */ + $order = $this->orderRepository->get($orderId); + + $store = $this->storeManager->getStore($order->getStoreId()); + $stock = $this->stockByWebsiteIdResolver->execute((int)$store->getWebsiteId()); + + $inventoryRequest = $this->inventoryRequestFactory->create([ + 'stockId' => $stock->getStockId(), + 'items' => $requestItems + ]); + + $address = $this->getAddressFromOrder($order); + if ($address !== null) { + $extensionAttributes = $this->inventoryRequestExtensionFactory->create(); + $extensionAttributes->setDestinationAddress($address); + $inventoryRequest->setExtensionAttributes($extensionAttributes); + } + + return $inventoryRequest; + } + + /** + * Create an address from an order + * + * @param OrderInterface $order + * @return null|AddressInterface + */ + private function getAddressFromOrder(OrderInterface $order): ?AddressInterface + { + /** @var Address $shippingAddress */ + $shippingAddress = $order->getShippingAddress(); + if ($shippingAddress === null) { + return null; + } + + return $this->addressInterfaceFactory->create([ + 'country' => $shippingAddress->getCountryId(), + 'postcode' => $shippingAddress->getPostcode(), + 'streetAddress' => implode("\n", $shippingAddress->getStreet()), + 'region' => $shippingAddress->getRegion() ?? $shippingAddress->getRegionCode() ?? '', + 'city' => $shippingAddress->getCity() + ]); + } +} diff --git a/app/code/Magento/InventorySourceSelection/Model/SourceSelectionService.php b/app/code/Magento/InventorySourceSelectionApi/Model/SourceSelectionService.php similarity index 95% rename from app/code/Magento/InventorySourceSelection/Model/SourceSelectionService.php rename to app/code/Magento/InventorySourceSelectionApi/Model/SourceSelectionService.php index e50ebdf0c635..3efc11d40849 100644 --- a/app/code/Magento/InventorySourceSelection/Model/SourceSelectionService.php +++ b/app/code/Magento/InventorySourceSelectionApi/Model/SourceSelectionService.php @@ -5,7 +5,7 @@ */ declare(strict_types=1); -namespace Magento\InventorySourceSelection\Model; +namespace Magento\InventorySourceSelectionApi\Model; use Magento\Framework\ObjectManagerInterface; use Magento\InventorySourceSelectionApi\Api\Data\InventoryRequestInterface; @@ -28,6 +28,7 @@ class SourceSelectionService implements SourceSelectionServiceInterface /** * @param ObjectManagerInterface $objectManager * @param array $sourceSelectionMethods + * @SuppressWarnings(PHPMD.LongVariable) */ public function __construct( ObjectManagerInterface $objectManager, diff --git a/app/code/Magento/InventorySourceSelectionApi/composer.json b/app/code/Magento/InventorySourceSelectionApi/composer.json index f08060e278e8..a15fef7b8fe0 100644 --- a/app/code/Magento/InventorySourceSelectionApi/composer.json +++ b/app/code/Magento/InventorySourceSelectionApi/composer.json @@ -3,6 +3,10 @@ "description": "N/A", "require": { "php": "~7.1.3||~7.2.0", + "magento/module-inventory-api": "*", + "magento/module-inventory-sales-api": "*", + "magento/module-store": "*", + "magento/module-sales": "*", "magento/framework": "*" }, "type": "magento2-module", diff --git a/app/code/Magento/InventorySourceSelectionApi/etc/di.xml b/app/code/Magento/InventorySourceSelectionApi/etc/di.xml index aa13acc5e3db..80c5ed83b490 100644 --- a/app/code/Magento/InventorySourceSelectionApi/etc/di.xml +++ b/app/code/Magento/InventorySourceSelectionApi/etc/di.xml @@ -5,8 +5,13 @@ * See COPYING.txt for license details. */ --> - - + + + + diff --git a/composer.json b/composer.json index 18602a843296..894877e54391 100644 --- a/composer.json +++ b/composer.json @@ -187,6 +187,9 @@ "magento/module-inventory-configurable-product-indexer": "*", "magento/module-inventory-configuration": "*", "magento/module-inventory-configuration-api": "*", + "magento/module-inventory-distance-based-source-selection": "*", + "magento/module-inventory-distance-based-source-selection-admin-ui": "*", + "magento/module-inventory-distance-based-source-selection-api": "*", "magento/module-inventory-elasticsearch": "*", "magento/module-inventory-grouped-product": "*", "magento/module-inventory-grouped-product-admin-ui": "*", diff --git a/composer.lock b/composer.lock index 7b63500b35d5..7bd788f03bde 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "cb81f96c1cda2bf879bc09c46f3d4e4a", + "content-hash": "15a88b954c17d1ce1e095faa823a47e4", "packages": [ { "name": "braintree/braintree_php",