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

1.11.1 Correção em valores das parcelas quando são feitas alterações no carrinho #90

Merged
merged 3 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ jobs:
uses: mathieudutour/[email protected]
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
custom_tag: "1.11.0"
custom_tag: "1.11.1"

# Generate new release
- name: Generate new Release
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 1.11.1 - 25/09/2024
* Correção em valores das parcelas quando são feitas alterações no carrinho.

# 1.11.0 - 02/09/2024
* Adição de traduções para campo de CPF para pagamentos com Pix.
* Adição compatibilidade com configuração para alterar status quando o pedido for pago.
Expand Down
6 changes: 5 additions & 1 deletion README.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Donate link: https://www.linknacional.com.br/wordpress/woocommerce/cielo/
Tags: woocommerce, payment, paymethod, card, credit
Requires at least: 5.7
Tested up to: 6.6
Stable tag: 1.11.0
Stable tag: 1.11.1
Requires PHP: 7.2
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Expand Down Expand Up @@ -72,6 +72,10 @@ Payment Gateway for Cielo API on WooCommerce plugin is dependent on WooCommerce

== Changelog ==

= 1.11.1 =
**25/09/2024**
* Fix installment values when changes are made to the cart.

= 1.11.0 =
**02/09/2024**
* Add translations for CPF field for Pix payments.
Expand Down
4 changes: 2 additions & 2 deletions lkn-wc-gateway-cielo.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Plugin URI: https://www.linknacional.com.br/wordpress/woocommerce/cielo/
* Description: Adds the Cielo API 3.0 Payments gateway to your WooCommerce website.
*
* Version: 1.11.0
* Version: 1.11.1
*
* Author: Link Nacional
* Author URI: https://linknacional.com.br
Expand Down Expand Up @@ -311,7 +311,7 @@ public static function email_order_meta_fields($fields, $sent_to_admin, $order)
private static function setup_constants(): void {
// Defines addon version number for easy reference.
if ( ! defined('LKN_WC_CIELO_VERSION')) {
define('LKN_WC_CIELO_VERSION', '1.11.0');
define('LKN_WC_CIELO_VERSION', '1.11.1');
}
if ( ! defined('LKN_WC_CIELO_TRANSLATION_PATH')) {
define('LKN_WC_CIELO_TRANSLATION_PATH', plugin_dir_path(__FILE__) . 'languages/');
Expand Down
192 changes: 115 additions & 77 deletions resources/js/creditCard/lknCieloCredit.js
Original file line number Diff line number Diff line change
@@ -1,128 +1,166 @@
const lknCCSettingsCielo = window.wc.wcSettings.getSetting('lkn_cielo_credit_data', {})
const lknCCLabelCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.title)
const lknCCActiveInstallmentCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.activeInstallment)
const lknCCTotalCartCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.totalCart)
const lknCCInstallmentLimitCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.installmentLimit)
const lknCCinstallmentsCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.installments)
const lknCCTranslationsCielo = lknCCSettingsCielo.translations
const lknCCNonceCieloCredit = lknCCSettingsCielo.nonceCieloCredit
const lknCCSettingsCielo = window.wc.wcSettings.getSetting('lkn_cielo_credit_data', {});
const lknCCLabelCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.title);
const lknCCActiveInstallmentCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.activeInstallment);
const lknCCTotalCartCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.totalCart);
const lknCCInstallmentLimitCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.installmentLimit);
const lknCCinstallmentsCielo = window.wp.htmlEntities.decodeEntities(lknCCSettingsCielo.installments);
const lknCCTranslationsCielo = lknCCSettingsCielo.translations;
const lknCCNonceCieloCredit = lknCCSettingsCielo.nonceCieloCredit;
const lknCCContentCielo = props => {
const [options, setOptions] = window.wp.element.useState([])
const [options, setOptions] = window.wp.element.useState([]);
const {
eventRegistration,
emitResponse
} = props
} = props;
const {
onPaymentSetup
} = eventRegistration
} = eventRegistration;
const [creditObject, setCreditObject] = window.wp.element.useState({
lkn_cc_cardholder_name: '',
lkn_ccno: '',
lkn_cc_expdate: '',
lkn_cc_cvc: '',
lkn_cc_installments: '1' // Definir padrão como 1 parcela
})
});
const formatCreditCardNumber = value => {
if (value?.length > 24) return creditObject.lkn_ccno
if (value?.length > 24) return creditObject.lkn_ccno;
// Remove caracteres não numéricos
const cleanedValue = value?.replace(/\D/g, '')
const cleanedValue = value?.replace(/\D/g, '');
// Adiciona espaços a cada quatro dígitos
const formattedValue = cleanedValue?.replace(/(.{4})/g, '$1 ')?.trim()
return formattedValue
}
const formattedValue = cleanedValue?.replace(/(.{4})/g, '$1 ')?.trim();
return formattedValue;
};
const updateCreditObject = (key, value) => {
switch (key) {
case 'lkn_cc_cardholder_name':
// Atualiza o estado
setCreditObject({
...creditObject,
[key]: value
})
break
});
break;
case 'lkn_cc_expdate':
if (value.length > 7) return
if (value.length > 7) return;

// Verifica se o valor é uma data válida (MM/YY)
const isValidDate = /^\d{2}\/\d{2}$/.test(value)
const isValidDate = /^\d{2}\/\d{2}$/.test(value);
if (!isValidDate) {
// Remove caracteres não numéricos
const cleanedValue = value?.replace(/\D/g, '')
let formattedValue = cleanedValue?.replace(/^(.{2})(.{2})$/, '$1 / $2')
const cleanedValue = value?.replace(/\D/g, '');
let formattedValue = cleanedValue?.replace(/^(.{2})(.{2})$/, '$1 / $2');

// Se o tamanho da string for 6 (MMYYYY), formate para MM / YY
if (cleanedValue.length === 6) {
formattedValue = cleanedValue?.replace(/^(.{2})(.{2})(.{2})$/, '$1 / $3')
formattedValue = cleanedValue?.replace(/^(.{2})(.{2})(.{2})$/, '$1 / $3');
}

// Atualiza o estado
setCreditObject({
...creditObject,
[key]: formattedValue
})
});
}
return
return;
case 'lkn_cc_cvc':
if (value.length > 8) return
break
if (value.length > 8) return;
break;
default:
break
break;
}
setCreditObject({
...creditObject,
[key]: value
})
}
const wcComponents = window.wc.blocksComponents
window.wp.element.useEffect(() => {
const installmentMin = 5
// Verifica se 'lknCCActiveInstallmentCielo' é 'yes' e o valor total é maior que 10
});
};
const wcComponents = window.wc.blocksComponents;
const calculateInstallments = lknCCTotalCartCielo => {
const installmentMin = 5;
if (lknCCActiveInstallmentCielo === 'yes' && lknCCTotalCartCielo > 10) {
const maxInstallments = lknCCInstallmentLimitCielo // Limita o parcelamento até 12 vezes, deixei fixo para teste

const maxInstallments = lknCCInstallmentLimitCielo;
for (let index = 1; index <= maxInstallments; index++) {
const installmentAmount = (lknCCTotalCartCielo / index).toLocaleString('pt-BR', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
let nextInstallmentAmount = lknCCTotalCartCielo / index
});
let nextInstallmentAmount = lknCCTotalCartCielo / index;
if (nextInstallmentAmount < installmentMin) {
break
break;
}
let formatedInterest = false
let formatedInterest = false;
for (let t = 0; t < lknCCinstallmentsCielo.length; t++) {
const installmentObj = lknCCinstallmentsCielo[t]
// Verify if it is the right installment
const installmentObj = lknCCinstallmentsCielo[t];
if (installmentObj.id === index) {
nextInstallmentAmount = (lknCCTotalCartCielo + lknCCTotalCartCielo * (parseFloat(installmentObj.interest) / 100)) / index
nextInstallmentAmount = (lknCCTotalCartCielo + lknCCTotalCartCielo * (parseFloat(installmentObj.interest) / 100)) / index;
formatedInterest = new Intl.NumberFormat('pt-br', {
style: 'currency',
currency: 'BRL'
}).format(nextInstallmentAmount)
}).format(nextInstallmentAmount);
}
}
if (formatedInterest) {
setOptions(prevOptions => [...prevOptions, {
key: index,
label: `${index}x de ${formatedInterest}`
}])
}]);
} else {
setOptions(prevOptions => [...prevOptions, {
key: index,
label: `${index}x de R$ ${installmentAmount} sem juros`
}])
}]);
}
}
} else {
setOptions(prevOptions => [...prevOptions, {
key: '1',
label: `1x de R$ ${lknCCTotalCartCielo} (à vista)`
}])
}]);
}
}, [])
};
window.wp.element.useEffect(() => {
calculateInstallments(lknCCTotalCartCielo);
const intervalId = setInterval(() => {
var targetNode = document.querySelector('.wc-block-formatted-money-amount.wc-block-components-formatted-money-amount.wc-block-components-totals-footer-item-tax-value');
// Configuração do observer: quais mudanças serão observadas
if (targetNode) {
var config = {
childList: true,
subtree: true,
characterData: true
};
var changeValue = () => {
setOptions([]);
// Remover tudo exceto os números e a vírgula
let newValue = targetNode.textContent.replace(/[^\d,]/g, '');

// Substituir a vírgula por um ponto
newValue = newValue.replace(',', '.');

// Converter para número
newValue = parseFloat(newValue);
calculateInstallments(newValue);
};
changeValue();

// Função de callback que será executada quando ocorrerem mudanças
var callback = function (mutationsList, observer) {
for (var mutation of mutationsList) {
if (mutation.type === 'childList' || mutation.type === 'characterData') {
changeValue();
}
}
};

// Cria uma instância do observer e o conecta ao nó alvo
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);
clearInterval(intervalId);
}
}, 500);
}, []);
window.wp.element.useEffect(() => {
const unsubscribe = onPaymentSetup(async () => {
// Verifica se todos os campos do creditObject estão preenchidos
const allFieldsFilled = Object.values(creditObject).every(field => field.trim() !== '')
const allFieldsFilled = Object.values(creditObject).every(field => field.trim() !== '');
if (allFieldsFilled) {
return {
type: emitResponse.responseTypes.SUCCESS,
Expand All @@ -136,65 +174,65 @@ const lknCCContentCielo = props => {
nonce_lkn_cielo_credit: lknCCNonceCieloCredit
}
}
}
};
}
return {
type: emitResponse.responseTypes.ERROR,
message: 'Por favor, preencha todos os campos.'
}
})
};
});

// Cancela a inscrição quando este componente é desmontado.
return () => {
unsubscribe()
}
}, [creditObject, emitResponse.responseTypes.ERROR, emitResponse.responseTypes.SUCCESS, onPaymentSetup])
return /* #__PURE__ */React.createElement(React.Fragment, null, /* #__PURE__ */React.createElement('div', null, /* #__PURE__ */React.createElement('h4', null, 'Pagamento processado pela Cielo API 3.0')), /* #__PURE__ */React.createElement(wcComponents.TextInput, {
id: 'lkn_cc_cardholder_name',
unsubscribe();
};
}, [creditObject, emitResponse.responseTypes.ERROR, emitResponse.responseTypes.SUCCESS, onPaymentSetup]);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("h4", null, "Pagamento processado pela Cielo API 3.0")), /*#__PURE__*/React.createElement(wcComponents.TextInput, {
id: "lkn_cc_cardholder_name",
label: lknCCTranslationsCielo.cardHolder,
value: creditObject.lkn_cc_cardholder_name,
onChange: value => {
updateCreditObject('lkn_cc_cardholder_name', value)
updateCreditObject('lkn_cc_cardholder_name', value);
},
required: true
}), /* #__PURE__ */React.createElement(wcComponents.TextInput, {
id: 'lkn_ccno',
}), /*#__PURE__*/React.createElement(wcComponents.TextInput, {
id: "lkn_ccno",
label: lknCCTranslationsCielo.cardNumber,
value: creditObject.lkn_ccno,
onChange: value => {
updateCreditObject('lkn_ccno', formatCreditCardNumber(value))
updateCreditObject('lkn_ccno', formatCreditCardNumber(value));
},
required: true
}), /* #__PURE__ */React.createElement(wcComponents.TextInput, {
id: 'lkn_cc_expdate',
}), /*#__PURE__*/React.createElement(wcComponents.TextInput, {
id: "lkn_cc_expdate",
label: lknCCTranslationsCielo.cardExpiryDate,
value: creditObject.lkn_cc_expdate,
onChange: value => {
updateCreditObject('lkn_cc_expdate', value)
updateCreditObject('lkn_cc_expdate', value);
},
required: true
}), /* #__PURE__ */React.createElement(wcComponents.TextInput, {
id: 'lkn_cc_cvc',
}), /*#__PURE__*/React.createElement(wcComponents.TextInput, {
id: "lkn_cc_cvc",
label: lknCCTranslationsCielo.securityCode,
value: creditObject.lkn_cc_cvc,
onChange: value => {
updateCreditObject('lkn_cc_cvc', value)
updateCreditObject('lkn_cc_cvc', value);
},
required: true
}), /* #__PURE__ */React.createElement('div', {
}), /*#__PURE__*/React.createElement("div", {
style: {
marginBottom: '20px'
}
}), lknCCActiveInstallmentCielo === 'yes' && /* #__PURE__ */React.createElement(wcComponents.SortSelect, {
id: 'lkn_cc_installments',
}), lknCCActiveInstallmentCielo === 'yes' && /*#__PURE__*/React.createElement(wcComponents.SortSelect, {
id: "lkn_cc_installments",
label: lknCCTranslationsCielo.installments,
value: creditObject.lkn_cc_installments,
onChange: event => {
updateCreditObject('lkn_cc_installments', event.target.value)
updateCreditObject('lkn_cc_installments', event.target.value);
},
options
}))
}
options: options
}));
};
const Lkn_CC_Block_Gateway_Cielo = {
name: 'lkn_cielo_credit',
label: lknCCLabelCielo,
Expand All @@ -205,5 +243,5 @@ const Lkn_CC_Block_Gateway_Cielo = {
supports: {
features: lknCCSettingsCielo.supports
}
}
window.wc.wcBlocksRegistry.registerPaymentMethod(Lkn_CC_Block_Gateway_Cielo)
};
window.wc.wcBlocksRegistry.registerPaymentMethod(Lkn_CC_Block_Gateway_Cielo);
Loading
Loading