diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 329360d..4731e7e 100755 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -46,7 +46,7 @@ jobs: uses: mathieudutour/github-tag-action@v6.0 with: github_token: ${{ secrets.GITHUB_TOKEN }} - custom_tag: "1.11.0" + custom_tag: "1.11.1" # Generate new release - name: Generate new Release diff --git a/CHANGELOG.md b/CHANGELOG.md index a06af2f..5a6a386 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.txt b/README.txt index 92eeb50..85fc774 100755 --- a/README.txt +++ b/README.txt @@ -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 @@ -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. diff --git a/lkn-wc-gateway-cielo.php b/lkn-wc-gateway-cielo.php index c422f01..e7081b9 100755 --- a/lkn-wc-gateway-cielo.php +++ b/lkn-wc-gateway-cielo.php @@ -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 @@ -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/'); diff --git a/resources/js/creditCard/lknCieloCredit.js b/resources/js/creditCard/lknCieloCredit.js index a80e8c8..3558378 100755 --- a/resources/js/creditCard/lknCieloCredit.js +++ b/resources/js/creditCard/lknCieloCredit.js @@ -1,35 +1,35 @@ -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': @@ -37,92 +37,130 @@ const lknCCContentCielo = props => { 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, @@ -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, @@ -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); \ No newline at end of file diff --git a/resources/js/creditCard/lknCieloCredit.tsx b/resources/js/creditCard/lknCieloCredit.tsx index b072ed4..7cee109 100755 --- a/resources/js/creditCard/lknCieloCredit.tsx +++ b/resources/js/creditCard/lknCieloCredit.tsx @@ -76,50 +76,93 @@ const lknCCContentCielo = (props) => { const wcComponents = window.wc.blocksComponents - window.wp.element.useEffect(() => { - const installmentMin = 5; - // Verifica se 'lknCCActiveInstallmentCielo' é 'yes' e o valor total é maior que 10 + 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; - formatedInterest = new Intl.NumberFormat('pt-br', { style: 'currency', currency: 'BRL' }).format(nextInstallmentAmount) + nextInstallmentAmount = (lknCCTotalCartCielo + lknCCTotalCartCielo * (parseFloat(installmentObj.interest) / 100)) / index + formatedInterest = new Intl.NumberFormat('pt-br', { + style: 'currency', + currency: 'BRL' + }).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)` } - ]) + 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(() => { @@ -158,7 +201,7 @@ const lknCCContentCielo = (props) => { emitResponse.responseTypes.ERROR, emitResponse.responseTypes.SUCCESS, onPaymentSetup - ]); + ]); return ( <> diff --git a/resources/js/debitCard/lknCieloDebit.js b/resources/js/debitCard/lknCieloDebit.js index fc5f83c..04faaa3 100755 --- a/resources/js/debitCard/lknCieloDebit.js +++ b/resources/js/debitCard/lknCieloDebit.js @@ -1,64 +1,64 @@ -const lknDCsettingsCielo = window.wc.wcSettings.getSetting('lkn_cielo_debit_data', {}) -const lknDCLabelCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.title) -const lknDCAccessTokenCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.accessToken) -const lknDCActiveInstallmentCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.activeInstallment) -const lknDCUrlCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.url) -const lknDCTotalCartCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.totalCart) -const lknDCOrderNumberCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.orderNumber) -const lknDCDirScript3DSCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.dirScript3DS) -const lknDCInstallmentLimitCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.installmentLimit) -const lknDCDirScriptConfig3DSCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.dirScriptConfig3DS) -const lknDCTranslationsDebitCielo = lknDCsettingsCielo.translations -const lknDCNonceCieloDebit = lknDCsettingsCielo.nonceCieloDebit -const lknDCTranslationsCielo = lknDCsettingsCielo.translations +const lknDCsettingsCielo = window.wc.wcSettings.getSetting('lkn_cielo_debit_data', {}); +const lknDCLabelCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.title); +const lknDCAccessTokenCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.accessToken); +const lknDCActiveInstallmentCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.activeInstallment); +const lknDCUrlCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.url); +const lknDCTotalCartCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.totalCart); +const lknDCOrderNumberCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.orderNumber); +const lknDCDirScript3DSCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.dirScript3DS); +const lknDCInstallmentLimitCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.installmentLimit); +const lknDCDirScriptConfig3DSCielo = window.wp.htmlEntities.decodeEntities(lknDCsettingsCielo.dirScriptConfig3DS); +const lknDCTranslationsDebitCielo = lknDCsettingsCielo.translations; +const lknDCNonceCieloDebit = lknDCsettingsCielo.nonceCieloDebit; +const lknDCTranslationsCielo = lknDCsettingsCielo.translations; const lknDCHideCheckoutButton = () => { - const lknDCElement = document.querySelectorAll('.wc-block-components-checkout-place-order-button') + const lknDCElement = document.querySelectorAll('.wc-block-components-checkout-place-order-button'); if (lknDCElement && lknDCElement[0]) { - lknDCElement[0].style.display = 'none' + lknDCElement[0].style.display = 'none'; } -} +}; const lknDCInitCieloPaymentForm = () => { - document.addEventListener('DOMContentLoaded', lknDCHideCheckoutButton) - lknDCHideCheckoutButton() + document.addEventListener('DOMContentLoaded', lknDCHideCheckoutButton); + lknDCHideCheckoutButton(); // Load Cielo 3DS BpMPI Script - const scriptUrlBpmpi = lknDCDirScript3DSCielo - const existingScriptBpmpi = document.querySelector(`script[src="${scriptUrlBpmpi}"]`) + const scriptUrlBpmpi = lknDCDirScript3DSCielo; + const existingScriptBpmpi = document.querySelector(`script[src="${scriptUrlBpmpi}"]`); if (!existingScriptBpmpi) { - const scriptBpmpi = document.createElement('script') - scriptBpmpi.src = scriptUrlBpmpi - scriptBpmpi.async = true - document.body.appendChild(scriptBpmpi) + const scriptBpmpi = document.createElement('script'); + scriptBpmpi.src = scriptUrlBpmpi; + scriptBpmpi.async = true; + document.body.appendChild(scriptBpmpi); } // Load Cielo 3DS Config Script - const scriptUrl = lknDCDirScriptConfig3DSCielo - const existingScript = document.querySelector(`script[src="${scriptUrl}"]`) + const scriptUrl = lknDCDirScriptConfig3DSCielo; + const existingScript = document.querySelector(`script[src="${scriptUrl}"]`); if (!existingScript) { - const script = document.createElement('script') - script.src = scriptUrl - script.async = true - document.body.appendChild(script) + const script = document.createElement('script'); + script.src = scriptUrl; + script.async = true; + document.body.appendChild(script); } -} +}; const lknDCContentCielo = props => { - const wcComponents = window.wc.blocksComponents + const wcComponents = window.wc.blocksComponents; const { eventRegistration, emitResponse - } = props + } = props; const { onPaymentSetup - } = eventRegistration - const [options, setOptions] = window.wp.element.useState([]) - const [cardBinState, setCardBinState] = window.wp.element.useState(0) + } = eventRegistration; + const [options, setOptions] = window.wp.element.useState([]); + const [cardBinState, setCardBinState] = window.wp.element.useState(0); const [cardTypeOptions, setCardTypeOptions] = window.wp.element.useState([{ key: 'Credit', label: lknDCTranslationsCielo.creditCard }, { key: 'Debit', label: lknDCTranslationsCielo.debitCard - }]) + }]); const [debitObject, setdebitObject] = window.wp.element.useState({ lkn_dc_cardholder_name: '', lkn_dcno: '', @@ -67,16 +67,15 @@ const lknDCContentCielo = props => { lkn_cc_installments: '1', // Definir padrão como 1 parcela lkn_cc_type: 'Credit' - }) + }); const formatDebitCardNumber = value => { - let _cleanedValue$replace - if ((value === null || value === void 0 ? void 0 : value.length) > 24) return debitObject.lkn_dcno + if (value?.length > 24) return debitObject.lkn_dcno; // Remove caracteres não numéricos - const cleanedValue = value === null || value === void 0 ? void 0 : value.replace(/\D/g, '') + const cleanedValue = value?.replace(/\D/g, ''); // Adiciona espaços a cada quatro dígitos - const formattedValue = cleanedValue === null || cleanedValue === void 0 || (_cleanedValue$replace = cleanedValue.replace(/(.{4})/g, '$1 ')) === null || _cleanedValue$replace === void 0 ? void 0 : _cleanedValue$replace.trim() - return formattedValue - } + const formattedValue = cleanedValue?.replace(/(.{4})/g, '$1 ')?.trim(); + return formattedValue; + }; const updatedebitObject = (key, value) => { switch (key) { case 'lkn_dc_cardholder_name': @@ -84,68 +83,68 @@ const lknDCContentCielo = props => { setdebitObject({ ...debitObject, [key]: value - }) - break + }); + break; case 'lkn_dc_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 setdebitObject({ ...debitObject, [key]: formattedValue - }) + }); } - return + return; case 'lkn_dc_cvc': - if (value.length > 8) return + if (value.length > 8) return; case 'lkn_dcno': if (value.length > 7) { - const cardBin = value.replace(' ', '').substring(0, 6) - const url = window.location.origin + '/wp-json/lknWCGatewayCielo/checkCard?cardbin=' + cardBin + var cardBin = value.replace(' ', '').substring(0, 6); + var url = window.location.origin + '/wp-json/lknWCGatewayCielo/checkCard?cardbin=' + cardBin; if (cardBin !== cardBinState) { - setCardBinState(cardBin) // Mova o setCardBinState para antes da requisição + setCardBinState(cardBin); // Mova o setCardBinState para antes da requisição fetch(url, { method: 'GET', headers: { - Accept: 'application/json' + 'Accept': 'application/json' } }).then(response => { if (!response.ok) { - throw new Error('Network response was not ok ' + response.statusText) + throw new Error('Network response was not ok ' + response.statusText); } - return response.json() + return response.json(); }).then(data => { - if (data.CardType == 'Crédito') { + if ('Crédito' == data.CardType) { setCardTypeOptions([{ key: 'Credit', label: lknDCTranslationsCielo.creditCard - }]) + }]); setdebitObject(prevState => ({ ...prevState, lkn_cc_type: 'Credit' - })) - } else if (data.CardType == 'Débito') { + })); + } else if ('Débito' == data.CardType) { setCardTypeOptions([{ key: 'Debit', label: lknDCTranslationsCielo.debitCard - }]) + }]); setdebitObject(prevState => ({ ...prevState, lkn_cc_type: 'Debit' - })) + })); } else { setCardTypeOptions([{ key: 'Credit', @@ -153,89 +152,89 @@ const lknDCContentCielo = props => { }, { key: 'Debit', label: lknDCTranslationsCielo.debitCard - }]) + }]); } }).catch(error => { - console.error('Erro:', error) - }) + console.error('Erro:', error); + }); } setdebitObject(prevState => ({ ...prevState, lkn_dcno: value - })) + })); } - break + break; default: - break + break; } setdebitObject({ ...debitObject, [key]: value - }) - } + }); + }; window.wp.element.useEffect(() => { - const lknDCElement = document.querySelectorAll('.wc-block-components-checkout-place-order-button') + const lknDCElement = document.querySelectorAll('.wc-block-components-checkout-place-order-button'); if (lknDCElement && lknDCElement[0]) { // Hides the checkout button on cielo debit select - lknDCElement[0].style.display = 'none' + lknDCElement[0].style.display = 'none'; // Shows the checkout button on payment change return () => { - lknDCElement[0].style.display = '' - } + lknDCElement[0].style.display = ''; + }; } - }) + }); const handleButtonClick = () => { // Verifica se todos os campos do debitObject estão preenchidos - const allFieldsFilled = Object.values(debitObject).every(field => field.trim() !== '') + const allFieldsFilled = Object.values(debitObject).every(field => field.trim() !== ''); // Seleciona os lknDCElements dos campos de entrada - const cardNumberInput = document.getElementById('lkn_dcno') - const expDateInput = document.getElementById('lkn_dc_expdate') - const cvvInput = document.getElementById('lkn_dc_cvc') - const cardHolder = document.getElementById('lkn_dc_cardholder_name') + const cardNumberInput = document.getElementById('lkn_dcno'); + const expDateInput = document.getElementById('lkn_dc_expdate'); + const cvvInput = document.getElementById('lkn_dc_cvc'); + const cardHolder = document.getElementById('lkn_dc_cardholder_name'); // Remove classes de erro e mensagens de validação existentes - cardNumberInput === null || cardNumberInput === void 0 || cardNumberInput.classList.remove('has-error') - expDateInput === null || expDateInput === void 0 || expDateInput.classList.remove('has-error') - cvvInput === null || cvvInput === void 0 || cvvInput.classList.remove('has-error') - cardHolder === null || cardHolder === void 0 || cardHolder.classList.remove('has-error') + cardNumberInput?.classList.remove('has-error'); + expDateInput?.classList.remove('has-error'); + cvvInput?.classList.remove('has-error'); + cardHolder?.classList.remove('has-error'); if (allFieldsFilled) { - lknDCProccessButton() + lknDCProccessButton(); } else { // Adiciona classes de erro aos campos vazios if (debitObject.lkn_dc_cardholder_name.trim() === '') { - const parentDiv = cardHolder === null || cardHolder === void 0 ? void 0 : cardHolder.parentElement - parentDiv === null || parentDiv === void 0 || parentDiv.classList.add('has-error') + const parentDiv = cardHolder?.parentElement; + parentDiv?.classList.add('has-error'); } if (debitObject.lkn_dcno.trim() === '') { - const parentDiv = cardNumberInput === null || cardNumberInput === void 0 ? void 0 : cardNumberInput.parentElement - parentDiv === null || parentDiv === void 0 || parentDiv.classList.add('has-error') + const parentDiv = cardNumberInput?.parentElement; + parentDiv?.classList.add('has-error'); } if (debitObject.lkn_dc_expdate.trim() === '') { - const parentDiv = expDateInput === null || expDateInput === void 0 ? void 0 : expDateInput.parentElement - parentDiv === null || parentDiv === void 0 || parentDiv.classList.add('has-error') + const parentDiv = expDateInput?.parentElement; + parentDiv?.classList.add('has-error'); } if (debitObject.lkn_dc_cvc.trim() === '') { - const parentDiv = cvvInput === null || cvvInput === void 0 ? void 0 : cvvInput.parentElement - parentDiv === null || parentDiv === void 0 || parentDiv.classList.add('has-error') + const parentDiv = cvvInput?.parentElement; + parentDiv?.classList.add('has-error'); } } - } + }; window.wp.element.useEffect(() => { - lknDCInitCieloPaymentForm() + lknDCInitCieloPaymentForm(); const unsubscribe = onPaymentSetup(async () => { - const Button3dsEnviar = document.querySelectorAll('.wc-block-components-checkout-place-order-button')[0].closest('form') - const paymentCavv = Button3dsEnviar === null || Button3dsEnviar === void 0 ? void 0 : Button3dsEnviar.getAttribute('data-payment-cavv') - const paymentEci = Button3dsEnviar === null || Button3dsEnviar === void 0 ? void 0 : Button3dsEnviar.getAttribute('data-payment-eci') - const paymentReferenceId = Button3dsEnviar === null || Button3dsEnviar === void 0 ? void 0 : Button3dsEnviar.getAttribute('data-payment-ref_id') - const paymentVersion = Button3dsEnviar === null || Button3dsEnviar === void 0 ? void 0 : Button3dsEnviar.getAttribute('data-payment-version') - const paymentXid = Button3dsEnviar === null || Button3dsEnviar === void 0 ? void 0 : Button3dsEnviar.getAttribute('data-payment-xid') + const Button3dsEnviar = document.querySelectorAll('.wc-block-components-checkout-place-order-button')[0].closest('form'); + const paymentCavv = Button3dsEnviar?.getAttribute('data-payment-cavv'); + const paymentEci = Button3dsEnviar?.getAttribute('data-payment-eci'); + const paymentReferenceId = Button3dsEnviar?.getAttribute('data-payment-ref_id'); + const paymentVersion = Button3dsEnviar?.getAttribute('data-payment-version'); + const paymentXid = Button3dsEnviar?.getAttribute('data-payment-xid'); return { type: emitResponse.responseTypes.SUCCESS, meta: { paymentMethodData: { - // TODO Corrigir campos faltando + //TODO Corrigir campos faltando lkn_dcno: debitObject.lkn_dcno, lkn_dc_cardholder_name: debitObject.lkn_dc_cardholder_name, lkn_dc_expdate: debitObject.lkn_dc_expdate, @@ -250,210 +249,251 @@ const lknDCContentCielo = props => { lkn_cc_type: debitObject.lkn_cc_type } } - } - }) + }; + }); // Cancela a inscrição quando este componente é desmontado. return () => { - unsubscribe() - } - }, [debitObject, emitResponse.responseTypes.ERROR, emitResponse.responseTypes.SUCCESS, onPaymentSetup]) - window.wp.element.useEffect(() => { - const installmentMin = 5 + unsubscribe(); + }; + }, [debitObject, emitResponse.responseTypes.ERROR, emitResponse.responseTypes.SUCCESS, onPaymentSetup]); + const calculateInstallments = lknDCTotalCartCielo => { + const installmentMin = 5; // Verifica se 'lknCCActiveInstallmentCielo' é 'yes' e o valor total é maior que 10 if (lknDCActiveInstallmentCielo === 'yes' && lknDCTotalCartCielo > 10) { - const maxInstallments = lknDCInstallmentLimitCielo // Limita o parcelamento até 12 vezes, deixei fixo para teste + const maxInstallments = lknDCInstallmentLimitCielo; // Limita o parcelamento até 12 vezes, deixei fixo para teste for (let index = 1; index <= maxInstallments; index++) { const installmentAmount = (lknDCTotalCartCielo / index).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 - }) - const nextInstallmentAmount = lknDCTotalCartCielo / index + }); + const nextInstallmentAmount = lknDCTotalCartCielo / index; if (nextInstallmentAmount < installmentMin) { - break + break; } setOptions(prevOptions => [...prevOptions, { key: index, label: `${index}x de R$ ${installmentAmount} sem juros` - }]) + }]); } } else { setOptions(prevOptions => [...prevOptions, { key: '1', label: `1x de R$ ${lknDCTotalCartCielo} (à vista)` - }]) + }]); } - }, []) - 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_dc_cardholder_name', + }; + window.wp.element.useEffect(() => { + calculateInstallments(lknDCTotalCartCielo); + 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 valorNumerico = targetNode.textContent.replace(/[^\d,]/g, ''); + + // Substituir a vírgula por um ponto + valorNumerico = valorNumerico.replace(',', '.'); + + // Converter para número + valorNumerico = parseFloat(valorNumerico); + calculateInstallments(valorNumerico); + }; + 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); + }, []); + 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_dc_cardholder_name", label: lknDCTranslationsDebitCielo.cardHolder, value: debitObject.lkn_dc_cardholder_name, onChange: value => { - updatedebitObject('lkn_dc_cardholder_name', value) + updatedebitObject('lkn_dc_cardholder_name', value); }, required: true - }), /* #__PURE__ */React.createElement(wcComponents.TextInput, { - id: 'lkn_dcno', + }), /*#__PURE__*/React.createElement(wcComponents.TextInput, { + id: "lkn_dcno", label: lknDCTranslationsDebitCielo.cardNumber, value: debitObject.lkn_dcno, onChange: value => { - updatedebitObject('lkn_dcno', formatDebitCardNumber(value)) + updatedebitObject('lkn_dcno', formatDebitCardNumber(value)); }, required: true - }), /* #__PURE__ */React.createElement(wcComponents.TextInput, { - id: 'lkn_dc_expdate', + }), /*#__PURE__*/React.createElement(wcComponents.TextInput, { + id: "lkn_dc_expdate", label: lknDCTranslationsDebitCielo.cardExpiryDate, value: debitObject.lkn_dc_expdate, onChange: value => { - updatedebitObject('lkn_dc_expdate', value) + updatedebitObject('lkn_dc_expdate', value); }, required: true - }), /* #__PURE__ */React.createElement(wcComponents.TextInput, { - id: 'lkn_dc_cvc', + }), /*#__PURE__*/React.createElement(wcComponents.TextInput, { + id: "lkn_dc_cvc", label: lknDCTranslationsDebitCielo.securityCode, value: debitObject.lkn_dc_cvc, onChange: value => { - updatedebitObject('lkn_dc_cvc', value) + updatedebitObject('lkn_dc_cvc', value); }, required: true - }), /* #__PURE__ */React.createElement('div', { + }), /*#__PURE__*/React.createElement("div", { style: { marginBottom: '30px' } - }), /* #__PURE__ */React.createElement(wcComponents.SortSelect, { - id: 'lkn_cc_type', + }), /*#__PURE__*/React.createElement(wcComponents.SortSelect, { + id: "lkn_cc_type", label: lknDCTranslationsCielo.cardType, value: debitObject.lkn_cc_type, onChange: event => { - updatedebitObject('lkn_cc_type', event.target.value) + updatedebitObject('lkn_cc_type', event.target.value); }, options: cardTypeOptions - }), /* #__PURE__ */React.createElement('div', { + }), /*#__PURE__*/React.createElement("div", { style: { marginBottom: '30px' } - }), lknDCActiveInstallmentCielo === 'yes' && debitObject.lkn_cc_type == 'Credit' && /* #__PURE__ */React.createElement(wcComponents.SortSelect, { - id: 'lkn_cc_installments', + }), lknDCActiveInstallmentCielo === 'yes' && debitObject.lkn_cc_type == 'Credit' && /*#__PURE__*/React.createElement(wcComponents.SortSelect, { + id: "lkn_cc_installments", label: lknDCTranslationsCielo.cardType, value: debitObject.lkn_cc_installments, onChange: event => { - updatedebitObject('lkn_cc_installments', event.target.value) + updatedebitObject('lkn_cc_installments', event.target.value); }, - options - }), /* #__PURE__ */React.createElement('div', { + options: options + }), /*#__PURE__*/React.createElement("div", { style: { marginBottom: '30px' } - }), /* #__PURE__ */React.createElement('div', { + }), /*#__PURE__*/React.createElement("div", { style: { display: 'flex', justifyContent: 'center' } - }, /* #__PURE__ */React.createElement(wcComponents.Button, { - id: 'sendOrder', + }, /*#__PURE__*/React.createElement(wcComponents.Button, { + id: "sendOrder", onClick: handleButtonClick - }, /* #__PURE__ */React.createElement('span', null, 'Finalizar pedido'))), /* #__PURE__ */React.createElement('div', { + }, /*#__PURE__*/React.createElement("span", null, "Finalizar pedido"))), /*#__PURE__*/React.createElement("div", { style: { marginBottom: '20px' } - }), /* #__PURE__ */React.createElement('div', null, /* #__PURE__ */React.createElement('input', { - type: 'hidden', - name: 'lkn_auth_enabled', - className: 'bpmpi_auth', - value: 'true' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - name: 'lkn_auth_enabled_notifyonly', - className: 'bpmpi_auth_notifyonly', - value: 'true' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - name: 'lkn_access_token', - className: 'bpmpi_accesstoken', + }), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("input", { + type: "hidden", + name: "lkn_auth_enabled", + className: "bpmpi_auth", + value: "true" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + name: "lkn_auth_enabled_notifyonly", + className: "bpmpi_auth_notifyonly", + value: "true" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + name: "lkn_access_token", + className: "bpmpi_accesstoken", value: lknDCAccessTokenCielo - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - size: '50', - name: 'lkn_order_number', - className: 'bpmpi_ordernumber', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + size: "50", + name: "lkn_order_number", + className: "bpmpi_ordernumber", value: lknDCOrderNumberCielo - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - name: 'lkn_currency', - className: 'bpmpi_currency', - value: 'BRL' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - size: '50', - className: 'bpmpi_merchant_url', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + name: "lkn_currency", + className: "bpmpi_currency", + value: "BRL" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + size: "50", + className: "bpmpi_merchant_url", value: lknDCUrlCielo - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - size: '50', - id: 'lkn_cielo_3ds_value', - name: 'lkn_amount', - className: 'bpmpi_totalamount', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + size: "50", + id: "lkn_cielo_3ds_value", + name: "lkn_amount", + className: "bpmpi_totalamount", value: lknDCTotalCartCielo - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - size: '2', - name: 'lkn_installments', - className: 'bpmpi_installments', - value: '1' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - name: 'lkn_payment_method', - className: 'bpmpi_paymentmethod', - value: 'Debit' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_bpmpi_cardnumber', - className: 'bpmpi_cardnumber' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_bpmpi_expmonth', - maxLength: '2', - name: 'lkn_card_expiry_month', - className: 'bpmpi_cardexpirationmonth' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_bpmpi_expyear', - maxLength: '4', - name: 'lkn_card_expiry_year', - className: 'bpmpi_cardexpirationyear' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - size: '50', - className: 'bpmpi_order_productcode', - value: 'PHY' - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_cavv', - name: 'lkn_cielo_3ds_cavv', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + size: "2", + name: "lkn_installments", + className: "bpmpi_installments", + value: "1" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + name: "lkn_payment_method", + className: "bpmpi_paymentmethod", + value: "Debit" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_bpmpi_cardnumber", + className: "bpmpi_cardnumber" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_bpmpi_expmonth", + maxLength: "2", + name: "lkn_card_expiry_month", + className: "bpmpi_cardexpirationmonth" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_bpmpi_expyear", + maxLength: "4", + name: "lkn_card_expiry_year", + className: "bpmpi_cardexpirationyear" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + size: "50", + className: "bpmpi_order_productcode", + value: "PHY" + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_cavv", + name: "lkn_cielo_3ds_cavv", value: true - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_eci', - name: 'lkn_cielo_3ds_eci', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_eci", + name: "lkn_cielo_3ds_eci", value: true - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_ref_id', - name: 'lkn_cielo_3ds_ref_id', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_ref_id", + name: "lkn_cielo_3ds_ref_id", value: true - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_version', - name: 'lkn_cielo_3ds_version', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_version", + name: "lkn_cielo_3ds_version", value: true - }), /* #__PURE__ */React.createElement('input', { - type: 'hidden', - id: 'lkn_xid', - name: 'lkn_cielo_3ds_xid', + }), /*#__PURE__*/React.createElement("input", { + type: "hidden", + id: "lkn_xid", + name: "lkn_cielo_3ds_xid", value: true - }))) -} + }))); +}; const Lkn_DC_Block_Gateway_Cielo = { name: 'lkn_cielo_debit', label: lknDCLabelCielo, @@ -464,5 +504,5 @@ const Lkn_DC_Block_Gateway_Cielo = { supports: { features: lknDCsettingsCielo.supports } -} -window.wc.wcBlocksRegistry.registerPaymentMethod(Lkn_DC_Block_Gateway_Cielo) +}; +window.wc.wcBlocksRegistry.registerPaymentMethod(Lkn_DC_Block_Gateway_Cielo); \ No newline at end of file diff --git a/resources/js/debitCard/lknCieloDebit.tsx b/resources/js/debitCard/lknCieloDebit.tsx index 814bb63..e3719f5 100755 --- a/resources/js/debitCard/lknCieloDebit.tsx +++ b/resources/js/debitCard/lknCieloDebit.tsx @@ -274,7 +274,7 @@ const lknDCContentCielo = (props) => { onPaymentSetup ]); - window.wp.element.useEffect(() => { + const calculateInstallments = (lknDCTotalCartCielo) => { const installmentMin = 5; // Verifica se 'lknCCActiveInstallmentCielo' é 'yes' e o valor total é maior que 10 if (lknDCActiveInstallmentCielo === 'yes' && lknDCTotalCartCielo > 10) { @@ -303,6 +303,49 @@ const lknDCContentCielo = (props) => { { key: '1', label: `1x de R$ ${lknDCTotalCartCielo} (à vista)` } ]) } + } + + window.wp.element.useEffect(() => { + calculateInstallments(lknDCTotalCartCielo); + + 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 valorNumerico = targetNode.textContent.replace(/[^\d,]/g, ''); + + // Substituir a vírgula por um ponto + valorNumerico = valorNumerico.replace(',', '.'); + + // Converter para número + valorNumerico = parseFloat(valorNumerico); + + calculateInstallments(valorNumerico) + } + + 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); }, []) diff --git a/resources/js/frontend/lkn-cc-dc-installment.js b/resources/js/frontend/lkn-cc-dc-installment.js index b79a070..9a1fcd2 100755 --- a/resources/js/frontend/lkn-cc-dc-installment.js +++ b/resources/js/frontend/lkn-cc-dc-installment.js @@ -7,6 +7,9 @@ $('body').on('updated_checkout', lknWCCieloLoadInstallments) }) + lknWCCieloLoadInstallments() + $('body').on('updated_checkout', lknWCCieloLoadInstallments) + function lknWCCieloShowInstallments () { const installmentShow = $('#lkn_cielo_3ds_installment_show') const installmentRow = $('#lkn-cc-dc-installment-row') diff --git a/resources/js/frontend/lkn-cc-installment.js b/resources/js/frontend/lkn-cc-installment.js index 899b71b..98e8d76 100755 --- a/resources/js/frontend/lkn-cc-installment.js +++ b/resources/js/frontend/lkn-cc-installment.js @@ -7,6 +7,9 @@ $('body').on('updated_checkout', lknWCCieloLoadInstallments) }) + lknWCCieloLoadInstallments() + $('body').on('updated_checkout', lknWCCieloLoadInstallments) + function lknWCCieloLoadInstallments () { const lknInstallmentSelect = document.getElementById('lkn_cc_installments') const lknTotal = document.getElementById('lkn_cc_installment_total')