Skip to content

Commit

Permalink
fix(add transaction): Check if the product exists and edit the transa…
Browse files Browse the repository at this point in the history
…ction amount in galaxpay if necessary
  • Loading branch information
wisley7l committed Nov 13, 2023
1 parent 1f66c49 commit 8b21ecb
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 20 deletions.
57 changes: 48 additions & 9 deletions functions/lib/galaxpay/update-subscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,22 @@ const GalaxpayAxios = require('./create-access')
const axios = require('axios')
const { getProductsById } = require('../store-api/request-api')

const checkProducstExists = async (appSdk, storeId, items, auth) => {
// product may have been deleted but still belong to a subscription
let i = 0
while (i < items.length) {
const item = items[i]
const product = await getProductsById(appSdk, storeId, item.product_id, auth)
.catch(console.error)

if (!product) {
items.splice(i, 1)
} else {
i += 1
}
}
}

const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOriginal, appSdk, auth) => {
if (!shippingLineOriginal.app) return null
const items = []
Expand All @@ -13,19 +29,23 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig
if (!item.dimensions) {
// add dimensions for shipping calculation
const product = await getProductsById(appSdk, storeId, item.product_id, auth)
.catch(console.error)

let dimensions = product?.dimensions
let weight = product?.weight

if (item.variation_id) {
const variation = product.variations.find(itemFind => itemFind.sku === item.sku)
if (variation.dimensions) {
dimensions = variation.dimensions
}
if (variation.weight) {
weight = variation.weight
if (product) {
if (item.variation_id) {
const variation = product.variations.find(itemFind => itemFind.sku === item.sku)
if (variation.dimensions) {
dimensions = variation.dimensions
}
if (variation.weight) {
weight = variation.weight
}
}
items.push({ ...item, dimensions, weight })
}
items.push({ ...item, dimensions, weight })
} else {
items.push({ ...item })
}
Expand Down Expand Up @@ -130,6 +150,11 @@ const checkItemsAndRecalculeteOrder = async (amount, items, plan, newItem, shipp
let subtotal = 0
let item
let i = 0

if (appSdk) {
await checkProducstExists(appSdk, storeId, items, auth)
}

while (i < items.length) {
item = items[i]
if (newItem && item.sku === newItem.sku) {
Expand Down Expand Up @@ -268,10 +293,24 @@ const compareDocItemsWithOrder = (docItemsAndAmount, originalItems, originalAmou
}
}

const updateTransactionGalaxpay = async (galaxpayAxios, galaxPayId, value) => {
const { data } = await galaxpayAxios.axios
.put(`/transactions/${galaxPayId}/galaxPayId`,
{
value
}
)

if (data) {
console.log('> Successful transaction edit on Galax Pay #', galaxPayId)
}
}

module.exports = {
checkAndUpdateSubscriptionGalaxpay,
checkItemsAndRecalculeteOrder,
updateValueSubscriptionGalaxpay,
getSubscriptionsByListMyIds,
compareDocItemsWithOrder
compareDocItemsWithOrder,
updateTransactionGalaxpay
}
5 changes: 4 additions & 1 deletion functions/lib/store-api/request-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ const findOrderById = (appSdk, storeId, orderId, auth) => new Promise((resolve,
})
})

const getProductsById = (appSdk, storeId, productId, auth) => new Promise((resolve, reject) => {
const getProductsById = (appSdk, storeId, productId, auth, isRetry) => new Promise((resolve, reject) => {
appSdk.apiRequest(storeId, `/products/${productId}.json`, 'GET', null, auth)
.then(({ response }) => {
resolve(response.data)
})
.catch(err => {
if (!isRetry && err.response && err.response.status >= 429) {
setTimeout(() => getProductsById(appSdk, storeId, productId, auth, true), 10)
}
reject(err)
})
})
Expand Down
33 changes: 29 additions & 4 deletions functions/routes/ecom/webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const { baseUri } = require('../../__env')
const {
checkItemsAndRecalculeteOrder,
updateValueSubscriptionGalaxpay,
getSubscriptionsByListMyIds
getSubscriptionsByListMyIds,
updateTransactionGalaxpay
} = require('../../lib/galaxpay/update-subscription')

const {
Expand Down Expand Up @@ -153,8 +154,8 @@ exports.post = async ({ appSdk, admin }, req, res) => {
})
} else if (
trigger.resource === 'orders' && trigger.body.status &&
trigger.body.status !== 'cancelled' && trigger.action !== 'create' &&
trigger.fields.includes('items')
trigger.body.status !== 'cancelled' && trigger.action !== 'create' &&
trigger.fields.includes('items')
) {
console.log('>> ', JSON.stringify(trigger))
// When the original order is edited
Expand Down Expand Up @@ -257,9 +258,12 @@ exports.post = async ({ appSdk, admin }, req, res) => {
const subscription = galaxPaySubscriptions[i]
try {
const order = await findOrderById(appSdk, storeId, subscription.myId, auth)
.catch(console.error)

const product = await getProductsById(appSdk, storeId, resourceId, auth)
.catch(console.error)

if (order) {
if (order && product) {
const docSubscription = await getDocSubscription(order._id, collectionSubscription)

order.items.forEach(async (orderItem) => {
Expand Down Expand Up @@ -340,6 +344,27 @@ exports.post = async ({ appSdk, admin }, req, res) => {

throw err
}
//
// subscription.galaxPayId
// console.log('>Sub: ', JSON.stringify(subscription))
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) {
await updateTransactionGalaxpay(galaxpayAxios, transaction.galaxPayId, newSubscriptionValue)
.catch(console.error)
}
i += 1
}
} catch (err) {
console.error(err)
}
}
}
} catch (err) {
Expand Down
16 changes: 10 additions & 6 deletions functions/routes/galaxpay/webhooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ const {
checkAndUpdateSubscriptionGalaxpay,
checkItemsAndRecalculeteOrder,
compareDocItemsWithOrder,
updateValueSubscriptionGalaxpay
updateValueSubscriptionGalaxpay,
updateTransactionGalaxpay
} = require('../../lib/galaxpay/update-subscription')
const {
createItemsAndAmount,
Expand Down Expand Up @@ -553,7 +554,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
compareDocItemsWithOrder(itemsAndAmount, order.items, order.amount, GalaxPayTransactionValue)
}

const { value } = await checkItemsAndRecalculeteOrder(
await checkItemsAndRecalculeteOrder(
order.amount,
order.items,
plan,
Expand All @@ -566,10 +567,11 @@ exports.post = async ({ appSdk, admin }, req, res) => {
itemsAndAmount = createItemsAndAmount(order.amount, order.items)

await collectionTransactions.doc(`${storeId}-${GalaxPayTransaction.galaxPayId}`)
.set({
itemsAndAmount,
updatedAt: new Date().toISOString()
},
.set(
{
itemsAndAmount,
updatedAt: new Date().toISOString()
},
{ merge: true }
)

Expand All @@ -595,6 +597,8 @@ exports.post = async ({ appSdk, admin }, req, res) => {
}
await updateDocSubscription(collectionSubscription, body, subscriptionId)
}
// Update transaction
await updateTransactionGalaxpay(galaxpayAxios, GalaxPayTransaction.galaxPayId, total)
}
} catch (error) {
console.error(error)
Expand Down

0 comments on commit 8b21ecb

Please sign in to comment.