Skip to content

Commit

Permalink
fix: prevent duplicated tags for same order (check custom field)
Browse files Browse the repository at this point in the history
debug unexpected response from mandabem api on tag creation
  • Loading branch information
leomp12 committed Sep 9, 2024
1 parent 9528018 commit e27e6c9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
9 changes: 7 additions & 2 deletions functions/lib/mandabem/create-tag.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { logger } = require('firebase-functions')
const axios = require('axios')
const qs = require('querystring')

Expand Down Expand Up @@ -78,8 +79,8 @@ module.exports = ({ appSdk, storeId, auth }, {
}
}
).then(({ data }) => {
console.log('Tag created with success', order._id)
if (String(data?.resultado?.sucesso) === 'true') {
logger.info(`Tag created with success ${order._id}`)
const tagId = String(data.resultado.envio_id)
const customFields = shippingLine.custom_fields || []
customFields.push({
Expand All @@ -94,7 +95,11 @@ module.exports = ({ appSdk, storeId, auth }, {
auth
)
}
return data
logger.info(`Unexpected response for ${order._id} tag`, {
order,
data
})
return null
}).catch(console.error))
}
}
Expand Down
20 changes: 18 additions & 2 deletions functions/routes/ecom/webhook.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { logger } = require('firebase-functions')
const getAppData = require('./../../lib/store-api/get-app-data')
const createMandaBemTag = require('./../../lib/mandabem/create-tag')

Expand Down Expand Up @@ -25,6 +26,19 @@ const parseStatus = (status) => {
}
}

const getShippingCustomField = (order, field) => {
if (order.shipping_lines) {
for (let i = 0; i < order.shipping_lines.length; i++) {
const shippingLineFields = order.shipping_lines[i].custom_fields
const customField = shippingLineFields?.find(custom => custom.field === field)
if (customField) {
return customField.value
}
}
}
return false
}

exports.post = ({ appSdk }, req, res) => {
// receiving notification from Store API
const { storeId } = req
Expand Down Expand Up @@ -68,7 +82,10 @@ exports.post = ({ appSdk }, req, res) => {

.then(({ response }) => {
const order = response.data
console.log(`Shipping tag for #${storeId} ${order._id}`)
if (getShippingCustomField(order, 'mandabem_id')) {
return null
}
logger.info(`Shipping tag for #${storeId} ${order._id}`)
return createMandaBemTag({ appSdk, storeId, auth }, {
mandaBemId,
mandaBemKey,
Expand All @@ -83,7 +100,6 @@ exports.post = ({ appSdk }, req, res) => {
})

.catch(err => {
console.log('didnt workout at any point', err)
if (err.name === SKIP_TRIGGER_NAME) {
// trigger ignored by app configuration
res.send(ECHO_SKIP)
Expand Down

0 comments on commit e27e6c9

Please sign in to comment.