Skip to content

Commit

Permalink
feat: setup tracking routine for orders with created mandabem tag
Browse files Browse the repository at this point in the history
  • Loading branch information
leomp12 committed Sep 2, 2024
1 parent 820867c commit 151f075
Show file tree
Hide file tree
Showing 3 changed files with 165 additions and 0 deletions.
6 changes: 6 additions & 0 deletions functions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,9 @@ exports.updateTokens = functions.pubsub.schedule(cron).onRun(() => {
})
})
console.log(`-- Sheduled update E-Com Plus tokens '${cron}'`)

const cronCheckTracking = '*/20 * * * *'
const checkOrdersTracking = require('./lib/mandabem/check-orders-tracking')
exports.checkOrdersTracking = functions.runWith({ timeoutSeconds: 540 })
.pubsub.schedule(cronCheckTracking).onRun(checkOrdersTracking)
console.log(`-- Sheduled check tracking from MandaBem API ${cronCheckTracking}`)
98 changes: 98 additions & 0 deletions functions/lib/mandabem/check-orders-tracking.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
const { firestore } = require('firebase-admin')
const { setup } = require('@ecomplus/application-sdk')
const logger = require('firebase-functions/logger')
const getAppData = require('../store-api/get-app-data')
const importOrderStatus = require('./import-order-status')

const listStoreIds = () => {
const storeIds = []
const date = new Date()
date.setHours(date.getHours() - 48)
return firestore()
.collection('ecomplus_app_auth')
.where('updated_at', '>', firestore.Timestamp.fromDate(date))
.get().then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
const storeId = documentSnapshot.get('store_id')
if (storeIds.indexOf(storeId) === -1) {
storeIds.push(storeId)
}
})
return storeIds
})
}

const fetchUndeliveredOrders = async ({ appSdk, storeId }) => {
const auth = await appSdk.getAuth(storeId)
return new Promise((resolve, reject) => {
getAppData({ appSdk, storeId, auth })
.then(async (appData) => {
resolve()
const mandaBemId = appData.mandabem_id
const mandaBemKey = appData.mandabem_token
if (mandaBemId && mandaBemKey) {
const d1 = new Date()
d1.setDate(d1.getDate() - 30)
const d2 = new Date()
d2.setHours(d2.getHours() - 2)
const endpoint = '/orders.json' +
'?fields=_id,number,fulfillment_status,shipping_lines' +
'&shipping_lines.tracking_codes.tag=mandabem' +
'&financial_status.current=paid' +
'&fulfillment_status.current!=delivered' +
`&updated_at>=${d1.toISOString()}` +
`&updated_at<=${d2.toISOString()}` +
'&sort=updated_at' +
'&limit=200'
try {
const { response } = await appSdk.apiRequest(storeId, endpoint, 'GET')
const orders = response.data.result
for (let i = 0; i < orders.length; i++) {
const order = orders[i]
try {
await importOrderStatus(
{ appSdk, storeId, auth },
{ order, mandaBemId, mandaBemKey }
)
} catch (error) {
if (
error.response?.data?.error?.code === '404' ||
(error.response?.status > 403 && error.response.status <= 500)
) {
const err = new Error(`Failed importing order ${order.number} status for #${storeId}`)
logger.error(err, {
request: error.config,
response: error.response.data
})
} else {
throw error
}
}
}
} catch (_err) {
if (_err.response) {
const err = new Error(`Failed importing orders status for #${storeId}`)
logger.error(err, {
request: _err.config,
response: _err.response.data
})
} else {
logger.error(_err)
}
}
}
})
.catch(reject)
})
}

module.exports = context => setup(null, true, firestore())
.then(appSdk => {
return listStoreIds().then(storeIds => {
const runAllStores = fn => storeIds
.sort(() => Math.random() - Math.random())
.map(storeId => fn({ appSdk, storeId }))
return Promise.all(runAllStores(fetchUndeliveredOrders))
})
})
.catch(logger.error)
61 changes: 61 additions & 0 deletions functions/lib/mandabem/import-order-status.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const logger = require('firebase-functions/logger')
const axios = require('axios')
const qs = require('querystring')

const parseMandabemStatus = (status) => {
if (/entregue/i.test(status)) return 'delivered'
if (/encaminhado/i.test(status)) return 'shipped'
if (/enviado/i.test(status)) return 'shipped'
return null
}

module.exports = async (
{ appSdk, storeId, auth },
{ order, mandaBemId, mandaBemKey }
) => {
const { number } = order
logger.info(`Tracking #${storeId} ${number}`)
const { data } = await axios.post(
'https://mandabem.com.br/ws/gerar_envio',
qs.stringify({
ref_id: number,
plataforma_id: mandaBemId,
plataforma_chave: mandaBemKey
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 7000
}
)
const trackingResult = typeof data === 'string'
? JSON.parse(data)
: (data || {})
const status = parseMandabemStatus(trackingResult?.resultado?.dados?.status)
if (!status) {
logger.warn(`No parsed fulfillment status for #${storeId} ${number}`, {
trackingResult,
data
})
return
}
if (status !== order.fulfillment_status?.current) {
const shippingLine = order.shipping_lines?.find(({ flags }) => {
return flags?.find((flag) => flag.startsWith('mandabem-'))
})
await appSdk.apiRequest(
storeId,
`/orders/${order._id}/fulfillments.json`,
'POST',
{
shipping_line_id: shippingLine?._id,
date_time: new Date().toISOString(),
status,
flags: ['mandabem']
},
auth
)
logger.info(`#${storeId} ${number} updated to ${status}`)
}
}

0 comments on commit 151f075

Please sign in to comment.