Skip to content

Commit

Permalink
chore(events): update files
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Sep 27, 2024
1 parent 9383f56 commit 266a9b3
Show file tree
Hide file tree
Showing 2 changed files with 256 additions and 206 deletions.
209 changes: 3 additions & 206 deletions functions/lib/cron-events-horus.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
const { firestore } = require('firebase-admin')
// const { setup } = require('@ecomplus/application-sdk')
const getAppData = require('./store-api/get-app-data')
const updateAppData = require('./store-api/update-app-data')
const {
collectionHorusEvents,
topicResourceToEcom
} = require('./utils-variables')
const { parseDate } = require('./parsers/parse-to-horus')

const Horus = require('./horus/client')
const requestHorus = require('./horus/request')
const checkHorusApi = require('./horus/check-horus-api')
const { sendMessageTopic } = require('./pub-sub/utils')
const { getAllItemsHorusToImport } = require('../lib/integration/imports/utils')
const ecomClient = require('@ecomplus/client')
const releaseDate = '2024-04-01T00:00:00.000Z'
const { productsStocksEvents, productsPriceEvents } = require('./events/product-events')

const listStoreIds = async () => {
const storeIds = []
const date = new Date()
date.setHours(date.getHours() - 48)

// console.log('>> ', date.toISOString(), ' <<')
const querySnapshot = await firestore()
.collection('ecomplus_app_auth')
.where('updated_at', '>', firestore.Timestamp.fromDate(date))
Expand Down Expand Up @@ -76,202 +68,6 @@ const checkProductsImports = async ({ appSdk, storeId }, horus, opts) => {
})
}

const productsStocksEvents = async (horus, storeId, opts) => {
const resourcePrefix = 'products_stocks'
let dateInit = new Date(releaseDate)
let dateEnd = new Date()

let offset = 0
const limit = 50

const docRef = firestore()
.doc(`${collectionHorusEvents}/${storeId}_${resourcePrefix}`)

const docSnapshot = await docRef.get()
if (docSnapshot.exists) {
const data = docSnapshot.data()
const dateInitDoc = data?.dateInit
const dateEndtDoc = data?.dateEnd
const offsetDoc = data?.offset
const hasRepeatDoc = data?.hasRepeat

if (hasRepeatDoc) {
dateInit = dateInitDoc ? new Date(dateInitDoc) : dateInit
dateEnd = dateEndtDoc ? new Date(dateEndtDoc) : dateEnd
offset = offsetDoc || 0
} else {
dateInit = dateEndtDoc ? new Date(dateEndtDoc) : dateEnd
}
}
const companyCode = opts.appData?.company_code || 1
const subsidiaryCode = opts.appData?.subsidiary_code || 1
let stockCode = opts.appData?.stock_code
if (storeId === 51504) {
stockCode = stockCode || 20
}

const codCaract = opts?.appData?.code_characteristic || 5
const codTpoCaract = opts?.appData?.code_type_characteristic || 3

console.log(`>> Check STOCKS ${parseDate(dateInit, true)} at ${parseDate(dateEnd, true)} offset ${offset}`)
const query = `?DATA_INI=${parseDate(dateInit, true)}&DATA_FIM=${parseDate(dateEnd, true)}` +
`&COD_TPO_CARACT=${codTpoCaract}&COD_CARACT=${codCaract}` +
`&COD_EMPRESA=${companyCode}&COD_FILIAL=${subsidiaryCode}` +
`&TIPO_SALDO=V${stockCode ? `&COD_LOCAL_ESTOQUE=${stockCode}` : ''}`

console.log(' Query: ', query)

let hasRepeat = true

let total = 0
// const init = Date.now()
const promisesSendTopics = []
// while (hasRepeat) {
// create Object Horus to request api Horus
const endpoint = `/Estoque${query}&offset=${offset}&limit=${limit}`
const products = await requestHorus(horus, endpoint, 'get', true)
.catch((_err) => {
// if (_err.response) {
// console.warn(JSON.stringify(_err.response))
// } else {
// console.error(_err)
// }
return null
})

hasRepeat = products?.length === limit

if (products?.length) {
total += products.length
products.forEach((productHorus, index) => {
promisesSendTopics.push(
sendMessageTopic(
topicResourceToEcom,
{
storeId,
resource: resourcePrefix,
objectHorus: productHorus,
opts
})
)
})
}

offset = hasRepeat ? offset + limit : 0
// }
console.log(`>>Cron STOCKS #${storeId} Updates: ${total} Repeat ${hasRepeat}`)

return Promise.all(promisesSendTopics)
.then(async () => {
await docRef.set({
dateInit: dateInit.toISOString(),
dateEnd: dateEnd.toISOString(),
offset,
hasRepeat,
updated_at: new Date().toISOString()
}, { merge: true })
.catch(console.error)
console.log(`Finish Exec STOCKS in #${storeId}`)
})
}

const productsPriceEvents = async (horus, storeId, opts) => {
const resourcePrefix = 'products_price'
let dateInit = new Date(releaseDate)
let dateEnd = new Date()

let offset = 0
const limit = 50

const docRef = firestore()
.doc(`${collectionHorusEvents}/${storeId}_${resourcePrefix}`)

// console.log('>> ', resource, ' => ', field)
const docSnapshot = await docRef.get()
let isExec = true
if (docSnapshot.exists) {
const data = docSnapshot.data()
const dateInitDoc = data?.dateInit
const dateEndtDoc = data?.dateEnd
const offsetDoc = data?.offset
const hasRepeatDoc = data?.hasRepeat
const updatedAtDoc = data?.updated_at && new Date(data?.updated_at)
const now = new Date()

if (hasRepeatDoc || updatedAtDoc) {
isExec = Boolean(hasRepeatDoc || (now.getTime() >= (updatedAtDoc.getTime() + (24 * 60 * 60 * 1000))))
}

if (hasRepeatDoc) {
dateInit = dateInitDoc ? new Date(dateInitDoc) : dateInit
dateEnd = dateEndtDoc ? new Date(dateEndtDoc) : dateEnd
offset = offsetDoc || 0
} else {
dateInit = dateEndtDoc ? new Date(dateEndtDoc) : dateEnd
}
}

// Runs if there are repeats or every 24 hours
if (isExec) {
const codCaract = opts?.appData?.code_characteristic || 5
const codTpoCaract = opts?.appData?.code_type_characteristic || 3

console.log(`>> Check PRICE ${parseDate(dateInit, true)} at ${parseDate(dateEnd, true)}`)
const query = `?DATA_INI=${parseDate(dateInit, true)}&DATA_FIM=${parseDate(dateEnd, true)}` +
`&COD_TPO_CARACT=${codTpoCaract}&COD_CARACT=${codCaract}`

let hasRepeat = true

let total = 0
const promisesSendTopics = []
// create Object Horus to request api Horus
const endpoint = `/Busca_preco_item${query}&offset=${offset}&limit=${limit}`
const products = await requestHorus(horus, endpoint, 'get', true)
.catch((_err) => {
// if (_err.response) {
// console.warn(JSON.stringify(_err.response))
// } else {
// console.error(_err)
// }
return null
})

hasRepeat = products?.length === limit

if (products?.length) {
total += products.length
products.forEach((productHorus, index) => {
promisesSendTopics.push(
sendMessageTopic(
topicResourceToEcom,
{
storeId,
resource: resourcePrefix,
objectHorus: productHorus,
opts
})
)
})
}

offset = hasRepeat ? offset + limit : 0
console.log(`>>Cron PRICE #${storeId} Updates: ${total} Repeat ${hasRepeat}`)

return Promise.all(promisesSendTopics)
.then(async () => {
await docRef.set({
dateInit: dateInit.toISOString(),
dateEnd: dateEnd.toISOString(),
offset,
hasRepeat,
updated_at: new Date().toISOString()
}, { merge: true })
.catch(console.error)
console.log(`Finish Exec PRICE in #${storeId}`)
})
}
}

module.exports = async (appSdk) => {
const storeIds = await listStoreIds()
const promises = []
Expand All @@ -295,6 +91,7 @@ module.exports = async (appSdk) => {
console.log('>> Horus API', isHorusApiOk ? 'OK' : 'OffLine')
if (isHorusApiOk) {
promises.push(productsStocksEvents(horus, storeId, opts))
// promises.push(productsEvents({ appSdk, storeId }, horus, appData))
// check in the function
promises.push(productsPriceEvents(horus, storeId, opts))

Expand Down
Loading

0 comments on commit 266a9b3

Please sign in to comment.