From ee1b9ff165f3d70187744d1cdcdfcb9b96c0fba0 Mon Sep 17 00:00:00 2001 From: Graham Wharton Date: Mon, 9 Sep 2024 14:14:00 +0100 Subject: [PATCH] First Issue of Updated Modules --- .github/workflows/autorelease.yaml | 26 ++ LICENSE.md | 44 +++ Model/TaxScheme.php | 508 +++++++++++++++++++++++++++++ README.md | 24 ++ Test/Integration/TaxSchemeTest.php | 310 ++++++++++++++++++ Test/Unit/TaxSchemeTest.php | 139 ++++++++ composer.json | 7 +- etc/adminhtml/system.xml | 149 +++++++++ etc/config.xml | 21 ++ etc/di.xml | 17 + registration.php | 1 + 11 files changed, 1245 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/autorelease.yaml create mode 100644 LICENSE.md create mode 100644 Model/TaxScheme.php create mode 100644 README.md create mode 100644 Test/Integration/TaxSchemeTest.php create mode 100644 Test/Unit/TaxSchemeTest.php create mode 100644 etc/adminhtml/system.xml create mode 100644 etc/config.xml create mode 100644 etc/di.xml diff --git a/.github/workflows/autorelease.yaml b/.github/workflows/autorelease.yaml new file mode 100644 index 0000000..0288c33 --- /dev/null +++ b/.github/workflows/autorelease.yaml @@ -0,0 +1,26 @@ +name: AutoRelease +on: + push: + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Auto Increment Semver Action + uses: MCKanpolat/auto-semver-action@1.0.11 + id: versioning + with: + releaseType: patch + incrementPerCommit: true + github_token: ${{ secrets.GITHUB_TOKEN }} + - name: Next Release Number + run: echo ${{ steps.versioning.outputs.version }} + - name: Checkout + uses: actions/checkout@v4 + - name: Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.versioning.outputs.version }} + make_latest: true diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5c7798b --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,44 @@ +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: + +a) to reproduce the Original Work in copies, either alone or as part of a collective work; + +b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + +c) 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; + +d) to perform the Original Work publicly; and + +e) to display the Original Work publicly. +
  2. +
  3. 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.
  4. + +
  5. 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.
  6. + +
  7. 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.
  8. + +
  9. 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).
  10. + +
  11. 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.
  12. + +
  13. 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.
  14. + +
  15. 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.
  16. + +
  17. 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).
  18. + +
  19. 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.
  20. + +
  21. 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.
  22. + +
  23. 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.
  24. + +
  25. 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.
  26. + +
  27. 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.
  28. + +
  29. 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.
  30. + +
  31. 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 "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.
  32. diff --git a/Model/TaxScheme.php b/Model/TaxScheme.php new file mode 100644 index 0000000..dfef19b --- /dev/null +++ b/Model/TaxScheme.php @@ -0,0 +1,508 @@ +scopeConfig = $scopeConfig; + $this->logger = $logger; + $this->storeManager = $storeManager; + $this->currencyFactory = $currencyFactory; + $this->ticrFactory = $ticrFactory; + $this->dateTime = $dateTime; + } + + /** + * Get the order value, in scheme currency + * + * The "GST on low value imported goods" guide details how to handle shipments that contain multiple low value + * items that will be shipped together, that when combined present an order value that is above 1,000 AUD. + * In this case, even though individual items may be classed as low value items and would attract GST, + * the value of the entire shipment is above the threshold and VAT should not be charged at the point + * of sale. + * + * https://www.ato.gov.au/businesses-and-organisations/international-tax-for-business/gst-on-imported-goods-and-services/gst-on-low-value-imported-goods + * + * @param Quote $quote + * @return float + */ + public function getOrderValue(Quote $quote): float + { + $orderValue = 0.0; + foreach ($quote->getItemsCollection() as $item) { + $orderValue += ($item->getBaseRowTotal() - $item->getBaseDiscountAmount()); + } + return $orderValue / $this->getSchemeExchangeRate($quote->getStoreId()); + } + + /** + * Get customer group based on Validation Result and Country of customer + * @param string $customerCountryCode + * @param string|null $customerPostCode + * @param bool $taxIdValidated + * @param float $orderValue + * @param int|null $storeId + * @return int|null + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + * @SuppressWarnings(PHPMD.NPathComplexity) + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function getCustomerGroup( + string $customerCountryCode, + ?string $customerPostCode, + bool $taxIdValidated, + float $orderValue, + ?int $storeId + ): ?int { + $merchantCountry = $this->scopeConfig->getValue( + StoreInformation::XML_PATH_STORE_INFO_COUNTRY_CODE, + ScopeInterface::SCOPE_STORE, + $storeId + ); + if (empty($merchantCountry)) { + $this->logger->critical( + "Gw/AutoCustomerGroupAustralia/Model/TaxScheme::getCustomerGroup() : " . + "Merchant country not set." + ); + return null; + } + + $importThreshold = $this->getThresholdInSchemeCurrency($storeId); + + //Merchant Country is in Australia + //Item shipped to Australia + //Therefore Domestic + if (in_array($merchantCountry, self::SCHEME_COUNTRIES) && + in_array($customerCountryCode, self::SCHEME_COUNTRIES)) { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/domestic", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + //Merchant Country is not in Australia + //Item shipped to Australia + //GST Validated ABN Number Supplied + //Therefore Import B2B + if (!in_array($merchantCountry, self::SCHEME_COUNTRIES) && + in_array($customerCountryCode, self::SCHEME_COUNTRIES) && + $taxIdValidated) { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/importb2b", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + //Merchant Country is not in Australia + //Item shipped to Australia + //Order Value equal or below threshold + //Therefore Import Taxed + if (!in_array($merchantCountry, self::SCHEME_COUNTRIES) && + in_array($customerCountryCode, self::SCHEME_COUNTRIES) && + ($orderValue <= $importThreshold)) { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/importtaxed", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + //Merchant Country is not in Australia + //Item shipped to Australia + //Order value below threshold + //Therefore Import Unaxed + if (!in_array($merchantCountry, self::SCHEME_COUNTRIES) && + in_array($customerCountryCode, self::SCHEME_COUNTRIES) && + ($orderValue > $importThreshold)) { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/importuntaxed", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + return null; + } + + /** + * Peform validation of the ABN, returning a gatewayResponse object + * + * @param string $countryCode + * @param string|null $taxId + * @return TaxIdCheckResponseInterface + * @SuppressWarnings(PHPMD.CyclomaticComplexity) + */ + public function checkTaxId( + string $countryCode, + ?string $taxId + ): TaxIdCheckResponseInterface { + $taxIdCheckResponse = $this->ticrFactory->create(); + + if (!in_array($countryCode, self::SCHEME_COUNTRIES)) { + $taxIdCheckResponse->setRequestMessage(__('Unsupported country.')); + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(false); + return $taxIdCheckResponse; + } + + if ($taxId) { + $taxId = str_replace([' ', '-'], ['', ''], $taxId); + } + + $taxIdCheckResponse = $this->validateFormat($taxIdCheckResponse, $taxId); + + if ($taxIdCheckResponse->getIsValid() && $this->scopeConfig->isSetFlag( + "autocustomergroup/" . self::CODE . "/validate_online", + ScopeInterface::SCOPE_STORE + )) { + $taxIdCheckResponse = $this->validateOnline($taxIdCheckResponse, $taxId); + } + + return $taxIdCheckResponse; + } + + /** + * Perform offline validation of the Tax Identifier + * + * @param $taxIdCheckResponse + * @param $taxId + * @return TaxIdCheckResponseInterface + */ + private function validateFormat($taxIdCheckResponse, $taxId): TaxIdCheckResponseInterface + { + if (($taxId === null || strlen($taxId) < 1)) { + $taxIdCheckResponse->setRequestMessage(__('You didn\'t supply an ABN to check.')); + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(true); + return $taxIdCheckResponse; + } + if (preg_match("/^[0-9]{11}$/i", $taxId)) { + $taxIdCheckResponse->setIsValid(true); + $taxIdCheckResponse->setRequestSuccess(true); + $taxIdCheckResponse->setRequestMessage(__('ABN is the correct format.')); + } else { + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(true); + $taxIdCheckResponse->setRequestMessage(__('ABN is not the correct format.')); + return $taxIdCheckResponse; + } + if ($this->isValidAbn($taxId)) { + $taxIdCheckResponse->setIsValid(true); + $taxIdCheckResponse->setRequestSuccess(true); + $taxIdCheckResponse->setRequestMessage(__('ABN is validated (Offline).')); + } else { + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(true); + $taxIdCheckResponse->setRequestMessage(__('ABN is not valid (Offline).')); + return $taxIdCheckResponse; + } + return $taxIdCheckResponse; + } + + /** + * Perform online validation of the Tax Identifier + * + * @param $taxIdCheckResponse + * @param $taxId + * @return TaxIdCheckResponseInterface + */ + private function validateOnline($taxIdCheckResponse, $taxId): TaxIdCheckResponseInterface + { + $apiguid = $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/apiguid", + ScopeInterface::SCOPE_STORE + ); + if (empty($apiguid)) { + $this->logger->critical( + "Gw/AutoCustomerGroupUk/Model/TaxScheme::checkTaxId() : API GUID not set." + ); + $taxIdCheckResponse->setRequestMessage(__('API GUID not set.')); + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(false); + return $taxIdCheckResponse; + } + + try { + $soapClient = new SoapClient("https://abr.business.gov.au/abrxmlsearch/ABRXMLSearch.asmx?WSDL"); + + $requestParams = []; + $requestParams['searchString'] = $taxId; + $requestParams['includeHistoricalDetails'] ='N'; + $requestParams['authenticationGuid'] = $apiguid; + + $result = $soapClient->ABRSearchByABN($requestParams); + + $isCurrent = $result->ABRPayloadSearchResults->response->businessEntity->ABN->isCurrentIndicator; + $gstValid = false; + + if (isset($result->ABRPayloadSearchResults->response->businessEntity->goodsAndServicesTax)) { + $gstValid = true; + $gstFrom = $result->ABRPayloadSearchResults->response + ->businessEntity->goodsAndServicesTax->effectiveFrom; + $day = $this->dateTime->gmtDate("Y-m-d"); + if ($gstFrom > $day) { + $gstValid = false; + } else { + $gstTo = $result->ABRPayloadSearchResults->response + ->businessEntity->goodsAndServicesTax->effectiveTo; + if (($gstTo != "0001-01-01") && + ($gstTo < $day)) { + $gstValid = false; + } + } + } + $identifier = $result->ABRPayloadSearchResults->response->businessEntity->ABN->identifierValue; + $datetime = $result->ABRPayloadSearchResults->response->dateTimeRetrieved; + + if (preg_match("/^[Y](es)?$/i", $isCurrent) && + $gstValid && + !empty($datetime)) { + $taxIdCheckResponse->setRequestIdentifier($identifier); + $taxIdCheckResponse->setRequestDate($datetime); + $taxIdCheckResponse->setRequestSuccess(true); + $taxIdCheckResponse->setIsValid(true); + $taxIdCheckResponse->setRequestMessage(__('ABN validated and business is registered for GST with ATO.')); + } else { + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(true); + $taxIdCheckResponse->setRequestDate(''); + $taxIdCheckResponse->setRequestMessage(__('Please enter a valid ABN number, where the business is registered for GST.')); + } + } catch (Exception $exception) { + $taxIdCheckResponse->setIsValid(false); + $taxIdCheckResponse->setRequestSuccess(false); + $taxIdCheckResponse->setRequestDate(''); + $taxIdCheckResponse->setRequestIdentifier(''); + $taxIdCheckResponse->setRequestMessage(__('There was an error checking the ABN.')); + } + return $taxIdCheckResponse; + } + + /** + * Validate an Australian Business Number (ABN) + * + * @param string|null $abn + * @return bool + */ + public function isValidAbn(?string $abn): bool + { + $weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]; + + // Strip non-numbers from the acn + $abn = preg_replace('/[^0-9]/', '', $abn ?? ""); + + // Check abn is 11 chars long + if (strlen($abn) != 11) { + return false; + } + + // Subtract one from first digit + $abn[0] = ((int)$abn[0] - 1); + + // Sum the products + $sum = 0; + foreach (str_split($abn) as $key => $digit) { + $sum += ((int) $digit * $weights[$key]); + } + + if (($sum % 89) != 0) { + return false; + } + return true; + } + + /** + * Get the scheme name + * + * @return string + */ + public function getSchemeName(): string + { + return __("Australia GST for Non Residents Scheme"); + } + + /** + * Get the scheme code + * + * @return string + */ + public function getSchemeId(): string + { + return self::CODE; + } + + /** + * @param int|null $storeId + * @return string|null + */ + public function getFrontEndPrompt(?int $storeId): ?string + { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/frontendprompt", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @return string + */ + public function getSchemeCurrencyCode(): string + { + return self::SCHEME_CURRENCY; + } + + /** + * @param int|null $storeId + * @return float + */ + public function getThresholdInSchemeCurrency(?int $storeId): float + { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/importthreshold", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int|null $storeId + * @return string|null + */ + public function getSchemeRegistrationNumber(?int $storeId): ?string + { + return $this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/registrationnumber", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @return array + */ + public function getSchemeCountries(): array + { + return self::SCHEME_COUNTRIES; + } + + /** + * @param int|null $storeId + * @return bool + */ + public function isEnabled(?int $storeId): bool + { + return $this->scopeConfig->isSetFlag( + "autocustomergroup/" . self::CODE . "/enabled", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } + + /** + * @param int|null $storeId + * @return float + */ + public function getSchemeExchangeRate(?int $storeId): float + { + if ($this->scopeConfig->isSetFlag( + "autocustomergroup/" . self::CODE . '/usemagentoexchangerate', + ScopeInterface::SCOPE_STORE, + $storeId + )) { + $websiteBaseCurrency = $this->scopeConfig->getValue( + Currency::XML_PATH_CURRENCY_BASE, + ScopeInterface::SCOPE_STORE, + $storeId + ); + $exchangerate = $this->currencyFactory + ->create() + ->load($this->getSchemeCurrencyCode()) + ->getAnyRate($websiteBaseCurrency); + if (!$exchangerate) { + $this->logger->critical( + "Gw/AutoCustomerGroupAustralia/Model/TaxScheme::getSchemeExchangeRate() : " . + "No Magento Exchange Rate configured for " . self::SCHEME_CURRENCY . " to " . + $websiteBaseCurrency . ". Using 1.0" + ); + $exchangerate = 1.0; + } + return (float)$exchangerate; + } + return (float)$this->scopeConfig->getValue( + "autocustomergroup/" . self::CODE . "/exchangerate", + ScopeInterface::SCOPE_STORE, + $storeId + ); + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..85625fd --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +

    AutoCustomerGroup - Australia Addon

    +

    Magento 2 Module - Module to add Australia functionality to gwharton/module-autocustomergroup

    +

    Australia GST for Non Residents Scheme

    +

    Configuration Options

    + +

    Integration Tests

    +

    To run the integration tests, you need your own credentials for the Australian Business Register API. Please add them to config-global.php.

    +

    Please note that the Australian Business Register API does not have a sandbox for testing, so a live API GUID should be used.

    + diff --git a/Test/Integration/TaxSchemeTest.php b/Test/Integration/TaxSchemeTest.php new file mode 100644 index 0000000..fc905ad --- /dev/null +++ b/Test/Integration/TaxSchemeTest.php @@ -0,0 +1,310 @@ +objectManager = Bootstrap::getObjectManager(); + $this->taxScheme = $this->objectManager->get(TaxScheme::class); + $this->config = $this->objectManager->get(ReinitableConfigInterface::class); + $this->storeManager = $this->objectManager->get(StoreManagerInterface::class); + $this->productFactory = $this->objectManager->get(ProductFactory::class); + $this->guestCartManagement = $this->objectManager->get(GuestCartManagementInterface::class); + $this->guestCartRepository = $this->objectManager->get(GuestCartRepositoryInterface::class); + $this->quoteRepository = $this->objectManager->get(CartRepositoryInterface::class); + $this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class); + } + + /** + * @magentoAdminConfigFixture current_store currency/options/default GBP + * @magentoAdminConfigFixture current_store currency/options/base GBP + * @magentoConfigFixture current_store autocustomergroup/australiagst/usemagentoexchangerate 0 + * @magentoConfigFixture current_store autocustomergroup/australiagst/exchangerate 0.4985 + * @dataProvider getOrderValueDataProvider + */ + public function testGetOrderValue( + $qty1, + $price1, + $qty2, + $price2, + $expectedValue + ): void { + $product1 = $this->productFactory->create(); + $product1->setTypeId('simple') + ->setId(1) + ->setAttributeSetId(4) + ->setWebsiteIds([1]) + ->setName('Simple Product 1') + ->setSku('simple1') + ->setPrice($price1) + ->setVisibility(Visibility::VISIBILITY_BOTH) + ->setStatus(Status::STATUS_ENABLED) + ->setStockData(['use_config_manage_stock' => 0]); + $this->productRepository->save($product1); + $product2 = $this->productFactory->create(); + $product2->setTypeId('simple') + ->setId(2) + ->setAttributeSetId(4) + ->setWebsiteIds([1]) + ->setName('Simple Product 2') + ->setSku('simple2') + ->setPrice($price2) + ->setVisibility(Visibility::VISIBILITY_BOTH) + ->setStatus(Status::STATUS_ENABLED) + ->setStockData(['use_config_manage_stock' => 0]); + $this->productRepository->save($product2); + $maskedCartId = $this->guestCartManagement->createEmptyCart(); + $quote = $this->guestCartRepository->get($maskedCartId); + $quote->addProduct($product1, $qty1); + $quote->addProduct($product2, $qty2); + $this->quoteRepository->save($quote); + $result = $this->taxScheme->getOrderValue( + $quote + ); + $this->assertEqualsWithDelta($expectedValue, $result, 0.009); + } + + /** + * Remember for AUS, it is the sum of the item prices that counts, + * i.e total order value including discounts without shipping + * + * @return array + */ + public function getOrderValueDataProvider(): array + { + // Quantity 1 + // Base Price 1 + // Quantity 2 + // Base Price 2 + // Expected Order Value Scheme Currency + return [ + [1, 100.00, 2, 50.00, 401.20], // 200.00GBP in AUD + [2, 100.00, 1, 100.00, 601.80], // 400.00GBP in AUD + [7, 25.50, 2, 0.99, 362.05], // 180.48GBP in AUD + [7, 25.50, 4, 100.00, 1160.48], // 578.50GBP in AUD + [7, 25.50, 10, 1000.00, 20418.25] // 10178.50GBP in AUD + ]; + } + + /** + * @magentoConfigFixture current_store autocustomergroup/australiagst/domestic 1 + * @magentoConfigFixture current_store autocustomergroup/australiagst/importb2b 2 + * @magentoConfigFixture current_store autocustomergroup/australiagst/importtaxed 3 + * @magentoConfigFixture current_store autocustomergroup/australiagst/importuntaxed 4 + * @magentoConfigFixture current_store autocustomergroup/australiagst/importthreshold 1000 + * @dataProvider getCustomerGroupDataProvider + */ + public function testGetCustomerGroup( + $merchantCountryCode, + $merchantPostCode, + $customerCountryCode, + $customerPostCode, + $taxIdValidated, + $orderValue, + $expectedGroup + ): void { + $storeId = $this->storeManager->getStore()->getId(); + $this->config->setValue( + StoreInformation::XML_PATH_STORE_INFO_COUNTRY_CODE, + $merchantCountryCode, + ScopeInterface::SCOPE_STORE + ); + $this->config->setValue( + StoreInformation::XML_PATH_STORE_INFO_POSTCODE, + $merchantPostCode, + ScopeInterface::SCOPE_STORE + ); + $result = $this->taxScheme->getCustomerGroup( + $customerCountryCode, + $customerPostCode, + $taxIdValidated, + $orderValue, + $storeId + ); + $this->assertEquals($expectedGroup, $result); + } + + /** + * @return array + */ + public function getCustomerGroupDataProvider(): array + { + //Merchant Country Code + //Merchant Post Code + //Customer Country Code + //Customer Post Code + //taxIdValidated + //OrderValue + //Expected Group + return [ + // AU to AU, value doesn't matter, GST number status doesn't matter - Domestic + ['AU', null, 'AU', null, false, 999, 1], + ['AU', null, 'AU', null, true, 1001, 1], + ['AU', null, 'AU', null, false, 999, 1], + ['AU', null, 'AU', null, false, 999, 1], + ['AU', null, 'AU', null, true, 999, 1], + ['AU', null, 'AU', null, false, 1001, 1], + ['AU', null, 'AU', null, false, 1001, 1], + // Import into AU, value doesn't matter, valid GST - Import B2B + ['FR', null, 'AU', null, true, 999, 2], + ['FR', null, 'AU', null, true, 1001, 2], + // Import into AU, value below threshold, Should only be B2C at this point - Import Taxed + ['FR', null, 'AU', null, false, 999, 3], + ['FR', null, 'AU', null, false, 999, 3], + // Import into AU, value above threshold, Should only be B2C at this point - Import Untaxed + ['FR', null, 'AU', null, false, 1001, 4], + ['FR', null, 'AU', null, false, 1001, 4], + ]; + } + + /** + * @magentoConfigFixture current_store autocustomergroup/australiagst/validate_online 1 + * @dataProvider checkTaxIdDataProviderOnline + * + */ + public function testCheckTaxIdOnline( + $countryCode, + $taxId, + $isValid + ): void { + $result = $this->taxScheme->checkTaxId( + $countryCode, + $taxId + ); + $this->assertEquals($isValid, $result->getIsValid()); + } + + /** + * @return array + */ + public function checkTaxIdDataProviderOnline(): array + { + //Country code + //Tax Id + //IsValid + return [ + ['AU', '', false], + ['AU', null, false], + ['AU', '72 629 951 766', true], // Correct format, valid ABN, valid GST + ['AU', '50 110 219 460', false], // Correct format, valid ABN, no GST + ['AU', '9429032097351', false], + ['AU', '9429036975273', false], + ['AU', 'htght', false], + ['AU', 'nntreenhrhnjrehh', false], + ['AU', '4363546743743', false], + ['AU', '7234767476612', false], + ['AU', 'th', false], + ['AU', '786176152', false], + ['GB', '72 629 951 766', false], // Unsupported country, despite valid number + ]; + } + + /** + * @dataProvider checkTaxIdDataProviderOfline + * + */ + public function testCheckTaxIdOffline( + $countryCode, + $taxId, + $isValid + ): void { + $result = $this->taxScheme->checkTaxId( + $countryCode, + $taxId + ); + $this->assertEquals($isValid, $result->getIsValid()); + } + + /** + * @return array + */ + public function checkTaxIdDataProviderOfline(): array + { + //Country code + //Tax Id + //IsValid + return [ + ['AU', '', false], + ['AU', null, false], + ['AU', '72 629 951 766', true], // Correct format + ['AU', '50 110 219 460', true], // Correct format + ['AU', '9429032097351', false], + ['AU', '9429036975273', false], + ['AU', 'htght', false], + ['AU', 'nntreenhrhnjrehh', false], + ['AU', '4363546743743', false], + ['AU', '7234767476612', false], + ['AU', 'th', false], + ['AU', '786176152', false] + ]; + } +} + diff --git a/Test/Unit/TaxSchemeTest.php b/Test/Unit/TaxSchemeTest.php new file mode 100644 index 0000000..4e744d4 --- /dev/null +++ b/Test/Unit/TaxSchemeTest.php @@ -0,0 +1,139 @@ +scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->storeManagerMock = $this->getMockBuilder(StoreManagerInterface::class) + ->disableOriginalConstructor() + ->getMockForAbstractClass(); + + $this->currencyFactoryMock = $this->getMockBuilder(CurrencyFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->taxIdCheckResponseInterfaceFactoryMock = $this->getMockBuilder(TaxIdCheckResponseInterfaceFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->dateTimeMock = $this->getMockBuilder(DateTime::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->helperMock = $this->getMockBuilder(TaxSchemeHelper::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->model = new TaxScheme( + $this->scopeConfigMock, + $this->loggerMock, + $this->storeManagerMock, + $this->currencyFactoryMock, + $this->taxIdCheckResponseInterfaceFactoryMock, + $this->dateTimeMock, + $this->helperMock + ); + } + + public function testGetSchemeName(): void + { + $schemeName = $this->model->getSchemeName(); + $this->assertIsString($schemeName); + $this->assertGreaterThan(0, strlen($schemeName)); + } + + /** + * @param $number + * @param $valid + * @return void + * @dataProvider isValidAbnDataProvider + */ + public function testIsValidAbn($number, $valid): void + { + $this->assertEquals($valid, $this->model->isValidAbn($number)); + } + + /** + * Data provider for testIsValidAbn() + * + * @return array + */ + public function isValidAbnDataProvider(): array + { + //Valid numbers from https://abr.business.gov.au/Search/ResultsActive?SearchText=example + return [ + ["50 110 219 460", true], + ["99 644 068 913", true], + ["36 643 591 119", true], + ["90 929 922 193", true], + ["58 630 144 375", true], + ["oygyg", false], + ["98 765 432 111", false], + ["12 345 678 999", false], + ["", false] + ]; + } +} + diff --git a/composer.json b/composer.json index 0599101..59bfcbf 100644 --- a/composer.json +++ b/composer.json @@ -1,9 +1,14 @@ { "name": "gwharton/module-autocustomergroup-australia", + "license": "OSL-3.0", "type": "magento2-module", "require": { + "ext-soap": "*", + "gwharton/module-autocustomergroup": "*", "magento/framework": "*", - "gwharton/module-autocustomergroup": "*" + "magento/module-quote": "*", + "magento/module-store": "*", + "psr/log": "*" }, "config": { "sort-packages": true diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml new file mode 100644 index 0000000..6f29f1a --- /dev/null +++ b/etc/adminhtml/system.xml @@ -0,0 +1,149 @@ + + + +
    + + + +

    This Scheme applies to shipments being sent from anywhere in the world to Consumers (Not B2B transactions) in Australia.

    +

    As of 1st July 2017, all sellers must (if their turnover to Australia exceeds 75,000 AUD) register for the Australia GST for Non Residents scheme, + and collect GST for B2C transactions at the point of sale and remit to the Australian Government.

    +

    The module assumes the following rules :

    +
      +
    • Domestic - For shipments within Australia, normal Australia GST rules apply.
    • +
    • Import B2B - For shipments from outside of Australia to Australia and the buyer presents a validated for GST ABN number, then + GST should not be charged.
    • +
    • Import Taxed - For imports into Australia, where the total goods value is equal to or below 1,000 AUD, then + GST should be charged.
    • +
    • Import Untaxed - For imports into Australia, where the total goods value is above 1,000 AUD, then GST should + NOT be charged and instead will be collected at the Australia border along with any duties due.
    • +
    +

    For the Australia GST for Non Residents Scheme, the following applies (This can be confirmed + here) :

    +
      +
    • Total Goods value is the sum of the sale price of all items sold (including any discounts)
    • +
    • When determining whether GST should be charged (GST Threshold) Shipping or Insurance Costs are not included in the value of the goods.
    • +
    • When determining the amount of GST to charge the Goods value does include Shipping and Insurance Costs.
    • +
    +

    The GST on low value imported goods + guide details how to handle shipments that contain multiple low value items that will be shipped together, that when combined present an order + value that is above 1,000 AUD. In this case, even though individual items may be classed as low value items and would attract GST, the value + of the entire shipment is above the threshold and VAT should not be charged at the point of sale.

    +

    More information on the scheme can be found on the + Australian Tax Office Website

    +

    Credentials for the Australian Tax Office ABN checker API can be obtained by signing up on the Australian Business Register Website.

    +

    If the customer enters a valid format AU ABN number at checkout, the number will be validated with the Australian Business Register. Credentials + for the Australian Business Register API can be obtained by signing up on the Australian Business Register Website.

    + + ]]>
    + + 1 + + + + Magento\Config\Model\Config\Source\Yesno + + + + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + +
  33. Yes : GST number is checked with the ATO's Australian Business Register.
  34. +
  35. No : Only the format of the ABN Number is checked.
  36. + + ]]>
    + + 1 + +
    + + + + 1 + 1 + + + + + + 1 + + + + + + 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + 1 + + + + + + Australian Tax Office Website. + ]]> + + 0 + 1 + + + + + AuGstImportThresholdStoreBaseCurrency + The order value above which no GST should be charged. Calculated as the sum of all line items after discount ex Tax. + + 1 + + + + + Gw\AutoCustomerGroup\Model\Config\Source\Group + Merchant Country is in Australia, Item is being shipped to Australia. + + 1 + + + + + Gw\AutoCustomerGroup\Model\Config\Source\Group + Merchant Country is not in Australia, Item is being shipped to Australia, Validated for GST ABN Number Supplied. + + 1 + + + + + Gw\AutoCustomerGroup\Model\Config\Source\Group + Merchant Country is not in Australia, Item is being shipped to Australia, Goods Value is below or equal to Import GST Threshold. + + 1 + + + + + Gw\AutoCustomerGroup\Model\Config\Source\Group + Merchant Country is not in Australia, Item is being shipped to Australia, Goods Value is above the Import GST Threshold. + + 1 + + +
    +
    +
    +
    diff --git a/etc/config.xml b/etc/config.xml new file mode 100644 index 0000000..4bd398e --- /dev/null +++ b/etc/config.xml @@ -0,0 +1,21 @@ + + + + + + 0 + GST Registered Businesses, please enter your ABN so we can apply the correct rate of GST to your order. + 0 + + + 1000 + 1 + 1 + 0 + 0 + 0 + 0 + + + + diff --git a/etc/di.xml b/etc/di.xml new file mode 100644 index 0000000..72b888a --- /dev/null +++ b/etc/di.xml @@ -0,0 +1,17 @@ + + + + + + Gw\AutoCustomerGroupAustralia\Model\TaxScheme + + + + + + Gw\AutoCustomerGroupAustralia\Model\TaxScheme + + + diff --git a/registration.php b/registration.php index 29661f5..4b7d5cc 100644 --- a/registration.php +++ b/registration.php @@ -1,4 +1,5 @@