diff --git a/functions/assets/onload-expression.js b/functions/assets/onload-expression.js new file mode 100644 index 0000000..9a337b7 --- /dev/null +++ b/functions/assets/onload-expression.js @@ -0,0 +1,25 @@ +; (function () { + window._galaxyHashcard = function (card) { + return new Promise(function (resolve, reject) { + // https://docs.galaxpay.com.br/tokenizacao-cartao-js + const token = window._galaxPayPublicToken + // const environment = false // !window._galaxPaySandbox // false = sandbox, true = production + const isSandbox = window._galaxPaySandbox + const galaxPay = new GalaxPay(token) + if (isSandbox) { + galaxPay._setApiUrl('https://api.sandbox.cloud.galaxpay.com.br/v2') + } + const galaxpayCard = galaxPay.newCard({ + number: card.number, + holder: card.name, + expiresAt: '20' + card.year.toString() + '-' + card.month.toString(), + cvv: card.cvc + }) + galaxPay.hashCreditCard(galaxpayCard, function (hash) { + resolve(hash) + }, function (error) { + reject(error) + }) + }) + } +}()) diff --git a/functions/lib/galaxpay/update-subscription.js b/functions/lib/galaxpay/update-subscription.js index 23157ca..22b93d4 100644 --- a/functions/lib/galaxpay/update-subscription.js +++ b/functions/lib/galaxpay/update-subscription.js @@ -59,7 +59,10 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig serviceFind => serviceFind.service_code === shippingLineOriginal.app.service_code ) - return service || sameApp.response?.shipping_services[0] + return { + app: sameApp, + service: service || sameApp.response?.shipping_services[0] + } } else { let minPrice = result[0]?.response?.shipping_services[0]?.shipping_line?.total_price const indexPosition = { app: 0, service: 0 } @@ -70,7 +73,7 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig const service = app.response?.shipping_services[j] if (service.service_code === shippingLineOriginal.app.service_code) { - return service + return { app, service } } else if (minPrice > service?.shipping_line?.total_price) { minPrice = service?.shipping_line?.total_price indexPosition.app = i @@ -78,7 +81,10 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig } } } - return result[indexPosition.app]?.response?.shipping_services[indexPosition.service] + return { + app: result[indexPosition.app], + service: result[indexPosition.app]?.response?.shipping_services[indexPosition.service] + } } } catch (err) { console.error(err) @@ -103,7 +109,7 @@ const updateValueSubscriptionGalaxpay = async (galaxpayAxios, subscriptionId, va } const checkAndUpdateSubscriptionGalaxpay = async (appSdk, storeId, auth, subscriptionId, amount, items, plan, oldValue, shippingLine) => { - const value = await checkItemsAndRecalculeteOrder( + const { value } = await checkItemsAndRecalculeteOrder( { ...amount }, [...items], { ...plan }, @@ -150,13 +156,21 @@ const checkItemsAndRecalculeteOrder = async (amount, items, plan, newItem, shipp if (subtotal > 0) { if (shippingLine && storeId && appSdk && auth) { - const service = await getNewFreight(storeId, items, shippingLine.to, subtotal, shippingLine, appSdk, auth) - - if (service && service?.shipping_line?.total_price) { - shippingLine = { ...shippingLine, ...service.shipping_line } - delete shippingLine._id + const { app, service } = await getNewFreight(storeId, items, shippingLine.to, subtotal, shippingLine, appSdk, auth) + if (service && service?.service_code !== shippingLine.app.service_code) { + shippingLine = { + ...service.shipping_line, + app: { + _id: app._id, + service_code: service?.service_code, + label: service?.label + } + } amount.freight = service.shipping_line.total_price } + delete shippingLine._id + delete shippingLine.tracking_codes + delete shippingLine.invoices } amount.subtotal = subtotal @@ -173,10 +187,13 @@ const checkItemsAndRecalculeteOrder = async (amount, items, plan, newItem, shipp amount.discount = planDiscount || amount.discount || 0 amount.total -= amount.discount - return amount.total > 0 ? Math.floor((amount.total).toFixed(2) * 1000) / 10 : 0 + return { + value: amount.total > 0 ? Math.floor((amount.total).toFixed(2) * 1000) / 10 : 0, + shippingLine, + } } - return 0 + return { value: 0, shippingLine } } const getSubscriptionsByListMyIds = async ( diff --git a/functions/routes/ecom/webhook.js b/functions/routes/ecom/webhook.js index 7310498..5661124 100644 --- a/functions/routes/ecom/webhook.js +++ b/functions/routes/ecom/webhook.js @@ -69,7 +69,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, storeId) const collectionSubscription = admin.firestore().collection('subscriptions') - if (trigger.resource === 'orders' && trigger.body.status === 'cancelled') { + if (trigger.resource === 'orders' && trigger.body?.status === 'cancelled') { console.log('>>> ', JSON.stringify(trigger.body)) galaxpayAxios.preparing .then(async () => { @@ -151,8 +151,9 @@ exports.post = async ({ appSdk, admin }, req, res) => { }) }) }) - } else if (trigger.resource === 'orders' && trigger.body.status !== 'cancelled' && - trigger.action !== 'create' && trigger.fields.includes('items')) { + } else if (trigger.resource === 'orders' && trigger.body.status + && trigger.body.status !== 'cancelled' && trigger.action !== 'create' + && trigger.fields.includes('items')) { console.log('>> ', JSON.stringify(trigger)) // When the original order is edited try { @@ -163,7 +164,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { const { plan } = docSubscription // Calculates new value - const newValue = await checkItemsAndRecalculeteOrder( + const { value: newValue } = await checkItemsAndRecalculeteOrder( { ...amount }, [...items], { ...plan }, @@ -300,7 +301,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { }) // Calculates new value - const newSubscriptionValue = await checkItemsAndRecalculeteOrder( + const { value: newSubscriptionValue } = await checkItemsAndRecalculeteOrder( order.amount, order.items, docSubscription.plan, diff --git a/functions/routes/galaxpay/webhooks.js b/functions/routes/galaxpay/webhooks.js index 06a7183..2ffa520 100644 --- a/functions/routes/galaxpay/webhooks.js +++ b/functions/routes/galaxpay/webhooks.js @@ -2,11 +2,16 @@ const { parseId, parseStatus, parsePeriodicity } = require('../../lib/galaxpay/p const { checkAndUpdateSubscriptionGalaxpay, checkItemsAndRecalculeteOrder, - compareDocItemsWithOrder + compareDocItemsWithOrder, + updateValueSubscriptionGalaxpay } = require('../../lib/galaxpay/update-subscription') -const { createItemsAndAmount } = require('./../../lib/firestore/utils') +const { + createItemsAndAmount, + updateDocSubscription +} = require('./../../lib/firestore/utils') const getAppData = require('./../../lib/store-api/get-app-data') const GalaxpayAxios = require('./../../lib/galaxpay/create-access') +const ecomUtils = require('@ecomplus/utils') exports.post = async ({ appSdk, admin }, req, res) => { // const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, appData.galaxpay_sandbox) @@ -104,7 +109,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { const domain = oldOrder.domain const amount = oldOrder.amount const shippingLines = oldOrder.shipping_lines - const shippingMethodLabel = oldOrder.shipping_method_label + let shippingMethodLabel = oldOrder.shipping_method_label const paymentMethodLabel = oldOrder.payment_method_label const originalTransaction = oldOrder.transactions[0] const quantity = installment @@ -124,9 +129,16 @@ exports.post = async ({ appSdk, admin }, req, res) => { compareDocItemsWithOrder(itemsAndAmount, items, amount, GalaxPayTransactionValue) } // recalculate order - const shippingLine = shippingLines[0] - await checkItemsAndRecalculeteOrder(amount, items, plan, null, shippingLine, storeId, appSdk, auth) - shippingLines[0] = shippingLine + const shippingLine = { ...shippingLines[0] } + // console.log('>>SL1 ', JSON.stringify(shippingLine)) + + const { shippingLine: newShippingLine } = await checkItemsAndRecalculeteOrder(amount, items, plan, null, shippingLine, storeId, appSdk, auth) + shippingLines[0] = { + _id: ecomUtils.randomObjectId(), + ...newShippingLine + } + shippingMethodLabel = newShippingLine.label + if (amount.balance) { delete amount.balance @@ -169,9 +181,11 @@ exports.post = async ({ appSdk, admin }, req, res) => { ? plan.discount.type === 'percentage' || plan.discount.percentage : null let notes = `Parcela #${quantity} desconto de ${planPergentage ? '' : 'R$'}` - notes += ` ${plan.discount.value} ${planPergentage ? '%' : ''}` - notes += ` sobre ${plan.discount.apply_at}` - notes += ` referente à ${subscriptionLabel} ${periodicity}` + if (planPergentage) { + notes += ` ${plan?.discount?.value || ''} ${planPergentage ? '%' : ''}` + notes += ` sobre ${plan?.discount?.apply_at || ''}` + notes += ` referente à ${subscriptionLabel} ${periodicity}` + } body = { opened_at: new Date().toISOString(), @@ -205,6 +219,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { .then(({ response }) => { const { result } = response.data if (!result.length) { + // console.log('>>Test ', JSON.stringify(body)) appSdk.apiRequest(storeId, 'orders.json', 'POST', body, auth) .then(({ response }) => { // console.log('> Created new order API') @@ -309,7 +324,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { const oldValue = GalaxPayTransactionValue // Calculates new value - const newValue = await checkItemsAndRecalculeteOrder( + const { value: newValue } = await checkItemsAndRecalculeteOrder( order.amount, order.items, plan, @@ -539,7 +554,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { compareDocItemsWithOrder(itemsAndAmount, order.items, order.amount, GalaxPayTransactionValue) } - await checkItemsAndRecalculeteOrder( + const { value } = await checkItemsAndRecalculeteOrder( order.amount, order.items, plan, @@ -558,6 +573,33 @@ exports.post = async ({ appSdk, admin }, req, res) => { }, { merge: true } ) + + try{ + const appData = await getAppData({ appSdk, storeId, auth }) + + const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, storeId) + await galaxpayAxios.preparing + + let { data } = await galaxpayAxios.axios + .get(`/transactions?galaxPayIds=${GalaxPayTransaction.galaxPayId}&startAt=0&limit=1`) + + const total = itemsAndAmount?.amount?.total && Math.floor((itemsAndAmount?.amount?.total).toFixed(2) * 100) + // console.log('>> ', data?.Transactions[0]?.value, ' ', total , ' ', JSON.stringify(data)) + const hasUpdateValue = total && data?.Transactions[0]?.value && total !== data?.Transactions[0]?.value + if (hasUpdateValue) { + const resp = await updateValueSubscriptionGalaxpay(galaxpayAxios, subscriptionId, total) + if (resp) { + console.log('> Successful signature edit on Galax Pay') + const body = { itemsAndAmount } + if (total) { + body.value = total + } + await updateDocSubscription(collectionSubscription, body, subscriptionId) + } + } + } catch (error){ + console.error(error) + } res.sendStatus(200) } else {