generated from ecomplus/application-starter
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: setup tracking routine for orders with created mandabem tag
- Loading branch information
Showing
3 changed files
with
165 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`) | ||
} | ||
} |