diff --git a/functions/lib/galaxpay/update-subscription.js b/functions/lib/galaxpay/update-subscription.js index 9dbd1ca..3c202ed 100644 --- a/functions/lib/galaxpay/update-subscription.js +++ b/functions/lib/galaxpay/update-subscription.js @@ -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 = [] @@ -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 }) } @@ -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) { @@ -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 } diff --git a/functions/lib/store-api/request-api.js b/functions/lib/store-api/request-api.js index 7b4e88a..504b649 100644 --- a/functions/lib/store-api/request-api.js +++ b/functions/lib/store-api/request-api.js @@ -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) }) }) diff --git a/functions/routes/ecom/webhook.js b/functions/routes/ecom/webhook.js index f993c03..59373e9 100644 --- a/functions/routes/ecom/webhook.js +++ b/functions/routes/ecom/webhook.js @@ -8,7 +8,8 @@ const { baseUri } = require('../../__env') const { checkItemsAndRecalculeteOrder, updateValueSubscriptionGalaxpay, - getSubscriptionsByListMyIds + getSubscriptionsByListMyIds, + updateTransactionGalaxpay } = require('../../lib/galaxpay/update-subscription') const { @@ -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 @@ -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) => { @@ -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) { diff --git a/functions/routes/galaxpay/webhooks.js b/functions/routes/galaxpay/webhooks.js index ad44287..553fde7 100644 --- a/functions/routes/galaxpay/webhooks.js +++ b/functions/routes/galaxpay/webhooks.js @@ -3,7 +3,8 @@ const { checkAndUpdateSubscriptionGalaxpay, checkItemsAndRecalculeteOrder, compareDocItemsWithOrder, - updateValueSubscriptionGalaxpay + updateValueSubscriptionGalaxpay, + updateTransactionGalaxpay } = require('../../lib/galaxpay/update-subscription') const { createItemsAndAmount, @@ -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, @@ -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 } ) @@ -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)