Skip to content

Commit

Permalink
fix(out-of-stock-subscriptions): Cancel pending transactions for out-…
Browse files Browse the repository at this point in the history
…of-stock subscriptions
  • Loading branch information
wisley7l committed Dec 20, 2023
1 parent 1d3363c commit 07fa122
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 25 deletions.
17 changes: 15 additions & 2 deletions functions/lib/galaxpay/update-subscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
40 changes: 38 additions & 2 deletions functions/routes/ecom/webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const {
checkItemsAndRecalculeteOrder,
updateValueSubscriptionGalaxpay,
getSubscriptionsByListMyIds,
updateTransactionGalaxpay
updateTransactionGalaxpay,
cancellTransactionGalaxpay
} = require('../../lib/galaxpay/update-subscription')

const {
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
49 changes: 28 additions & 21 deletions functions/routes/galaxpay/webhooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ const {
checkItemsAndRecalculeteOrder,
compareDocItemsWithOrder,
updateValueSubscriptionGalaxpay,
updateTransactionGalaxpay
updateTransactionGalaxpay,
cancellTransactionGalaxpay
} = require('../../lib/galaxpay/update-subscription')
const {
createItemsAndAmount,
Expand Down Expand Up @@ -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] = {
Expand Down Expand Up @@ -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)
})
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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), ' **')

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand All @@ -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)
Expand Down

0 comments on commit 07fa122

Please sign in to comment.