├── .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_length' => 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_length' => 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_length' => 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_length' => 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_length' => 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 |