Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Built-in checkout address #483

Merged
merged 15 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions assets/javascripts/front/checkout/checkoutFields.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/* globals wc_pagarme_checkout */
/* jshint esversion: 6 */
const pagarmeCustomerFields = {
billingDocumentId: 'billing_document',
shippingDocumentId: 'shipping_document',
blocksBillingDocumentId: 'billing-address-document',
blocksShippingDocumentId: 'shipping-address-document',
fabiano-mallmann marked this conversation as resolved.
Show resolved Hide resolved

documentMasks: [
'000.000.000-00999',
'00.000.000/0000-00'
],
documentMaskOptions: {
onKeyPress: function (document, e, field, options) {
const masks = pagarmeCustomerFields.documentMasks,
mask = document.length > 14 ? masks[1] : masks[0];
field.mask(mask, options);
}
},

applyDocumentMask() {
jQuery('#' + this.billingDocumentId).mask(this.documentMasks[0], this.documentMaskOptions);
jQuery('#' + this.shippingDocumentId).mask(this.documentMasks[0], this.documentMaskOptions);
jQuery('#' + this.blocksBillingDocumentId).mask(this.documentMasks[0], this.documentMaskOptions);
jQuery('#' + this.blocksShippingDocumentId).mask(this.documentMasks[0], this.documentMaskOptions);
},

addEventListener() {
jQuery(document.body).on('checkout_error', function () {
const documentFieldIds = [
pagarmeCustomerFields.billingDocumentId,
pagarmeCustomerFields.shippingDocumentId,
pagarmeCustomerFields.blocksBillingDocumentId,
pagarmeCustomerFields.blocksShippingDocumentId
];
jQuery.each(documentFieldIds, function () {
const documentField = '#' + this + '_field',
isDocumentEmpty = jQuery('.woocommerce-error li[data-id="' + this + '"]').length,
isDocumentInvalid = jQuery('.woocommerce-error li[data-pagarme-error="' + this + '"]').length;
if (isDocumentEmpty || isDocumentInvalid) {
jQuery(documentField).addClass('woocommerce-invalid');
} else {
jQuery(documentField).removeClass('woocommerce-invalid');
}
});
});
},

start: function () {
this.addEventListener();

setTimeout(function() {
pagarmeCustomerFields.applyDocumentMask();
}, 2000);
}
};

pagarmeCustomerFields.start();
Binary file modified languages/woo-pagarme-payments-pt_BR.mo
Binary file not shown.
79 changes: 59 additions & 20 deletions languages/woo-pagarme-payments-pt_BR.po
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ msgstr ""
"Project-Id-Version: WooCommerce Pagar.me Payments 1.0\n"
"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woo-pagarme-payments\n"
"POT-Creation-Date: 2018-06-22 13:58-0300\n"
"PO-Revision-Date: 2024-09-19 16:32-0300\n"
"PO-Revision-Date: 2024-09-30 17:07-0300\n"
"Last-Translator: Pagar.me\n"
"Language-Team: \n"
"Language: pt_BR\n"
Expand Down Expand Up @@ -423,6 +423,16 @@ msgstr "Logs"
msgid "Log Pagar.me events, you can check this log in WooCommerce>Status>Logs."
msgstr "Registra eventos da Pagar.me, você pode conferir esse arquivo de log em WooCommerce>Status>Logs."

msgid "Modify address fields"
msgstr "Modificar campos de endereço"

msgid ""
"Corrects the 'label' and 'placeholder' attributes of the 'Address' and 'Complement' fields to instruct users on how "
"to fill them in correctly."
msgstr ""
"Corrige os atributos 'label' e 'placeholder' dos campos de 'Endereço' e 'Complemento' para instruir os usuários no "
"preenchimento correto dos mesmos."

msgid "Allow order without address"
msgstr "Permitir compras sem endereço"

Expand Down Expand Up @@ -849,8 +859,12 @@ msgid "The following checkout fields are required, but were not found:"
msgstr "Os seguintes campos de checkout são obrigatórios, mas não foram encontrados:"

#: woo-pagarme-payments.php:194
msgid "Please, make sure to include them for Pagar.me module to work."
msgstr "Por favor, certifique-se de incluí-los para que o módulo da Pagar.me funcione."
msgid ""
"Please, make sure to include them for Pagar.me plugin to work. If you are customizing the checkout, the address "
"fields must have the 'name' attribute exactly as listed above. %sRead documentation »%s"
msgstr ""
"Por favor, certifique-se de incluí-los para que o plugin Pagar.me funcione. Se você estiver personalizando o "
"checkout, os campos de endereço devem ter o atributo 'name' exatamente como listado acima. %sLeia a documentação »%s"

msgid "You can install %s or any other plugin of your choice to add the missing fields. %sRead documentation »%s"
msgstr ""
Expand Down Expand Up @@ -1223,22 +1237,6 @@ msgstr ""
"Sua conta está desativada na Dash da Pagar.me. Por favor, entre em contato com o nosso time de atendimento para "
"habilitá-la."

#: src/Controller/HubAccounts.php:90 src/Controller/HubAccounts.php:96
msgid ""
"No domain registered on Pagar.me Dash. Please enter your website's domain on the Dash to be able to process payment "
"in your store."
msgstr ""
"Nenhum domínio cadastrado na Dash da Pagar.me. Por favor, insira o domínio do seu site na Dash para poder processar o "
"pagamento em sua loja."

#: src/Controller/HubAccounts.php:90 src/Controller/HubAccounts.php:96
msgid ""
"The registered domain is different from the URL of your website. Please correct the domain configured on the Dash to "
"be able to process payment in your store."
msgstr ""
"O domínio cadastrado é diferente da URL do seu site. Por favor, corrija o domínio configurado na Dash para poder "
"processar o pagamento em sua loja."

msgid ""
"Pix payment method is enabled on your store, but disabled on Pagar.me Dash. Please, access the Dash configurations "
"and enable it to be able to process Pix payment on your store."
Expand Down Expand Up @@ -1502,7 +1500,7 @@ msgid "See: Settings → Keys → Account ID"
msgstr "Consulte em: Configurações → Chaves → ID da Conta"

msgid "Google Merchant Identifier, get yours <a href=\"%s\">here</a>."
msgstr "Identificador de comerciante do Google, adquira o seu <a href=\"%s\">aqui</a>"
msgstr "Identificador de comerciante do Google, adquira o seu <a href=\"%s\">aqui</a>."

msgid "Your store name that will be displayed to the customer while purchasing through Google Pay."
msgstr "Nome da sua loja que será exibido ao cliente enquanto compra através do Google Pay."
Expand All @@ -1512,3 +1510,44 @@ msgstr "Nome da loja na Google Pay"

msgid "Pagar.me account ID"
msgstr "ID da conta Pagar.me"

msgid "Document"
msgstr "Documento"

msgid "CPF or CNPJ"
msgstr "CPF ou CNPJ"

msgctxt "checkout-document-error"
msgid "Billing"
msgstr "faturamento"

msgctxt "checkout-document-error"
msgid "Shipping"
msgstr "envio"

msgid "Please, enter a valid document number."
msgstr "Por favor, digite um número de documento válido."

msgid "Please, enter a valid %s number."
msgstr "Por favor, digite um número de %s válido."

msgid "Please, enter a valid document number in the <b>%s Document</b>."
msgstr "Por favor, digite um número de documento válido <b>no campo Documento de %s</b>."

msgid "Please, enter a valid %s number in the <b>%s Document</b>."
msgstr "Por favor, digite um número de %s válido <b>no campo &quot;Documento&quot; do endereço de %s</b>."

msgid "%s Document"
msgstr "Documento de %s"

msgid "Billing"
msgstr "Faturamento"

msgid "Shipping"
msgstr "Envio"

msgid "Street name, house number and neighbourhood"
msgstr "Nome da rua, número da casa e bairro"

msgid "Additional address data"
msgstr "Complemento"
6 changes: 5 additions & 1 deletion src/Action/ActionsRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@

namespace Woocommerce\Pagarme\Action;

/**
* @uses CustomerFieldsActions, OrderActions
*/
class ActionsRunner implements RunnerInterface
{
private $actionClasses = [
"OrderActions"
"OrderActions",
"CustomerFieldsActions"
];

public function run()
Expand Down
181 changes: 181 additions & 0 deletions src/Action/CustomerFieldsActions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php
/**
* @author Open Source Team
* @copyright 2024 Pagar.me (https://pagar.me)
* @license https://pagar.me Copyright
* @link https://pagar.me
*/

declare(strict_types = 1);

namespace Woocommerce\Pagarme\Action;

use Exception;
use Woocommerce\Pagarme\Controller\Checkout\CustomerFields;
use Woocommerce\Pagarme\Helper\Utils;
use Woocommerce\Pagarme\Model\Config;
use WP_Error;

defined('ABSPATH') || exit;

/**
* @used-by ActionsRunner
*/
class CustomerFieldsActions implements RunnerInterface
{
private $customerFields;

public function __construct()
{
$this->customerFields = new CustomerFields();
}

public function run()
{
add_filter('woocommerce_checkout_init', array($this, 'enqueueScript'));
add_filter('woocommerce_checkout_fields', array($this, 'addDocumentField'));
add_action('woocommerce_checkout_process', array($this, 'validateDocument'));
add_action('woocommerce_init', array($this, 'addDocumentFieldOnCheckoutBlocks'));
add_action('woocommerce_validate_additional_field', array($this, 'validateCheckoutBlocksDocument'), 10, 3);
add_action(
'woocommerce_admin_order_data_after_billing_address',
array($this, 'displayBillingDocumentOrderMeta')
);
add_action(
'woocommerce_admin_order_data_after_shipping_address',
array($this, 'displayShippingDocumentOrderMeta')
);
add_filter('woocommerce_default_address_fields', array($this, 'overrideAddressFields'));
}

public function enqueueScript()
{
$parameters = Utils::getRegisterScriptParameters('front/checkout', 'checkoutFields', ['jquery.mask']);
wp_register_script(
'pagarme_customer_fields',
$parameters['src'],
$parameters['deps'],
$parameters['ver'],
true
);
wp_enqueue_script('pagarme_customer_fields');
}

/**
* @param array $fields
*
* @return array
*/
public function addDocumentField(array $fields): array
{
if ($this->customerFields->hasDocumentField($fields)) {
return $fields;
}

foreach ($this->customerFields::ADDRESS_TYPES as $addressType) {
$fields[$addressType]["{$addressType}_document"] = array(
'label' => __('Document', 'woo-pagarme-payments'),
'placeholder' => __('CPF or CNPJ', 'woo-pagarme-payments'),
'required' => true,
'class' => array('form-row-wide'),
'priority' => 25
);
}

return $fields;
}

/**
* @throws Exception
*/
public function addDocumentFieldOnCheckoutBlocks()
{
if (
$this->customerFields->hasCheckoutBlocksDocumentField()
|| !function_exists('woocommerce_register_additional_checkout_field')
) {
return;
}

woocommerce_register_additional_checkout_field(
array(
'id' => 'address/document',
'label' => __('CPF or CNPJ', 'woo-pagarme-payments'),
'location' => 'address',
'type' => 'text',
'class' => array('form-row-wide'),
'required' => true,
'index' => 25,
'show_in_order_confirmation' => true
)
);
}

/**
* @return void
*/
public function validateDocument()
{
$this->customerFields->validateDocument();
}

/**
* @param WP_Error $errors
* @param $fieldKey
* @param $documentNumber
*
* @return void
*/
public function validateCheckoutBlocksDocument(WP_Error $errors, $fieldKey, $documentNumber)
{
if ($fieldKey == 'address/document') {
$this->customerFields->validateCheckoutBlocksDocument($errors, $documentNumber);
}
}

/**
* @param $order
*
* @return void
*/
public function displayBillingDocumentOrderMeta($order)
{
$this->customerFields->displayDocumentOrderMeta($order, $this->customerFields::ADDRESS_TYPES[0]);
}

/**
* @param $order
*
* @return void
*/
public function displayShippingDocumentOrderMeta($order)
{
$this->customerFields->displayDocumentOrderMeta($order, $this->customerFields::ADDRESS_TYPES[1]);
}

/**
* @param array $fields
*
* @return array
*/
public function overrideAddressFields(array $fields): array
{
$config = new Config();

if (!$config->getModifyAddress()) {
return $fields;
}

$fields['address_1']['placeholder'] = __(
'Street name, house number and neighbourhood',
'woo-pagarme-payments'
);
$fields['address_2']['label'] = __(
'Additional address data',
'woo-pagarme-payments'
);
$fields['address_2']['label_class'] = '';

return $fields;
}
}
5 changes: 4 additions & 1 deletion src/Action/OrderActions.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

use Woocommerce\Pagarme\Model\Order;

/**
* @used-by ActionsRunner
*/
class OrderActions implements RunnerInterface
{

Expand Down Expand Up @@ -32,7 +35,7 @@ public function showInstallmentFeesToCustomer($total_rows, $order, $tax_display)
if (!$orderPagarme->isPagarmePaymentMethod()) {
return $total_rows;
}

$total = $order->get_total();
$installmentsValue = $orderPagarme->get_meta('pagarme_card_tax');
if (empty($installmentsValue)) {
Expand Down
Loading
Loading