From 7e10deec0e664452ad83c09c40e6cbf743d0cd1a Mon Sep 17 00:00:00 2001 From: Felipe Dominguesche Date: Mon, 23 Nov 2020 15:10:51 -0300 Subject: [PATCH 1/3] =?UTF-8?q?Remo=C3=A7=C3=A3o=20das=20labels=20dos=20ca?= =?UTF-8?q?mpos=20field-name-firstname=20e=20field-name-lastname,=20com=20?= =?UTF-8?q?esse=20tratamento=20faz=20parecer=20que=20os=20campos=20Social?= =?UTF-8?q?=20Name=20e=20Trade=20Name=20est=C3=A3o=20duplicados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- view/frontend/web/change-person-type.js | 18 +----------------- 1 file changed, 1 insertion(+), 17 deletions(-) diff --git a/view/frontend/web/change-person-type.js b/view/frontend/web/change-person-type.js index 93b1c49..2f7deb6 100755 --- a/view/frontend/web/change-person-type.js +++ b/view/frontend/web/change-person-type.js @@ -47,14 +47,6 @@ define([ _showIndividual: function () { $(this.options.individualContainer).show(); $(this.options.corporateContainer).hide(); - - if(this.options.changeFirstnameLabel){ - $(".field-name-firstname label span").text($.mage.__('First Name')); - } - - if(this.options.changeLastnameLabel){ - $(".field-name-lastname label span").text($.mage.__('Last Name')); - } }, /** @@ -64,16 +56,8 @@ define([ _showCorporate: function () { $(this.options.corporateContainer).show(); $(this.options.individualContainer).hide(); - - if(this.options.changeFirstnameLabel){ - $(".field-name-firstname label span").text($.mage.__('Social Name')); - } - - if(this.options.changeLastnameLabel){ - $(".field-name-lastname label span").text($.mage.__('Trade Name')); - } } }); return $.mage.changePersonType; -}); \ No newline at end of file +}); From 3ccadde57a74a05a2d7717f32b72869d4f38ff95 Mon Sep 17 00:00:00 2001 From: Felipe Dominguesche Date: Tue, 24 Nov 2020 00:36:29 -0300 Subject: [PATCH 2/3] Fixes #63 #64 --- Helper/Data.php | 46 ++++- .../GetCustomer/Builders/SearchCriteria.php | 48 +++++ Model/Customer/GetCustomer/Command.php | 58 ++++++ Observer/CustomerValidations.php | 189 +++++++++++------- i18n/en_US.csv | 4 +- i18n/pt_BR.csv | 4 +- view/frontend/requirejs-config.js | 7 +- .../templates/widget/persontypefields.phtml | 17 +- .../templates/widget/persontypetoggle.phtml | 7 +- view/frontend/web/change-person-type.js | 32 ++- view/frontend/web/exempt-ie.js | 54 +++++ .../widget/create-customer-account-mixin.js | 24 +++ view/frontend/web/string-utils.js | 98 +++++++++ 13 files changed, 501 insertions(+), 87 deletions(-) create mode 100644 Model/Customer/GetCustomer/Builders/SearchCriteria.php create mode 100644 Model/Customer/GetCustomer/Command.php create mode 100644 view/frontend/web/exempt-ie.js create mode 100644 view/frontend/web/js/widget/create-customer-account-mixin.js create mode 100644 view/frontend/web/string-utils.js diff --git a/Helper/Data.php b/Helper/Data.php index 2e55161..fd45720 100755 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -2,6 +2,8 @@ namespace SystemCode\BrazilCustomerAttributes\Helper; +use Magento\Store\Model\ScopeInterface; + /** * * Helper for validations and commons functions @@ -17,12 +19,30 @@ */ class Data extends \Magento\Framework\App\Helper\AbstractHelper { + const ACCOUNT_SHARE_SCOPE_FLAG_PATH = 'customer/account_share/scope'; + const COPY_CNPJ_SOCIAL_NAME = 'brazilcustomerattributes/cnpj/copy_firstname'; + const COPY_CNPJ_TRADE_NAME = 'brazilcustomerattributes/cnpj/copy_lastname'; public function getConfig($config_path) { return $this->scopeConfig->getValue( $config_path, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE + ScopeInterface::SCOPE_STORE + ); + } + + /** + * @param string $config_path + * @param null|mixed $storeId + * + * @return bool + */ + protected function isSetFlag(string $config_path, $storeId = null): bool + { + return $this->scopeConfig->isSetFlag( + $config_path, + ScopeInterface::SCOPE_STORE, + $storeId ); } @@ -149,4 +169,28 @@ public function getRegionId($state){ } } + + /** + * @return bool + */ + public function isAccountSharedByWebsite(): bool + { + return $this->isSetFlag(self::ACCOUNT_SHARE_SCOPE_FLAG_PATH); + } + + /** + * @return bool + */ + public function copySocialName(): bool + { + return $this->isSetFlag(self::COPY_CNPJ_SOCIAL_NAME); + } + + /** + * @return bool + */ + public function copyTradeName(): bool + { + return $this->isSetFlag(self::COPY_CNPJ_TRADE_NAME); + } } diff --git a/Model/Customer/GetCustomer/Builders/SearchCriteria.php b/Model/Customer/GetCustomer/Builders/SearchCriteria.php new file mode 100644 index 0000000..83ab33b --- /dev/null +++ b/Model/Customer/GetCustomer/Builders/SearchCriteria.php @@ -0,0 +1,48 @@ +searchCriteriaBuilder = $searchCriteriaBuilder; + } + + /** + * @param mixed $customer + * @param string $fieldName + * @param bool $websiteScope + * + * @return \Magento\Framework\Api\SearchCriteria + */ + public function build($customer, string $fieldName, bool $websiteScope): \Magento\Framework\Api\SearchCriteria + { + $this->searchCriteriaBuilder->addFilter($fieldName, $customer->getData($fieldName)); + + if ($websiteScope){ + $this->searchCriteriaBuilder->addFilter('website_id', $customer->getWebsiteId()); + } + + $customerId = $customer->getId(); + if ($customerId) { + $this->searchCriteriaBuilder->addFilter('entity_id', $customerId, 'neq'); + } + + return $this->searchCriteriaBuilder->create(); + } +} diff --git a/Model/Customer/GetCustomer/Command.php b/Model/Customer/GetCustomer/Command.php new file mode 100644 index 0000000..424e46f --- /dev/null +++ b/Model/Customer/GetCustomer/Command.php @@ -0,0 +1,58 @@ +helper = $helper; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->customerRepository = $customerRepository; + } + + /** + * @param mixed $customer + * @param string $fieldName + * + * @return CustomerSearchResultsInterface + * @throws LocalizedException + */ + public function execute($customer, string $fieldName): CustomerSearchResultsInterface + { + $websiteScope = $this->helper->isAccountSharedByWebsite(); + $searchCriteria = $this->searchCriteriaBuilder->build($customer, $fieldName, $websiteScope); + + return $this->customerRepository->getList($searchCriteria); + } +} diff --git a/Observer/CustomerValidations.php b/Observer/CustomerValidations.php index 0bf96f7..07c0ec0 100755 --- a/Observer/CustomerValidations.php +++ b/Observer/CustomerValidations.php @@ -2,11 +2,15 @@ namespace SystemCode\BrazilCustomerAttributes\Observer; -use \Magento\Framework\Message\ManagerInterface; +use Magento\Customer\Api\Data\CustomerInterface; +use Magento\Framework\Event\Observer; use \Magento\Framework\App\RequestInterface; +use Magento\Framework\Event\ObserverInterface; use \Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\LocalizedException; use SystemCode\BrazilCustomerAttributes\Helper\Data as Helper; use \Magento\Customer\Model\Session; +use SystemCode\BrazilCustomerAttributes\Model\Customer\GetCustomer\Command as GetCustomerCommand; /** * @@ -21,118 +25,163 @@ * @copyright System Code LTDA-ME * @license http://opensource.org/licenses/osl-3.0.php */ -class CustomerValidations implements \Magento\Framework\Event\ObserverInterface +class CustomerValidations implements ObserverInterface { - private $_request; - private $_helper; - private $_session; + const EXEMPT_IE = 'EXEMPT'; + + /** @var RequestInterface */ + private $request; + + /** @var Helper */ + private $helper; + + /** @var Session */ + private $session; + + /** @var GetCustomerCommand */ + private $getCustomerCommand; + + /** @var CustomerInterface */ + private $customer = null; public function __construct( - ManagerInterface $messageManager, RequestInterface $request, Helper $helper, - Session $session + Session $session, + GetCustomerCommand $getCustomerCommand ) { - $this->_request = $request; - $this->_helper = $helper; - $this->_session = $session; + $this->request = $request; + $this->helper = $helper; + $this->session = $session; + $this->getCustomerCommand = $getCustomerCommand; } - public function execute(\Magento\Framework\Event\Observer $observer) + /** + * @param Observer $observer + * + * @throws CouldNotSaveException + * @throws LocalizedException + */ + public function execute(Observer $observer) { - $params = $this->_request->getParams(); - - if(isset($params["person_type"]) && $params["person_type"]=="cpf"){ - $cpf = (isset($params["cpf"])?$params["cpf"]:""); - $rg = (isset($params["rg"])?$params["rg"]:""); - - if($cpf!="") { - if (!$this->_helper->validateCPF($cpf)) { - throw new CouldNotSaveException( - __("%1 is invalid.", "CPF") - ); - } + $params = $this->request->getParams(); + $personType = $params['person_type'] ?? null; + $this->customer = $observer->getCustomer(); + + if ($personType === 'cpf') { + $cpf = $params['cpf'] ?? ''; + $rg = $params['rg'] ?? ''; + + if ($cpf !== '' && ($this->helper->validateCPF($cpf) === false)) { + throw new CouldNotSaveException( + __('%1 is invalid.', 'CPF') + ); } - if(!$this->_validateInput($cpf, "cpf", "cpf/cpf_show")){ + if ($this->_validateInput($cpf, 'cpf', 'cpf/cpf_show') === false){ throw new CouldNotSaveException( - __("%1 already in use.", "CPF") + __('%1 already in use.', 'CPF') ); } - if(!$this->_validateInput($rg, "rg", "cpf/rg_show")){ + if ($this->_validateInput($rg, 'rg', 'cpf/rg_show') === false) { throw new CouldNotSaveException( - __("%1 already in use.", "RG") + __('%1 already in use.', 'RG') ); } + } elseif ($personType === 'cnpj') { + if ($this->helper->copySocialName()) { + $firstName = $params['firstname']; + $params['socialname'] = $firstName; + $this->customer->setData('socialname', $firstName); + } - }else if(isset($params["person_type"]) && $params["person_type"]=="cnpj"){ - $cnpj = (isset($params["cnpj"])?$params["cnpj"]:""); - $ie = (isset($params["ie"])?$params["ie"]:""); - $socialName = (isset($params["socialname"])?$params["socialname"]:""); - $tradeName = (isset($params["tradename"])?$params["tradename"]:""); - - if($cnpj!=""){ - if(!$this->_helper->validateCNPJ($cnpj)){ - throw new CouldNotSaveException( - __("%1 is invalid.", "CNPJ") - ); - } + if ($this->helper->copyTradeName()) { + $lastname = $params['lastname']; + $params['tradename'] = $lastname; + $this->customer->setData('tradename', $lastname); } - if(!$this->_validateInput($cnpj, "cnpj", "cnpj/cnpj_show")){ + $cnpj = $params['cnpj'] ?? ''; + $ie = strtoupper($params['ie'] ?? __(self::EXEMPT_IE)); + $socialName = $params['socialname'] ?? ''; + $tradeName = $params['tradename'] ?? ''; + + if ($cnpj !== '' && ($this->helper->validateCNPJ($cnpj) === false)) { throw new CouldNotSaveException( - __("%1 already in use.", "CNPJ") + __('%1 is invalid.', 'CNPJ') ); } - if(!$this->_validateInput($ie, "ie", "cnpj/ie_show")){ + if ($this->_validateInput($cnpj, 'cnpj', 'cnpj/cnpj_show') === false) { throw new CouldNotSaveException( - __("%1 already in use.", "ie") + __('%1 already in use.', 'CNPJ') ); } - if(!$this->_validateInput($socialName, "socialname", "cnpj/socialname_show")){ + if ( + $ie !== strtoupper(__(self::EXEMPT_IE)) + && $this->_validateInput($ie, 'ie', 'cnpj/ie_show') === false + ) { throw new CouldNotSaveException( - __("%1 already in use.", "Social Name") + __('%1 already in use.', 'IE') ); } - if(!$this->_validateInput($tradeName, "tradename", "cnpj/tradename_show")){ + if ($this->_validateInput($socialName, 'socialname', 'cnpj/socialname_show') === false) { throw new CouldNotSaveException( - __("%1 already in use.", "Trade Name") + __('%1 already in use.', 'Social Name') + ); + } + + if ($this->_validateInput($tradeName, 'tradename', 'cnpj/tradename_show') === false) { + throw new CouldNotSaveException( + __('%1 already in use.', 'Trade Name') ); } } } - protected function _validateInput($value, $fieldName, $path){ - $show = $this->_helper->getConfig("brazilcustomerattributes/".$path); - if($show == "req" || $show == "requni"){ - if($value == ""){ + /** + * @param $value + * @param $fieldName + * @param $path + * + * @return bool + * @throws LocalizedException + */ + protected function _validateInput($value, $fieldName, $path): bool + { + $show = $this->helper->getConfig('brazilcustomerattributes/'.$path); + + if ($show === 'req' || $show === 'requni') { // checks if is required + if ($value === '') { return false; } - //verify if is unique - if($show == "requni"){ - if($this->_session->getCustomer()->getId()!="" && $this->_session->getCustomer()->getData($fieldName) == $value){ //verifico se é ele mesmo que utiliza - return true; - } + } - //check if field already being used - $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); + if ($show === 'requni' || $show === 'optuni') { // checks if is unique + return ( + ( + $this->session->getCustomer()->getId() !== '' + && $this->session->getCustomer()->getData($fieldName) === $value + ) || $this->isUnique($fieldName) + ); + } - $customerObj = $objectManager->create('Magento\Customer\Model\Customer')->getCollection(); - $customerObj->addFieldToFilter($fieldName, $value); + return true; + } + /** + * @param string $fieldName + * + * @return bool + * @throws LocalizedException + */ + protected function isUnique(string $fieldName): bool + { + $customerList = $this->getCustomerCommand->execute($this->customer, $fieldName); - foreach ($customerObj as $customer){ - if($customer->getCreatedAt()){ - return true; - } - return false; - } - } - } - return true; + return $customerList->getTotalCount() <= 0; } -} \ No newline at end of file +} diff --git a/i18n/en_US.csv b/i18n/en_US.csv index da89581..320ac02 100755 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -92,4 +92,6 @@ Loading,Loading Options,Options "Add Option","Add Option" "Street Prefix","Street Prefix" -"Please select a street prefix.","Please select a street prefix." \ No newline at end of file +"Please select a street prefix.","Please select a street prefix." +"EXEMPT", "EXEMPT" +"Exempt IE", "Exempt IE" diff --git a/i18n/pt_BR.csv b/i18n/pt_BR.csv index 0041c21..8db7313 100755 --- a/i18n/pt_BR.csv +++ b/i18n/pt_BR.csv @@ -90,4 +90,6 @@ Loading,Carregando Options,Opções "Add Option","Adicionar Opção" "Street Prefix",Logradouro -"Please select a street prefix.","Por favor selecione o logradouro." \ No newline at end of file +"Please select a street prefix.","Por favor selecione o logradouro." +"EXEMPT", "ISENTO" +"Exempt IE", "IE Isento" diff --git a/view/frontend/requirejs-config.js b/view/frontend/requirejs-config.js index 870486c..fbc82da 100755 --- a/view/frontend/requirejs-config.js +++ b/view/frontend/requirejs-config.js @@ -7,7 +7,9 @@ var config = { map: { '*': { changePersonType: 'SystemCode_BrazilCustomerAttributes/change-person-type', - inputMask: 'SystemCode_BrazilCustomerAttributes/jquery.mask' + exemptIe: 'SystemCode_BrazilCustomerAttributes/exempt-ie', + inputMask: 'SystemCode_BrazilCustomerAttributes/jquery.mask', + stringUtils: 'SystemCode_BrazilCustomerAttributes/string-utils' }, }, config: { @@ -23,6 +25,9 @@ var config = { }, 'Magento_Checkout/js/action/place-order': { 'SystemCode_BrazilCustomerAttributes/js/action/place-order-mixin': true + }, + 'mage/validation': { + 'SystemCode_BrazilCustomerAttributes/js/widget/create-customer-account-mixin': true } } } diff --git a/view/frontend/templates/widget/persontypefields.phtml b/view/frontend/templates/widget/persontypefields.phtml index 6f9a234..bad414f 100755 --- a/view/frontend/templates/widget/persontypefields.phtml +++ b/view/frontend/templates/widget/persontypefields.phtml @@ -52,7 +52,7 @@
getStatus("show", "cnpj", "socialname")): ?> -
"> +
">
" title="" class="input-text" - data-validate="{required:getStatus("required", "cnpj", "socialname"), true) ?>, 'validate-cpf':true}" > + data-validate="{required:getStatus("required", "cnpj", "socialname"), true) ?>}" >
getStatus("show", "cnpj", "tradename")): ?> -
"> +
">
" title="" class="input-text" - data-validate="{required:getStatus("required", "cnpj", "cnpj"), true) ?>}" > + data-validate="{required:getStatus("required", "cnpj", "cnpj"), true) ?>, 'validate-cnpj':true}" >
@@ -108,6 +108,10 @@ id="ie" data-validate="{required:getStatus("required", "cnpj", "ie"), true) ?>}" >
+ +
@@ -121,6 +125,9 @@ "changeFirstnameLabel": getConfigAdmin("cnpj", "copy_firstname")?"true":"false"); ?>, "changeLastnameLabel": getConfigAdmin("cnpj", "copy_lastname")?"true":"false"); ?> } + }, + "#exemptIe": { + "exemptIe": {} } } @@ -133,4 +140,4 @@ $('#cpf').mask('000.000.000-00', {clearIfNotMatch: true}); $('#cnpj').mask('00.000.000/0000-00', {clearIfNotMatch: true}); }); - \ No newline at end of file + diff --git a/view/frontend/templates/widget/persontypetoggle.phtml b/view/frontend/templates/widget/persontypetoggle.phtml index 4886e09..526785e 100755 --- a/view/frontend/templates/widget/persontypetoggle.phtml +++ b/view/frontend/templates/widget/persontypetoggle.phtml @@ -14,17 +14,12 @@ */ ?> showCpf && $block->showCnpj): ?> - showCpf): ?>
getPersonType() == 'cpf' || $block->getPersonType() == false?'checked':'') ?> title="" class="radio person_type" />
- - - showCnpj): ?>
getPersonType() == 'cnpj'?'checked':'') ?> title="" class="radio person_type" />
- - \ No newline at end of file + diff --git a/view/frontend/web/change-person-type.js b/view/frontend/web/change-person-type.js index 2f7deb6..5c31036 100755 --- a/view/frontend/web/change-person-type.js +++ b/view/frontend/web/change-person-type.js @@ -13,7 +13,7 @@ define([ individualContainer: '[data-container=type-individual]', corporateContainer: '[data-container=type-corporation]', changeFirstnameLabel: false, - changeLastnameLabel: false + changeLastnameLabel: false, }, /** @@ -35,7 +35,7 @@ define([ _checkChoice: function () { if ($(this.options.corporateSelector).is(':checked')) { this._showCorporate(); - } else { + } else { this._showIndividual(); } }, @@ -47,6 +47,14 @@ define([ _showIndividual: function () { $(this.options.individualContainer).show(); $(this.options.corporateContainer).hide(); + + if (this.options.changeFirstnameLabel) { + $(".field-name-firstname label span").text($.mage.__('First Name')); + } + + if (this.options.changeLastnameLabel) { + $(".field-name-lastname label span").text($.mage.__('Last Name')); + } }, /** @@ -56,6 +64,26 @@ define([ _showCorporate: function () { $(this.options.corporateContainer).show(); $(this.options.individualContainer).hide(); + + if (this.options.changeFirstnameLabel) { + const fieldNameSocialnameBlock = $(".field-name-socialname"); + fieldNameSocialnameBlock.hide(); + fieldNameSocialnameBlock.removeClass('required'); + + $('#socialvalue').removeAttr('data-validate'); + + $(".field-name-firstname label span").text($.mage.__('Social Name')); + } + + if (this.options.changeLastnameLabel) { + const fieldNameTradenameBlock = $(".field-name-tradename"); + fieldNameTradenameBlock.hide(); + fieldNameTradenameBlock.removeClass('required'); + + $('#tradevalue').removeAttr('data-validate'); + + $(".field-name-lastname label span").text($.mage.__('Trade Name')); + } } }); diff --git a/view/frontend/web/exempt-ie.js b/view/frontend/web/exempt-ie.js new file mode 100644 index 0000000..2e7d5eb --- /dev/null +++ b/view/frontend/web/exempt-ie.js @@ -0,0 +1,54 @@ +/*jshint browser:true jquery:true expr:true*/ +define([ + 'jquery', +], function ($) { + 'use strict'; + + $.widget('mage.ie', { + options: { + ieFieldSelector: '#ie', + exemptIeFieldSelector: '#exemptIe', + }, + + /** + * Create widget + * @private + */ + _create: function () { + this.element.on('change', $.proxy(function () { + this._checkChoice(); + }, this)); + + this._checkChoice(true); + }, + + /** + * Check choice + * @private + */ + _checkChoice: function (create = false) { + const ieField = $(this.options.ieFieldSelector); + const ieFieldValue = ieField.val(); + const exemptIeField = $(this.options.exemptIeFieldSelector); + const exemptValue = $.mage.__('EXEMPT'); + + if (exemptValue === ieFieldValue && create === true) { + exemptIeField.attr('checked', true); + ieField.val(exemptValue).attr('readonly', true); + return; + } + + if (exemptIeField.is(':checked')) { + ieField.val(exemptValue).attr('readonly', true); + return; + } + + exemptIeField.attr('checked', false); + ieField.val('').attr('readonly', false); + }, + }); + + $('#exempt_ie').mage('ie'); + + return $.mage.ie; +}); diff --git a/view/frontend/web/js/widget/create-customer-account-mixin.js b/view/frontend/web/js/widget/create-customer-account-mixin.js new file mode 100644 index 0000000..d18bf61 --- /dev/null +++ b/view/frontend/web/js/widget/create-customer-account-mixin.js @@ -0,0 +1,24 @@ +define([ + 'jquery', + 'stringUtils' +], function($, stringUtils) { + 'use strict'; + + return function () { + $.validator.addMethod( + 'validate-cpf', + function(value) { + return stringUtils.taxvat.isValidCPF(value); + }, + $.mage.__('Invalid CPF.'), + ); + + $.validator.addMethod( + 'validate-cnpj', + function(value) { + return stringUtils.taxvat.isValidCNPJ(value); + }, + $.mage.__('Invalid CNPJ.'), + ); + }; +}); diff --git a/view/frontend/web/string-utils.js b/view/frontend/web/string-utils.js new file mode 100644 index 0000000..039f736 --- /dev/null +++ b/view/frontend/web/string-utils.js @@ -0,0 +1,98 @@ +define([], function () { + 'use strict'; + + return { + unMask: (value) => value.replace(/[^\d]+/g, ''), + taxvat: { + isValidCPF: (value) => { + const invalidCPFs = [ + '00000000000', + '11111111111', + '22222222222', + '33333333333', + '44444444444', + '55555555555', + '66666666666', + '77777777777', + '88888888888', + '99999999999', + ] + + const isValidDigit = (value, digitPos) => { + let add = 0; + + for (let i = 0; i < digitPos; i += 1) { + add += Number.parseInt(value.charAt(i), 10) * (digitPos + 1 - i); + } + + let digit = 11 - (add % 11); + + if (digit === 10 || digit === 11) { + digit = 0; + } + + return digit === Number.parseInt(value.charAt(digitPos), 10); + }; + + const unMaskedValue = this.unMask(value); + + return unMaskedValue.length === 11 + && invalidCPFs.includes(unMaskedValue) === false + && isValidDigit(unMaskedValue, 9) // First check digit + && isValidDigit(unMaskedValue, 10); // Second check digit + }, + isValidCNPJ: (value) => { + const invalidCNPJs = [ + '00000000000000', + '11111111111111', + '22222222222222', + '33333333333333', + '44444444444444', + '55555555555555', + '66666666666666', + '77777777777777', + '88888888888888', + '99999999999999', + ]; + + const isValidDigit = (value, size) => { + const numbers = value.substring(0, size); + + let sum = 0; + let pos = size - 7; + + for (let i = size; i >= 1; i -= 1) { + sum += numbers.charAt(size - i) * pos; + + pos -= 1; + + if (pos < 2) { + pos = 9; + } + } + + let digit = 0; + + const rest = sum % 11; + + if (rest >= 2) { + digit = 11 - rest; + } + + return digit === Number.parseInt(value.charAt(size), 10); + }; + + const unMaskedValue = this.unMask(value); + + return unMaskedValue.length === 14 + && invalidCNPJs.includes(unMaskedValue) === false + && isValidDigit(unMaskedValue, 12) + && isValidDigit(unMaskedValue, 13); + }, + isValidTaxvat: (value) => { + this.isValidCPF(value) + || this.isValidCPF(value) + }, + } + }; +}); From 1bb4b5c8527feef4cd96ddeeae50f1530a2ce564 Mon Sep 17 00:00:00 2001 From: Felipe Dominguesche Date: Tue, 24 Nov 2020 00:49:00 -0300 Subject: [PATCH 3/3] Compatibilidade PHP --- Model/Customer/GetCustomer/Builders/SearchCriteria.php | 2 +- Model/Customer/GetCustomer/Command.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Model/Customer/GetCustomer/Builders/SearchCriteria.php b/Model/Customer/GetCustomer/Builders/SearchCriteria.php index 83ab33b..551ee8e 100644 --- a/Model/Customer/GetCustomer/Builders/SearchCriteria.php +++ b/Model/Customer/GetCustomer/Builders/SearchCriteria.php @@ -12,7 +12,7 @@ class SearchCriteria { /** @var SearchCriteriaBuilder */ - protected SearchCriteriaBuilder $searchCriteriaBuilder; + protected $searchCriteriaBuilder; /** * SearchCriteria constructor. diff --git a/Model/Customer/GetCustomer/Command.php b/Model/Customer/GetCustomer/Command.php index 424e46f..7438cab 100644 --- a/Model/Customer/GetCustomer/Command.php +++ b/Model/Customer/GetCustomer/Command.php @@ -16,13 +16,13 @@ class Command { /** @var Data */ - protected Data $helper; + protected $helper; /** @var SearchCriteria */ - protected SearchCriteria $searchCriteriaBuilder; + protected $searchCriteriaBuilder; /** @var CustomerRepositoryInterface */ - protected CustomerRepositoryInterface $customerRepository; + protected $customerRepository; /** * Command constructor.