Skip to content

Commit

Permalink
fix(webhook-edit-product): Fix outdated items in subscriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Feb 6, 2024
1 parent b2f67af commit f9f3e14
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 7 deletions.
3 changes: 2 additions & 1 deletion functions/lib/galaxpay/update-subscription.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const getNewFreight = async (storeId, itemsOrder, to, subtotal, shippingLineOrig
for (let i = 0; i < result.length; i++) {
const app = result[i]

for (let j = 0; j < app.response?.shipping_services.length; j++) {
for (let j = 0; j < app.response?.shipping_services?.length; j++) {
const service = app.response?.shipping_services[j]

if (service.service_code === shippingLineOriginal.app.service_code) {
Expand Down Expand Up @@ -161,6 +161,7 @@ const checkItemsAndRecalculeteOrder = async (amount, items, plan, newItem, shipp
item = items[i]
if (newItem && item.sku === newItem.sku) {
if (newItem.quantity === 0) {
console.log('>> Item Stock at zero ', JSON.stringify(newItem))
items.splice(i, 1)
} else {
if (item.final_price) {
Expand Down
6 changes: 4 additions & 2 deletions functions/routes/ecom/modules/create-transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,12 @@ exports.post = ({ appSdk, admin }, req, res) => {
const finalAmount = Math.floor(amount.total * 100)
const fristPayment = new Date()

const recorrenceQuantity = 0

const galaxpaySubscriptions = {
myId: `${orderId}`, // requered
value: finalAmount,
quantity: 0, // recorrence quantity
quantity: recorrenceQuantity,
periodicity: parsePeriodicityGalaxPay(plan.periodicity),
// additionalInfo: '', // optional
ExtraFields: extraFields
Expand Down Expand Up @@ -201,7 +203,7 @@ exports.post = ({ appSdk, admin }, req, res) => {
status: 'open',
orderNumber: params.order_number,
transactionId: transactionGalaxPay.galaxPayId,
quantity: 0,
quantity: recorrenceQuantity,
create_at: new Date().toISOString(),
plan,
value: finalAmount
Expand Down
55 changes: 52 additions & 3 deletions functions/routes/ecom/webhook.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
/* DO YOUR CUSTOM STUFF HERE */
const galaxpayAxios = new GalaxpayAxios(appData.galaxpay_id, appData.galaxpay_hash, storeId)
const collectionSubscription = admin.firestore().collection('subscriptions')
const collectionTransactions = admin.firestore().collection('transactions')

if (trigger.resource === 'orders' && trigger.body?.status === 'cancelled') {
console.log('>>> ', JSON.stringify(trigger.body))
Expand Down Expand Up @@ -270,9 +271,11 @@ exports.post = async ({ appSdk, admin }, req, res) => {
.catch(console.error)

if (order && product) {
const docSubscription = await getDocSubscription(order._id, collectionSubscription)
const items = [...order.items]
let docSubscription = await getDocSubscription(order._id, collectionSubscription)
const hasItems = docSubscription?.itemsAndAmount?.items

order.items.forEach(async (orderItem) => {
items.forEach(async (orderItem) => {
let dimensions = product?.dimensions
let weight = product?.weight

Expand All @@ -292,6 +295,8 @@ exports.post = async ({ appSdk, admin }, req, res) => {
weight = variation.weight
}
const newItem = {
subscription_id: order._id,
product_id: product._id,
sku: variation.sku,
price: ecomUtils.price({ ...product, ...variation }),
quantity
Expand All @@ -300,6 +305,8 @@ exports.post = async ({ appSdk, admin }, req, res) => {
checkItemsAndRecalculeteOrder(order.amount, order.items, docSubscription.plan, newItem)
} else {
const newItem = {
subscription_id: order._id,
product_id: product._id,
sku: product.sku,
price: ecomUtils.price(product),
quantity: product.quantity < orderItem.quantity ? product.quantity : orderItem.quantity
Expand All @@ -309,6 +316,22 @@ exports.post = async ({ appSdk, admin }, req, res) => {
}
orderItem.dimensions = dimensions
orderItem.weight = weight
} else if (hasItems) {
// It is necessary to update the reading in firebase, as the item may have already been updated
docSubscription = await getDocSubscription(order._id, collectionSubscription)
const docItems = docSubscription?.itemsAndAmount?.items
let newItem = docItems?.find(item => item.sku === orderItem.sku)

if (!newItem) {
newItem = {
subscription_id: order._id,
product_id: product._id,
sku: orderItem.sku,
price: orderItem.price,
quantity: 0
}
}
checkItemsAndRecalculeteOrder(order.amount, order.items, docSubscription.plan, newItem)
}
})

Expand Down Expand Up @@ -366,6 +389,19 @@ exports.post = async ({ appSdk, admin }, req, res) => {
// console.log('>>Transaction ', transaction)
if (transaction.value !== newSubscriptionValue && transaction.galaxPayId !== docSubscription.transactionId) {
await updateTransactionGalaxpay(galaxpayAxios, transaction.galaxPayId, newSubscriptionValue)
.then(async () => {
const transactionDocId = `${storeId}-${transaction.galaxPayId}`
console.log('>> Update Doc Transaction ', transactionDocId)
const itemsAndAmount = createItemsAndAmount(order.amount, order.items)
await collectionTransactions.doc(transactionDocId)
.set(
{
itemsAndAmount,
updatedAt: new Date().toISOString()
},
{ merge: true }
)
})
.catch(error => {
if (error.response) {
const { status, data } = error.response
Expand All @@ -384,7 +420,20 @@ exports.post = async ({ appSdk, admin }, req, res) => {
console.log('>> Attempts to cancel transactions already created from the subscription: ',
order._id, ' new value is: ', newSubscriptionValue)

await updateDocSubscription(collectionSubscription, { value: 0 }, order._id)
// signature without items, use a copy of the items from the original order and reset the quantity, to maintain the correct items
const itemsAndAmount = createItemsAndAmount(order.amount, items)
itemsAndAmount?.items?.forEach(item => {
item.quantity = 0
})

await updateDocSubscription(
collectionSubscription,
{
value: 0,
itemsAndAmount
},
order._id
)

let queryString = `subscriptionGalaxPayIds=${subscription.galaxPayId}`
queryString += '&status=notSend,pendingBoleto,pendingPix&order=payday.desc'
Expand Down
2 changes: 1 addition & 1 deletion functions/routes/galaxpay/webhooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ exports.post = async ({ appSdk, admin }, req, res) => {
let { itemsAndAmount } = documentSnapshot.data()
try {
const transactionDoc = (await collectionTransactions.doc(`${storeId}-${GalaxPayTransaction.galaxPayId}`).get())?.data()
if(transactionDoc && transactionDoc.itemsAndAmount){
if (transactionDoc && transactionDoc.itemsAndAmount) {
itemsAndAmount = transactionDoc?.itemsAndAmount
console.log('>> items to transaction')
}
Expand Down

0 comments on commit f9f3e14

Please sign in to comment.