From 07fa122a3a776b502a47be679ad7d4309fa09eb1 Mon Sep 17 00:00:00 2001 From: Wisley Date: Tue, 19 Dec 2023 21:38:16 -0300 Subject: [PATCH] fix(out-of-stock-subscriptions): Cancel pending transactions for out-of-stock subscriptions --- functions/lib/galaxpay/update-subscription.js | 17 ++++++- functions/routes/ecom/webhook.js | 40 ++++++++++++++- functions/routes/galaxpay/webhooks.js | 49 +++++++++++-------- 3 files changed, 81 insertions(+), 25 deletions(-) diff --git a/functions/lib/galaxpay/update-subscription.js b/functions/lib/galaxpay/update-subscription.js index 4a360ec..34c95de 100644 --- a/functions/lib/galaxpay/update-subscription.js +++ b/functions/lib/galaxpay/update-subscription.js @@ -271,7 +271,10 @@ const getSubscriptionsByListMyIds = async ( const compareDocItemsWithOrder = (docItemsAndAmount, originalItems, originalAmount, galapayTransactionValue) => { const finalAmount = Math.floor((originalAmount.total).toFixed(2) * 1000) / 1000 - console.log(`>>Compare values: ${JSON.stringify(originalAmount)} => total: ${finalAmount} GP: ${galapayTransactionValue}`) + console.log(`>> Compare values: ${JSON.stringify(originalAmount)} total: ${finalAmount} GP: ${galapayTransactionValue}`) + console.log('>> DocItems: ', docItemsAndAmount?.items && JSON.stringify(docItemsAndAmount?.items)) + console.log('>> originalItems: ', JSON.stringify(originalItems)) + if (galapayTransactionValue !== finalAmount) { // need update itens and recalculate order let i = 0 @@ -311,11 +314,21 @@ const updateTransactionGalaxpay = async (galaxpayAxios, galaxPayId, value) => { } } +const cancellTransactionGalaxpay = async (galaxpayAxios, galaxPayId) => { + const { data } = await galaxpayAxios.axios + .delete(`/transactions/${galaxPayId}/galaxPayId`) + + if (data) { + console.log('> Transaction successfully canceled on Galax Pay#', galaxPayId) + } +} + module.exports = { checkAndUpdateSubscriptionGalaxpay, checkItemsAndRecalculeteOrder, updateValueSubscriptionGalaxpay, getSubscriptionsByListMyIds, compareDocItemsWithOrder, - updateTransactionGalaxpay + updateTransactionGalaxpay, + cancellTransactionGalaxpay } diff --git a/functions/routes/ecom/webhook.js b/functions/routes/ecom/webhook.js index 4fc1c49..7ad1048 100644 --- a/functions/routes/ecom/webhook.js +++ b/functions/routes/ecom/webhook.js @@ -9,7 +9,8 @@ const { checkItemsAndRecalculeteOrder, updateValueSubscriptionGalaxpay, getSubscriptionsByListMyIds, - updateTransactionGalaxpay + updateTransactionGalaxpay, + cancellTransactionGalaxpay } = require('../../lib/galaxpay/update-subscription') const { @@ -257,6 +258,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { ) if (galaxPaySubscriptions && galaxPaySubscriptions.length) { + console.log('>> body ', JSON.stringify(trigger.body)) let error for (let i = 0; i < galaxPaySubscriptions.length; i++) { const subscription = galaxPaySubscriptions[i] @@ -321,7 +323,10 @@ exports.post = async ({ appSdk, admin }, req, res) => { appSdk, auth ) - if (newSubscriptionValue && newSubscriptionValue !== subscription.value) { + if ( + (newSubscriptionValue && newSubscriptionValue !== subscription.value) || + (newSubscriptionValue && docSubscription.value === 0) + ) { await addItemsAndValueSubscriptionDoc( collectionSubscription, order.amount, @@ -375,6 +380,37 @@ exports.post = async ({ appSdk, admin }, req, res) => { } catch (err) { console.error(err) } + } else if (newSubscriptionValue === 0) { + console.log('>> Attempts to cancel transactions already created from the subscription: ', + order._id, ' new value is: ', newSubscriptionValue) + + await updateDocSubscription(collectionSubscription, { value: 0 }, order._id) + + let queryString = `subscriptionGalaxPayIds=${subscription.galaxPayId}` + queryString += '&status=notSend,pendingBoleto,pendingPix&order=payday.desc' + + try { + const { data: { Transactions } } = await galaxpayAxios.axios + .get(`/transactions?startAt=0&limit=100&${queryString}`) + let i = 0 + while (i < Transactions?.length) { + const transaction = Transactions[i] + if (transaction.value !== newSubscriptionValue && transaction.galaxPayId !== docSubscription.transactionId) { + await cancellTransactionGalaxpay(galaxpayAxios, transaction.galaxPayId) + .catch(error => { + if (error.response) { + const { status, data } = error.response + console.error('Error response: ', status, ' ', data && JSON.stringify(data)) + } else { + console.error(error) + } + }) + } + i += 1 + } + } catch (err) { + console.error(err) + } } } } catch (err) { diff --git a/functions/routes/galaxpay/webhooks.js b/functions/routes/galaxpay/webhooks.js index e874d55..a5de792 100644 --- a/functions/routes/galaxpay/webhooks.js +++ b/functions/routes/galaxpay/webhooks.js @@ -4,7 +4,8 @@ const { checkItemsAndRecalculeteOrder, compareDocItemsWithOrder, updateValueSubscriptionGalaxpay, - updateTransactionGalaxpay + updateTransactionGalaxpay, + cancellTransactionGalaxpay } = require('../../lib/galaxpay/update-subscription') const { createItemsAndAmount, @@ -131,7 +132,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { } // recalculate order const shippingLine = { ...shippingLines[0] } - // console.log('>>SL1 ', JSON.stringify(shippingLine)) + console.log('>> check items ', JSON.stringify(items)) const { shippingLine: newShippingLine } = await checkItemsAndRecalculeteOrder(amount, items, plan, null, shippingLine, storeId, appSdk, auth) shippingLines[0] = { @@ -212,7 +213,10 @@ exports.post = async ({ appSdk, admin }, req, res) => { // GalaxPayTransactionValue === finalAmount // return findOrderByTransactionId(appSdk, storeId, auth, transactionId) // } else { - console.log(`>>[Transaction Error GP: #${GalaxPayTransaction.galaxPayId}] s: ${storeId} amount: ${JSON.stringify(amount)}, Galaxpay value: ${GalaxPayTransactionValue}, items: ${JSON.stringify(items)},`) + console.log(`>>[Transaction Error GP: #${GalaxPayTransaction.galaxPayId}] s: ${storeId}` + + `total: ${amount.total}, Galaxpay value: ${GalaxPayTransactionValue}` + + `amount: ${JSON.stringify(amount)}, items: ${JSON.stringify(items)},` + + `itemsAndAmount: ${itemsAndAmount && JSON.stringify(itemsAndAmount)}`) } return findOrderByTransactionId(appSdk, storeId, auth, transactionId) }) @@ -273,8 +277,8 @@ exports.post = async ({ appSdk, admin }, req, res) => { // const orderNumber = documentSnapshot.data().orderNumber const transactionId = documentSnapshot.data().transactionId const plan = documentSnapshot.data().plan + const docValue = documentSnapshot.data().value - let updates = documentSnapshot.data().updates if (documentSnapshot.exists && storeId) { appSdk.getAuth(storeId) .then(async (auth) => { @@ -347,22 +351,15 @@ exports.post = async ({ appSdk, admin }, req, res) => { oldValue, order.shipping_lines[0] ) - const updatedAt = new Date().toISOString() - if (updates) { - updates.push({ value: newValue, updatedAt }) - } else { - updates = [] - updates.push({ value: newValue, updatedAt }) - } - - collectionSubscription.doc(subscriptionId) - .set({ - updates, - updatedAt, - value: newValue - }, { merge: true }) - .catch(console.error) } + // if docValue is zero, the subscription has no products (no stock), keep the value in firebase as zero + await updateDocSubscription( + collectionSubscription, + { + value: docValue === 0 ? 0 : newValue + }, + subscriptionId + ) } // console.log('ORDER: ', JSON.stringify(order.amount), ' **') @@ -543,7 +540,7 @@ exports.post = async ({ appSdk, admin }, req, res) => { try { console.log('>> Add transaction') const subscriptionDoc = (await collectionSubscription.doc(subscriptionId).get())?.data() - const { storeId, plan, transactionId } = subscriptionDoc + const { storeId, plan, transactionId, value: subscriptionValue } = subscriptionDoc if (storeId) { if (transactionId !== GalaxPayTransaction.galaxPayId) { const auth = await appSdk.getAuth(storeId) @@ -588,6 +585,8 @@ exports.post = async ({ appSdk, admin }, req, res) => { 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 + const { status } = data?.Transactions[0] + console.log('>> new value ', subscriptionValue, ' status ', status) if (hasUpdateValue) { const resp = await updateValueSubscriptionGalaxpay(galaxpayAxios, subscriptionId, total) if (resp) { @@ -599,10 +598,18 @@ exports.post = async ({ appSdk, admin }, req, res) => { await updateDocSubscription(collectionSubscription, body, subscriptionId) } // Update transaction - const { status } = data?.Transactions[0] if (!status || status === 'notSend' || status === 'pendingBoleto' || status === 'pendingPix') { await updateTransactionGalaxpay(galaxpayAxios, GalaxPayTransaction.galaxPayId, total) } + } else if (subscriptionValue === 0) { + console.log('Try canceling transaction: ', + GalaxPayTransaction.galaxPayId, ' subscriptions is ', + subscriptionValue + ) + // cancell transaction + if (!status || status === 'notSend' || status === 'pendingBoleto' || status === 'pendingPix') { + await cancellTransactionGalaxpay(galaxpayAxios, GalaxPayTransaction.galaxPayId) + } } } catch (error) { console.error(error)