diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100755 index 0000000..49525fd --- /dev/null +++ b/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/LICENSE_AFL.txt b/LICENSE_AFL.txt new file mode 100755 index 0000000..87943b9 --- /dev/null +++ b/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. \ No newline at end of file diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 29b7f28..48506cf --- a/README.md +++ b/README.md @@ -1,2 +1,76 @@ -# module-matrixrate -WebShopApps MatrixRates for Magento2 +# ShipperHQ and WebShopApps MatrixRate + +A Shipping Rate module for Magento 2.x which supports showing multiple shipping methods. This is based on the Magento Tablerate module and is managed via a csv file. + +## Installation + +Installation is via composer. + +Add the following to the composer.json file in your magento root directory: + + "webshopapps/mage2-matrixrate": "dev-master" + +You also need to specify the repository: + + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/webshopapps/m2ShipperHQ.git" + } + ] + +You can now install the module via `composer update` from the root directory. + +Finally you need to get the actual module loaded within Magento itself. In Magento 1.x you add a file to app/etc/modules. + In Magento 2.x run the following command for each module you wish to enable + php -f bin/magento module:enable --clear-static-content Module_Name + php -f bin/magento setup:upgrade + + +## Resources +* [View Source on GitHub][code] +* [Report Issues on GitHub][issues] + +[code]: https://github.com/webshopapps/m2ShipperHQ +[issues]: https://github.com/webshopapps/m2ShipperHQ/issues + +## Usage Examples + +## Tests + + +## Supported Versions +This library aims to support and is [tested against][travis] the following PHP +implementations: + +* PHP 5.5 + +It has been developed against Magento 2 v2.0.0 but should work against later versions. The version is not +enforced in the composer.json + +## Credits + +This extension borrows heavily from the Tablerate capability in Magento2. In order to keep codebase as bug-free and +conformant as possible the tablerate code is used in preference to writing from scratch. This hopefully also +allows for easier understanding by users. + +We would like to acknowledge and thank the Magento 2 Development team for making their codebase open for such use. + +The composer structure is taken from various sources, most heavily using structure from https://github.com/sjparkinson/static-review. + +Assistance around composer, Magento2 structure, etc was also taken from these sources: + +* [https://github.com/Genmato/MultiStoreSearchFields](http://) +* [https://alankent.wordpress.com/2014/08/03/creating-a-magento-2-composer-module/](http://) +* [https://github.com/SchumacherFM/mage2-advanced-rest-permissions](http://) + + +## License +Copyright (c) 2015 Zowta LLC & Zowta Ltd. See [LICENSE][] for +details. + +We also dutifully respect the [Magento][] OSL license, which is included in this codebase. + + +[license]: LICENSE.md +[magento]: Magento2_LICENSE.md diff --git a/composer.json b/composer.json new file mode 100755 index 0000000..e69f0c4 --- /dev/null +++ b/composer.json @@ -0,0 +1,38 @@ +{ + "name": "webshopapps/module-matrixrate", + + "description": "Magento Shipping Multiple Table Rates - MatrixRate", + + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + + "authors": [ + { + "name": "ShipperHQ", + "email": "sales@wshipperhq.com", + "homepage": "http://www.Shipperhq.com" + }, + { + "name": "Karen Baker" + } + ], + + "type": "magento2-module", + + "version": "20.0.1", + + "support": { + "documentation": "http://docs.shipperhq.com" + }, + + "autoload": { + "files": [ + "src/registration.php" + ], + "psr-4": { + "WebShopApps\\MatrixRate\\": "src/" + } + } +} diff --git a/src/Block/Adminhtml/Carrier/Matrixrate/Grid.php b/src/Block/Adminhtml/Carrier/Matrixrate/Grid.php new file mode 100755 index 0000000..3841837 --- /dev/null +++ b/src/Block/Adminhtml/Carrier/Matrixrate/Grid.php @@ -0,0 +1,207 @@ +_collectionFactory = $collectionFactory; + $this->_matrixrate = $matrixrate; + parent::__construct($context, $backendHelper, $data); + } + + /** + * Define grid properties + * + * @return void + */ + protected function _construct() + { + parent::_construct(); + $this->setId('shippingMatrixrateGrid'); + $this->_exportPageSize = 10000; + } + + /** + * Set current website + * + * @param int $websiteId + * @return $this + */ + public function setWebsiteId($websiteId) + { + $this->_websiteId = $this->_storeManager->getWebsite($websiteId)->getId(); + return $this; + } + + /** + * Retrieve current website id + * + * @return int + */ + public function getWebsiteId() + { + if ($this->_websiteId === null) { + $this->_websiteId = $this->_storeManager->getWebsite()->getId(); + } + return $this->_websiteId; + } + + /** + * Set current website + * + * @param string $name + * @return $this + */ + public function setConditionName($name) + { + $this->_conditionName = $name; + return $this; + } + + /** + * Retrieve current website id + * + * @return int + */ + public function getConditionName() + { + return $this->_conditionName; + } + + /** + * Prepare shipping table rate collection + * + * @return \WebShopApps\MatrixRate\Block\Adminhtml\Carrier\Matrixrate\Grid + */ + protected function _prepareCollection() + { + /** @var $collection \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate\Collection */ + $collection = $this->_collectionFactory->create(); + $collection->setConditionFilter($this->getConditionName())->setWebsiteFilter($this->getWebsiteId()); + + $this->setCollection($collection); + + return parent::_prepareCollection(); + } + + /** + * Prepare table columns + * + * @return \Magento\Backend\Block\Widget\Grid\Extended + */ + protected function _prepareColumns() + { + $this->addColumn( + 'dest_country', + ['header' => __('Country'), 'index' => 'dest_country', 'default' => '*'] + ); + + $this->addColumn( + 'dest_region', + ['header' => __('Region/State'), 'index' => 'dest_region', 'default' => '*'] + ); + $this->addColumn( + 'dest_city', + ['header' => __('City'), 'index' => 'dest_city', 'default' => '*'] + ); + $this->addColumn( + 'dest_zip', + ['header' => __('Zip/Postal Code From'), 'index' => 'dest_zip', 'default' => '*'] + ); + $this->addColumn( + 'dest_zip_to', + ['header' => __('Zip/Postal Code To'), 'index' => 'dest_zip_to', 'default' => '*'] + ); + + + $label = $this->_matrixrate->getCode('condition_name_short', $this->getConditionName()); + + $this->addColumn( + 'condition_from_value', + ['header' => $label.__('>'), 'index' => 'condition_from_value'] + ); + + $this->addColumn( + 'condition_to_value', + ['header' => $label.__('<='), 'index' => 'condition_to_value'] + ); + + $this->addColumn('price', ['header' => __('Shipping Price'), 'index' => 'price']); + + $this->addColumn( + 'shipping_method', + ['header' => __('Shipping Method'), 'index' => 'shipping_method'] + ); + + return parent::_prepareColumns(); + } +} diff --git a/src/Block/Adminhtml/Form/Field/Export.php b/src/Block/Adminhtml/Form/Field/Export.php new file mode 100755 index 0000000..eaceb78 --- /dev/null +++ b/src/Block/Adminhtml/Form/Field/Export.php @@ -0,0 +1,88 @@ + + */ +class Export extends \Magento\Framework\Data\Form\Element\AbstractElement +{ + /** + * @var \Magento\Backend\Model\UrlInterface + */ + protected $_backendUrl; + + /** + * @param \Magento\Framework\Data\Form\Element\Factory $factoryElement + * @param \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection + * @param \Magento\Framework\Escaper $escaper + * @param \Magento\Backend\Helper\Data $helper + * @param array $data + */ + public function __construct( + \Magento\Framework\Data\Form\Element\Factory $factoryElement, + \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection, + \Magento\Framework\Escaper $escaper, + \Magento\Backend\Model\UrlInterface $backendUrl, + array $data = [] + ) { + parent::__construct($factoryElement, $factoryCollection, $escaper, $data); + $this->_backendUrl = $backendUrl; + } + + /** + * @return string + */ + public function getElementHtml() + { + /** @var \Magento\Backend\Block\Widget\Button $buttonBlock */ + $buttonBlock = $this->getForm()->getParent()->getLayout()->createBlock('Magento\Backend\Block\Widget\Button'); + + $params = ['website' => $buttonBlock->getRequest()->getParam('website')]; + + $url = $this->_backendUrl->getUrl("shqmatrixrate/system/exportMatrixrates", $params); + $data = [ + 'label' => __('Export CSV'), + 'onclick' => "setLocation('" . + $url . + "conditionName/' + $('carriers_matrixrate_condition_name').value + '/matrixrates.csv' )", + 'class' => '', + ]; + + $html = $buttonBlock->setData($data)->toHtml(); + return $html; + } +} diff --git a/src/Block/Adminhtml/Form/Field/Import.php b/src/Block/Adminhtml/Form/Field/Import.php new file mode 100755 index 0000000..784292f --- /dev/null +++ b/src/Block/Adminhtml/Form/Field/Import.php @@ -0,0 +1,82 @@ + + */ +class Import extends \Magento\Framework\Data\Form\Element\AbstractElement +{ + /** + * @return void + */ + protected function _construct() + { + parent::_construct(); + $this->setType('file'); + } + + /** + * Enter description here... + * + * @return string + */ + public function getElementHtml() + { + $html = ''; + + $html .= ''; + + $html .= << + require(['prototype'], function(){ + Event.observe($('carriers_matrixrate_condition_name'), 'change', checkConditionName.bind(this)); + function checkConditionName(event) + { + var conditionNameElement = Event.element(event); + if (conditionNameElement && conditionNameElement.id) { + $('time_condition').value = '_' + conditionNameElement.value + '/' + Math.random(); + } + } + }); + +EndHTML; + + $html .= parent::getElementHtml(); + + return $html; + } +} diff --git a/src/Controller/Adminhtml/System/ExportMatrixrates.php b/src/Controller/Adminhtml/System/ExportMatrixrates.php new file mode 100755 index 0000000..c193a66 --- /dev/null +++ b/src/Controller/Adminhtml/System/ExportMatrixrates.php @@ -0,0 +1,93 @@ +_storeManager = $storeManager; + $this->_fileFactory = $fileFactory; + parent::__construct($context, $configStructure, $sectionChecker); + } + + /** + * Export shipping table rates in csv format + * + * @return ResponseInterface + */ + public function execute() + { + $fileName = 'matrixrates.csv'; + /** @var $gridBlock \WebShopApps\MatrixRate\Block\Adminhtml\Carrier\Matrixrate\Grid */ + $gridBlock = $this->_view->getLayout()->createBlock( + 'WebShopApps\MatrixRate\Block\Adminhtml\Carrier\Matrixrate\Grid' + ); + $website = $this->_storeManager->getWebsite($this->getRequest()->getParam('website')); + if ($this->getRequest()->getParam('conditionName')) { + $conditionName = $this->getRequest()->getParam('conditionName'); + } else { + $conditionName = $website->getConfig('carriers/matrixrate/condition_name'); + } + $gridBlock->setWebsiteId($website->getId())->setConditionName($conditionName); + $content = $gridBlock->getCsvFile(); + return $this->_fileFactory->create($fileName, $content, DirectoryList::VAR_DIR); + } +} diff --git a/src/Model/Carrier/Matrixrate.php b/src/Model/Carrier/Matrixrate.php new file mode 100755 index 0000000..b9d0080 --- /dev/null +++ b/src/Model/Carrier/Matrixrate.php @@ -0,0 +1,283 @@ +_rateResultFactory = $rateResultFactory; + $this->_resultMethodFactory = $resultMethodFactory; + $this->_matrixrateFactory = $matrixrateFactory; + parent::__construct($scopeConfig, $rateErrorFactory, $logger, $data); + foreach ($this->getCode('condition_name') as $k => $v) { + $this->_conditionNames[] = $k; + } + } + + /** + * @param RateRequest $request + * @return \Magento\Shipping\Model\Rate\Result + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + * @SuppressWarnings(PHPMD.ExcessiveMethodLength) + */ + public function collectRates(RateRequest $request) + { + if (!$this->getConfigFlag('active')) { + return false; + } + + // exclude Virtual products price from Package value if pre-configured + if (!$this->getConfigFlag('include_virtual_price') && $request->getAllItems()) { + foreach ($request->getAllItems() as $item) { + if ($item->getParentItem()) { + continue; + } + if ($item->getHasChildren() && $item->isShipSeparately()) { + foreach ($item->getChildren() as $child) { + if ($child->getProduct()->isVirtual()) { + $request->setPackageValue($request->getPackageValue() - $child->getBaseRowTotal()); + } + } + } elseif ($item->getProduct()->isVirtual()) { + $request->setPackageValue($request->getPackageValue() - $item->getBaseRowTotal()); + } + } + } + + // Free shipping by qty + $freeQty = 0; + if ($request->getAllItems()) { + $freePackageValue = 0; + foreach ($request->getAllItems() as $item) { + if ($item->getProduct()->isVirtual() || $item->getParentItem()) { + continue; + } + + if ($item->getHasChildren() && $item->isShipSeparately()) { + foreach ($item->getChildren() as $child) { + if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) { + $freeShipping = is_numeric($child->getFreeShipping()) ? $child->getFreeShipping() : 0; + $freeQty += $item->getQty() * ($child->getQty() - $freeShipping); + } + } + } elseif ($item->getFreeShipping()) { + $freeShipping = is_numeric($item->getFreeShipping()) ? $item->getFreeShipping() : 0; + $freeQty += $item->getQty() - $freeShipping; + $freePackageValue += $item->getBaseRowTotal(); + } + } + $oldValue = $request->getPackageValue(); + $request->setPackageValue($oldValue - $freePackageValue); + } + + if (!$request->getConditionMRName()) { + $conditionName = $this->getConfigData('condition_name'); + $request->setConditionMRName($conditionName ? $conditionName : $this->_defaultConditionName); + } + + // Package weight and qty free shipping + $oldWeight = $request->getPackageWeight(); + $oldQty = $request->getPackageQty(); + + $request->setPackageWeight($request->getFreeMethodWeight()); + $request->setPackageQty($oldQty - $freeQty); + + /** @var \Magento\Shipping\Model\Rate\Result $result */ + $result = $this->_rateResultFactory->create(); + $zipRange = $this->getConfigData('zip_range'); + $rateArray = $this->getRate($request, $zipRange); + + $request->setPackageWeight($oldWeight); + $request->setPackageQty($oldQty); + + $foundRates = false; + + foreach ($rateArray as $rate) { + if (!empty($rate) && $rate['price'] >= 0) { + /** @var \Magento\Quote\Model\Quote\Address\RateResult\Method $method */ + $method = $this->_resultMethodFactory->create(); + + $method->setCarrier('matrixrate'); + $method->setCarrierTitle($this->getConfigData('title')); + + $method->setMethod('matrixrate_' . $rate['pk']); + $method->setMethodTitle(__($rate['shipping_method'])); + + if ($request->getFreeShipping() === true || $request->getPackageQty() == $freeQty) { + $shippingPrice = 0; + } else { + $shippingPrice = $this->getFinalPriceWithHandlingFee($rate['price']); + } + + $method->setPrice($shippingPrice); + $method->setCost($rate['cost']); + + $result->append($method); + $foundRates = true; // have found some valid rates + } + } + + if (!$foundRates){ + /** @var \Magento\Quote\Model\Quote\Address\RateResult\Error $error */ + $error = $this->_rateErrorFactory->create( + [ + 'data' => [ + 'carrier' => $this->_code, + 'carrier_title' => $this->getConfigData('title'), + 'error_message' => $this->getConfigData('specificerrmsg'), + ], + ] + ); + $result->append($error); + } + + return $result; + } + + /** + * @param \Magento\Quote\Model\Quote\Address\RateRequest $request + * @param bool $zipRange + * @return array|bool + */ + public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request, $zipRange) + { + return $this->_matrixrateFactory->create()->getRate($request, $zipRange); + } + + /** + * @param string $type + * @param string $code + * @return array + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function getCode($type, $code = '') + { + $codes = [ + 'condition_name' => [ + 'package_weight' => __('Weight vs. Destination'), + 'package_value' => __('Order Subtotal vs. Destination'), + 'package_qty' => __('# of Items vs. Destination'), + ], + 'condition_name_short' => [ + 'package_weight' => __('Weight'), + 'package_value' => __('Order Subtotal'), + 'package_qty' => __('# of Items'), + ], + ]; + + if (!isset($codes[$type])) { + throw new LocalizedException(__('Please correct Matrix Rate code type: %1.', $type)); + } + + if ('' === $code) { + return $codes[$type]; + } + + if (!isset($codes[$type][$code])) { + throw new LocalizedException(__('Please correct Matrix Rate code for type %1: %2.', $type, $code)); + } + + return $codes[$type][$code]; + } + + /** + * Get allowed shipping methods + * + * @return array + */ + public function getAllowedMethods() + { + return ['matrixrate' => $this->getConfigData('name')]; + } +} diff --git a/src/Model/Config/Backend/Matrixrate.php b/src/Model/Config/Backend/Matrixrate.php new file mode 100755 index 0000000..2b342d8 --- /dev/null +++ b/src/Model/Config/Backend/Matrixrate.php @@ -0,0 +1,84 @@ + + */ +class Matrixrate extends \Magento\Framework\App\Config\Value +{ + /** + * @var \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\MatrixrateFactory + */ + protected $_matrixrateFactory; + + /** + * @param \Magento\Framework\Model\Context $context + * @param \Magento\Framework\Registry $registry + * @param \Magento\Framework\App\Config\ScopeConfigInterface $config + * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList + * @param \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\MatrixrateFactory $matrixrateFactory + * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource + * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection + * @param array $data + */ + public function __construct( + \Magento\Framework\Model\Context $context, + \Magento\Framework\Registry $registry, + \Magento\Framework\App\Config\ScopeConfigInterface $config, + \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, + \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\MatrixrateFactory $matrixrateFactory, + \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, + \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, + array $data = [] + ) { + $this->_matrixrateFactory = $matrixrateFactory; + parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); + } + + /** + * @return \Magento\Framework\Model\AbstractModel|void + */ + public function afterSave() + { + /** @var \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate $matrixRate */ + $matrixRate = $this->_matrixrateFactory->create(); + $matrixRate->uploadAndImport($this); + return parent::afterSave(); + } +} diff --git a/src/Model/Config/Source/Matrixrate.php b/src/Model/Config/Source/Matrixrate.php new file mode 100755 index 0000000..2894435 --- /dev/null +++ b/src/Model/Config/Source/Matrixrate.php @@ -0,0 +1,62 @@ +_carrierMatrixrate = $carrierMatrixrate; + } + + /** + * @return array + */ + public function toOptionArray() + { + $arr = []; + foreach ($this->_carrierMatrixrate->getCode('condition_name') as $k => $v) { + $arr[] = ['value' => $k, 'label' => $v]; + } + return $arr; + } +} diff --git a/src/Model/ResourceModel/Carrier/Matrixrate.php b/src/Model/ResourceModel/Carrier/Matrixrate.php new file mode 100755 index 0000000..39df88e --- /dev/null +++ b/src/Model/ResourceModel/Carrier/Matrixrate.php @@ -0,0 +1,663 @@ +_coreConfig = $coreConfig; + $this->_logger = $logger; + $this->_storeManager = $storeManager; + $this->_carrierMatrixrate = $carrierMatrixrate; + $this->_countryCollectionFactory = $countryCollectionFactory; + $this->_regionCollectionFactory = $regionCollectionFactory; + $this->_filesystem = $filesystem; + } + + /** + * Define main table and id field name + * + * @return void + */ + protected function _construct() + { + $this->_init('webshopapps_matrixrate', 'pk'); + } + + /** + * Return table rate array or false by rate request + * + * @param \Magento\Quote\Model\Quote\Address\RateRequest $request + * @param bool $zipRangeSet + * @return array|bool + */ + public function getRate(\Magento\Quote\Model\Quote\Address\RateRequest $request, $zipRangeSet = false) + { + $adapter = $this->getConnection(); + $shippingData=array(); + $postcode = $request->getDestPostcode(); + if ($zipRangeSet && is_numeric($postcode)) { + # Want to search for postcodes within a range + $zipSearchString = ' AND :postcode BETWEEN dest_zip AND dest_zip_to '; + } else { + $zipSearchString = " AND :postcode LIKE dest_zip "; + } + + for ($j=0;$j<8;$j++) { + + $select = $adapter->select()->from( + $this->getMainTable() + )->where( + 'website_id = :website_id' + )->order( + ['dest_country_id DESC', 'dest_region_id DESC', 'dest_zip DESC', 'condition_from_value DESC'] + ); + + $zoneWhere=''; + $bind=array(); + switch($j) { + case 0: // country, region, city, postcode + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND STRCMP(LOWER(dest_city),LOWER(:city))= 0 " .$zipSearchString; // TODO Add city + $bind = [ + ':country_id' => $request->getDestCountryId(), + ':region_id' => (int)$request->getDestRegionId(), + ':city' => $request->getDestCity(), + ':postcode' => $request->getDestPostcode(), + ]; + break; + case 1: // country, region, no city, postcode + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_city='' ".$zipSearchString; + $bind = [ + ':country_id' => $request->getDestCountryId(), + ':region_id' => (int)$request->getDestRegionId(), + ':postcode' => $request->getDestPostcode(), + ]; + break; + case 2: // country, state, city, no postcode + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND STRCMP(LOWER(dest_city),LOWER(:city))= 0 AND dest_zip ='*'"; // TODO Add city search + $bind = [ + ':country_id' => $request->getDestCountryId(), + ':region_id' => (int)$request->getDestRegionId(), + ':city' => $request->getDestCity(), + ]; + break; + case 3: //country, city, no region, no postcode + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = '0' AND STRCMP(LOWER(dest_city),LOWER(:city))= 0 AND dest_zip ='*'"; // TODO Add city + $bind = [ + ':country_id' => $request->getDestCountryId(), + ':city' => $request->getDestCity(), + ]; + break; + case 4: // country, postcode + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = '0' AND dest_city ='*' ".$zipSearchString; + $bind = [ + ':country_id' => $request->getDestCountryId(), + ':postcode' => $request->getDestPostcode(), + ]; + break; + case 5: // country, region + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = :region_id AND dest_city ='*' AND dest_zip ='*'"; + $bind = [ + ':country_id' => $request->getDestCountryId(), + ':region_id' => (int)$request->getDestRegionId(), + ]; + break; + case 6: // country + $zoneWhere = "dest_country_id = :country_id AND dest_region_id = '0' AND dest_city ='*' AND dest_zip ='*'"; + $bind = [ + ':country_id' => $request->getDestCountryId(), + ]; + break; + case 7: // nothing + $zoneWhere = "dest_country_id = '0' AND dest_region_id = '0' AND dest_city ='*' AND dest_zip ='*'"; + break; + } + + $select->where($zoneWhere); + + $bind[':website_id'] = (int)$request->getWebsiteId(); + $bind[':condition_name'] = $request->getConditionMRName(); + $bind[':condition_value'] = $request->getData($request->getConditionMRName()); + + $select->where('condition_name = :condition_name'); + $select->where('condition_from_value < :condition_value'); + $select->where('condition_to_value >= :condition_value'); + + $this->_logger->debug('SQL Select: ',$select->getPart('where')); + $this->_logger->debug('Bindings: ',$bind); + + $results = $adapter->fetchAll($select, $bind); + + if (!empty($results)) { + + $this->_logger->debug('SQL Results: ',$results); + foreach ($results as $data) { + $shippingData[]=$data; + } + break; + } + + } + + return $shippingData; + } + + /** + * Upload table rate file and import data from it + * + * @param \Magento\Framework\Object $object + * @throws \Magento\Framework\Exception\LocalizedException + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate + * @todo: this method should be refactored as soon as updated design will be provided + * @see https://wiki.corp.x.com/display/MCOMS/Magento+Filesystem+Decisions + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + */ + public function uploadAndImport(\Magento\Framework\DataObject $object) + { + if (empty($_FILES['groups']['tmp_name']['matrixrate']['fields']['import']['value'])) { + return $this; + } + + $csvFile = $_FILES['groups']['tmp_name']['matrixrate']['fields']['import']['value']; + $website = $this->_storeManager->getWebsite($object->getScopeId()); + + $this->_importWebsiteId = (int)$website->getId(); + $this->_importUniqueHash = []; + $this->_importErrors = []; + $this->_importedRows = 0; + + $tmpDirectory = $this->_filesystem->getDirectoryRead(DirectoryList::SYS_TMP); + $path = $tmpDirectory->getRelativePath($csvFile); + $stream = $tmpDirectory->openFile($path); + + // check and skip headers + $headers = $stream->readCsv(); + if ($headers === false || count($headers) < 5) { + $stream->close(); + throw new \Magento\Framework\Exception\LocalizedException(__('Please correct Matrix Rates File Format.')); + } + + if ($object->getData('groups/matrixrate/fields/condition_name/inherit') == '1') { + $conditionName = (string)$this->_coreConfig->getValue('carriers/matrixrate/condition_name', 'default'); + } else { + $conditionName = $object->getData('groups/matrixrate/fields/condition_name/value'); + } + $this->_importConditionName = $conditionName; + + $adapter = $this->getConnection(); + $adapter->beginTransaction(); + + try { + $rowNumber = 1; + $importData = []; + + $this->_loadDirectoryCountries(); + $this->_loadDirectoryRegions(); + + // delete old data by website and condition name + $condition = [ + 'website_id = ?' => $this->_importWebsiteId, + 'condition_name = ?' => $this->_importConditionName, + ]; + $adapter->delete($this->getMainTable(), $condition); + + while (false !== ($csvLine = $stream->readCsv())) { + $rowNumber++; + + if (empty($csvLine)) { + continue; + } + + $row = $this->_getImportRow($csvLine, $rowNumber); + if ($row !== false) { + $importData[] = $row; + } + + if (count($importData) == 5000) { + $this->_saveImportData($importData); + $importData = []; + } + } + $this->_saveImportData($importData); + $stream->close(); + } catch (\Magento\Framework\Exception\LocalizedException $e) { + $adapter->rollback(); + $stream->close(); + throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); + } catch (\Exception $e) { + $adapter->rollback(); + $stream->close(); + $this->_logger->critical($e); + throw new \Magento\Framework\Exception\LocalizedException( + __('Something went wrong while importing matrix rates.') + ); + } + + $adapter->commit(); + + if ($this->_importErrors) { + $error = __( + 'We couldn\'t import this file because of these errors: %1', + implode(" \n", $this->_importErrors) + ); + throw new \Magento\Framework\Exception\LocalizedException($error); + } + + return $this; + } + + /** + * Load directory countries + * + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate + */ + protected function _loadDirectoryCountries() + { + if ($this->_importIso2Countries !== null && $this->_importIso3Countries !== null) { + return $this; + } + + $this->_importIso2Countries = []; + $this->_importIso3Countries = []; + + /** @var $collection \Magento\Directory\Model\ResourceModel\Country\Collection */ + $collection = $this->_countryCollectionFactory->create(); + foreach ($collection->getData() as $row) { + $this->_importIso2Countries[$row['iso2_code']] = $row['country_id']; + $this->_importIso3Countries[$row['iso3_code']] = $row['country_id']; + } + + return $this; + } + + /** + * Load directory regions + * + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate + */ + protected function _loadDirectoryRegions() + { + if ($this->_importRegions !== null) { + return $this; + } + + $this->_importRegions = []; + + /** @var $collection \Magento\Directory\Model\ResourceModel\Region\Collection */ + $collection = $this->_regionCollectionFactory->create(); + foreach ($collection->getData() as $row) { + $this->_importRegions[$row['country_id']][$row['code']] = (int)$row['region_id']; + } + + return $this; + } + + /** + * Return import condition full name by condition name code + * + * @param string $conditionName + * @return string + */ + protected function _getConditionFullName($conditionName) + { + if (!isset($this->_conditionFullNames[$conditionName])) { + $name = $this->_carrierMatrixrate->getCode('condition_name_short', $conditionName); + $this->_conditionFullNames[$conditionName] = $name; + } + + return $this->_conditionFullNames[$conditionName]; + } + + /** + * Validate row for import and return table rate array or false + * Error will be add to _importErrors array + * + * @param array $row + * @param int $rowNumber + * @return array|false + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + */ + protected function _getImportRow($row, $rowNumber = 0) + { + // validate row + if (count($row) < 7) { + $this->_importErrors[] = __('Please correct Matrix Rates format in Row #%1. Invalid Number of Rows', $rowNumber); + return false; + } + + // strip whitespace from the beginning and end of each row + foreach ($row as $k => $v) { + $row[$k] = trim($v); + } + + // validate country + if (isset($this->_importIso2Countries[$row[0]])) { + $countryId = $this->_importIso2Countries[$row[0]]; + } elseif (isset($this->_importIso3Countries[$row[0]])) { + $countryId = $this->_importIso3Countries[$row[0]]; + } elseif ($row[0] == '*' || $row[0] == '') { + $countryId = '0'; + } else { + $this->_importErrors[] = __('Please correct Country "%1" in Row #%2.', $row[0], $rowNumber); + return false; + } + + // validate region + if ($countryId != '0' && isset($this->_importRegions[$countryId][$row[1]])) { + $regionId = $this->_importRegions[$countryId][$row[1]]; + } elseif ($row[1] == '*' || $row[1] == '') { + $regionId = 0; + } else { + $this->_importErrors[] = __('Please correct Region/State "%1" in Row #%2.', $row[1], $rowNumber); + return false; + } + + // detect city + if ($row[2] == '*' || $row[2] == '') { + $city = '*'; + } else { + $city = $row[2]; + } + + + // detect zip code + if ($row[3] == '*' || $row[3] == '') { + $zipCode = '*'; + } else { + $zipCode = $row[3]; + } + + //zip from + + + if ($row[4] == '*' || $row[4] == '') { + $zip_to = ''; + } else { + $zip_to = $row[4]; + } + + // validate condition from value + $valueFrom = $this->_parseDecimalValue($row[5]); + if ($valueFrom === false) { + $this->_importErrors[] = __( + 'Please correct %1 From "%2" in Row #%3.', + $this->_getConditionFullName($this->_importConditionName), + $row[5], + $rowNumber + ); + return false; + } + // validate conditionto to value + $valueTo = $this->_parseDecimalValue($row[6]); + if ($valueTo === false) { + $this->_importErrors[] = __( + 'Please correct %1 To "%2" in Row #%3.', + $this->_getConditionFullName($this->_importConditionName), + $row[6], + $rowNumber + ); + return false; + } + + + // validate price + $price = $this->_parseDecimalValue($row[7]); + if ($price === false) { + $this->_importErrors[] = __('Please correct Shipping Price "%1" in Row #%2.', $row[7], $rowNumber); + return false; + } + + // validate shipping method + if ($row[8] == '*' || $row[8] == '') { + $this->_importErrors[] = __('Please correct Shipping Method "%1" in Row #%2.', $row[8], $rowNumber); + return false; + } else { + $shippingMethod = $row[8]; + } + + // protect from duplicate + $hash = sprintf("%s-%d-%s-%s-%F-%F-%s", $countryId, $city, $regionId, $zipCode, $valueFrom, $valueTo,$shippingMethod ); + if (isset($this->_importUniqueHash[$hash])) { + $this->_importErrors[] = __( + 'Duplicate Row #%1 (Country "%2", Region/State "%3", City "%4", Zip from "%5", Zip to "%6", From Value "%7", To Value "%8", and Shipping Method "%9")', + $rowNumber, + $row[0], + $row[1], + $city, + $zipCode, + $zip_to, + $valueFrom, + $valueTo, + $shippingMethod + ); + return false; + } + $this->_importUniqueHash[$hash] = true; + + return [ + $this->_importWebsiteId, // website_id + $countryId, // dest_country_id + $regionId, // dest_region_id, + $city, // city, + $zipCode, // dest_zip + $zip_to, //zip to + $this->_importConditionName,// condition_name, + $valueFrom, // condition_value From + $valueTo, // condition_value To + $price, // price + $shippingMethod + ]; + } + + /** + * Save import data batch + * + * @param array $data + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate + */ + protected function _saveImportData(array $data) + { + if (!empty($data)) { + $columns = [ + 'website_id', + 'dest_country_id', + 'dest_region_id', + 'dest_city', + 'dest_zip', + 'dest_zip_to', + 'condition_name', + 'condition_from_value', + 'condition_to_value', + 'price', + 'shipping_method', + ]; + $this->getConnection()->insertArray($this->getMainTable(), $columns, $data); + $this->_importedRows += count($data); + } + + return $this; + } + + /** + * Parse and validate positive decimal value + * Return false if value is not decimal or is not positive + * + * @param string $value + * @return bool|float + */ + protected function _parseDecimalValue($value) + { + if (!is_numeric($value)) { + return false; + } + $value = (double)sprintf('%.4F', $value); + if ($value < 0.0000) { + return false; + } + return $value; + } +} diff --git a/src/Model/ResourceModel/Carrier/Matrixrate/Collection.php b/src/Model/ResourceModel/Carrier/Matrixrate/Collection.php new file mode 100755 index 0000000..5f914ce --- /dev/null +++ b/src/Model/ResourceModel/Carrier/Matrixrate/Collection.php @@ -0,0 +1,129 @@ + + */ +class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection +{ + /** + * Directory/country table name + * + * @var string + */ + protected $_countryTable; + + /** + * Directory/country_region table name + * + * @var string + */ + protected $_regionTable; + + /** + * Define resource model and item + * + * @return void + */ + protected function _construct() + { + $this->_init( + 'WebShopApps\MatrixRate\Model\Carrier\Matrixrate', + 'WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate' + ); + $this->_countryTable = $this->getTable('directory_country'); + $this->_regionTable = $this->getTable('directory_country_region'); + } + + /** + * Initialize select, add country iso3 code and region name + * + * @return void + */ + public function _initSelect() + { + parent::_initSelect(); + + $this->_select->joinLeft( + ['country_table' => $this->_countryTable], + 'country_table.country_id = main_table.dest_country_id', + ['dest_country' => 'iso3_code'] + )->joinLeft( + ['region_table' => $this->_regionTable], + 'region_table.region_id = main_table.dest_region_id', + ['dest_region' => 'code'] + ); + + $this->addOrder('dest_country', self::SORT_ORDER_ASC); + $this->addOrder('dest_region', self::SORT_ORDER_ASC); + $this->addOrder('dest_zip', self::SORT_ORDER_ASC); + $this->addOrder('condition_name', self::SORT_ORDER_ASC); + } + + /** + * Add website filter to collection + * + * @param int $websiteId + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate\Collection + */ + public function setWebsiteFilter($websiteId) + { + return $this->addFieldToFilter('website_id', $websiteId); + } + + /** + * Add condition name (code) filter to collection + * + * @param string $conditionName + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate\Collection + */ + public function setConditionFilter($conditionName) + { + return $this->addFieldToFilter('condition_name', $conditionName); + } + + /** + * Add country filter to collection + * + * @param string $countryId + * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate\Collection + */ + public function setCountryFilter($countryId) + { + return $this->addFieldToFilter('dest_country_id', $countryId); + } +} diff --git a/src/Setup/InstallSchema.php b/src/Setup/InstallSchema.php new file mode 100755 index 0000000..015caea --- /dev/null +++ b/src/Setup/InstallSchema.php @@ -0,0 +1,158 @@ +startSetup(); + + /** + * Create table 'webshopapps_matrixrate' + */ + $table = $installer->getConnection()->newTable( + $installer->getTable('webshopapps_matrixrate') + )->addColumn( + 'pk', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true], + 'Primary key' + )->addColumn( + 'website_id', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + ['nullable' => false, 'default' => '0'], + 'Website Id' + )->addColumn( + 'dest_country_id', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 4, + ['nullable' => false, 'default' => '0'], + 'Destination coutry ISO/2 or ISO/3 code' + )->addColumn( + 'dest_region_id', + \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, + null, + ['nullable' => false, 'default' => '0'], + 'Destination Region Id' + )->addColumn( + 'dest_city', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 30, + ['nullable' => false, 'default' => ''], + 'Destination City' + )->addColumn( + 'dest_zip', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 10, + ['nullable' => false, 'default' => '*'], + 'Destination Post Code (Zip)' + )->addColumn( + 'dest_zip_to', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 10, + ['nullable' => false, 'default' => '*'], + 'Destination Post Code To (Zip)' + )->addColumn( + 'condition_name', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 20, + ['nullable' => false], + 'Rate Condition name' + )->addColumn( + 'condition_from_value', + \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, + '12,4', + ['nullable' => false, 'default' => '0.0000'], + 'Rate condition from value' + )->addColumn( + 'condition_to_value', + \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, + '12,4', + ['nullable' => false, 'default' => '0.0000'], + 'Rate condition to value' + )->addColumn( + 'price', + \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, + '12,4', + ['nullable' => false, 'default' => '0.0000'], + 'Price' + )->addColumn( + 'cost', + \Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL, + '12,4', + ['nullable' => false, 'default' => '0.0000'], + 'Cost' + )->addColumn( + 'shipping_method', + \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, + 255, + ['nullable' => false], + 'Shipping Method' + )->addIndex( + $installer->getIdxName( + 'webshopapps_matrixrate', + ['website_id', 'dest_country_id', 'dest_region_id', 'dest_city', 'dest_zip', 'condition_name', + 'condition_from_value','condition_to_value','shipping_method'], + \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE + ), + ['website_id', 'dest_country_id', 'dest_region_id', 'dest_city', 'dest_zip', 'condition_name', + 'condition_from_value','condition_to_value','shipping_method'], + ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE] + )->setComment( + 'WebShopApps Shipping MatrixRate' + ); + $installer->getConnection()->createTable($table); + + + $installer->endSetup(); + + } +} diff --git a/src/Test/Unit/Block/Adminhtml/Carrier/Matrixrate/GridTest.php b/src/Test/Unit/Block/Adminhtml/Carrier/Matrixrate/GridTest.php new file mode 100755 index 0000000..f170fb7 --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/Carrier/Matrixrate/GridTest.php @@ -0,0 +1,160 @@ +objectManagerHelper = new ObjectManagerHelper($this); + + $this->storeManagerMock = $this->getMockBuilder('Magento\Store\Model\StoreManagerInterface') + ->disableOriginalConstructor() + ->getMock(); + + $this->context = $this->objectManagerHelper->getObject('Magento\Backend\Block\Template\Context', [ + 'storeManager' => $this->storeManagerMock + ]); + + $this->backendHelperMock = $this->getMockBuilder('\Magento\Backend\Helper\Data') + ->disableOriginalConstructor() + ->getMock(); + + $this->collectionFactoryMock = + $this->getMockBuilder('\WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate\CollectionFactory') + ->disableOriginalConstructor() + ->getMock(); + + $this->matrixrateMock = $this->getMockBuilder('WebShopApps\MatrixRate\Model\Carrier\Matrixrate') + ->disableOriginalConstructor() + ->getMock(); + + $this->model = new \WebShopApps\MatrixRate\Block\Adminhtml\Carrier\Matrixrate\Grid( + $this->context, + $this->backendHelperMock, + $this->collectionFactoryMock, + $this->matrixrateMock + ); + } + + public function testSetWebsiteId() + { + $websiteId = 1; + + $websiteMock = $this->getMockBuilder('Magento\Store\Model\Website') + ->setMethods(['getId']) + ->disableOriginalConstructor() + ->getMock(); + + $this->storeManagerMock->expects($this->once()) + ->method('getWebsite') + ->with($websiteId) + ->willReturn($websiteMock); + + $websiteMock->expects($this->once()) + ->method('getId') + ->willReturn($websiteId); + + $this->assertSame($this->model, $this->model->setWebsiteId($websiteId)); + $this->assertEquals($websiteId, $this->model->getWebsiteId()); + } + + public function testGetWebsiteId() + { + $websiteId = 10; + + $websiteMock = $this->getMockBuilder('Magento\Store\Model\Website') + ->disableOriginalConstructor() + ->setMethods(['getId']) + ->getMock(); + + $websiteMock->expects($this->once()) + ->method('getId') + ->willReturn($websiteId); + + $this->storeManagerMock->expects($this->once()) + ->method('getWebsite') + ->willReturn($websiteMock); + + $this->assertEquals($websiteId, $this->model->getWebsiteId()); + + $this->storeManagerMock->expects($this->never()) + ->method('getWebsite') + ->willReturn($websiteMock); + + $this->assertEquals($websiteId, $this->model->getWebsiteId()); + } + + public function testSetAndGetConditionName() + { + $conditionName = 'someName'; + $this->assertEquals($this->model, $this->model->setConditionName($conditionName)); + $this->assertEquals($conditionName, $this->model->getConditionName()); + } +} diff --git a/src/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php b/src/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php new file mode 100755 index 0000000..ce01c6e --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/Form/Field/ExportTest.php @@ -0,0 +1,94 @@ +getMock('Magento\Backend\Model\UrlInterface', [], [], '', false, false); + $backendUrl->expects($this->once())->method('getUrl')->with("*/*/exportMatrixrates", ['website' => 1]); + + // $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->_object = $this->objectManagerHelper->getObject( + 'WebShopApps\MatrixRate\Block\Adminhtml\Form\Field\Export', + ['backendUrl' => $backendUrl] + ); + } + + public function testGetElementHtml() + { + $expected = 'some test data'; + + $form = $this->getMock('Magento\Framework\Data\Form', ['getParent'], [], '', false, false); + $parentObjectMock = $this->getMock( + 'Magento\Backend\Block\Template', + ['getLayout'], + [], + '', + false, + false + ); + $layoutMock = $this->getMock('Magento\Framework\View\Layout', [], [], '', false, false); + + $blockMock = $this->getMock('Magento\Backend\Block\Widget\Button', [], [], '', false, false); + + $requestMock = $this->getMock('Magento\Framework\App\RequestInterface', [], [], '', false, false); + $requestMock->expects($this->once())->method('getParam')->with('website')->will($this->returnValue(1)); + + $mockData = $this->getMock('StdClass', ['toHtml']); + $mockData->expects($this->once())->method('toHtml')->will($this->returnValue($expected)); + + $blockMock->expects($this->once())->method('getRequest')->will($this->returnValue($requestMock)); + $blockMock->expects($this->any())->method('setData')->will($this->returnValue($mockData)); + + $layoutMock->expects($this->once())->method('createBlock')->will($this->returnValue($blockMock)); + $parentObjectMock->expects($this->once())->method('getLayout')->will($this->returnValue($layoutMock)); + $form->expects($this->once())->method('getParent')->will($this->returnValue($parentObjectMock)); + + $this->_object->setForm($form); + $this->assertEquals($expected, $this->_object->getElementHtml()); + } +} diff --git a/src/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php b/src/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php new file mode 100755 index 0000000..706a69c --- /dev/null +++ b/src/Test/Unit/Block/Adminhtml/Form/Field/ImportTest.php @@ -0,0 +1,110 @@ +_formMock = $this->getMock( + 'Magento\Framework\Data\Form', + ['getFieldNameSuffix', 'addSuffixToName'], + [], + '', + false, + false + ); + $testData = ['name' => 'test_name', 'html_id' => 'test_html_id']; + $testHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_object = $testHelper->getObject( + 'WebShopApps\MatrixRate\Block\Adminhtml\Form\Field\Import', + ['data' => $testData] + ); + $this->_object->setForm($this->_formMock); + } + + public function testGetNameWhenFormFiledNameSuffixIsEmpty() + { + $this->_formMock->expects($this->once())->method('getFieldNameSuffix')->will($this->returnValue(false)); + $this->_formMock->expects($this->never())->method('addSuffixToName'); + $actual = $this->_object->getName(); + $this->assertEquals('test_name', $actual); + } + + public function testGetNameWhenFormFiledNameSuffixIsNotEmpty() + { + $this->_formMock->expects($this->once())->method('getFieldNameSuffix')->will($this->returnValue(true)); + $this->_formMock->expects($this->once())->method('addSuffixToName')->will($this->returnValue('test_suffix')); + $actual = $this->_object->getName(); + $this->assertEquals('test_suffix', $actual); + } + + public function testGetElementHtml() + { + $this->_formMock->expects( + $this->any() + )->method( + 'getHtmlIdPrefix' + )->will( + $this->returnValue('test_name_prefix') + ); + $this->_formMock->expects( + $this->any() + )->method( + 'getHtmlIdSuffix' + )->will( + $this->returnValue('test_name_suffix') + ); + $testString = $this->_object->getElementHtml(); + $this->assertStringStartsWith( + '', + $testString + ); + } +} diff --git a/src/Test/Unit/Model/Config/Backend/MatrixrateTest.php b/src/Test/Unit/Model/Config/Backend/MatrixrateTest.php new file mode 100755 index 0000000..8a3dda9 --- /dev/null +++ b/src/Test/Unit/Model/Config/Backend/MatrixrateTest.php @@ -0,0 +1,84 @@ +objectManagerHelper = new ObjectManagerHelper($this); + + $this->tableateFactoryMock = + $this->getMockBuilder('WebShopApps\MatrixRate\Model\ResourceModel\Carrier\MatrixrateFactory') + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + + $this->model = $this->objectManagerHelper->getObject('\WebShopApps\MatrixRate\Model\Config\Backend\Matrixrate', [ + 'matrixrateFactory' => $this->tableateFactoryMock + ]); + } + + public function testAfterSave() + { + $matrixrateMock = $this->getMockBuilder('WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate') + ->disableOriginalConstructor() + ->setMethods(['uploadAndImport']) + ->getMock(); + + $this->tableateFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($matrixrateMock); + + $matrixrateMock->expects($this->once()) + ->method('uploadAndImport') + ->with($this->model); + + $this->model->afterSave(); + } +} diff --git a/src/Test/Unit/Model/Config/Source/MatrixrateTest.php b/src/Test/Unit/Model/Config/Source/MatrixrateTest.php new file mode 100755 index 0000000..68e79fa --- /dev/null +++ b/src/Test/Unit/Model/Config/Source/MatrixrateTest.php @@ -0,0 +1,80 @@ +carrierMatrixrateMock = $this->getMockBuilder('\WebShopApps\MatrixRate\Model\Carrier\Matrixrate') + ->disableOriginalConstructor() + ->setMethods(['getCode']) + ->getMock(); + + $this->objectManagerHelper = new ObjectManagerHelper($this); + + $this->model = $this->objectManagerHelper->getObject('WebShopApps\MatrixRate\Model\Config\Source\Matrixrate', [ + 'carrierMatrixrate' => $this->carrierMatrixrateMock + ]); + } + + public function testToOptionArray() + { + $codes = [1, 2, 3, 4, 5]; + $expected = []; + foreach ($codes as $k => $v) { + $expected[] = ['value' => $k, 'label' => $v]; + } + + $this->carrierMatrixrateMock->expects($this->once()) + ->method('getCode') + ->willReturn($codes); + + $this->assertEquals($expected, $this->model->toOptionArray()); + } +} diff --git a/src/etc/adminhtml/routes.xml b/src/etc/adminhtml/routes.xml new file mode 100755 index 0000000..a446b34 --- /dev/null +++ b/src/etc/adminhtml/routes.xml @@ -0,0 +1,42 @@ + + + + + + + + + diff --git a/src/etc/adminhtml/system.xml b/src/etc/adminhtml/system.xml new file mode 100755 index 0000000..a1ab0cd --- /dev/null +++ b/src/etc/adminhtml/system.xml @@ -0,0 +1,112 @@ + + + + +
+ + + + + This module was developed by www.WebShopApps.com - Magento Shipping Extension Specialists. +
For docs & examples refer to the WebShopApps knowledge base. + + ]]> +
+ + + Magento\Config\Model\Config\Source\Yesno + + + + + + + WebShopApps\MatrixRate\Model\Config\Source\Matrixrate + + + + Magento\Config\Model\Config\Source\Yesno + + + + + + + WebShopApps\MatrixRate\Model\Config\Backend\Matrixrate + + + + Magento\Config\Model\Config\Source\Yesno + You should only set this to Yes if you use purely numeric zipcodes (e.g. USA/AUS clients) + + + + + Magento\Shipping\Model\Source\HandlingType + + + + validate-number validate-zero-or-greater + + + + + shipping-applicable-country + Magento\Shipping\Model\Config\Source\Allspecificcountries + + + + Magento\Directory\Model\Config\Source\Country + 1 + + + + shipping-skip-hide + Magento\Config\Model\Config\Source\Yesno + + + + + + + + + +
+
+
+
diff --git a/src/etc/config.xml b/src/etc/config.xml new file mode 100755 index 0000000..58ef385 --- /dev/null +++ b/src/etc/config.xml @@ -0,0 +1,52 @@ + + + + + + + 0 + 0 + package_weight + 1 + WebShopApps\MatrixRate\Model\Carrier\Matrixrate + Matrix Rate + Select Shipping Method + This shipping method is not available. To use this shipping method, please contact us. + F + + + + diff --git a/src/etc/crontab.xml b/src/etc/crontab.xml new file mode 100755 index 0000000..d6158c4 --- /dev/null +++ b/src/etc/crontab.xml @@ -0,0 +1,42 @@ + + + + + + 0 0 1,10,20 * * + + + diff --git a/src/etc/module.xml b/src/etc/module.xml new file mode 100755 index 0000000..38422f8 --- /dev/null +++ b/src/etc/module.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + diff --git a/src/i18n/en_US.csv b/src/i18n/en_US.csv new file mode 100755 index 0000000..94fb409 --- /dev/null +++ b/src/i18n/en_US.csv @@ -0,0 +1,26 @@ +Country,Country +"Region/State","Region/State" +"Zip/Postal Code","Zip/Postal Code" +City,City +"Shipping Price","Shipping Price" +"Shipping Method","Shipping Method" +"Export CSV","Export CSV" +"Weight vs. Destination","Weight vs. Destination" +"Order Subtotal vs. Destination","Order Subtotal vs. Destination" +"# of Items vs. Destination","# of Items vs. Destination" +Weight,Weight +"Order Subtotal","Order Subtotal" +"# of Items","# of Items" +"Please correct Matrix Rate code type: %1.","Please correct Matrix Rate code type: %1." +"Please correct Matrix Rate code for type %1: %2.","Please correct Matrix Rate code for type %1: %2." +"Please correct Matrix Rates File Format.","Please correct Matrix Rates File Format." +"Something went wrong while importing matrix rates.","Something went wrong while importing matrix rates." +"We couldn\'t import this file because of these errors: %1","We couldn\'t import this file because of these errors: %1" +"Please correct Matrix Rates format in Row #%1. Invalid Number of Rows","Please correct Matrix Rates format in Row #%1. Invalid Number of Rows" +"Please correct Country "%1" in Row #%2.","Please correct Country "%1" in Row #%2." +"Please correct Region/State "%1" in Row #%2.","Please correct Region/State "%1" in Row #%2." +"Please correct %1 From "%2" in Row #%3.","Please correct %1 From "%2" in Row #%3." +"Please correct %1 To "%2" in Row #%3.","Please correct %1 To "%2" in Row #%3." +"Please correct Shipping Price "%1" in Row #%2.","Please correct Shipping Price "%1" in Row #%2." +"Please correct Shipping Method "%1" in Row #%2.","Please correct Shipping Method "%1" in Row #%2." +"Duplicate Row #%1 (Country "%2", Region/State "%3", City "%4", Zip from "%5", Zip to "%6", From Value "%7", To Value "%8", and Shipping Method "%9")","Duplicate Row #%1 (Country "%2", Region/State "%3", City "%4", Zip from "%5", Zip to "%6", From Value "%7", To Value "%8", and Shipping Method "%9")" diff --git a/src/registration.php b/src/registration.php new file mode 100755 index 0000000..34f1c54 --- /dev/null +++ b/src/registration.php @@ -0,0 +1,6 @@ +