11const { logger } = require ( 'firebase-functions' )
22const { firestore } = require ( 'firebase-admin' )
3+ const https = require ( 'https' )
4+ const axios = require ( 'axios' )
35const getCategories = require ( './categories-to-ecom' )
46const getBrands = require ( './brands-to-ecom' )
57const {
@@ -91,10 +93,44 @@ module.exports = async ({ appSdk, storeId, auth }, productHorus, opts) => {
9193 const isUpdatePriceOrStock = ! opts . queueEntry ?. mustUpdateAppQueue && ( updatePrice || updateStock )
9294 const isUpdateStock = updateStock && ( SALDO_DISPONIVEL >= 0 || SALDO >= 0 )
9395
96+ let inventory
97+ if ( quantity !== product ?. quantity && isUpdateStock ) {
98+ const { stocks_url : stocksUrl , stocks_token : stocksToken } = opts . appData
99+ if ( stocksUrl && stocksToken ) {
100+ const res = await axios . get ( `${ stocksUrl } ?cod_item=${ COD_ITEM } ` , {
101+ httpsAgent : new https . Agent ( {
102+ rejectUnauthorized : false
103+ } ) ,
104+ headers : {
105+ Authorization : `Bearer ${ stocksToken } `
106+ }
107+ } ) . catch ( ( err ) => {
108+ logger . warn ( `Failed fetching stocks URL for ${ COD_ITEM } ` , {
109+ url : err . config ?. url ,
110+ response : {
111+ status : err . response ?. status ,
112+ data : err . response ?. data
113+ }
114+ } )
115+ } )
116+ if ( res ?. data ?. produtos ?. itensEstoque ?. length > 1 ) {
117+ inventory = { }
118+ quantity = 0
119+ res . data . produtos . itensEstoque . forEach ( ( { codigoestoque, saldo } ) => {
120+ const qnt = parseInt ( saldo , 10 )
121+ quantity += qnt
122+ inventory [ `${ codigoestoque } ` ] = qnt
123+ } )
124+ }
125+ }
126+ }
127+
94128 logger . info ( `COD_ITEM ${ COD_ITEM } ` , {
95129 productHorus,
96130 isUpdatePriceOrStock,
97- isUpdateStock
131+ isUpdateStock,
132+ quantity,
133+ inventory
98134 } )
99135
100136 if ( ( isUpdatePriceOrStock || ( product && ! updateProduct ) ) ) {
@@ -123,8 +159,9 @@ module.exports = async ({ appSdk, storeId, auth }, productHorus, opts) => {
123159 }
124160 }
125161
126- if ( quantity !== product . quantity && isUpdateStock ) {
162+ if ( ( quantity !== product . quantity || inventory ) && isUpdateStock ) {
127163 body . quantity = quantity
164+ body . inventory = inventory
128165 }
129166
130167 if ( Object . keys ( body ) . length ) {
@@ -145,8 +182,8 @@ module.exports = async ({ appSdk, storeId, auth }, productHorus, opts) => {
145182 . replace ( / [ ^ a - z 0 - 9 - _ ./ ] / gi, '-' ) ,
146183 status : STATUS_ITEM ,
147184 quantity,
185+ inventory,
148186 dimensions : {
149-
150187 width : {
151188 value : LARGURA_ITEM || 5 ,
152189 unit : 'cm'
0 commit comments