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..551ee8e --- /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..7438cab --- /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 @@