├── .github └── ISSUE_TEMPLATE │ ├── -en--bug-report.md │ ├── -en--feature-request.md │ ├── -pt-br--reportar-um-erro.md │ └── -pt-br--sugerir-uma-melhoria.md ├── .gitignore ├── Block ├── Adminhtml │ └── Form │ │ └── Field │ │ └── Prefixoptions.php └── Magento │ └── Customer │ └── Widget │ ├── Persontype.php │ ├── Street.php │ ├── Streetedit.php │ ├── StreetprefixEdit.php │ └── StreetprefixRegister.php ├── Config └── Backend │ └── Prefixoptions.php ├── Controller └── Consult │ └── Address.php ├── Helper └── Data.php ├── Model ├── Config │ ├── Backend │ │ └── Show │ │ │ └── Customer.php │ └── Source │ │ ├── Customeredit.php │ │ ├── Customergroup.php │ │ ├── Nooptrequn.php │ │ └── Streetprefix.php └── Magento │ └── Customer │ └── ResourceModel │ └── AddressRepository.php ├── Observer ├── CustomerData.php ├── CustomerValidations.php └── QuoteToOrder.php ├── Plugin ├── Checkout │ ├── LayoutProcessor.php │ └── PaymentInformationManagement.php └── Quote │ ├── BillingAddressManagement.php │ └── ShippingAddressManagement.php ├── Setup ├── InstallData.php ├── UpgradeData.php └── UpgradeSchema.php ├── composer.json ├── etc ├── acl.xml ├── adminhtml │ ├── config.xml │ ├── menu.xml │ ├── routes.xml │ └── system.xml ├── config.xml ├── di.xml ├── events.xml ├── extension_attributes.xml ├── frontend │ └── routes.xml └── module.xml ├── i18n ├── en_US.csv └── pt_BR.csv ├── readme.md ├── registration.php └── view └── frontend ├── layout ├── customer_account_create.xml ├── customer_account_edit.xml └── customer_address_form.xml ├── requirejs-config.js ├── templates ├── address │ └── edit.phtml ├── form │ ├── edit.phtml │ └── register.phtml └── widget │ ├── persontypefields.phtml │ ├── persontypetoggle.phtml │ ├── street.phtml │ └── streetprefix.phtml └── web ├── change-person-type.js ├── css └── source │ └── _module.less ├── jquery.mask.js ├── js ├── action │ ├── create-billing-address-mixin.js │ ├── create-shipping-address-mixin.js │ ├── place-order-mixin.js │ └── set-shipping-information-mixin.js ├── form │ └── address-mixin.js └── shipping-address │ └── address-renderer │ ├── streetprefix.js │ ├── telephone.js │ └── zip-code.js └── template └── shipping-address └── address-renderer ├── streetprefix.html └── zip-code.html /.github/ISSUE_TEMPLATE/-en--bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "[EN] Bug report" 3 | about: Create a report to help us improve 4 | title: "[BUG] " 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Preconditions (*) 11 | 14 | 1. BrazilCustomerAttributes (1.?.?) 15 | 2. Magento (2.?.?) 16 | 3. 17 | 18 | ### Steps to reproduce (*) 19 | 22 | 1. 23 | 2. 24 | 25 | ### Expected result (*) 26 | 27 | 1. [Screenshots, logs or description] 28 | 2. 29 | 30 | ### Actual result (*) 31 | 32 | 1. [Screenshots, logs or description] 33 | 2. 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/-en--feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "[EN] Feature request" 3 | about: Suggest an idea for this project 4 | title: "[FEATURE] " 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Description (*) 11 | 12 | 13 | ### Expected behavior (*) 14 | 15 | 16 | ### Benefits 17 | 18 | 19 | ### Additional information 20 | 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/-pt-br--reportar-um-erro.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "[PT-BR] Reportar um erro" 3 | about: Crie um relatório para nos ajudar a melhorar 4 | title: "[BUG] " 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Precondições (*) 11 | 14 | 1. BrazilCustomerAttributes (1.?.?) 15 | 2. Magento (2.?.?) 16 | 3. 17 | 18 | ### Passos para reproduzir (*) 19 | 22 | 1. 23 | 2. 24 | 25 | ### Resultado esperado (*) 26 | 27 | 1. [Imagens, logs ou descrição] 28 | 2. 29 | 30 | ### Resultado ocorrido (*) 31 | 32 | 1. [Imagens, logs ou descrição] 33 | 2. 34 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/-pt-br--sugerir-uma-melhoria.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "[PT-BR] Sugerir uma melhoria" 3 | about: Sugira uma melhoria para este projeto 4 | title: "[FEATURE] " 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Descrição (*) 11 | 12 | 13 | ### Resultado Esperado (*) 14 | 15 | 16 | ### Benefícios 17 | 18 | 19 | ### Informações Adicionais 20 | 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /Block/Adminhtml/Form/Field/Prefixoptions.php: -------------------------------------------------------------------------------- 1 | 17 | * @copyright System Code LTDA-ME 18 | * @license http://opensource.org/licenses/osl-3.0.php 19 | */ 20 | class Prefixoptions extends AbstractFieldArray 21 | { 22 | /** 23 | * {@inheritdoc} 24 | */ 25 | protected function _prepareToRender() 26 | { 27 | $this->addColumn('prefix_options', ['label' => __('Options'), 'class' => 'required-entry']); 28 | $this->_addAfter = false; 29 | $this->_addButtonLabel = __('Add Option'); 30 | } 31 | } -------------------------------------------------------------------------------- /Block/Magento/Customer/Widget/Persontype.php: -------------------------------------------------------------------------------- 1 | 24 | * @copyright System Code LTDA-ME 25 | * @license http://opensource.org/licenses/osl-3.0.php 26 | */ 27 | class Persontype extends \Magento\Customer\Block\Widget\AbstractWidget 28 | { 29 | /** 30 | * @var \Magento\Customer\Model\Session 31 | */ 32 | protected $_customerSession; 33 | 34 | /** 35 | * @var CustomerRepositoryInterface 36 | */ 37 | protected $customerRepository; 38 | 39 | protected $helper; 40 | 41 | public $showCpf; 42 | 43 | public $showCnpj; 44 | 45 | public $selectedPersonType; 46 | 47 | /** 48 | * Create an instance of the Gender widget 49 | * 50 | * @param SystemCode\BrazilCustomerAttributes\Helper\Data $helper 51 | * @param \Magento\Framework\View\Element\Template\Context $context 52 | * @param \Magento\Customer\Helper\Address $addressHelper 53 | * @param CustomerMetadataInterface $customerMetadata 54 | * @param CustomerRepositoryInterface $customerRepository 55 | * @param \Magento\Customer\Model\Session $customerSession 56 | * @param array $data 57 | */ 58 | public function __construct( 59 | Helper $helper, 60 | Context $context, 61 | Address $addressHelper, 62 | CustomerMetadataInterface $customerMetadata, 63 | CustomerRepositoryInterface $customerRepository, 64 | Session $customerSession, 65 | array $data = [] 66 | ) { 67 | $this->helper = $helper; 68 | $this->_customerSession = $customerSession; 69 | $this->customerRepository = $customerRepository; 70 | parent::__construct($context, $addressHelper, $customerMetadata, $data); 71 | $this->_isScopePrivate = true; 72 | 73 | $this->showCpf = (($this->getPersonType()=="cpf" //o tipo da pessoa é cpf 74 | || $this->getPersonType()==false //a pessoa ainda não tem um tipo (registro de usuário) 75 | || $this->getConfigAdmin("general", "customer_edit") == "yesall") //ou ela pode trocar de grupo 76 | && ($this->getStatus("show", "cpf", "cpf") //os campos de cpf estão visíveis 77 | || $this->getStatus("show", "cpf", "rg"))); 78 | 79 | 80 | $this->showCnpj = (($this->getPersonType() //o tipo da pessoa é cnpj 81 | || $this->getPersonType()==false //a pessoa ainda não tem um tipo (registro de usuário) 82 | || $this->getConfigAdmin("general", "customer_edit") == "yesall") //ou ela pode trocar de grupo 83 | && ($this->getStatus("show", "cnpj", "cnpj") //os campos de cnpj estão visíveis 84 | || $this->getStatus("show", "cnpj", "ie") 85 | || $this->getStatus("show", "cnpj", "socialname") 86 | || $this->getStatus("show", "cnpj", "tradename") 87 | || $this->getConfigAdmin("cnpj", "copy_firstname") 88 | || $this->getConfigAdmin("cnpj", "copy_lastname"))); 89 | } 90 | 91 | /** 92 | * Initialize block 93 | * 94 | * @return void 95 | */ 96 | public function _construct() 97 | { 98 | parent::_construct(); 99 | //$this->setTemplate('SystemCode_BrazilCustomerAttributes::widget/persontype.phtml'); 100 | } 101 | 102 | /** 103 | * Check if gender attribute enabled in system 104 | * @return bool 105 | */ 106 | public function getConfigAdmin($group, $field) 107 | { 108 | return $this->helper->getConfig("brazilcustomerattributes/".$group."/".$field); 109 | } 110 | 111 | /** 112 | * Check if an attribute is visible or required 113 | * @return bool 114 | */ 115 | public function getStatus($type, $group, $field) 116 | { 117 | $fieldConfig = $this->helper->getConfig("brazilcustomerattributes/".$group."/".$field."_show"); 118 | 119 | if($type == "show" && $fieldConfig != "" || 120 | $type == "required" && ($fieldConfig == "req" || $fieldConfig == "requni") ){ 121 | return true; 122 | } 123 | return false; 124 | } 125 | 126 | 127 | /** 128 | * Get current customer from session 129 | * 130 | * @return CustomerInterface 131 | */ 132 | public function getCustomer() 133 | { 134 | if($id = $this->_customerSession->getId()){ 135 | return $this->customerRepository->getById($id); 136 | } 137 | return null; 138 | } 139 | 140 | /** 141 | * Returns options from gender attribute 142 | * @return OptionInterface[] 143 | */ 144 | public function getCustomerValue($attribute) 145 | { 146 | if($this->getCustomer()!=null && $this->getCustomer()->getCustomAttribute($attribute)){ 147 | return $this->getCustomer()->getCustomAttribute($attribute)->getValue(); 148 | } 149 | return; 150 | } 151 | 152 | public function getPersonType() 153 | { 154 | //verifico se é exibido somente cpf ou somente cnpj 155 | if($this->showCpf == true && $this->showCnpj == false){ 156 | return "cpf"; 157 | }else if($this->showCpf == false && $this->showCnpj == true){ 158 | return "cnpj"; 159 | } 160 | 161 | //verificação pelo grupo do cliente 162 | if ($this->getConfigAdmin("general", "customer_group_cpf") 163 | != $this->getConfigAdmin("general", "customer_group_cnpj") 164 | ) { 165 | if ($this->_customerSession->getCustomer()->getGroupId() == 166 | $this->getConfigAdmin("general", "customer_group_cpf") 167 | ) { 168 | return "cpf"; 169 | } else if ($this->_customerSession->getCustomer()->getGroupId() == 170 | $this->getConfigAdmin("general", "customer_group_cnpj") 171 | ) { 172 | return "cnpj"; 173 | } 174 | } 175 | 176 | //verifico se o cliente tem algum dado de cnpj preenchido, caso não tenha assimilo como cpf 177 | if($this->getCustomerValue('cnpj')!="" || 178 | $this->getCustomerValue('ie')!="" || 179 | $this->getCustomerValue('socialname')!="" || 180 | $this->getCustomerValue('tradename')!=""){ 181 | return "cnpj"; 182 | } 183 | return false; 184 | } 185 | 186 | } 187 | -------------------------------------------------------------------------------- /Block/Magento/Customer/Widget/Street.php: -------------------------------------------------------------------------------- 1 | 18 | * @copyright System Code LTDA-ME 19 | * @license http://opensource.org/licenses/osl-3.0.php 20 | */ 21 | class Street extends \Magento\Customer\Block\Widget\AbstractWidget 22 | { 23 | 24 | protected $helper; 25 | 26 | /** 27 | * Create an instance of the Gender widget 28 | * 29 | * @param Helper $helper 30 | * @param \Magento\Framework\View\Element\Template\Context $context 31 | * @param \Magento\Customer\Helper\Address $addressHelper 32 | * @param CustomerMetadataInterface $customerMetadata 33 | * @param array $data 34 | */ 35 | public function __construct( 36 | Helper $helper, 37 | \Magento\Framework\View\Element\Template\Context $context, 38 | \Magento\Customer\Helper\Address $addressHelper, 39 | CustomerMetadataInterface $customerMetadata, 40 | array $data = [] 41 | ) { 42 | $this->helper = $helper; 43 | parent::__construct($context, $addressHelper, $customerMetadata, $data); 44 | } 45 | 46 | /** 47 | * Initialize block 48 | * 49 | * @return void 50 | */ 51 | public function _construct() 52 | { 53 | parent::_construct(); 54 | $this->setTemplate('SystemCode_BrazilCustomerAttributes::widget/street.phtml'); 55 | } 56 | 57 | /** 58 | * Check if gender attribute enabled in system 59 | * @return bool 60 | */ 61 | public function getSecondLineNumber() 62 | { 63 | return $this->helper->getConfig("brazilcustomerattributes/general/line_number"); 64 | } 65 | 66 | /** 67 | * Check if gender attribute enabled in system 68 | * @return bool 69 | */ 70 | public function getThirdLineNeighborhood() 71 | { 72 | return $this->helper->getConfig("brazilcustomerattributes/general/line_neighborhood"); 73 | } 74 | 75 | /** 76 | * Check if gender attribute enabled in system 77 | * @return bool 78 | */ 79 | public function getFourthLineComplement() 80 | { 81 | return $this->helper->getConfig("brazilcustomerattributes/general/line_complement"); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /Block/Magento/Customer/Widget/Streetedit.php: -------------------------------------------------------------------------------- 1 | 18 | * @copyright System Code LTDA-ME 19 | * @license http://opensource.org/licenses/osl-3.0.php 20 | */ 21 | class Streetedit extends \Magento\Customer\Block\Address\Edit 22 | { 23 | 24 | protected $helper; 25 | 26 | /** 27 | * Create an instance of the Gender widget 28 | * @param \Magento\Framework\View\Element\Template\Context $context 29 | * @param \Magento\Directory\Helper\Data $directoryHelper 30 | * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder 31 | * @param \Magento\Framework\App\Cache\Type\Config $configCacheType 32 | * @param \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory 33 | * @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory 34 | * @param \Magento\Customer\Model\Session $customerSession 35 | * @param \Magento\Customer\Api\AddressRepositoryInterface $addressRepository 36 | * @param \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory 37 | * @param \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer 38 | * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper 39 | * @param Helper $helper 40 | * @param array $data 41 | */ 42 | public function __construct( 43 | \Magento\Framework\View\Element\Template\Context $context, 44 | \Magento\Directory\Helper\Data $directoryHelper, 45 | \Magento\Framework\Json\EncoderInterface $jsonEncoder, 46 | \Magento\Framework\App\Cache\Type\Config $configCacheType, 47 | \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory, 48 | \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory, 49 | \Magento\Customer\Model\Session $customerSession, 50 | \Magento\Customer\Api\AddressRepositoryInterface $addressRepository, 51 | \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory, 52 | \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer, 53 | \Magento\Framework\Api\DataObjectHelper $dataObjectHelper, 54 | Helper $helper, 55 | array $data = [] 56 | ) { 57 | $this->helper = $helper; 58 | 59 | parent::__construct( 60 | $context, 61 | $directoryHelper, 62 | $jsonEncoder, 63 | $configCacheType, 64 | $regionCollectionFactory, 65 | $countryCollectionFactory, 66 | $customerSession, 67 | $addressRepository, 68 | $addressDataFactory, 69 | $currentCustomer, 70 | $dataObjectHelper, 71 | $data 72 | ); 73 | } 74 | 75 | /** 76 | * Initialize block 77 | * 78 | * @return void 79 | */ 80 | public function _construct() 81 | { 82 | parent::_construct(); 83 | $this->setTemplate('SystemCode_BrazilCustomerAttributes::widget/street.phtml'); 84 | } 85 | 86 | /** 87 | * Check if gender attribute enabled in system 88 | * @return bool 89 | */ 90 | public function getSecondLineNumber() 91 | { 92 | return $this->helper->getConfig("brazilcustomerattributes/general/line_number"); 93 | } 94 | 95 | /** 96 | * Check if gender attribute enabled in system 97 | * @return bool 98 | */ 99 | public function getThirdLineNeighborhood() 100 | { 101 | return $this->helper->getConfig("brazilcustomerattributes/general/line_neighborhood"); 102 | } 103 | 104 | /** 105 | * Check if gender attribute enabled in system 106 | * @return bool 107 | */ 108 | public function getFourthLineComplement() 109 | { 110 | return $this->helper->getConfig("brazilcustomerattributes/general/line_complement"); 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /Block/Magento/Customer/Widget/StreetprefixEdit.php: -------------------------------------------------------------------------------- 1 | 17 | * @copyright System Code LTDA-ME 18 | * @license http://opensource.org/licenses/osl-3.0.php 19 | */ 20 | class StreetprefixEdit extends \Magento\Customer\Block\Address\Edit 21 | { 22 | 23 | protected $helper; 24 | 25 | protected $streetprefix; 26 | 27 | /** 28 | * Create an instance of the Gender widget 29 | * @param \Magento\Framework\View\Element\Template\Context $context 30 | * @param \Magento\Directory\Helper\Data $directoryHelper 31 | * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder 32 | * @param \Magento\Framework\App\Cache\Type\Config $configCacheType 33 | * @param \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory 34 | * @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory 35 | * @param \Magento\Customer\Model\Session $customerSession 36 | * @param \Magento\Customer\Api\AddressRepositoryInterface $addressRepository 37 | * @param \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory 38 | * @param \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer 39 | * @param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper 40 | * @param Helper $helper 41 | * @param array $data 42 | */ 43 | public function __construct( 44 | \Magento\Framework\View\Element\Template\Context $context, 45 | \Magento\Directory\Helper\Data $directoryHelper, 46 | \Magento\Framework\Json\EncoderInterface $jsonEncoder, 47 | \Magento\Framework\App\Cache\Type\Config $configCacheType, 48 | \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory, 49 | \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory, 50 | \Magento\Customer\Model\Session $customerSession, 51 | \Magento\Customer\Api\AddressRepositoryInterface $addressRepository, 52 | \Magento\Customer\Api\Data\AddressInterfaceFactory $addressDataFactory, 53 | \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer, 54 | \Magento\Framework\Api\DataObjectHelper $dataObjectHelper, 55 | Helper $helper, 56 | \SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix $streetprefix, 57 | array $data = [] 58 | ) { 59 | $this->helper = $helper; 60 | $this->streetprefix = $streetprefix; 61 | 62 | parent::__construct( 63 | $context, 64 | $directoryHelper, 65 | $jsonEncoder, 66 | $configCacheType, 67 | $regionCollectionFactory, 68 | $countryCollectionFactory, 69 | $customerSession, 70 | $addressRepository, 71 | $addressDataFactory, 72 | $currentCustomer, 73 | $dataObjectHelper, 74 | $data 75 | ); 76 | } 77 | 78 | /** 79 | * Initialize block 80 | * 81 | * @return void 82 | */ 83 | public function _construct() 84 | { 85 | parent::_construct(); 86 | $this->setTemplate('SystemCode_BrazilCustomerAttributes::widget/streetprefix.phtml'); 87 | } 88 | 89 | /** 90 | * Check if street prefix is enabled 91 | * @return bool 92 | */ 93 | public function getIsEnabled() 94 | { 95 | return $this->helper->getConfig("brazilcustomerattributes/general/prefix_enabled"); 96 | } 97 | 98 | /** 99 | * Check if street prefix is enabled 100 | * @return array 101 | */ 102 | public function getStreetPrefixOptions() 103 | { 104 | return $this->streetprefix->getAllOptions(); 105 | } 106 | 107 | 108 | /** 109 | * Check if address already has street prefix 110 | * @return value 111 | */ 112 | public function getCurrentStreetPrefix() 113 | { 114 | if(null != ($current = $this->getAddress()->getCustomAttribute('street_prefix'))){ 115 | return $current->getValue(); 116 | } 117 | return; 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /Block/Magento/Customer/Widget/StreetprefixRegister.php: -------------------------------------------------------------------------------- 1 | 19 | * @copyright System Code LTDA-ME 20 | * @license http://opensource.org/licenses/osl-3.0.php 21 | */ 22 | class StreetprefixRegister extends \Magento\Directory\Block\Data 23 | { 24 | 25 | protected $helper; 26 | 27 | protected $streetprefix; 28 | 29 | /** 30 | * Streetprefix constructor. 31 | * @param \Magento\Framework\View\Element\Template\Context $context 32 | * @param \Magento\Directory\Helper\Data $directoryHelper 33 | * @param \Magento\Framework\Json\EncoderInterface $jsonEncoder 34 | * @param \Magento\Framework\App\Cache\Type\Config $configCacheType 35 | * @param \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory 36 | * @param \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory 37 | * @param Helper $helper 38 | * @param \SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix $streetprefix 39 | * @param array $data 40 | */ 41 | public function __construct( 42 | \Magento\Framework\View\Element\Template\Context $context, 43 | \Magento\Directory\Helper\Data $directoryHelper, 44 | \Magento\Framework\Json\EncoderInterface $jsonEncoder, 45 | \Magento\Framework\App\Cache\Type\Config $configCacheType, 46 | \Magento\Directory\Model\ResourceModel\Region\CollectionFactory $regionCollectionFactory, 47 | \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryCollectionFactory, 48 | Helper $helper, 49 | \SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix $streetprefix, 50 | array $data = []) 51 | { 52 | $this->helper = $helper; 53 | $this->streetprefix = $streetprefix; 54 | 55 | parent::__construct($context, $directoryHelper, $jsonEncoder, $configCacheType, $regionCollectionFactory, $countryCollectionFactory, $data); 56 | } 57 | 58 | /** 59 | * Initialize block 60 | * 61 | * @return void 62 | */ 63 | public function _construct() 64 | { 65 | parent::_construct(); 66 | $this->setTemplate('SystemCode_BrazilCustomerAttributes::widget/streetprefix.phtml'); 67 | } 68 | 69 | /** 70 | * Check if street prefix is enabled 71 | * @return bool 72 | */ 73 | public function getIsEnabled() 74 | { 75 | return $this->helper->getConfig("brazilcustomerattributes/general/prefix_enabled"); 76 | } 77 | 78 | /** 79 | * Check if street prefix is enabled 80 | * @return array 81 | */ 82 | public function getStreetPrefixOptions() 83 | { 84 | return $this->streetprefix->getAllOptions(); 85 | } 86 | 87 | 88 | /** 89 | * Check if address already has street prefix 90 | * @return value 91 | */ 92 | public function getCurrentStreetPrefix() 93 | { 94 | return; 95 | } 96 | 97 | } -------------------------------------------------------------------------------- /Config/Backend/Prefixoptions.php: -------------------------------------------------------------------------------- 1 | 24 | * @copyright System Code LTDA-ME 25 | * @license http://opensource.org/licenses/osl-3.0.php 26 | */ 27 | class Prefixoptions extends ConfigValue 28 | { 29 | /** 30 | * Json Serializer 31 | * 32 | * @var SerializerInterface 33 | */ 34 | protected $serializer; 35 | 36 | /** 37 | * Prefixoptions constructor. 38 | * @param SerializerInterface $serializer 39 | * @param Context $context 40 | * @param Registry $registry 41 | * @param ScopeConfigInterface $config 42 | * @param TypeListInterface $cacheTypeList 43 | * @param AbstractResource|null $resource 44 | * @param AbstractDb|null $resourceCollection 45 | * @param array $data 46 | */ 47 | public function __construct( 48 | SerializerInterface $serializer, 49 | Context $context, 50 | Registry $registry, 51 | ScopeConfigInterface $config, 52 | TypeListInterface $cacheTypeList, 53 | AbstractResource $resource = null, 54 | AbstractDb $resourceCollection = null, 55 | array $data = [] 56 | ) { 57 | $this->serializer = $serializer; 58 | parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); 59 | } 60 | 61 | /** 62 | * Prepare data before save 63 | * 64 | * @return void 65 | */ 66 | public function beforeSave() 67 | { 68 | /** @var array $value */ 69 | $value = $this->getValue(); 70 | unset($value['__empty']); 71 | $encodedValue = $this->serializer->serialize($value); 72 | 73 | $this->setValue($encodedValue); 74 | } 75 | 76 | /** 77 | * Process data after load 78 | * 79 | * @return void 80 | */ 81 | protected function _afterLoad() 82 | { 83 | /** @var string $value */ 84 | $value = $this->getValue(); 85 | if($value){ 86 | $decodedValue = $this->serializer->unserialize($value); 87 | 88 | $this->setValue($decodedValue); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Controller/Consult/Address.php: -------------------------------------------------------------------------------- 1 | 21 | * @copyright System Code LTDA-ME 22 | * @license http://opensource.org/licenses/osl-3.0.php 23 | */ 24 | class Address extends Action implements HttpGetActionInterface 25 | { 26 | /** 27 | * @var Helper 28 | */ 29 | protected $helper; 30 | 31 | /** 32 | * @var JsonFactory 33 | */ 34 | protected $_resultJsonFactory; 35 | 36 | /** 37 | * Address constructor. 38 | * @param Helper $helper 39 | * @param Context $context 40 | * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory 41 | */ 42 | public function __construct( 43 | Helper $helper, 44 | Context $context, 45 | JsonFactory $resultJsonFactory 46 | ) { 47 | $this->helper = $helper; 48 | $this->_resultJsonFactory = $resultJsonFactory; 49 | parent::__construct($context); 50 | } 51 | 52 | public function execute() 53 | { 54 | $data = ["error" => true]; 55 | 56 | if($zipcode = $this->getRequest()->getParam('zipcode')){ 57 | try { 58 | $client = new \SoapClient('https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl', 59 | ['exceptions' => true]); 60 | $result = $client->consultaCEP(['cep' => $zipcode]); 61 | } catch (\SoapFault $e) { 62 | 63 | } 64 | 65 | if(isset($result)){ 66 | $complement = trim(implode(' ', array($result->return->complemento??'', $result->return->complemento2??''))); 67 | $data = [ 68 | 'error' => false, 69 | 'zipcode' => $zipcode, 70 | 'street' => $result->return->end, 71 | 'neighborhood' => $result->return->bairro, 72 | 'complement' => $complement, 73 | 'city' => $result->return->cidade, 74 | 'uf' => $this->helper->getRegionId($result->return->uf) 75 | ]; 76 | } 77 | } 78 | 79 | $return = $this->_resultJsonFactory->create(); 80 | return $return->setData(str_replace("\\","",$data)); 81 | } 82 | } -------------------------------------------------------------------------------- /Helper/Data.php: -------------------------------------------------------------------------------- 1 | 15 | * @copyright System Code LTDA-ME 16 | * @license http://opensource.org/licenses/osl-3.0.php 17 | */ 18 | class Data extends \Magento\Framework\App\Helper\AbstractHelper 19 | { 20 | 21 | public function getConfig($config_path) 22 | { 23 | return $this->scopeConfig->getValue( 24 | $config_path, 25 | \Magento\Store\Model\ScopeInterface::SCOPE_STORE 26 | ); 27 | } 28 | 29 | function validateCPF($cpf) { 30 | // Extrai somente os números 31 | $cpf = preg_replace( '/[^0-9]/is', '', $cpf ); 32 | 33 | // Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11 34 | $invalidos = array('00000000000', '11111111111', '22222222222', '33333333333', '44444444444', '55555555555', '66666666666', '77777777777', '88888888888', '99999999999'); 35 | 36 | if (in_array($cpf, $invalidos)){ 37 | return false; 38 | } 39 | 40 | // Verifica se foi informado todos os digitos corretamente 41 | if (strlen($cpf) != 11) { 42 | return false; 43 | } 44 | 45 | // Faz o calculo para validar o CPF 46 | for ($t = 9; $t < 11; $t++) { 47 | for ($d = 0, $c = 0; $c < $t; $c++) { 48 | $d += $cpf[$c] * (($t + 1) - $c); 49 | } 50 | $d = ((10 * $d) % 11) % 10; 51 | if ($cpf[$c] != $d) { 52 | return false; 53 | } 54 | } 55 | return true; 56 | } 57 | 58 | 59 | function validateCNPJ($cnpj) { 60 | $cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj); 61 | 62 | if (strlen($cnpj) <> 14) 63 | return false; 64 | 65 | $sum = 0; 66 | 67 | $sum += ($cnpj[0] * 5); 68 | $sum += ($cnpj[1] * 4); 69 | $sum += ($cnpj[2] * 3); 70 | $sum += ($cnpj[3] * 2); 71 | $sum += ($cnpj[4] * 9); 72 | $sum += ($cnpj[5] * 8); 73 | $sum += ($cnpj[6] * 7); 74 | $sum += ($cnpj[7] * 6); 75 | $sum += ($cnpj[8] * 5); 76 | $sum += ($cnpj[9] * 4); 77 | $sum += ($cnpj[10] * 3); 78 | $sum += ($cnpj[11] * 2); 79 | 80 | $d1 = $sum % 11; 81 | $d1 = $d1 < 2 ? 0 : 11 - $d1; 82 | 83 | $sum = 0; 84 | $sum += ($cnpj[0] * 6); 85 | $sum += ($cnpj[1] * 5); 86 | $sum += ($cnpj[2] * 4); 87 | $sum += ($cnpj[3] * 3); 88 | $sum += ($cnpj[4] * 2); 89 | $sum += ($cnpj[5] * 9); 90 | $sum += ($cnpj[6] * 8); 91 | $sum += ($cnpj[7] * 7); 92 | $sum += ($cnpj[8] * 6); 93 | $sum += ($cnpj[9] * 5); 94 | $sum += ($cnpj[10] * 4); 95 | $sum += ($cnpj[11] * 3); 96 | $sum += ($cnpj[12] * 2); 97 | 98 | 99 | $d2 = $sum % 11; 100 | $d2 = $d2 < 2 ? 0 : 11 - $d2; 101 | 102 | if ($cnpj[12] == $d1 && $cnpj[13] == $d2) { 103 | return true; 104 | } 105 | else { 106 | return false; 107 | } 108 | 109 | } 110 | 111 | public function getRegionId($state){ 112 | 113 | $states = array( 114 | "AC"=>"Acre", 115 | "AL"=>"Alagoas", 116 | "AM"=>"Amazonas", 117 | "AP"=>"Amapá", 118 | "BA"=>"Bahia", 119 | "CE"=>"Ceará", 120 | "DF"=>"Distrito Federal", 121 | "ES"=>"Espírito Santo", 122 | "GO"=>"Goiás", 123 | "MA"=>"Maranhão", 124 | "MT"=>"Mato Grosso", 125 | "MS"=>"Mato Grosso do Sul", 126 | "MG"=>"Minas Gerais", 127 | "PA"=>"Pará", 128 | "PB"=>"Paraíba", 129 | "PR"=>"Paraná", 130 | "PE"=>"Pernambuco", 131 | "PI"=>"Piauí", 132 | "RJ"=>"Rio de Janeiro", 133 | "RN"=>"Rio Grande do Norte", 134 | "RO"=>"Rondônia", 135 | "RS"=>"Rio Grande do Sul", 136 | "RR"=>"Roraima", 137 | "SC"=>"Santa Catarina", 138 | "SE"=>"Sergipe", 139 | "SP"=>"São Paulo", 140 | "TO"=>"Tocantins"); 141 | 142 | if($states[$state]){ 143 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 144 | 145 | $region = $objectManager->create('Magento\Directory\Model\Region') 146 | ->loadByName($states[$state], "BR"); 147 | 148 | return $region->getId(); 149 | } 150 | 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /Model/Config/Backend/Show/Customer.php: -------------------------------------------------------------------------------- 1 | 14 | * @copyright System Code LTDA-ME 15 | * @license http://opensource.org/licenses/osl-3.0.php 16 | */ 17 | class Customer extends \Magento\Customer\Model\Config\Backend\Show\Customer{ 18 | /** 19 | * Actions after save 20 | * 21 | * @return $this 22 | */ 23 | public function afterSave() 24 | { 25 | $result = parent::afterSave(); 26 | 27 | $valueConfig = [ 28 | '' => ['is_required' => 0, 'is_visible' => 0, 'is_unique' => 0], 29 | 'opt' => ['is_required' => 0, 'is_visible' => 1, 'is_unique' => 0], 30 | '1' => ['is_required' => 0, 'is_visible' => 1, 'is_unique' => 0], 31 | 'req' => ['is_required' => 0, 'is_visible' => 1, 'is_unique' => 0], 32 | 'optuni' => ['is_required' => 0, 'is_visible' => 1, 'is_unique' => 1], 33 | 'requni' => ['is_required' => 0, 'is_visible' => 1, 'is_unique' => 1] 34 | ]; 35 | 36 | $value = $this->getValue(); 37 | if (isset($valueConfig[$value])) { 38 | $data = $valueConfig[$value]; 39 | } else { 40 | $data = $valueConfig['']; 41 | } 42 | 43 | if ($this->getScope() == 'websites') { 44 | $website = $this->storeManager->getWebsite($this->getScopeCode()); 45 | $dataFieldPrefix = 'scope_'; 46 | } else { 47 | $website = null; 48 | $dataFieldPrefix = ''; 49 | } 50 | 51 | foreach ($this->_getAttributeObjects() as $attributeObject) { 52 | if ($website) { 53 | $attributeObject->setWebsite($website); 54 | $attributeObject->load($attributeObject->getId()); 55 | } 56 | $attributeObject->setData($dataFieldPrefix . 'is_required', $data['is_required']); 57 | $attributeObject->setData($dataFieldPrefix . 'is_visible', $data['is_visible']); 58 | $attributeObject->setData($dataFieldPrefix . 'is_unique', $data['is_unique']); 59 | $attributeObject->save(); 60 | } 61 | 62 | return $result; 63 | } 64 | } -------------------------------------------------------------------------------- /Model/Config/Source/Customeredit.php: -------------------------------------------------------------------------------- 1 | 13 | * @copyright System Code LTDA-ME 14 | * @license http://opensource.org/licenses/osl-3.0.php 15 | */ 16 | class Customeredit implements \Magento\Framework\Option\ArrayInterface 17 | { 18 | /** 19 | * @return array 20 | */ 21 | public function toOptionArray() 22 | { 23 | return [ 24 | ['value' => '', 'label' => __('No')], 25 | ['value' => 'yes', 'label' => __('Yes, except change person type')], 26 | ['value' => 'yesall', 'label' => __('Yes, and allow change person type')] 27 | ]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Model/Config/Source/Customergroup.php: -------------------------------------------------------------------------------- 1 | 13 | * @copyright System Code LTDA-ME 14 | * @license http://opensource.org/licenses/osl-3.0.php 15 | */ 16 | class Customergroup implements \Magento\Framework\Option\ArrayInterface 17 | { 18 | /** 19 | * @return array 20 | */ 21 | public function toOptionArray() 22 | { 23 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 24 | $groups = $objectManager->get('\Magento\Customer\Model\ResourceModel\Group\Collection'); 25 | $groupsArr = []; 26 | $groupsArr[] = ['value' => '', 'label' => 'Use Default Group']; 27 | 28 | foreach ($groups as $group) { 29 | if($group->getCode()!="NOT LOGGED IN"){ 30 | $groupsArr[] = ['value' => $group->getId(), 'label' => $group->getCode()]; 31 | } 32 | } 33 | 34 | return $groupsArr; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Model/Config/Source/Nooptrequn.php: -------------------------------------------------------------------------------- 1 | 14 | * @copyright System Code LTDA-ME 15 | * @license http://opensource.org/licenses/osl-3.0.php 16 | */ 17 | class Nooptrequn implements \Magento\Framework\Option\ArrayInterface 18 | { 19 | /** 20 | * @return array 21 | */ 22 | public function toOptionArray() 23 | { 24 | return [ 25 | ['value' => '', 'label' => __('No')], 26 | ['value' => 'opt', 'label' => __('Optional')], 27 | ['value' => 'req', 'label' => __('Required')], 28 | ['value' => 'optuni', 'label' => __('Optional and Unique')], 29 | ['value' => 'requni', 'label' => __('Required and Unique')] 30 | ]; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Model/Config/Source/Streetprefix.php: -------------------------------------------------------------------------------- 1 | 20 | * @copyright System Code LTDA-ME 21 | * @license http://opensource.org/licenses/osl-3.0.php 22 | */ 23 | class Streetprefix extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource { 24 | 25 | /** 26 | * @var OptionFactory 27 | */ 28 | protected $optionFactory; 29 | 30 | /** 31 | * Json Serializer 32 | * 33 | * @var SerializerInterface 34 | */ 35 | protected $serializer; 36 | 37 | protected $helper; 38 | 39 | public function __construct( 40 | Helper $helper, 41 | SerializerInterface $serializer 42 | ) 43 | { 44 | $this->helper = $helper; 45 | $this->serializer = $serializer; 46 | } 47 | 48 | /** 49 | * Get all options 50 | * 51 | * @return array 52 | */ 53 | public function getAllOptions() 54 | { 55 | if($this->helper->getConfig('brazilcustomerattributes/general/prefix_enabled')){ 56 | $options = $this->helper->getConfig('brazilcustomerattributes/general/prefix_options'); 57 | $optionsArr = $this->serializer->unserialize($options); 58 | 59 | $this->_options[] = ['label' => __('Please select a street prefix.'), 'value' => '']; 60 | foreach ($optionsArr as $op){ 61 | $this->_options[] = ['label' => $op["prefix_options"], 'value' => $op["prefix_options"]]; 62 | } 63 | 64 | return $this->_options; 65 | } 66 | return []; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Model/Magento/Customer/ResourceModel/AddressRepository.php: -------------------------------------------------------------------------------- 1 | 15 | * @copyright System Code LTDA-ME 16 | * @license http://opensource.org/licenses/osl-3.0.php 17 | */ 18 | class AddressRepository extends \Magento\Customer\Model\ResourceModel\AddressRepository 19 | { 20 | protected $helper; 21 | 22 | /** 23 | * @param \Magento\Customer\Model\AddressFactory $addressFactory 24 | * @param \Magento\Customer\Model\AddressRegistry $addressRegistry 25 | * @param \Magento\Customer\Model\CustomerRegistry $customerRegistry 26 | * @param \Magento\Customer\Model\ResourceModel\Address $addressResourceModel 27 | * @param \Magento\Directory\Helper\Data $directoryData 28 | * @param \Magento\Customer\Api\Data\AddressSearchResultsInterfaceFactory $addressSearchResultsFactory 29 | * @param \Magento\Customer\Model\ResourceModel\Address\CollectionFactory $addressCollectionFactory 30 | * @param \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $extensionAttributesJoinProcessor 31 | */ 32 | public function __construct( 33 | Helper $helper, 34 | \Magento\Customer\Model\AddressFactory $addressFactory, 35 | \Magento\Customer\Model\AddressRegistry $addressRegistry, 36 | \Magento\Customer\Model\CustomerRegistry $customerRegistry, 37 | \Magento\Customer\Model\ResourceModel\Address $addressResourceModel, 38 | \Magento\Directory\Helper\Data $directoryData, 39 | \Magento\Customer\Api\Data\AddressSearchResultsInterfaceFactory $addressSearchResultsFactory, 40 | \Magento\Customer\Model\ResourceModel\Address\CollectionFactory $addressCollectionFactory, 41 | \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $extensionAttributesJoinProcessor 42 | ) { 43 | $this->helper = $helper; 44 | parent::__construct($addressFactory, $addressRegistry, $customerRegistry, $addressResourceModel, $directoryData, $addressSearchResultsFactory, $addressCollectionFactory, $extensionAttributesJoinProcessor); 45 | } 46 | 47 | /** 48 | * Validate Customer Addresses attribute values. 49 | * 50 | * @param CustomerAddressModel $customerAddressModel the model to validate 51 | * @return InputException 52 | * 53 | * @SuppressWarnings(PHPMD.NPathComplexity) 54 | * @SuppressWarnings(PHPMD.CyclomaticComplexity) 55 | */ 56 | private function _validate(CustomerAddressModel $customerAddressModel) 57 | { 58 | $exception = new InputException(); 59 | if ($customerAddressModel->getShouldIgnoreValidation()) { 60 | return $exception; 61 | } 62 | 63 | if (!\Zend_Validate::is($customerAddressModel->getFirstname(), 'NotEmpty')) { 64 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'firstname'])); 65 | } 66 | 67 | if (!\Zend_Validate::is($customerAddressModel->getLastname(), 'NotEmpty')) { 68 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'lastname'])); 69 | } 70 | 71 | if (!\Zend_Validate::is($customerAddressModel->getStreetLine(1), 'NotEmpty')) { 72 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'street'])); 73 | } 74 | 75 | /* Custom Street Validations */ 76 | if ($this->helper->getConfig("brazilcustomerattributes/general/line_number") && 77 | !\Zend_Validate::is($customerAddressModel->getStreetLine(2), 'NotEmpty')) { 78 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'number'])); 79 | } 80 | 81 | if ($this->helper->getConfig("brazilcustomerattributes/general/line_neighborhood") && 82 | !\Zend_Validate::is($customerAddressModel->getStreetLine(3), 'NotEmpty')) { 83 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'neighborhood'])); 84 | } 85 | 86 | if ($this->helper->getConfig("brazilcustomerattributes/general/line_complement") && 87 | !\Zend_Validate::is($customerAddressModel->getStreetLine(4), 'NotEmpty')) { 88 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'complement'])); 89 | } 90 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'complement'])); 91 | 92 | 93 | if (!\Zend_Validate::is($customerAddressModel->getCity(), 'NotEmpty')) { 94 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'city'])); 95 | } 96 | 97 | if (!\Zend_Validate::is($customerAddressModel->getTelephone(), 'NotEmpty')) { 98 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'telephone'])); 99 | } 100 | 101 | $havingOptionalZip = $this->directoryData->getCountriesWithOptionalZip(); 102 | if (!in_array($customerAddressModel->getCountryId(), $havingOptionalZip) 103 | && !\Zend_Validate::is($customerAddressModel->getPostcode(), 'NotEmpty') 104 | ) { 105 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'postcode'])); 106 | } 107 | 108 | if (!\Zend_Validate::is($customerAddressModel->getCountryId(), 'NotEmpty')) { 109 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'countryId'])); 110 | } 111 | 112 | if ($this->directoryData->isRegionRequired($customerAddressModel->getCountryId())) { 113 | $regionCollection = $customerAddressModel->getCountryModel()->getRegionCollection(); 114 | if (!$regionCollection->count() && empty($customerAddressModel->getRegion())) { 115 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'region'])); 116 | } elseif ( 117 | $regionCollection->count() 118 | && !in_array( 119 | $customerAddressModel->getRegionId(), 120 | array_column($regionCollection->getData(), 'region_id') 121 | ) 122 | ) { 123 | $exception->addError(__('%fieldName is a required field.', ['fieldName' => 'regionId'])); 124 | } 125 | } 126 | return $exception; 127 | } 128 | } -------------------------------------------------------------------------------- /Observer/CustomerData.php: -------------------------------------------------------------------------------- 1 | 20 | * @copyright System Code LTDA-ME 21 | * @license http://opensource.org/licenses/osl-3.0.php 22 | */ 23 | class CustomerData implements \Magento\Framework\Event\ObserverInterface 24 | { 25 | private $_request; 26 | private $_helper; 27 | private $_customer; 28 | 29 | public function __construct( 30 | ManagerInterface $messageManager, 31 | RequestInterface $request, 32 | Helper $helper, 33 | Session $session 34 | ) { 35 | $this->_request = $request; 36 | $this->_helper = $helper; 37 | $this->_customer = $session->getCustomer(); 38 | } 39 | 40 | public function execute(\Magento\Framework\Event\Observer $observer) 41 | { 42 | $params = $this->_request->getParams(); 43 | $customer = $observer->getCustomer(); 44 | 45 | if($customer->getId()){ 46 | if(isset($params["person_type"]) && $params["person_type"]=="cpf"){ 47 | $groupId = $this->_helper->getConfig("brazilcustomerattributes/general/customer_group_cpf"); 48 | 49 | $customer->setCnpj(); 50 | $customer->setSocialname(); 51 | $customer->setIe(); 52 | }else if(isset($params["person_type"]) && $params["person_type"]=="cnpj"){ 53 | $groupId = $this->_helper->getConfig("brazilcustomerattributes/general/customer_group_cnpj"); 54 | 55 | $customer->setCpf(); 56 | $customer->setRg(); 57 | } 58 | 59 | if(isset($params["cpf"]) && $params["cpf"]!=""){ 60 | $document = $params["cpf"]; 61 | }else if(isset($params["cnpj"]) && $params["cnpj"]!=""){ 62 | $document = $params["cnpj"]; 63 | } 64 | 65 | if(isset($groupId) && $groupId!=""){ 66 | $customer->setGroupId($groupId); 67 | } 68 | 69 | if(isset($document) && $this->_helper->getConfig("brazilcustomerattributes/general/copy_taxvat")){ 70 | $customer->setTaxvat($document); 71 | } 72 | 73 | $customer->save(); 74 | } 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Observer/CustomerValidations.php: -------------------------------------------------------------------------------- 1 | 21 | * @copyright System Code LTDA-ME 22 | * @license http://opensource.org/licenses/osl-3.0.php 23 | */ 24 | class CustomerValidations implements \Magento\Framework\Event\ObserverInterface 25 | { 26 | private $_request; 27 | private $_helper; 28 | private $_session; 29 | 30 | public function __construct( 31 | ManagerInterface $messageManager, 32 | RequestInterface $request, 33 | Helper $helper, 34 | Session $session 35 | ) { 36 | $this->_request = $request; 37 | $this->_helper = $helper; 38 | $this->_session = $session; 39 | } 40 | 41 | public function execute(\Magento\Framework\Event\Observer $observer) 42 | { 43 | $params = $this->_request->getParams(); 44 | 45 | if(isset($params["person_type"]) && $params["person_type"]=="cpf"){ 46 | $cpf = (isset($params["cpf"])?$params["cpf"]:""); 47 | $rg = (isset($params["rg"])?$params["rg"]:""); 48 | 49 | if($cpf!="") { 50 | if (!$this->_helper->validateCPF($cpf)) { 51 | throw new CouldNotSaveException( 52 | __("%1 is invalid.", "CPF") 53 | ); 54 | } 55 | } 56 | 57 | if(!$this->_validateInput($cpf, "cpf", "cpf/cpf_show")){ 58 | throw new CouldNotSaveException( 59 | __("%1 already in use.", "CPF") 60 | ); 61 | } 62 | 63 | if(!$this->_validateInput($rg, "rg", "cpf/rg_show")){ 64 | throw new CouldNotSaveException( 65 | __("%1 already in use.", "RG") 66 | ); 67 | } 68 | 69 | }else if(isset($params["person_type"]) && $params["person_type"]=="cnpj"){ 70 | $cnpj = (isset($params["cnpj"])?$params["cnpj"]:""); 71 | $ie = (isset($params["ie"])?$params["ie"]:""); 72 | $socialName = (isset($params["socialname"])?$params["socialname"]:""); 73 | $tradeName = (isset($params["tradename"])?$params["tradename"]:""); 74 | 75 | if($cnpj!=""){ 76 | if(!$this->_helper->validateCNPJ($cnpj)){ 77 | throw new CouldNotSaveException( 78 | __("%1 is invalid.", "CNPJ") 79 | ); 80 | } 81 | } 82 | 83 | if(!$this->_validateInput($cnpj, "cnpj", "cnpj/cnpj_show")){ 84 | throw new CouldNotSaveException( 85 | __("%1 already in use.", "CNPJ") 86 | ); 87 | } 88 | 89 | if(!$this->_validateInput($ie, "ie", "cnpj/ie_show")){ 90 | throw new CouldNotSaveException( 91 | __("%1 already in use.", "ie") 92 | ); 93 | } 94 | 95 | if(!$this->_validateInput($socialName, "socialname", "cnpj/socialname_show")){ 96 | throw new CouldNotSaveException( 97 | __("%1 already in use.", "Social Name") 98 | ); 99 | } 100 | 101 | if(!$this->_validateInput($tradeName, "tradename", "cnpj/tradename_show")){ 102 | throw new CouldNotSaveException( 103 | __("%1 already in use.", "Trade Name") 104 | ); 105 | } 106 | } 107 | } 108 | 109 | protected function _validateInput($value, $fieldName, $path){ 110 | $show = $this->_helper->getConfig("brazilcustomerattributes/".$path); 111 | if($show == "req" || $show == "requni"){ 112 | if($value == ""){ 113 | return false; 114 | } 115 | //verify if is unique 116 | if($show == "requni"){ 117 | if($this->_session->getCustomer()->getId()!="" && $this->_session->getCustomer()->getData($fieldName) == $value){ //verifico se é ele mesmo que utiliza 118 | return true; 119 | } 120 | 121 | //check if field already being used 122 | $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 123 | 124 | $customerObj = $objectManager->create('Magento\Customer\Model\Customer')->getCollection(); 125 | $customerObj->addFieldToFilter($fieldName, $value); 126 | 127 | 128 | foreach ($customerObj as $customer){ 129 | if($customer->getCreatedAt()){ 130 | return true; 131 | } 132 | return false; 133 | } 134 | } 135 | } 136 | return true; 137 | } 138 | } -------------------------------------------------------------------------------- /Observer/QuoteToOrder.php: -------------------------------------------------------------------------------- 1 | 17 | * @copyright System Code LTDA-ME 18 | * @license http://opensource.org/licenses/osl-3.0.php 19 | */ 20 | class QuoteToOrder implements \Magento\Framework\Event\ObserverInterface 21 | { 22 | /** 23 | * @var AddressRepositoryInterface 24 | */ 25 | protected $addressRepository; 26 | 27 | /** 28 | * QuoteToOrder constructor. 29 | * @param AddressRepositoryInterface $addressRepository 30 | */ 31 | public function __construct( 32 | AddressRepositoryInterface $addressRepository 33 | ) { 34 | $this->addressRepository = $addressRepository; 35 | } 36 | 37 | /** 38 | * 39 | * @param \Magento\Framework\Event\Observer $observer 40 | * @return $this 41 | */ 42 | public function execute(\Magento\Framework\Event\Observer $observer) 43 | { 44 | // copy shipping address street prefix 45 | $quoteShippingAdress = $observer->getQuote()->getShippingAddress(); 46 | $street_prefix = $quoteShippingAdress->getStreetPrefix(); 47 | if(isset($street_prefix)) { 48 | $orderShippingAdress = $observer->getOrder()->getShippingAddress(); 49 | $orderShippingAdress->setStreetPrefix($street_prefix)->save(); 50 | 51 | // copy shipping address street prefix to customer 52 | if ($addressId = $orderShippingAdress->getCustomerAddressId()) { 53 | $this->updateCustomerAddress($addressId, $street_prefix); 54 | } 55 | } 56 | 57 | // copy billing address street prefix 58 | $quoteBillingAddress = $observer->getQuote()->getBillingAddress(); 59 | $street_prefix = $quoteBillingAddress->getStreetPrefix(); 60 | if(isset($street_prefix)) { 61 | $orderBillingAddress = $observer->getOrder()->getBillingAddress(); 62 | $orderBillingAddress->setStreetPrefix($street_prefix)->save(); 63 | 64 | // copy billing address street prefix to customer 65 | if ($addressId = $orderBillingAddress->getCustomerAddressId()) { 66 | $this->updateCustomerAddress($addressId, $street_prefix); 67 | } 68 | } 69 | 70 | return $this; 71 | } 72 | 73 | /** 74 | * Update street prefix on customer address 75 | * @throws \Magento\Framework\Exception\LocalizedException 76 | * @return void 77 | */ 78 | protected function updateCustomerAddress($addressId, $streetPrefix) { 79 | $address = $this->addressRepository->getById($addressId); 80 | $address->setCustomAttribute('street_prefix', $streetPrefix); 81 | $this->addressRepository->save($address); 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /Plugin/Checkout/LayoutProcessor.php: -------------------------------------------------------------------------------- 1 | 15 | * @copyright System Code LTDA-ME 16 | * @license http://opensource.org/licenses/osl-3.0.php 17 | */ 18 | class LayoutProcessor 19 | { 20 | 21 | /** 22 | * @var Helper 23 | */ 24 | protected $helper; 25 | 26 | /** 27 | * @var \SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix 28 | */ 29 | protected $streetprefix; 30 | 31 | /** 32 | * @var Array 33 | */ 34 | protected $streetprefixoptions; 35 | 36 | /** 37 | * LayoutProcessorPlugin constructor. 38 | * 39 | * @param Helper $helper 40 | * @param \SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix $streetprefix 41 | */ 42 | public function __construct( 43 | Helper $helper, 44 | \SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix $streetprefix 45 | ) { 46 | $this->helper = $helper; 47 | $this->streetprefix = $streetprefix; 48 | } 49 | 50 | /** 51 | * @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject 52 | * @param array $jsLayout 53 | * @return array 54 | */ 55 | 56 | public function afterProcess( 57 | \Magento\Checkout\Block\Checkout\LayoutProcessor $subject, 58 | array $jsLayout 59 | ) { 60 | $numStreetLines = $this->helper->getConfig("customer/address/street_lines"); 61 | $this->setStreetPrefixOptions(); 62 | $jsLayout = $this->getShippingFormFields($jsLayout, $numStreetLines); 63 | $jsLayout = $this->getBillingFormFields($jsLayout, $numStreetLines); 64 | 65 | return $jsLayout; 66 | } 67 | 68 | public function setStreetPrefixOptions() 69 | { 70 | $this->streetprefixoptions = []; 71 | 72 | if($this->helper->getConfig("brazilcustomerattributes/general/prefix_enabled")) { 73 | foreach ($this->streetprefix->getAllOptions() as $op) { 74 | $this->streetprefixoptions[] = [ 75 | 'label' => $op["label"], 76 | 'value' => $op["value"] 77 | ]; 78 | } 79 | } 80 | } 81 | 82 | public function getShippingFormFields($jsLayout, $numStreetLines) 83 | { 84 | $shippingAddressFieldsetChild = $jsLayout['components']['checkout']['children']['steps']['children'] 85 | ['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']; 86 | 87 | // Street Label 88 | $shippingAddressFieldsetChild['street']['label'] = ''; 89 | $shippingAddressFieldsetChild['street']['required'] = false; 90 | 91 | // Street Line 0 92 | $shippingAddressFieldsetChild['street']['children'][0]['label'] = __('Address'); 93 | 94 | $shippingAddressFieldsetChild['street']['children'][0]['validation'] = [ 95 | 'required-entry' => true, 96 | 'min_text_len‌​gth' => 1, 97 | 'max_text_length' => 255 98 | ]; 99 | 100 | // Street Line 1 101 | if($this->helper->getConfig("brazilcustomerattributes/general/line_number") 102 | && $numStreetLines >= 2) { 103 | $shippingAddressFieldsetChild['street']['children'][1]['label'] = __('Number'); 104 | $shippingAddressFieldsetChild['street']['children'][1]['validation'] = [ 105 | 'required-entry' => true, 106 | 'min_text_len‌​gth' => 1, 107 | 'max_text_length' => 255 108 | ]; 109 | } 110 | 111 | // Street Line 2 112 | if($this->helper->getConfig("brazilcustomerattributes/general/line_neighborhood") 113 | && $numStreetLines >= 3) { 114 | $shippingAddressFieldsetChild['street']['children'][2]['label'] = __('Neighborhood'); 115 | $shippingAddressFieldsetChild['street']['children'][2]['validation'] = [ 116 | 'required-entry' => true, 117 | 'min_text_len‌​gth' => 1, 118 | 'max_text_length' => 255 119 | ]; 120 | } 121 | 122 | // Street Line 3 123 | if($this->helper->getConfig("brazilcustomerattributes/general/line_complement") 124 | && $numStreetLines == 4) { 125 | $shippingAddressFieldsetChild['street']['children'][3]['label'] = __('Complement'); 126 | } 127 | 128 | // Street Prefix 129 | if($this->helper->getConfig("brazilcustomerattributes/general/prefix_enabled")) { 130 | $shippingAddressFieldsetChild['street_prefix'] = [ 131 | 'component' => 'Magento_Ui/js/form/element/select', 132 | 'config' => [ 133 | 'customScope' => 'shippingAddress.custom_attributes', 134 | 'template' => 'ui/form/field', 135 | 'options' => $this->streetprefixoptions, 136 | 'id' => 'street-prefix' 137 | ], 138 | 'dataScope' => 'shippingAddress.custom_attributes.street_prefix', 139 | 'label' => __('Street Prefix'), 140 | 'provider' => 'checkoutProvider', 141 | 'visible' => true, 142 | 'validation' => [ 143 | 'required-entry' => true, 144 | ], 145 | 'sortOrder' => 65, 146 | 'id' => 'street-prefix' 147 | ]; 148 | } 149 | 150 | // Company 151 | $shippingAddressFieldsetChild['company']['sortOrder'] = 118; 152 | 153 | // Zipcode 154 | $shippingAddressFieldsetChild['postcode']['sortOrder'] = 40; 155 | $shippingAddressFieldsetChild['postcode']['component'] = 156 | 'SystemCode_BrazilCustomerAttributes/js/shipping-address/address-renderer/zip-code'; 157 | $shippingAddressFieldsetChild['postcode']['config']['elementTmpl'] = 158 | 'SystemCode_BrazilCustomerAttributes/shipping-address/address-renderer/zip-code'; 159 | 160 | // Telephone 161 | $shippingAddressFieldsetChild['telephone']['component'] = 162 | 'SystemCode_BrazilCustomerAttributes/js/shipping-address/address-renderer/telephone'; 163 | 164 | // Fax 165 | $shippingAddressFieldsetChild['fax']['component'] = 166 | 'SystemCode_BrazilCustomerAttributes/js/shipping-address/address-renderer/telephone'; 167 | 168 | $jsLayout['components']['checkout']['children']['steps']['children'] 169 | ['shipping-step']['children']['shippingAddress']['children'] 170 | ['shipping-address-fieldset']['children'] = $shippingAddressFieldsetChild; 171 | 172 | return $jsLayout; 173 | } 174 | 175 | public function getBillingFormFields($jsLayout, $numStreetLines) 176 | { 177 | if(isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step'] 178 | ['children']['payment']['children']['payments-list']) 179 | ) { 180 | $paymentForms = $jsLayout['components']['checkout']['children']['steps']['children'] 181 | ['billing-step']['children']['payment']['children'] 182 | ['payments-list']['children']; 183 | 184 | foreach ($paymentForms as $paymentMethodForm => $paymentMethodValue) { 185 | 186 | $paymentMethodCode = str_replace('-form', '', $paymentMethodForm); 187 | 188 | if (!isset($jsLayout['components']['checkout']['children']['steps']['children']['billing-step'] 189 | ['children']['payment']['children']['payments-list']['children'][$paymentMethodCode . '-form']) 190 | ) { 191 | continue; 192 | } 193 | 194 | $paymentFormChildren = $jsLayout['components']['checkout']['children']['steps']['children'] 195 | ['billing-step']['children']['payment']['children']['payments-list']['children'] 196 | [$paymentMethodCode . '-form']['children']['form-fields']['children']; 197 | 198 | // Street Label 199 | $paymentFormChildren['street']['label'] = ''; 200 | $paymentFormChildren['street']['required'] = false; 201 | 202 | // Street Line 0 203 | $paymentFormChildren['street']['children'][0]['label'] = __('Address'); 204 | 205 | // Street Line 1 206 | if($this->helper->getConfig("brazilcustomerattributes/general/line_number") 207 | && $numStreetLines >= 2) { 208 | $paymentFormChildren['street']['children'][1]['label'] = __('Number'); 209 | $paymentFormChildren['street']['children'][1]['validation'] = [ 210 | 'required-entry' => true, 211 | 'min_text_len‌​gth' => 1, 212 | 'max_text_length' => 255 213 | ]; 214 | } 215 | 216 | // Street Line 2 217 | if($this->helper->getConfig("brazilcustomerattributes/general/line_neighborhood") 218 | && $numStreetLines >= 3) { 219 | $paymentFormChildren['street']['children'][2]['label'] = __('Neighborhood'); 220 | $paymentFormChildren['street']['children'][2]['validation'] = [ 221 | 'required-entry' => true, 222 | 'min_text_len‌​gth' => 1, 223 | 'max_text_length' => 255 224 | ]; 225 | } 226 | 227 | // Street Line 3 228 | if($this->helper->getConfig("brazilcustomerattributes/general/line_complement") 229 | && $numStreetLines == 4) { 230 | $paymentFormChildren['street']['children'][3]['label'] = __('Complement'); 231 | } 232 | 233 | // Street Prefix 234 | if($this->helper->getConfig("brazilcustomerattributes/general/prefix_enabled")) { 235 | $paymentFormChildren['street_prefix'] = [ 236 | 'component' => 'Magento_Ui/js/form/element/select', 237 | 'config' => [ 238 | 'customScope' => 'billingAddress' . $paymentMethodCode . '.custom_attributes', 239 | 'template' => 'ui/form/field', 240 | 'options' => $this->streetprefixoptions, 241 | 'id' => 'street-prefix' 242 | ], 243 | 'dataScope' => 'billingAddress' . $paymentMethodCode . '.custom_attributes.street_prefix', 244 | 'label' => __('Street Prefix'), 245 | 'provider' => 'checkoutProvider', 246 | 'visible' => true, 247 | 'validation' => [ 248 | 'required-entry' => true, 249 | ], 250 | 'sortOrder' => 65, 251 | 'id' => 'street-prefix' 252 | ]; 253 | } 254 | 255 | // Company 256 | $paymentFormChildren['company']['sortOrder'] = 118; 257 | 258 | // Zipcode 259 | $paymentFormChildren['postcode']['sortOrder'] = 40; 260 | $paymentFormChildren['postcode']['component'] = 261 | 'SystemCode_BrazilCustomerAttributes/js/shipping-address/address-renderer/zip-code'; 262 | $paymentFormChildren['postcode']['config']['elementTmpl'] = 263 | 'SystemCode_BrazilCustomerAttributes/shipping-address/address-renderer/zip-code'; 264 | 265 | // Telephone 266 | $paymentFormChildren['telephone']['component'] = 267 | 'SystemCode_BrazilCustomerAttributes/js/shipping-address/address-renderer/telephone'; 268 | 269 | // Fax 270 | $paymentFormChildren['fax']['component'] = 271 | 'SystemCode_BrazilCustomerAttributes/js/shipping-address/address-renderer/telephone'; 272 | 273 | $jsLayout['components']['checkout']['children']['steps']['children'] 274 | ['billing-step']['children']['payment']['children']['payments-list']['children'] 275 | [$paymentMethodCode . '-form']['children']['form-fields']['children'] = $paymentFormChildren; 276 | } 277 | } 278 | 279 | return $jsLayout; 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /Plugin/Checkout/PaymentInformationManagement.php: -------------------------------------------------------------------------------- 1 | 19 | * @copyright System Code LTDA-ME 20 | * @license http://opensource.org/licenses/osl-3.0.php 21 | */ 22 | 23 | class PaymentInformationManagement { 24 | /** 25 | * @var BillingAddressManagementInterface 26 | * @deprecated 100.2.0 This call was substituted to eliminate extra quote::save call 27 | * 28 | * TODO: Shipping method still use similar method to assign, but on billing address this method is deprecated 29 | */ 30 | protected $billingAddressManagement; 31 | 32 | /** 33 | * @param BillingAddressManagementInterface $billingAddressManagement 34 | * @codeCoverageIgnore 35 | */ 36 | public function __construct( 37 | BillingAddressManagementInterface $billingAddressManagement 38 | ) { 39 | $this->billingAddressManagement = $billingAddressManagement; 40 | } 41 | 42 | /** 43 | * {@inheritDoc} 44 | */ 45 | public function beforeSavePaymentInformationAndPlaceOrder( 46 | CorePaymentInformationManagement $subject, 47 | $cartId, 48 | PaymentInterface $paymentMethod, 49 | AddressInterface $billingAddress = null 50 | ) { 51 | if($billingAddress){ 52 | $this->billingAddressManagement->assign($cartId, $billingAddress); 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /Plugin/Quote/BillingAddressManagement.php: -------------------------------------------------------------------------------- 1 | 16 | * @copyright System Code LTDA-ME 17 | * @license http://opensource.org/licenses/osl-3.0.php 18 | */ 19 | 20 | class BillingAddressManagement 21 | { 22 | 23 | /** 24 | * @var LoggerInterface 25 | */ 26 | protected $logger; 27 | 28 | /** 29 | * Construct 30 | * 31 | * BillingAddressManagement constructor. 32 | * 33 | * @param LoggerInterface $logger 34 | */ 35 | public function __construct( 36 | LoggerInterface $logger 37 | ) { 38 | $this->logger = $logger; 39 | } 40 | 41 | /** 42 | * Before Assign 43 | * 44 | * @param CoreBillingAddressManagement $subject 45 | * @param $cartId 46 | * @param AddressInterface $address 47 | * @param bool $useForShipping 48 | */ 49 | public function beforeAssign( 50 | CoreBillingAddressManagement $subject, 51 | $cartId, 52 | AddressInterface $address, 53 | $useForShipping = false 54 | ) { 55 | $extAttributes = $address->getExtensionAttributes(); 56 | 57 | if (!empty($extAttributes->getStreetPrefix())) { 58 | try { 59 | $address->setStreetPrefix($extAttributes->getStreetPrefix()); 60 | } catch (\Exception $e) { 61 | $this->logger->critical($e->getMessage()); 62 | } 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /Plugin/Quote/ShippingAddressManagement.php: -------------------------------------------------------------------------------- 1 | 15 | * @copyright System Code LTDA-ME 16 | * @license http://opensource.org/licenses/osl-3.0.php 17 | */ 18 | class ShippingAddressManagement 19 | { 20 | 21 | /** 22 | * @var LoggerInterface 23 | */ 24 | protected $logger; 25 | 26 | /** 27 | * Construct 28 | * 29 | * ShippingAddressManagement constructor. 30 | * @param LoggerInterface $logger 31 | */ 32 | public function __construct( 33 | LoggerInterface $logger 34 | ) { 35 | $this->logger = $logger; 36 | } 37 | 38 | /** 39 | * Before Assign 40 | * 41 | * @param CoreShippingAddressManagement $subject 42 | * @param $cartId 43 | * @param AddressInterface $address 44 | */ 45 | public function beforeAssign( 46 | CoreShippingAddressManagement $subject, 47 | $cartId, 48 | AddressInterface $address 49 | ) { 50 | $extAttributes = $address->getExtensionAttributes(); 51 | 52 | if (!empty($extAttributes->getStreetPrefix())) { 53 | try { 54 | $address->setStreetPrefix($extAttributes->getStreetPrefix()); 55 | } catch (\Exception $e) { 56 | $this->logger->critical($e->getMessage()); 57 | } 58 | } 59 | } 60 | } -------------------------------------------------------------------------------- /Setup/InstallData.php: -------------------------------------------------------------------------------- 1 | 21 | * @copyright System Code LTDA-ME 22 | * @license http://opensource.org/licenses/osl-3.0.php 23 | */ 24 | class InstallData implements InstallDataInterface 25 | { 26 | /** 27 | * Customer setup factory 28 | * 29 | * @var CustomerSetupFactory 30 | */ 31 | private $customerSetupFactory; 32 | /** 33 | * @var AttributeSetFactory 34 | */ 35 | private $attributeSetFactory; 36 | /** 37 | * Init 38 | * 39 | * @param CustomerSetupFactory $customerSetupFactory 40 | */ 41 | public function __construct( 42 | CustomerSetupFactory $customerSetupFactory, 43 | AttributeSetFactory $attributeSetFactory 44 | ) { 45 | $this->customerSetupFactory = $customerSetupFactory; 46 | $this->attributeSetFactory = $attributeSetFactory; 47 | } 48 | /** 49 | * {@inheritdoc} 50 | * @SuppressWarnings(PHPMD.ExcessiveMethodLength) 51 | */ 52 | public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) 53 | { 54 | /** @var CustomerSetup $customerSetup */ 55 | $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]); 56 | $setup->startSetup(); 57 | $attributesInfo = [ 58 | 'cpf' => [ 59 | 'label' => 'CPF', 60 | 'type' => 'varchar', 61 | 'input' => 'text', 62 | 'position' => 1000, 63 | 'visible' => true, 64 | 'required' => false, 65 | 'system' => 0, 66 | 'user_defined' => true 67 | ], 68 | 'cnpj' => [ 69 | 'label' => 'CNPJ', 70 | 'type' => 'varchar', 71 | 'input' => 'text', 72 | 'position' => 1000, 73 | 'visible' => true, 74 | 'required' => false, 75 | 'system' => 0, 76 | 'user_defined' => true 77 | ], 78 | 'rg' => [ 79 | 'label' => 'RG', 80 | 'type' => 'varchar', 81 | 'input' => 'text', 82 | 'position' => 1100, 83 | 'visible' => true, 84 | 'required' => false, 85 | 'system' => 0, 86 | 'user_defined' => true 87 | ], 88 | 'socialname' => [ 89 | 'label' => 'Social Name', 90 | 'type' => 'varchar', 91 | 'input' => 'text', 92 | 'position' => 1200, 93 | 'visible' => true, 94 | 'required' => false, 95 | 'system' => 0, 96 | 'user_defined' => true 97 | ], 98 | 'tradename' => [ 99 | 'label' => 'Trade Name', 100 | 'type' => 'varchar', 101 | 'input' => 'text', 102 | 'position' => 1300, 103 | 'visible' => true, 104 | 'required' => false, 105 | 'system' => 0, 106 | 'user_defined' => true 107 | ], 108 | 'ie' => [ 109 | 'label' => 'IE', 110 | 'type' => 'varchar', 111 | 'input' => 'text', 112 | 'position' => 1400, 113 | 'visible' => true, 114 | 'required' => false, 115 | 'system' => 0, 116 | 'user_defined' => true 117 | ] 118 | 119 | ]; 120 | $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer'); 121 | $attributeSetId = $customerEntity->getDefaultAttributeSetId(); 122 | /** @var $attributeSet AttributeSet */ 123 | $attributeSet = $this->attributeSetFactory->create(); 124 | $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId); 125 | foreach ($attributesInfo as $attributeCode => $attributeParams) { 126 | $customerSetup->addAttribute(Customer::ENTITY, $attributeCode, $attributeParams); 127 | } 128 | 129 | 130 | // REGISTER THE FIELD CPF 131 | $customerCpfAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'cpf'); 132 | $customerCpfAttribute->addData([ 133 | 'attribute_set_id' => $attributeSetId, 134 | 'attribute_group_id' => $attributeGroupId, 135 | 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout'], 136 | ]); 137 | $customerCpfAttribute->save(); 138 | 139 | 140 | // REGISTER THE FIELD CNPJ 141 | $customerCnpjAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'cnpj'); 142 | $customerCnpjAttribute->addData([ 143 | 'attribute_set_id' => $attributeSetId, 144 | 'attribute_group_id' => $attributeGroupId, 145 | 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout'], 146 | ]); 147 | $customerCnpjAttribute->save(); 148 | 149 | 150 | // REGISTER THE FIELD RG 151 | $customerRgAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'rg'); 152 | $customerRgAttribute->addData([ 153 | 'attribute_set_id' => $attributeSetId, 154 | 'attribute_group_id' => $attributeGroupId, 155 | 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout'], 156 | ]); 157 | $customerRgAttribute->save(); 158 | 159 | // REGISTER THE FIELD SOCIAL NAME 160 | $customerSocialNameAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'socialname'); 161 | $customerSocialNameAttribute->addData([ 162 | 'attribute_set_id' => $attributeSetId, 163 | 'attribute_group_id' => $attributeGroupId, 164 | 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout'], 165 | ]); 166 | $customerSocialNameAttribute->save(); 167 | 168 | 169 | // REGISTER THE FIELD TRADE NAME 170 | $customerTradeNameAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'tradename'); 171 | $customerTradeNameAttribute->addData([ 172 | 'attribute_set_id' => $attributeSetId, 173 | 'attribute_group_id' => $attributeGroupId, 174 | 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout'], 175 | ]); 176 | $customerTradeNameAttribute->save(); 177 | 178 | 179 | // REGISTER THE FIELD IE 180 | $customerIeAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'ie'); 181 | $customerIeAttribute->addData([ 182 | 'attribute_set_id' => $attributeSetId, 183 | 'attribute_group_id' => $attributeGroupId, 184 | 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout'], 185 | ]); 186 | $customerIeAttribute->save(); 187 | $setup->endSetup(); 188 | } 189 | } -------------------------------------------------------------------------------- /Setup/UpgradeData.php: -------------------------------------------------------------------------------- 1 | 21 | * @copyright System Code LTDA-ME 22 | * @license http://opensource.org/licenses/osl-3.0.php 23 | */ 24 | class UpgradeData implements UpgradeDataInterface { 25 | 26 | /** 27 | * @var CustomerSetupFactory 28 | */ 29 | private $customerSetupFactory; 30 | 31 | /** 32 | * @var AttributeRepositoryInterface 33 | */ 34 | private $attributeRepository; 35 | 36 | /** 37 | * Constructor 38 | * 39 | * @param CustomerSetupFactory $customerSetupFactory 40 | * @param AttributeRepositoryInterface $attributeRepository 41 | */ 42 | public function __construct( 43 | CustomerSetupFactory $customerSetupFactory, 44 | AttributeRepositoryInterface $attributeRepository 45 | ) 46 | { 47 | $this->customerSetupFactory = $customerSetupFactory; 48 | $this->attributeRepository = $attributeRepository; 49 | } 50 | 51 | /** 52 | * @inheritdoc 53 | */ 54 | public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) 55 | { 56 | $setup->startSetup(); 57 | 58 | if (version_compare($context->getVersion(), '1.0.1') < 0) { 59 | $this->addStreetPrefix($setup); 60 | } 61 | 62 | $setup->endSetup(); 63 | } 64 | 65 | private function addStreetPrefix($setup) 66 | { 67 | $eavSetup = $this->customerSetupFactory->create(['setup' => $setup]); 68 | $eavSetup->addAttribute('customer_address', 'street_prefix', array( 69 | 'type' => 'varchar', 70 | 'input' => 'select', 71 | 'label' => 'Street Prefix', 72 | 'source' => 'SystemCode\BrazilCustomerAttributes\Model\Config\Source\Streetprefix', 73 | 'global' => 1, 74 | 'visible' => 1, 75 | 'required' => false, 76 | 'user_defined' => 1, 77 | 'system' => 0, 78 | 'visible_on_front' => 1, 79 | 'group'=>'General', 80 | 'position' => 65 81 | )); 82 | 83 | $eavSetup->getEavConfig()->getAttribute('customer_address','street_prefix') 84 | ->setUsedInForms(array('adminhtml_customer_address','customer_address_edit','customer_register_address')) 85 | ->save(); 86 | } 87 | } -------------------------------------------------------------------------------- /Setup/UpgradeSchema.php: -------------------------------------------------------------------------------- 1 | startSetup(); 23 | $connection = $installer->getConnection(); 24 | 25 | if (version_compare($context->getVersion(), "1.0.1", "<")) { 26 | $this->addStreetPrefix($connection, $setup); 27 | } 28 | 29 | $installer->endSetup(); 30 | } 31 | 32 | /** 33 | * @param $connection 34 | * @param $setup 35 | */ 36 | private function addStreetPrefix($connection, $setup) 37 | { 38 | if ($connection->tableColumnExists($setup->getTable('sales_order_address'), 'street_prefix') === false) { 39 | $connection->addColumn( 40 | $setup->getTable('sales_order_address'), 41 | 'street_prefix', 42 | [ 43 | 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 44 | 'length' => 20, 45 | 'nullable' => true, 46 | 'after' => 'lastname', 47 | 'comment' => 'Street Prefix' 48 | ] 49 | ); 50 | } 51 | 52 | if ($connection->tableColumnExists($setup->getTable('quote_address'), 'street_prefix') === false) { 53 | $connection->addColumn( 54 | $setup->getTable('quote_address'), 55 | 'street_prefix', 56 | [ 57 | 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 58 | 'length' => 20, 59 | 'nullable' => true, 60 | 'after' => 'company', 61 | 'comment' => 'Street Prefix' 62 | ] 63 | ); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "systemcode/brazilcustomerattributes", 3 | "description":"Magento 2 module to adapt customer and address fields to brazil.", 4 | "keywords": [ 5 | "magento 2", 6 | "brazil fields", 7 | "campos brasil", 8 | "magento2 campos", 9 | "magento2 endereço", 10 | "magento2 address brazil", 11 | "magento2 person type", 12 | "magento2 pessoa física", 13 | "magento2 pessoa jurídica", 14 | "magento2 tipo pessoa" 15 | ], 16 | "require": { 17 | "systemcode/base": "*", 18 | "magedev/brazilzipcode": "*" 19 | }, 20 | "type": "magento2-module", 21 | "version": "1.1.2", 22 | "license": [ 23 | "proprietary" 24 | ], 25 | "homepage": "https://www.systemcode.com.br/", 26 | "support": { 27 | "email": "contato@systemcode.com.br", 28 | "issues": "https://github.com/eduardoddias/Magento-SystemCode_BrazilCustomerAttributes/issues/" 29 | }, 30 | "authors": [ 31 | { 32 | "name": "Eduardo Diogo Dias", 33 | "email": "contato@systemcode.com.br", 34 | "homepage": "https://www.systemcode.com.br/", 35 | "role": "CTO" 36 | } 37 | ], 38 | "autoload": { 39 | "files": [ 40 | "registration.php" 41 | ], 42 | "psr-4": { 43 | "SystemCode\\BrazilCustomerAttributes\\": "" 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /etc/acl.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /etc/adminhtml/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 0 7 | yes 8 | 1 9 | 1 10 | 3 11 | false 12 | 13 | 1 14 | 1 15 | 1 16 | 17 | 18 | requni 19 | req 20 | 21 | 22 | 1 23 | 1 24 | requni 25 | opt 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /etc/adminhtml/menu.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /etc/adminhtml/routes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /etc/adminhtml/system.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | systemcode 10 | Magento_Config::config_general 11 | 12 | 13 | 14 | 15 | Magento\Config\Model\Config\Source\Yesno 16 | 17 | 18 | 19 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Customeredit 20 | Choose witch fields can customer edit after account created. 21 | 22 | 23 | 24 | Magento\Config\Model\Config\Source\Yesno 25 | 26 | 27 | 28 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Customergroup 29 | Assign individual person to a group. 30 | 31 | 32 | 33 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Customergroup 34 | Assign corporation person to a group. 35 | 36 | 37 | 38 | Magento\Config\Model\Config\Source\Yesno 39 | 40 | 41 | 42 | SystemCode\BrazilCustomerAttributes\Block\Adminhtml\Form\Field\Prefixoptions 43 | SystemCode\BrazilCustomerAttributes\Config\Backend\Prefixoptions 44 | One option per line. Like Street, Avenue, Street Cross, etc... 45 | 46 | 47 | 48 | Magento\Config\Model\Config\Source\Yesno 49 | Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '2'. 50 | 51 | 52 | 53 | Magento\Config\Model\Config\Source\Yesno 54 | Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '3'. 55 | 56 | 57 | 58 | Magento\Config\Model\Config\Source\Yesno 59 | Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '4'. 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Nooptrequn 68 | SystemCode\BrazilCustomerAttributes\Model\Config\Backend\Show\Customer 69 | 70 | 71 | 72 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Nooptrequn 73 | SystemCode\BrazilCustomerAttributes\Model\Config\Backend\Show\Customer 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | Magento\Config\Model\Config\Source\Yesno 82 | It will turn 'Social Name' a required field. Set 'Show Social Name' to 'No'. 83 | 84 | 85 | 86 | Magento\Config\Model\Config\Source\Yesno 87 | It will turn 'Last Name' a required field. Set 'Show Trade Name' to 'No'. 88 | 89 | 90 | 91 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Nooptrequn 92 | SystemCode\BrazilCustomerAttributes\Model\Config\Backend\Show\Customer 93 | 94 | 95 | 96 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Nooptrequn 97 | SystemCode\BrazilCustomerAttributes\Model\Config\Backend\Show\Customer 98 | 99 | 100 | 101 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Nooptrequn 102 | SystemCode\BrazilCustomerAttributes\Model\Config\Backend\Show\Customer 103 | 104 | 105 | 106 | SystemCode\BrazilCustomerAttributes\Model\Config\Source\Nooptrequn 107 | SystemCode\BrazilCustomerAttributes\Model\Config\Backend\Show\Customer 108 | 109 | 110 |
111 |
112 |
-------------------------------------------------------------------------------- /etc/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 1 8 | 0 9 | 1 10 | 1 11 | 12 | 13 | 1 14 | 1 15 | 0 16 | 1 17 | 0 18 | 19 | 20 | 1 21 | 1 22 | 1 23 | 0 24 | 1 25 | 0 26 | 1 27 | 0 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /etc/di.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /etc/events.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /etc/extension_attributes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /etc/frontend/routes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /etc/module.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /i18n/en_US.csv: -------------------------------------------------------------------------------- 1 | No,No 2 | "Yes, except change person type","Yes, except change person type" 3 | "Yes, and allow change person type","Yes, and allow change person type" 4 | Optional,Optional 5 | Required,Required 6 | "Optional and Unique","Optional and Unique" 7 | "Required and Unique","Required and Unique" 8 | "%fieldName is a required field.","%fieldName is a required field." 9 | "%1 is invalid.","%1 is invalid." 10 | "%1 already in use.","%1 already in use." 11 | "* Required Fields","* Required Fields" 12 | "Contact Information","Contact Information" 13 | Company,Company 14 | "Phone Number","Phone Number" 15 | Fax,Fax 16 | Address,Address 17 | "VAT Number","VAT Number" 18 | City,City 19 | State/Province,State/Province 20 | "Please select a region, state or province.","Please select a region, state or province." 21 | "Zip/Postal Code","Zip/Postal Code" 22 | Country,Country 23 | "It's a default billing address.","It's a default billing address." 24 | "Use as my default billing address","Use as my default billing address" 25 | "It's a default shipping address.","It's a default shipping address." 26 | "Use as my default shipping address","Use as my default shipping address" 27 | "Save Address","Save Address" 28 | "Go back","Go back" 29 | "Account Information","Account Information" 30 | "Change Email","Change Email" 31 | "Change Password","Change Password" 32 | "Change Email and Password","Change Email and Password" 33 | Email,Email 34 | "Current Password","Current Password" 35 | "New Password","New Password" 36 | "Password Strength","Password Strength" 37 | "No Password","No Password" 38 | "Confirm New Password","Confirm New Password" 39 | Save,Save 40 | "Personal Information","Personal Information" 41 | "Sign Up for Newsletter","Sign Up for Newsletter" 42 | "Address Information","Address Information" 43 | "Sign-in Information","Sign-in Information" 44 | Password,Password 45 | "Confirm Password","Confirm Password" 46 | "Create an Account","Create an Account" 47 | Back,Back 48 | "Individual Person","Individual Person" 49 | Corporation,Corporation 50 | CPF,CPF 51 | RG,RG 52 | CNPJ,CNPJ 53 | "Social Name","Social Name" 54 | "Trade Name","Trade Name" 55 | IE,IE 56 | "Street Address","Street Address" 57 | Number,Number 58 | Neighborhood,Neighborhood 59 | Complement,Complement 60 | "Not a valid Membership ID","Not a valid Membership ID" 61 | "Brazil Customer Attributes","Brazil Customer Attributes" 62 | Configuration,Configuration 63 | Enabled,Enabled 64 | "Customer Can Edit","Customer Can Edit" 65 | "Copy CPF/CNPJ to Tax/VAT Number","Copy CPF/CNPJ to Tax/VAT Number" 66 | "Customer Group Individual Person","Customer Group CPF" 67 | "Customer Group Corporation","Customer Group CNPJ" 68 | "Second Line of Street as Number","Second Line of Street as Number" 69 | "Third Line of Street as Neighborhood","Third Line of Street as Neighborhood" 70 | "Fourth Line of Street as Complement","Fourth Line of Street as Complement" 71 | "Show CPF","Show CPF" 72 | "Show RG","Show RG" 73 | "Use Firstname as Social Name","Use Firstname as Social Name" 74 | "Use Lastname as Trade Name ","Use Lastname as Trade Name" 75 | "Show CNPJ","Show CNPJ" 76 | "Show IE","Show IE" 77 | "Show Social Name","Show Social Name" 78 | "Show Trade Name","Show Trade Name" 79 | Loading,Loading 80 | "Choose witch fields can customer edit after account created.","Choose witch fields can customer edit after account created." 81 | "Assign individual person to a group.","Assign individual person to a group." 82 | "Assign corporation person to a group.","Assign corporation person to a group." 83 | "Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '2'.","Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '2'." 84 | "Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '3'.","Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '3'." 85 | "Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '4'.","Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '4'." 86 | "It will turn 'Social Name' a required field. Set 'Show Social Name' to 'No'.","It will turn 'Social Name' a required field. Set 'Show Social Name' to 'No'." 87 | "It will turn 'Last Name' a required field. Set 'Show Trade Name' to 'No'.","It will turn 'Last Name' a required field. Set 'Show Trade Name' to 'No'." 88 | "Enable Prefix Address","Enable Prefix Address" 89 | "Prefix Address Options","Prefix Address Options" 90 | "Examples: Street, Avenue, Street Cross, etc...","Exemplos: Rua, Avenida, Travessa, etc..." 91 | "Prefix Address Options","Prefix Address Options" 92 | Options,Options 93 | "Add Option","Add Option" 94 | "Street Prefix","Street Prefix" 95 | "Please select a street prefix.","Please select a street prefix." -------------------------------------------------------------------------------- /i18n/pt_BR.csv: -------------------------------------------------------------------------------- 1 | No,Não 2 | "Yes, except change person type","Sim, exceto mudar o tipo de pessoa" 3 | "Yes, and allow change person type","Sim, e permitir mudar o tipo de pessoa" 4 | Optional,Opcional 5 | Required,Obrigatório 6 | "Optional and Unique","Opcional e Único" 7 | "Required and Unique","Obrigatório e Único" 8 | "%fieldName is a required field.","%fieldName é um campo obrigatório." 9 | "%1 is invalid.","%1 é inválido." 10 | "%1 already in use.","%1 já está em uso." 11 | "* Required Fields","* Campos obrigatórios" 12 | "Contact Information","Informações de Contato" 13 | Company,Empresa 14 | "Phone Number","Número de Telefone" 15 | Fax,Fax 16 | Address,Endereço 17 | "VAT Number","Número VAT" 18 | City,Cidade 19 | State/Province,Estado 20 | "Please select a region, state or province.","Selecione uma região, estado ou província" 21 | "Zip/Postal Code","Código Postal" 22 | Country,País 23 | "It's a default billing address.","É um endereço de cobrança padrão." 24 | "Use as my default billing address","Usar como meu endereço de cobrança padrão" 25 | "It's a default shipping address.","É um endereço de envio padrão." 26 | "Use as my default shipping address","Usar como meu endereço de envio padrão" 27 | "Save Address","Salvar Endereço" 28 | "Go back","Voltar" 29 | "Account Information","Informações da Conta" 30 | "Change Email","Alterar E-mail" 31 | "Change Password","Alterar Senha" 32 | "Change Email and Password","Alterar E-mail e Senha" 33 | Email,E-mail 34 | "Current Password","Senha Atual" 35 | "New Password","Nova Senha" 36 | "Password Strength","Força da Senha" 37 | "No Password","Sem Senha" 38 | "Confirm New Password","Confirmar Nova Senha" 39 | Save,Salvar 40 | "Personal Information","Informações Pessoais" 41 | "Sign Up for Newsletter","Inscreva-se para Boletim Informativo" 42 | "Address Information","Informações do Endereço" 43 | "Sign-in Information","Informações da sessão" 44 | Password,Senha 45 | "Confirm Password","Confirmar Senha" 46 | "Create an Account","Criar uma Conta" 47 | Back,Voltar 48 | "Individual Person","Pessoa Física" 49 | Corporation,Pessoa Jurídica 50 | CPF,CPF 51 | RG,RG 52 | CNPJ,CNPJ 53 | "Social Name","Razão Social" 54 | "Trade Name","Nome Fantasia" 55 | IE,IE 56 | "Street Address","Endereço" 57 | Number,Número 58 | Neighborhood,Bairro 59 | Complement,Complemento 60 | "Not a valid Membership ID","ID de membro inválida" 61 | "Brazil Customer Attributes","Atributos de Cliente do Brasil" 62 | Configuration,Configuração 63 | Enabled,Ativado 64 | "Customer Can Edit","Cliente Pode Editar" 65 | "Copy CPF/CNPJ to Tax/VAT Number","Copiar CPF/CNPJ para o Número de Tax/VAT" 66 | "Customer Group Individual Person","Grupo de Clientes do CPF" 67 | "Customer Group Corporation","Grupo de Clientes do CNPJ" 68 | "Second Line of Street as Number","Segunda Linha de Rua como Número" 69 | "Third Line of Street as Neighborhood","Terceira Linha de Rua como Bairro" 70 | "Fourth Line of Street as Complement","Quarta Linha de Rua como Complemento" 71 | "Show CPF","Exibir CPF" 72 | "Show RG","Exibir RG" 73 | "Use Firstname as Social Name","Usar Primeiro Nome como Razão Social" 74 | "Use Lastname as Trade Name ","Usar Último Nome como Nome Fantasia" 75 | "Show CNPJ","Exibir CNPJ" 76 | "Show Social Name","Exibir Razão Social" 77 | "Show Trade Name","Exibir Nome Fantasia" 78 | "Show IE","Exibir IE" 79 | Loading,Carregando 80 | "Choose witch fields can customer edit after account created.","Escolha quais campos o cliente pode editar ápos criado a conta." 81 | "Assign individual person to a group.","Atribuir pessoa física a um grupo." 82 | "Assign corporation person to a group.","Atribuir pessoa jurídica a um grupo." 83 | "Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '2'.","Acesse 'Lojas > Configurações > Clientes > Configurações de cliente > Opções de Nome e Endereço' e em 'Número de Linhas em Endereço' coloque '2'." 84 | "Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '3'.","Acesse 'Lojas > Configurações > Clientes > Configurações de cliente > Opções de Nome e Endereço' e em 'Número de Linhas em Endereço' coloque '3'." 85 | "Go to 'Stores > Configuration > Customers > Customer Configuration > Name and Address Options' and set 'Number of Lines in a Street Address' to '4'.","Acesse 'Lojas > Configurações > Clientes > Configurações de cliente > Opções de Nome e Endereço' e em 'Número de Linhas em Endereço' coloque '4'." 86 | "It will turn 'Social Name' a required field. Set 'Show Social Name' to 'No'.","Isso tornará a 'Razão Social' obrigatório. Altere 'Exibir Razão Social' para 'Não'." 87 | "It will turn 'Last Name' a required field. Set 'Show Trade Name' to 'No'.","Isso tornará o 'Nome Fantasia' um campo obrigatório. Altere 'Show Trade Name' para 'Não'." 88 | "Examples: Street, Avenue, Street Cross, etc...","Explos: Street, Avenue, Street Cross, etc..." 89 | "Prefix Address Options","Opção de Logradouro" 90 | Options,Opções 91 | "Add Option","Adicionar Opção" 92 | "Street Prefix",Logradouro 93 | "Please select a street prefix.","Por favor selecione o logradouro." -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Brazil Customer Attributes 2 | 3 | ![](https://imgur.com/pqTS38g.png) 4 | 5 | ![](https://imgur.com/vSACNr5) 6 | 7 | ![](https://imgur.com/CpuyDjM.png) 8 | 9 | ![](https://imgur.com/igfXu19.png) 10 | 11 | ![](https://i.imgur.com/vKqlkbD.png) 12 | 13 | ## About Module 14 | 15 | Magento 2 module to adapt customer and address fields to brazil. 16 | 17 | PS: This module doesn't work with checkout as guest. 18 | 19 | ### How to install 20 | 21 | #### ✓ Install by Composer (recommended) 22 | ``` 23 | composer require systemcode/brazilcustomerattributes 24 | php bin/magento module:enable SystemCode_BrazilCustomerAttributes SystemCode_Base 25 | php bin/magento setup:upgrade 26 | ``` 27 | 28 | #### ✓ Install Manually 29 | - Install [System Code Base](https://github.com/eduardoddias/Magento-SystemCode_Base) first 30 | - After copy module to folder app/code/SystemCode/BrazilCustomerAttributes and run commands: 31 | ``` 32 | php bin/magento setup:di:compile 33 | php bin/magento setup:upgrade 34 | ``` 35 | 36 | ### Configuration 37 | 38 | Configure module on SystemCode > Brazil Customer Attributes > Configuration 39 | 40 | ### TODO 41 | * Refactor 42 | * Unity tests 43 | * Login by attributes CPF/CNPJ 44 | * Add mask for fields on admin 45 | * One Step Checkout (future module) 46 | * Add other zipcode consult methods 47 | 48 | ### Contribute 49 | To contribute make project fork and an pull request or edit on Github. 50 | 51 | ### License 52 | OSL-3.0 53 | 54 | ### Donators 55 | * [Ricardo Martins](https://www.magenteiro.com/) 56 | 57 | ### Contributors 58 | * [Max Souza](https://github.com/MaxSouza) 59 | 60 | ### Authors 61 | * [Eduardo Diogo Dias](https://github.com/eduardoddias) 62 | 63 | 64 | --- 65 | 66 | 67 | ## Sobre o Módulo 68 | 69 | Módulo em Magento 2 para adaptar os campos de usuário e endereço para o padrão brasileiro. 70 | 71 | OBS: O módulo não funciona com checkout como visitante. 72 | 73 | ### Como Instalar 74 | 75 | #### ✓ Instalação via Composer (recomendado) 76 | ``` 77 | composer require systemcode/brazilcustomerattributes 78 | php bin/magento module:enable SystemCode_BrazilCustomerAttributes SystemCode_Base 79 | php bin/magento setup:upgrade 80 | ``` 81 | 82 | #### ✓ Instalação Manual 83 | - Install [System Code Base](https://github.com/eduardoddias/Magento-SystemCode_Base) first 84 | - After copy module to folder app/code/SystemCode/BrazilCustomerAttributes and run commands: 85 | ``` 86 | php bin/magento setup:di:compile 87 | php bin/magento setup:upgrade 88 | ``` 89 | 90 | ### Configuração 91 | Configure o módulo em Lojas > Opções > Configurações > System Code > Atributos do Cliente do Brasil 92 | 93 | ### TODO 94 | * Refatorar 95 | * Testes unitários 96 | * Login via CPF/CNPJ 97 | * Adicionar máscaras no admin 98 | * One Step Checkout (módulo futuro) 99 | * Adicionar outros métodos de consulta de CEP 100 | 101 | ### Contribuir 102 | Para contribuir faça um fork do projeto e depois um pull request ou edite através do Github. 103 | 104 | ### Licença 105 | OSL-3.0 106 | 107 | ### Doadores 108 | * [Ricardo Martins](https://www.magenteiro.com/) 109 | 110 | ### Contribuidores 111 | * [Max Souza](https://github.com/MaxSouza) 112 | 113 | ### Autores 114 | * [Eduardo Diogo Dias](https://github.com/eduardoddias) 115 | -------------------------------------------------------------------------------- /registration.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | SystemCode_BrazilCustomerAttributes::form/register.phtml 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /view/frontend/layout/customer_account_edit.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | SystemCode_BrazilCustomerAttributes::form/edit.phtml 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /view/frontend/layout/customer_address_form.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | SystemCode_BrazilCustomerAttributes::address/edit.phtml 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /view/frontend/requirejs-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright © 2013-2017 Magento, Inc. All rights reserved. 3 | * See COPYING.txt for license details. 4 | */ 5 | 6 | var config = { 7 | map: { 8 | '*': { 9 | changePersonType: 'SystemCode_BrazilCustomerAttributes/change-person-type', 10 | inputMask: 'SystemCode_BrazilCustomerAttributes/jquery.mask' 11 | }, 12 | }, 13 | config: { 14 | mixins: { 15 | 'Magento_Checkout/js/action/set-shipping-information': { 16 | 'SystemCode_BrazilCustomerAttributes/js/action/set-shipping-information-mixin': true 17 | }, 18 | 'Magento_Checkout/js/action/create-shipping-address': { 19 | 'SystemCode_BrazilCustomerAttributes/js/action/create-shipping-address-mixin': true 20 | }, 21 | 'Magento_Checkout/js/action/create-billing-address': { 22 | 'SystemCode_BrazilCustomerAttributes/js/action/create-billing-address-mixin': true 23 | }, 24 | 'Magento_Checkout/js/action/place-order': { 25 | 'SystemCode_BrazilCustomerAttributes/js/action/place-order-mixin': true 26 | } 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /view/frontend/templates/address/edit.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | 21 |
22 |
23 |
24 | getBlockHtml('formkey')?> 25 | 26 | 27 | getNameBlockHtml() ?> 28 |
29 | 30 |
31 | 32 |
33 |
34 |
35 | 36 |
37 | 38 |
39 |
40 |
41 | 42 |
43 | 44 |
45 |
46 |
47 |
48 |
49 | 50 |
51 | 52 |
53 | 54 |
55 |
56 | 57 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\StreetprefixEdit')->toHtml() ?> 58 | 59 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\Streetedit')->toHtml() ?> 60 | 61 | helper('Magento\Customer\Helper\Address')->isVatAttributeVisible()) : ?> 62 |
63 | 64 |
65 | 66 |
67 |
68 | 69 |
70 | 71 |
72 | 73 |
74 |
75 |
76 | 77 |
78 | 81 | getConfig('general/region/display_all')) ? ' disabled="disabled"' : '';?>/> 82 |
83 |
84 |
85 | 86 |
87 | getCountryHtmlSelect() ?> 88 |
89 |
90 | 91 | isDefaultBilling()): ?> 92 |
93 | canSetAsDefaultBilling()): ?> 94 |
95 | 96 | 97 |
98 | 99 | 100 | 101 | 102 | isDefaultShipping()): ?> 103 |
104 | canSetAsDefaultShipping()): ?> 105 |
106 | 107 | 108 |
109 | 110 | 111 | 112 |
113 |
114 |
115 | 118 |
119 |
120 | 121 |
122 |
123 |
124 | -------------------------------------------------------------------------------- /view/frontend/templates/form/edit.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | 19 |
20 |
21 | getBlockHtml('formkey')?> 22 |
23 | 24 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\Persontype')->setTemplate('SystemCode_BrazilCustomerAttributes::widget/persontypetoggle.phtml') ?> 25 | getConfigAdmin ("general", "enabled") && 26 | $_persontype->getConfigAdmin("general", "customer_edit")!=""): ?> 27 | setCustomerId($block->getCustomer()->getId())->toHtml() ?> 28 | 29 | 30 | getLayout()->createBlock('Magento\Customer\Block\Widget\Name')->setObject($block->getCustomer())->toHtml() ?> 31 | 32 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\Persontype')->setTemplate('SystemCode_BrazilCustomerAttributes::widget/persontypefields.phtml') ?> 33 | getConfigAdmin ("general", "enabled") && 34 | $_persontype->getConfigAdmin("general", "customer_edit")!=""): ?> 35 | setCustomerId($block->getCustomer()->getId())->toHtml() ?> 36 | 37 | 38 | 39 | getLayout()->createBlock('Magento\Customer\Block\Widget\Dob') ?> 40 | getLayout()->createBlock('Magento\Customer\Block\Widget\Taxvat') ?> 41 | getLayout()->createBlock('Magento\Customer\Block\Widget\Gender') ?> 42 | isEnabled()): ?> 43 | setDate($block->getCustomer()->getDob())->toHtml() ?> 44 | 45 | isEnabled()): ?> 46 | setTaxvat($block->getCustomer()->getTaxvat())->toHtml() ?> 47 | 48 | isEnabled()): ?> 49 | setGender($block->getCustomer()->getGender())->toHtml() ?> 50 | 51 |
52 | 53 | 54 |
55 |
56 | getChangePassword()): ?> checked="checked" class="checkbox" /> 57 | 58 |
59 |
60 | 61 |
62 |
63 | 69 |
70 | 71 |
72 | 73 |
74 |
75 |
76 | 77 |
78 | 84 |
85 |
86 | : 87 | 88 | 89 | 90 |
91 |
92 |
93 |
94 |
95 | 96 |
97 | 100 |
101 |
102 | getChildHtml('form_additional_info'); ?> 103 |
104 |
105 |
106 | 107 |
108 |
109 | 110 |
111 |
112 |
113 | 143 | 154 | -------------------------------------------------------------------------------- /view/frontend/templates/form/register.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | 19 | 26 | getChildHtml('form_fields_before')?> 27 | 28 | getChildHtml('customer.form.register.extra')?> 29 |
30 | getBlockHtml('formkey'); ?> 31 |
32 |
33 | 34 | 35 | 36 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\Persontype')->setTemplate('SystemCode_BrazilCustomerAttributes::widget/persontypetoggle.phtml') ?> 37 | getConfigAdmin ("general", "enabled")): ?> 38 | toHtml() ?> 39 | 40 | 41 | getLayout()->createBlock('Magento\Customer\Block\Widget\Name')->setObject($block->getFormData())->setForceUseCustomerAttributes(true)->toHtml() ?> 42 | 43 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\Persontype')->setTemplate('SystemCode_BrazilCustomerAttributes::widget/persontypefields.phtml') ?> 44 | getConfigAdmin ("general", "enabled")): ?> 45 | toHtml() ?> 46 | 47 | 48 | 49 | isNewsletterEnabled()): ?> 50 | 54 | 55 | getChildHtml('customer.form.register.newsletter')?> 56 | 57 | 58 | getLayout()->createBlock('Magento\Customer\Block\Widget\Dob') ?> 59 | isEnabled()): ?> 60 | setDate($block->getFormData()->getDob())->toHtml() ?> 61 | 62 | 63 | getLayout()->createBlock('Magento\Customer\Block\Widget\Taxvat') ?> 64 | isEnabled()): ?> 65 | setTaxvat($block->getFormData()->getTaxvat())->toHtml() ?> 66 | 67 | 68 | getLayout()->createBlock('Magento\Customer\Block\Widget\Gender') ?> 69 | isEnabled()): ?> 70 | setGender($block->getFormData()->getGender())->toHtml() ?> 71 | 72 |
73 | getShowAddressFields()): ?> 74 |
75 |
76 | 77 | 78 |
79 | 80 |
81 | 82 |
83 |
84 | 85 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\StreetprefixRegister')->toHtml() ?> 86 | getLayout()->createBlock('SystemCode\BrazilCustomerAttributes\Block\Magento\Customer\Widget\Street')->toHtml() ?> 87 | 88 |
89 | 90 |
91 | 92 |
93 |
94 | 95 |
96 | 97 |
98 | 101 | 102 |
103 |
104 | 105 |
106 | 107 |
108 | getCountryHtmlSelect() ?> 109 |
110 |
111 | getChildBlock('customer_form_address_user_attributes');?> 112 | 113 | setEntityType('customer_address'); ?> 114 | setFieldIdFormat('address:%1$s')->setFieldNameFormat('address[%1$s]');?> 115 | restoreSessionData($addressAttributes->getMetadataForm(), 'address');?> 116 | setShowContainer(false)->toHtml()?> 117 | 118 | 119 |
120 | 121 |
122 | 123 |
124 |
125 |
126 | 127 |
128 | 129 |
130 |
131 | 132 | 133 | 134 |
135 | 136 | 137 |
138 |
139 |
140 | 141 |
142 | 143 |
144 |
145 |
146 | 147 |
148 | 155 |
156 |
157 | : 158 | 159 | 160 | 161 |
162 |
163 |
164 | 165 |
166 |
167 | 168 |
169 | 170 |
171 |
172 | getChildHtml('form_additional_info'); ?> 173 |
174 |
175 |
176 | 177 |
178 |
179 | 180 |
181 |
182 |
183 | 213 | getShowAddressFields()): ?> 214 | 230 | 231 | -------------------------------------------------------------------------------- /view/frontend/templates/widget/persontypefields.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | showCpf): ?> 17 |
18 | getStatus("show", "cpf", "cpf")): ?> 19 |
"> 20 | 21 |
22 | " 26 | title="" 27 | class="input-text" 28 | data-validate="{required:getStatus("required", "cpf", "cpf"), true) ?>, 'validate-cpf':true}"> 29 |
30 |
31 | 32 | 33 | getStatus("show", "cpf", "rg")): ?> 34 |
"> 35 | 36 |
37 | " 41 | title="" 42 | class="input-text" 43 | data-validate="{required:getStatus("required", "cpf", "rg"), true) ?>}" > 44 |
45 |
46 | 47 | 48 |
49 | 50 | 51 | showCnpj): ?> 52 |
53 | 54 | getStatus("show", "cnpj", "socialname")): ?> 55 |
"> 56 | 57 |
58 | " 62 | title="" 63 | class="input-text" 64 | data-validate="{required:getStatus("required", "cnpj", "socialname"), true) ?>, 'validate-cpf':true}" > 65 |
66 |
67 | 68 | 69 | getStatus("show", "cnpj", "tradename")): ?> 70 |
"> 71 | 72 |
73 | " 77 | title="" 78 | class="input-text" 79 | data-validate="{required:getStatus("required", "cnpj", "tradename"), true) ?>}" > 80 |
81 |
82 | 83 | 84 | getStatus("show", "cnpj", "cnpj")): ?> 85 |
"> 86 | 87 |
88 | " 92 | title="" 93 | class="input-text" 94 | data-validate="{required:getStatus("required", "cnpj", "cnpj"), true) ?>}" > 95 |
96 |
97 | 98 | 99 | getStatus("show", "cnpj", "ie")): ?> 100 |
"> 101 | 102 |
103 | " 106 | title="" 107 | class="input-text" 108 | id="ie" 109 | data-validate="{required:getStatus("required", "cnpj", "ie"), true) ?>}" > 110 |
111 |
112 | 113 | 114 |
115 | 116 | 117 | 127 | 128 | -------------------------------------------------------------------------------- /view/frontend/templates/widget/persontypetoggle.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | showCpf && $block->showCnpj): ?> 17 | showCpf): ?> 18 |
19 | getPersonType() == 'cpf' || $block->getPersonType() == false?'checked':'') ?> title="" class="radio person_type" /> 20 | 21 |
22 | 23 | 24 | showCnpj): ?> 25 |
26 | getPersonType() == 'cnpj'?'checked':'') ?> title="" class="radio person_type" /> 27 | 28 |
29 | 30 | -------------------------------------------------------------------------------- /view/frontend/templates/widget/street.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | helper('Magento\Customer\Helper\Address')->getAttributeValidationClass('street'); ?> 17 | helper('Magento\Customer\Helper\Address')->getStreetLines() ?> 18 |
19 | 20 |
21 | 22 |
23 | 24 | =2): ?> 25 |
26 | getSecondLineNumber()): ?> 27 | 28 | 29 |
30 | 31 |
32 | 33 | 34 | =3): ?> 35 |
36 | getThirdLineNeighborhood()): ?> 37 | 38 | 39 |
40 | 41 |
42 | 43 |
44 |
45 | 46 |
47 | getFourthLineComplement()): ?> 48 | 49 | 50 |
51 | 52 |
53 | 54 |
-------------------------------------------------------------------------------- /view/frontend/templates/widget/streetprefix.phtml: -------------------------------------------------------------------------------- 1 | 12 | * @copyright System Code LTDA-ME 13 | * @license http://opensource.org/licenses/osl-3.0.php 14 | */ 15 | ?> 16 | getIsEnabled()):?> 17 |
18 | 19 |
20 | 25 |
26 |
27 | -------------------------------------------------------------------------------- /view/frontend/web/change-person-type.js: -------------------------------------------------------------------------------- 1 | /*jshint browser:true jquery:true expr:true*/ 2 | define([ 3 | 'jquery', 4 | 'jquery/ui', 5 | 'mage/translate' 6 | ], function ($) { 7 | 'use strict'; 8 | 9 | $.widget('mage.changePersonType', { 10 | options: { 11 | individualSelector: '[data-role=type-individual]', 12 | corporateSelector: '[data-role=type-corporation]', 13 | individualContainer: '[data-container=type-individual]', 14 | corporateContainer: '[data-container=type-corporation]', 15 | changeFirstnameLabel: false, 16 | changeLastnameLabel: false 17 | }, 18 | 19 | /** 20 | * Create widget 21 | * @private 22 | */ 23 | _create: function () { 24 | this.element.on('change', $.proxy(function () { 25 | this._checkChoice(); 26 | }, this)); 27 | 28 | this._checkChoice(); 29 | }, 30 | 31 | /** 32 | * Check choice 33 | * @private 34 | */ 35 | _checkChoice: function () { 36 | if ($(this.options.corporateSelector).is(':checked')) { 37 | this._showCorporate(); 38 | } else { 39 | this._showIndividual(); 40 | } 41 | }, 42 | 43 | /** 44 | * Show individual input fields 45 | * @private 46 | */ 47 | _showIndividual: function () { 48 | $(this.options.individualContainer).show(); 49 | $(this.options.corporateContainer).hide(); 50 | 51 | if(this.options.changeFirstnameLabel){ 52 | $(".field-name-firstname label span").text($.mage.__('First Name')); 53 | } 54 | 55 | if(this.options.changeLastnameLabel){ 56 | $(".field-name-lastname label span").text($.mage.__('Last Name')); 57 | } 58 | }, 59 | 60 | /** 61 | * Show corporate input fields 62 | * @private 63 | */ 64 | _showCorporate: function () { 65 | $(this.options.corporateContainer).show(); 66 | $(this.options.individualContainer).hide(); 67 | 68 | if(this.options.changeFirstnameLabel){ 69 | $(".field-name-firstname label span").text($.mage.__('Social Name')); 70 | } 71 | 72 | if(this.options.changeLastnameLabel){ 73 | $(".field-name-lastname label span").text($.mage.__('Trade Name')); 74 | } 75 | } 76 | }); 77 | 78 | return $.mage.changePersonType; 79 | }); -------------------------------------------------------------------------------- /view/frontend/web/css/source/_module.less: -------------------------------------------------------------------------------- 1 | // 2 | // Common 3 | // _____________________________________________ 4 | 5 | & when (@media-common = true) { 6 | .checkout-index-index { 7 | .fieldset .field, 8 | .fieldset .fields .field { 9 | margin: 0 0 20px; 10 | } 11 | 12 | .fieldset .field.street { 13 | margin: 0; 14 | 15 | & > legend { 16 | margin: 0; 17 | } 18 | } 19 | 20 | .fieldset .field .label { 21 | display: inline !important; 22 | position: initial !important; 23 | overflow: initial !important; 24 | font-weight: 600; 25 | } 26 | 27 | #tooltip-label { 28 | display: none !important; 29 | } 30 | 31 | .fieldset .field.required .label:after, 32 | .fieldset .fields .field.required .label:after, 33 | .fieldset .field._required .label:after, 34 | .fieldset .fields .field._required .label:after { 35 | content: '*'; 36 | color: #e02b27; 37 | font-size: 1.2rem; 38 | margin: 0 0 0 5px; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /view/frontend/web/jquery.mask.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery' 3 | ], function ($) { 4 | 'use strict'; 5 | 6 | var Mask = function (el, mask, options) { 7 | 8 | var p = { 9 | invalid: [], 10 | getCaret: function () { 11 | try { 12 | var sel, 13 | pos = 0, 14 | ctrl = el.get(0), 15 | dSel = document.selection, 16 | cSelStart = ctrl.selectionStart; 17 | 18 | // IE Support 19 | if (dSel && navigator.appVersion.indexOf('MSIE 10') === -1) { 20 | sel = dSel.createRange(); 21 | sel.moveStart('character', -p.val().length); 22 | pos = sel.text.length; 23 | } 24 | // Firefox support 25 | else if (cSelStart || cSelStart === '0') { 26 | pos = cSelStart; 27 | } 28 | 29 | return pos; 30 | } catch (e) {} 31 | }, 32 | setCaret: function(pos) { 33 | try { 34 | if (el.is(':focus')) { 35 | var range, ctrl = el.get(0); 36 | 37 | // Firefox, WebKit, etc.. 38 | if (ctrl.setSelectionRange) { 39 | ctrl.focus(); 40 | ctrl.setSelectionRange(pos, pos); 41 | } else { // IE 42 | range = ctrl.createTextRange(); 43 | range.collapse(true); 44 | range.moveEnd('character', pos); 45 | range.moveStart('character', pos); 46 | range.select(); 47 | } 48 | } 49 | } catch (e) {} 50 | }, 51 | events: function() { 52 | el 53 | .on('keydown.mask', function(e) { 54 | el.data('mask-keycode', e.keyCode || e.which); 55 | }) 56 | .on($.jMaskGlobals.useInput ? 'input.mask' : 'keyup.mask', p.behaviour) 57 | .on('paste.mask drop.mask', function() { 58 | setTimeout(function() { 59 | el.keydown().keyup(); 60 | }, 100); 61 | }) 62 | .on('change.mask', function(){ 63 | el.data('changed', true); 64 | }) 65 | .on('blur.mask', function(){ 66 | if (oldValue !== p.val() && !el.data('changed')) { 67 | el.trigger('change'); 68 | } 69 | el.data('changed', false); 70 | }) 71 | // it's very important that this callback remains in this position 72 | // otherwhise oldValue it's going to work buggy 73 | .on('blur.mask', function() { 74 | oldValue = p.val(); 75 | }) 76 | // select all text on focus 77 | .on('focus.mask', function (e) { 78 | if (options.selectOnFocus === true) { 79 | $(e.target).select(); 80 | } 81 | }) 82 | // clear the value if it not complete the mask 83 | .on('focusout.mask', function() { 84 | if (options.clearIfNotMatch && !regexMask.test(p.val())) { 85 | p.val(''); 86 | } 87 | }); 88 | }, 89 | getRegexMask: function() { 90 | var maskChunks = [], translation, pattern, optional, recursive, oRecursive, r; 91 | 92 | for (var i = 0; i < mask.length; i++) { 93 | translation = jMask.translation[mask.charAt(i)]; 94 | 95 | if (translation) { 96 | 97 | pattern = translation.pattern.toString().replace(/.{1}$|^.{1}/g, ''); 98 | optional = translation.optional; 99 | recursive = translation.recursive; 100 | 101 | if (recursive) { 102 | maskChunks.push(mask.charAt(i)); 103 | oRecursive = {digit: mask.charAt(i), pattern: pattern}; 104 | } else { 105 | maskChunks.push(!optional && !recursive ? pattern : (pattern + '?')); 106 | } 107 | 108 | } else { 109 | maskChunks.push(mask.charAt(i).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')); 110 | } 111 | } 112 | 113 | r = maskChunks.join(''); 114 | 115 | if (oRecursive) { 116 | r = r.replace(new RegExp('(' + oRecursive.digit + '(.*' + oRecursive.digit + ')?)'), '($1)?') 117 | .replace(new RegExp(oRecursive.digit, 'g'), oRecursive.pattern); 118 | } 119 | 120 | return new RegExp(r); 121 | }, 122 | destroyEvents: function() { 123 | el.off(['input', 'keydown', 'keyup', 'paste', 'drop', 'blur', 'focusout', ''].join('.mask ')); 124 | }, 125 | val: function(v) { 126 | var isInput = el.is('input'), 127 | method = isInput ? 'val' : 'text', 128 | r; 129 | 130 | if (arguments.length > 0) { 131 | if (el[method]() !== v) { 132 | el[method](v); 133 | } 134 | r = el; 135 | } else { 136 | r = el[method](); 137 | } 138 | 139 | return r; 140 | }, 141 | getMCharsBeforeCount: function(index, onCleanVal) { 142 | for (var count = 0, i = 0, maskL = mask.length; i < maskL && i < index; i++) { 143 | if (!jMask.translation[mask.charAt(i)]) { 144 | index = onCleanVal ? index + 1 : index; 145 | count++; 146 | } 147 | } 148 | return count; 149 | }, 150 | caretPos: function (originalCaretPos, oldLength, newLength, maskDif) { 151 | var translation = jMask.translation[mask.charAt(Math.min(originalCaretPos - 1, mask.length - 1))]; 152 | 153 | return !translation ? p.caretPos(originalCaretPos + 1, oldLength, newLength, maskDif) 154 | : Math.min(originalCaretPos + newLength - oldLength - maskDif, newLength); 155 | }, 156 | behaviour: function(e) { 157 | e = e || window.event; 158 | p.invalid = []; 159 | 160 | var keyCode = el.data('mask-keycode'); 161 | 162 | if ($.inArray(keyCode, jMask.byPassKeys) === -1) { 163 | var caretPos = p.getCaret(), 164 | currVal = p.val(), 165 | currValL = currVal.length, 166 | newVal = p.getMasked(), 167 | newValL = newVal.length, 168 | maskDif = p.getMCharsBeforeCount(newValL - 1) - p.getMCharsBeforeCount(currValL - 1), 169 | changeCaret = caretPos < currValL; 170 | 171 | p.val(newVal); 172 | 173 | if (changeCaret) { 174 | // Avoid adjusting caret on backspace or delete 175 | if (!(keyCode === 8 || keyCode === 46)) { 176 | caretPos = p.caretPos(caretPos, currValL, newValL, maskDif); 177 | } 178 | p.setCaret(caretPos); 179 | } 180 | 181 | return p.callbacks(e); 182 | } 183 | }, 184 | getMasked: function(skipMaskChars, val) { 185 | var buf = [], 186 | value = val === undefined ? p.val() : val + '', 187 | m = 0, maskLen = mask.length, 188 | v = 0, valLen = value.length, 189 | offset = 1, addMethod = 'push', 190 | resetPos = -1, 191 | lastMaskChar, 192 | check; 193 | 194 | if (options.reverse) { 195 | addMethod = 'unshift'; 196 | offset = -1; 197 | lastMaskChar = 0; 198 | m = maskLen - 1; 199 | v = valLen - 1; 200 | check = function () { 201 | return m > -1 && v > -1; 202 | }; 203 | } else { 204 | lastMaskChar = maskLen - 1; 205 | check = function () { 206 | return m < maskLen && v < valLen; 207 | }; 208 | } 209 | 210 | while (check()) { 211 | var maskDigit = mask.charAt(m), 212 | valDigit = value.charAt(v), 213 | translation = jMask.translation[maskDigit]; 214 | 215 | if (translation) { 216 | if (valDigit.match(translation.pattern)) { 217 | buf[addMethod](valDigit); 218 | if (translation.recursive) { 219 | if (resetPos === -1) { 220 | resetPos = m; 221 | } else if (m === lastMaskChar) { 222 | m = resetPos - offset; 223 | } 224 | 225 | if (lastMaskChar === resetPos) { 226 | m -= offset; 227 | } 228 | } 229 | m += offset; 230 | } else if (translation.optional) { 231 | m += offset; 232 | v -= offset; 233 | } else if (translation.fallback) { 234 | buf[addMethod](translation.fallback); 235 | m += offset; 236 | v -= offset; 237 | } else { 238 | p.invalid.push({p: v, v: valDigit, e: translation.pattern}); 239 | } 240 | v += offset; 241 | } else { 242 | if (!skipMaskChars) { 243 | buf[addMethod](maskDigit); 244 | } 245 | 246 | if (valDigit === maskDigit) { 247 | v += offset; 248 | } 249 | 250 | m += offset; 251 | } 252 | } 253 | 254 | var lastMaskCharDigit = mask.charAt(lastMaskChar); 255 | if (maskLen === valLen + 1 && !jMask.translation[lastMaskCharDigit]) { 256 | buf.push(lastMaskCharDigit); 257 | } 258 | 259 | return buf.join(''); 260 | }, 261 | callbacks: function (e) { 262 | var val = p.val(), 263 | changed = val !== oldValue, 264 | defaultArgs = [val, e, el, options], 265 | callback = function(name, criteria, args) { 266 | if (typeof options[name] === 'function' && criteria) { 267 | options[name].apply(this, args); 268 | } 269 | }; 270 | 271 | callback('onChange', changed === true, defaultArgs); 272 | callback('onKeyPress', changed === true, defaultArgs); 273 | callback('onComplete', val.length === mask.length, defaultArgs); 274 | callback('onInvalid', p.invalid.length > 0, [val, e, el, p.invalid, options]); 275 | } 276 | }; 277 | 278 | el = $(el); 279 | var jMask = this, oldValue = p.val(), regexMask; 280 | 281 | mask = typeof mask === 'function' ? mask(p.val(), undefined, el, options) : mask; 282 | 283 | 284 | // public methods 285 | jMask.mask = mask; 286 | jMask.options = options; 287 | jMask.remove = function() { 288 | var caret = p.getCaret(); 289 | p.destroyEvents(); 290 | p.val(jMask.getCleanVal()); 291 | p.setCaret(caret - p.getMCharsBeforeCount(caret)); 292 | return el; 293 | }; 294 | 295 | // get value without mask 296 | jMask.getCleanVal = function() { 297 | return p.getMasked(true); 298 | }; 299 | 300 | // get masked value without the value being in the input or element 301 | jMask.getMaskedVal = function(val) { 302 | return p.getMasked(false, val); 303 | }; 304 | 305 | jMask.init = function(onlyMask) { 306 | onlyMask = onlyMask || false; 307 | options = options || {}; 308 | 309 | jMask.clearIfNotMatch = $.jMaskGlobals.clearIfNotMatch; 310 | jMask.byPassKeys = $.jMaskGlobals.byPassKeys; 311 | jMask.translation = $.extend({}, $.jMaskGlobals.translation, options.translation); 312 | 313 | jMask = $.extend(true, {}, jMask, options); 314 | 315 | regexMask = p.getRegexMask(); 316 | 317 | if (onlyMask === false) { 318 | 319 | if (options.placeholder) { 320 | el.attr('placeholder' , options.placeholder); 321 | } 322 | 323 | // this is necessary, otherwise if the user submit the form 324 | // and then press the "back" button, the autocomplete will erase 325 | // the data. Works fine on IE9+, FF, Opera, Safari. 326 | if (el.data('mask')) { 327 | el.attr('autocomplete', 'off'); 328 | } 329 | 330 | p.destroyEvents(); 331 | p.events(); 332 | 333 | var caret = p.getCaret(); 334 | p.val(p.getMasked()); 335 | p.setCaret(caret + p.getMCharsBeforeCount(caret, true)); 336 | 337 | } else { 338 | p.events(); 339 | p.val(p.getMasked()); 340 | } 341 | }; 342 | 343 | jMask.init(!el.is('input')); 344 | }; 345 | 346 | $.maskWatchers = {}; 347 | var HTMLAttributes = function () { 348 | var input = $(this), 349 | options = {}, 350 | prefix = 'data-mask-', 351 | mask = input.attr('data-mask'); 352 | 353 | if (input.attr(prefix + 'reverse')) { 354 | options.reverse = true; 355 | } 356 | 357 | if (input.attr(prefix + 'clearifnotmatch')) { 358 | options.clearIfNotMatch = true; 359 | } 360 | 361 | if (input.attr(prefix + 'selectonfocus') === 'true') { 362 | options.selectOnFocus = true; 363 | } 364 | 365 | if (notSameMaskObject(input, mask, options)) { 366 | return input.data('mask', new Mask(this, mask, options)); 367 | } 368 | }, 369 | notSameMaskObject = function(field, mask, options) { 370 | options = options || {}; 371 | var maskObject = $(field).data('mask'), 372 | stringify = JSON.stringify, 373 | value = $(field).val() || $(field).text(); 374 | try { 375 | if (typeof mask === 'function') { 376 | mask = mask(value); 377 | } 378 | return typeof maskObject !== 'object' || stringify(maskObject.options) !== stringify(options) || maskObject.mask !== mask; 379 | } catch (e) {} 380 | }, 381 | eventSupported = function(eventName) { 382 | var el = document.createElement('div'), isSupported; 383 | 384 | eventName = 'on' + eventName; 385 | isSupported = (eventName in el); 386 | 387 | if ( !isSupported ) { 388 | el.setAttribute(eventName, 'return;'); 389 | isSupported = typeof el[eventName] === 'function'; 390 | } 391 | el = null; 392 | 393 | return isSupported; 394 | }; 395 | 396 | $.fn.mask = function(mask, options) { 397 | options = options || {}; 398 | var selector = this.selector, 399 | globals = $.jMaskGlobals, 400 | interval = globals.watchInterval, 401 | watchInputs = options.watchInputs || globals.watchInputs, 402 | maskFunction = function() { 403 | if (notSameMaskObject(this, mask, options)) { 404 | return $(this).data('mask', new Mask(this, mask, options)); 405 | } 406 | }; 407 | 408 | $(this).each(maskFunction); 409 | 410 | if (selector && selector !== '' && watchInputs) { 411 | clearInterval($.maskWatchers[selector]); 412 | $.maskWatchers[selector] = setInterval(function(){ 413 | $(document).find(selector).each(maskFunction); 414 | }, interval); 415 | } 416 | return this; 417 | }; 418 | 419 | $.fn.masked = function(val) { 420 | return this.data('mask').getMaskedVal(val); 421 | }; 422 | 423 | $.fn.unmask = function() { 424 | clearInterval($.maskWatchers[this.selector]); 425 | delete $.maskWatchers[this.selector]; 426 | return this.each(function() { 427 | var dataMask = $(this).data('mask'); 428 | if (dataMask) { 429 | dataMask.remove().removeData('mask'); 430 | } 431 | }); 432 | }; 433 | 434 | $.fn.cleanVal = function() { 435 | return this.data('mask').getCleanVal(); 436 | }; 437 | 438 | $.applyDataMask = function(selector) { 439 | selector = selector || $.jMaskGlobals.maskElements; 440 | var $selector = (selector instanceof $) ? selector : $(selector); 441 | $selector.filter($.jMaskGlobals.dataMaskAttr).each(HTMLAttributes); 442 | }; 443 | 444 | var globals = { 445 | maskElements: 'input,td,span,div', 446 | dataMaskAttr: '*[data-mask]', 447 | dataMask: true, 448 | watchInterval: 300, 449 | watchInputs: true, 450 | useInput: eventSupported('input'), 451 | watchDataMask: false, 452 | byPassKeys: [9, 16, 17, 18, 36, 37, 38, 39, 40, 91], 453 | translation: { 454 | '0': {pattern: /\d/}, 455 | '9': {pattern: /\d/, optional: true}, 456 | '#': {pattern: /\d/, recursive: true}, 457 | 'A': {pattern: /[a-zA-Z0-9]/}, 458 | 'S': {pattern: /[a-zA-Z]/} 459 | } 460 | }; 461 | 462 | $.jMaskGlobals = $.jMaskGlobals || {}; 463 | globals = $.jMaskGlobals = $.extend(true, {}, globals, $.jMaskGlobals); 464 | 465 | // looking for inputs with data-mask attribute 466 | if (globals.dataMask) { 467 | $.applyDataMask(); 468 | } 469 | 470 | setInterval(function() { 471 | if ($.jMaskGlobals.watchDataMask) { 472 | $.applyDataMask(); 473 | } 474 | }, globals.watchInterval); 475 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/action/create-billing-address-mixin.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | 'mage/utils/wrapper', 4 | 'Magento_Checkout/js/model/quote' 5 | ], function ($, wrapper,quote) { 6 | 'use strict'; 7 | 8 | return function (setBillingInformationAction) { 9 | return wrapper.wrap(setBillingInformationAction, function (originalAction, messageContainer) { 10 | 11 | if (messageContainer.custom_attributes != undefined) { 12 | $.each(messageContainer.custom_attributes , function( key, value ) { 13 | messageContainer['custom_attributes'][key] = value; 14 | }); 15 | 16 | } 17 | return originalAction(messageContainer); 18 | }); 19 | }; 20 | }); 21 | -------------------------------------------------------------------------------- /view/frontend/web/js/action/create-shipping-address-mixin.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | 'mage/utils/wrapper', 4 | 'Magento_Checkout/js/model/quote' 5 | ], function ($, wrapper,quote) { 6 | 'use strict'; 7 | 8 | return function (setShippingInformationAction) { 9 | return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer) { 10 | if (messageContainer.custom_attributes != undefined) { 11 | $.each(messageContainer.custom_attributes , function( key, value ) { 12 | messageContainer['custom_attributes'][key] = value; 13 | }); 14 | } 15 | 16 | return originalAction(messageContainer); 17 | }); 18 | }; 19 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/action/place-order-mixin.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | 'mage/utils/wrapper', 4 | 'Magento_Checkout/js/model/quote' 5 | ], function ($, wrapper,quote) { 6 | 'use strict'; 7 | 8 | return function (placeOrderAction) { 9 | return wrapper.wrap(placeOrderAction, function (originalAction, messageContainer) { 10 | var billingAddress = quote.billingAddress(); 11 | 12 | if (billingAddress['extension_attributes'] === undefined) { 13 | billingAddress['extension_attributes'] = {}; 14 | } 15 | 16 | if (billingAddress.customAttributes !== undefined) { 17 | $.each(billingAddress.customAttributes, function (key, value) { 18 | var attrCode = value['attribute_code']; 19 | var attrValue = value['value']; 20 | 21 | billingAddress['customAttributes'][attrCode] = value; 22 | billingAddress['extension_attributes'][attrCode] = attrValue; 23 | }); 24 | } 25 | 26 | return originalAction(messageContainer); 27 | }); 28 | }; 29 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/action/set-shipping-information-mixin.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'jquery', 3 | 'mage/utils/wrapper', 4 | 'Magento_Checkout/js/model/quote' 5 | ], function ($, wrapper,quote) { 6 | 'use strict'; 7 | 8 | return function (setShippingInformationAction) { 9 | return wrapper.wrap(setShippingInformationAction, function (originalAction, messageContainer) { 10 | 11 | var shippingAddress = quote.shippingAddress(); 12 | 13 | if (shippingAddress['extension_attributes'] === undefined) { 14 | shippingAddress['extension_attributes'] = {}; 15 | } 16 | 17 | if (shippingAddress.customAttributes !== undefined) { 18 | $.each(shippingAddress.customAttributes, function (key, value) { 19 | 20 | var attrCode = value['attribute_code']; 21 | var attrValue = value['value']; 22 | 23 | shippingAddress['customAttributes'][attrCode] = value; 24 | shippingAddress['extension_attributes'][attrCode] = attrValue; 25 | }); 26 | } 27 | 28 | return originalAction(messageContainer); 29 | }); 30 | }; 31 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/form/address-mixin.js: -------------------------------------------------------------------------------- 1 | require([ 2 | 'jquery', 3 | 'inputMask', 4 | 'mage/url', 5 | 'loader' 6 | ], function ($, mask, url) { 7 | $("#postcode").mask('00000-000', {clearIfNotMatch: true}); 8 | $('#postcode').on('change', function(){ 9 | var zipcode = $(this).val().replace('-', ''); 10 | var ajaxurl = url.build('rest/V1/magedev-brazil-zipcode/search/' + zipcode); 11 | $('body').loader('show'); 12 | 13 | $.ajax({ 14 | url: ajaxurl, 15 | dataType: 'json', 16 | timeout: 4000, 17 | async: true 18 | }).done(function (data) { 19 | if(data.error){ 20 | // TODO 21 | }else{ 22 | $("#street_1").val(data.street??''); 23 | $("#street_3").val(data.neighborhood??''); 24 | $("#street_4").val(data.additional_info??''); 25 | $("#city").val(data.city??''); 26 | $("#country").val('BR'); 27 | $("#region_id").val(data.region_id??''); 28 | } 29 | }).error(function(){}); 30 | 31 | $('body').loader('hide'); 32 | }); 33 | 34 | var SPMaskBehavior = function (val) { 35 | return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; 36 | }, 37 | spOptions = { 38 | onKeyPress: function(val, e, field, options) { 39 | field.mask(SPMaskBehavior.apply({}, arguments), options); 40 | }, 41 | clearIfNotMatch: true 42 | }; 43 | 44 | $('#telephone').mask(SPMaskBehavior, spOptions); 45 | $('#fax').mask(SPMaskBehavior, spOptions); 46 | }); 47 | -------------------------------------------------------------------------------- /view/frontend/web/js/shipping-address/address-renderer/streetprefix.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'underscore', 3 | 'ko', 4 | 'uiRegistry', 5 | 'Magento_Ui/js/form/element/abstract' 6 | ], function (_, ko, registry, Abstract) { 7 | 'use strict'; 8 | 9 | return Abstract.extend({ 10 | defaults: { 11 | loading: ko.observable(false) 12 | }, 13 | 14 | initialize: function () { 15 | this._super(); 16 | return this; 17 | } 18 | }); 19 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/shipping-address/address-renderer/telephone.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'underscore', 3 | 'ko', 4 | 'uiRegistry', 5 | 'Magento_Ui/js/form/element/abstract', 6 | 'jquery', 7 | 'inputMask', 8 | 'mage/url', 9 | ], function (_, ko, registry, Abstract, jquery, mask, url) { 10 | 'use strict'; 11 | 12 | return Abstract.extend({ 13 | defaults: { 14 | loading: ko.observable(false) 15 | }, 16 | 17 | initialize: function () { 18 | this._super(); 19 | 20 | var SPMaskBehavior = function (val) { 21 | return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009'; 22 | }, 23 | spOptions = { 24 | onKeyPress: function(val, e, field, options) { 25 | field.mask(SPMaskBehavior.apply({}, arguments), options); 26 | }, 27 | clearIfNotMatch: true 28 | }; 29 | 30 | jquery('#'+this.uid).mask(SPMaskBehavior, spOptions); 31 | 32 | return this; 33 | } 34 | }); 35 | }); -------------------------------------------------------------------------------- /view/frontend/web/js/shipping-address/address-renderer/zip-code.js: -------------------------------------------------------------------------------- 1 | define([ 2 | 'underscore', 3 | 'ko', 4 | 'uiRegistry', 5 | 'Magento_Ui/js/form/element/abstract', 6 | 'jquery', 7 | 'inputMask', 8 | 'mage/url', 9 | 'loader' 10 | ], function (_, ko, registry, Abstract, jquery, mask, url) { 11 | 'use strict'; 12 | 13 | return Abstract.extend({ 14 | defaults: { 15 | loading: ko.observable(false), 16 | imports: { 17 | update: '${ $.parentName }.country_id:value' 18 | } 19 | }, 20 | 21 | initialize: function () { 22 | this._super(); 23 | jquery('#'+this.uid).mask('00000-000', {clearIfNotMatch: true}); 24 | return this; 25 | }, 26 | 27 | /** 28 | * @param {String} value 29 | */ 30 | update: function (value) { 31 | var country = registry.get(this.parentName + '.' + 'country_id'), 32 | options = country.indexedOptions, 33 | option; 34 | 35 | if (!value) { 36 | return; 37 | } 38 | 39 | if(options[value]){ 40 | option = options[value]; 41 | 42 | if (option['is_zipcode_optional']) { 43 | this.error(false); 44 | this.validation = _.omit(this.validation, 'required-entry'); 45 | } else { 46 | this.validation['required-entry'] = true; 47 | } 48 | 49 | this.required(!option['is_zipcode_optional']); 50 | 51 | } 52 | 53 | this.firstLoad = true; 54 | }, 55 | 56 | 57 | onUpdate: function () { 58 | this.bubble('update', this.hasChanged()); 59 | var validate = this.validate(); 60 | 61 | if(validate.valid == true && this.value() && this.value().length == 9){ 62 | jquery('body').loader('show'); 63 | 64 | var element = this; 65 | 66 | var value = this.value(); 67 | value = value.replace('-', ''); 68 | 69 | var ajaxurl = url.build('/rest/V1/magedev-brazil-zipcode/search/' + value); 70 | 71 | jquery.ajax({ 72 | url: ajaxurl, 73 | dataType: 'json', 74 | timeout: 4000 75 | }).done(function (data) { 76 | if(data.error){ 77 | // TODO 78 | }else{ 79 | if(registry.get(element.parentName + '.' + 'street.0')){ 80 | registry.get(element.parentName + '.' + 'street.0').value(data.street ?? ''); 81 | } 82 | if(registry.get(element.parentName + '.' + 'street.2')){ 83 | registry.get(element.parentName + '.' + 'street.2').value(data.neighborhood ?? ''); 84 | } 85 | if(registry.get(element.parentName + '.' + 'street.3')){ 86 | registry.get(element.parentName + '.' + 'street.3').value(data.additional_info ?? ''); 87 | } 88 | if(registry.get(element.parentName + '.' + 'city')){ 89 | registry.get(element.parentName + '.' + 'city').value(data.city ?? ''); 90 | } 91 | if(registry.get(element.parentName + '.' + 'region_id')){ 92 | registry.get(element.parentName + '.' + 'region_id').value(data.region_id ?? ''); 93 | } 94 | if(registry.get(element.parentName + '.' + 'country_id')){ 95 | registry.get(element.parentName + '.' + 'country_id').value('BR'); 96 | } 97 | } 98 | jquery('body').loader('hide'); 99 | }).error(function(){ 100 | jquery('body').loader('hide'); 101 | }); 102 | }else{ 103 | jquery('body').loader('hide'); 104 | } 105 | 106 | } 107 | }); 108 | }); 109 | -------------------------------------------------------------------------------- /view/frontend/web/template/shipping-address/address-renderer/streetprefix.html: -------------------------------------------------------------------------------- 1 | 12 | -------------------------------------------------------------------------------- /view/frontend/web/template/shipping-address/address-renderer/zip-code.html: -------------------------------------------------------------------------------- 1 | 12 | --------------------------------------------------------------------------------