diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..5c7247b --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,7 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [] +} \ No newline at end of file diff --git a/adapter/index.js b/adapter/index.js index 0f0be4b..11c6a50 100644 --- a/adapter/index.js +++ b/adapter/index.js @@ -49,9 +49,10 @@ const get = (message, num) => new Promise((resolve, reject) => { //MOD by CHV - */ if (process.env.DATABASE === 'none') { - + // console.log(message) var { key } = stepsInitial.find(k => k.keywords.includes(message)) || { key: null } - console.log("KEY="+key) + // console.log(stepsInitial) + // console.log("KEY="+key) /* ############################################### * REGEXP * #################################################### Si queremos usar RegExp, en los "keywords" de inital.json, en lugar de un arreglo usamos un string (quitamos los []) @@ -71,7 +72,7 @@ const get = (message, num) => new Promise((resolve, reject) => { //MOD by CHV - var {keywords} = stepsInitial.find(k => k.key.includes(key)) || { keywords: null } if(!Array.isArray(keywords)){key=null;}//Si "keywords" no es arreglo entonces ponemos "key" en null y usamos REGEXP para buscar reglas. if(key == null && message.length > 0){ - var logRegEx = true + var logRegEx = false console.log("======= KEY ES NULO, USAMOS REGEXP ======="); for (i=0; i x.message != "") //Quitamos mensajes en blanco. var inicio = laLista[i].search('%msjant_'); var final = laLista[i].indexOf("%", inicio+1); var subStr = laLista[i].substring(inicio, final+1); diff --git a/app.js b/app.js index b044a26..c32a4b5 100644 --- a/app.js +++ b/app.js @@ -31,7 +31,7 @@ app.use(express.json()) const MULTI_DEVICE = process.env.MULTI_DEVICE || 'true'; const server = require('http').Server(app) const port = process.env.PORT || 3000 - +const delay = (ms) => new Promise((resolve) => setTimeout(resolve,ms)) var client; var dialogflowFilter = false; var totalMsjs; //MOD by CHV - @@ -44,7 +44,7 @@ app.use('/', require('./routes/web')) /** * Escuchamos cuando entre un mensaje */ -const listenMessage = () => client.on('message', async msg => { +listenMessage = () => client.on('message', async msg => { const { from, body, hasMedia } = msg; if (vars[from] === undefined) vars[from] = [] // console.log("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); @@ -63,6 +63,9 @@ const listenMessage = () => client.on('message', async msg => { if (from === 'status@broadcast') { return } + let blackList = ['34692936038', '34678310819', '34660962689', '34649145761','34630283553','34648827637','34630255646','14178973313'] + console.log('BlackListed: ',blackList.includes(from.replace("@c.us",""))) + if (blackList.includes(from.replace("@c.us",""))) return message = newBody.toLowerCase(); const number = cleanNumber(from) client.theMsg['numero'] = number @@ -223,13 +226,13 @@ const listenMessage = () => client.on('message', async msg => { // console.log('RES=', RES) } } + /** * Llama el API para traer categorias de Guna. * @param {*} ctx El objeto del mensaje. */ async function getGunaCats(ctx) { - let par1 = ctx.theMsg.body - let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectTipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"${par1}"}}` + let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectTipoFerreroMty","exec":"ExecuteQuery","params":{"par1":"xxx"}}` const RES = await axios.get(theUrl).then(function (response) { let lasOpciones = [] for(reg=0;reg client.on('message', async msg => { return error }); } + /** * Llama el API para traer productos de Guna. * @param {*} ctx El objeto del mensaje. */ async function getGunaProds(ctx) { if(vars[from]['recompra'] === undefined) vars[from]['subtipo'] = ctx.theMsg.body + console.log(vars[from]['tipo'], vars[from]['subtipo']) let theUrl = `http://localhost:8888/dbrquery?j={"query":"selectProdsFerreroMty","exec":"ExecuteQuery","params":{"par1":"${vars[from]['tipo']}", "par2":"${vars[from]['subtipo']}"}}` const RES = await axios.get(theUrl).then(function (response) { let elMensaje = "Gracias,\nAhora un producto:\n\n" @@ -327,7 +332,7 @@ const listenMessage = () => client.on('message', async msg => { rows: lasOpciones, } ], - `SUBCATEGORÍA ${body}`, + `SUBCATEGORÍA ${vars[from]['subtipo']}`, "Footer" ) client.sendMessage(from, productList) @@ -337,6 +342,7 @@ const listenMessage = () => client.on('message', async msg => { return error }); } + /** * Llama el API para traer productos de Guna. * @param {*} ctx El objeto del mensaje. @@ -345,20 +351,34 @@ const listenMessage = () => client.on('message', async msg => { // vars[from]['subtipo'] = ctx.theMsg.body if(vars[from]['prods'] === undefined) { vars[from]['prods'] = [] } let elProd = ctx.theMsg.body - elProd = elProd.substring(0, elProd.indexOf(' $')).trim().toLowerCase() - var precio = ctx.theMsg.body.substring(ctx.theMsg.body.indexOf(' $')+2) - console.log("precio",precio) - precio = precio.substring(0, precio.indexOf(',')) - console.log("precio",precio) - vars[from]['prods'][elProd] = {"cant":0, "precio":precio} - console.log("EL_PROD=", elProd) - console.log(vars[from]['prods'][elProd]) - let elMensaje = ctx.theMsg.replyMessage - let re = ctx.theMsg.body.trim().toLowerCase() - elMensaje = elMensaje.replace(re, elProd.toLowerCase()) + let elMensaje = "" + if(elProd.indexOf(' $') > -1){ // Producto con formato correcto. + vars[from]['ultimoProd'] = elProd + elProd = elProd.substring(0, elProd.indexOf(' $')).trim().toLowerCase() + var precio = ctx.theMsg.body.substring(ctx.theMsg.body.indexOf(' $')+2) + console.log("precio",precio) + precio = precio.substring(0, precio.indexOf(',')) + console.log("precio",precio) + vars[from]['prods'][elProd] = {"cant":0, "precio":precio} + console.log("EL_PROD=", elProd) + console.log(vars[from]['prods']) + elMensaje = ctx.theMsg.replyMessage + let re = ctx.theMsg.body.trim().toLowerCase() + elMensaje = elMensaje.replace(re, elProd.toLowerCase()) + } + else{ // Producto SIN precio. + elMensaje = "El producto que seleccionaste es *incorrecto*, por favor intenta de nuevo." + sendMessage(client, from, elMensaje, ctx.theMsg.trigger, ctx.theMsg.step); + await delay(500) + vars[from]['recompra'] = true + getGunaProds() + vamosA(from, "gunaProds") + return + } sendMessage(client, from, elMensaje, ctx.theMsg.trigger, ctx.theMsg.step); return } + /** * Tomamos la cantidad del producto seleccionado. * @param {*} ctx El objeto del mensaje. @@ -366,33 +386,39 @@ const listenMessage = () => client.on('message', async msg => { async function prodCantidad(ctx) { // console.log("Entramos a prodCantidad") let laCant = ctx.theMsg.body.trim() - const reg = new RegExp('^[0-9]+$') - let elProd = remplazos("%msjant_2%").toLowerCase() + const reg = new RegExp(/^\d+$/) + let elProd = vars[from]['ultimoProd'].toLowerCase() elProd = elProd.substring(0, elProd.indexOf(' $')).trim() + console.log("SOLO NUMS |" + laCant + "|", reg.test(laCant)) if(reg.test(laCant)){ + console.log(vars) console.log("Recibimos cant = " + laCant) console.log("EL_PROD=", vars[from]['prods'][elProd]) console.log("precio=", vars[from]['prods'][elProd].precio) - console.log("precio=", vars[from]['prods'][elProd]['precio']) vars[from]['prods'][elProd] = {"cant":laCant, "precio":vars[from]['prods'][elProd]['precio']} - console.log(vars[from]['prods']) - var elMensaje = "" - const prods = Object.keys(vars[from]['prods']); - prods.forEach((prod, index) => { - elMensaje = elMensaje + `${vars[from]['prods'][prod].cant} - ${prod[0].toUpperCase() + prod.substring(1)}\n` - console.log(`${prod}: ${vars[from]['prods'][prod]}`); - }); - elMensaje = elMensaje + "\n¿Quieres agregar mas productos a tu orden?" - // for(pr=0;pr { + if( vars[from]['prods'][prod] !== undefined && prod[0] !== undefined ){ + elMensaje = elMensaje + `${vars[from]['prods'][prod].cant} - ${prod[0].toUpperCase() + prod.substring(1)}\n` + console.log("cant y precio=", vars[from]['prods'][prod].cant, vars[from]['prods'][prod].precio) + if(reg.test(vars[from]['prods'][prod].cant) && vars[from]['prods'][prod].precio != ""){ + total = total + (vars[from]['prods'][prod].cant * vars[from]['prods'][prod].precio) + } + } + console.log(prod, vars[from]['prods'][prod]); + }); + let pesos = Intl.NumberFormat('en-US') + elMensaje = elMensaje + "\n*Total*: $" + pesos.format(total) + elMensaje = elMensaje + "\n¿Quieres agregar mas productos a tu orden?" var bts = { "title":"Tu orden", "message":elMensaje, "buttons":[ - {"body":"Terminar"}, - {"body":"Agregar productos"} + {"body":"➕ Agregar productos"}, + {"body":"⬅️ Cambiar categoría"}, + {"body":"✖️ Terminar"} ] } sendMessageButton(client, from, "xxx", bts) @@ -412,11 +438,22 @@ const listenMessage = () => client.on('message', async msg => { async function comprarMas(ctx) { console.log("Entramos a comprarMas") vars[from]['recompra'] = true + vamosA(from, "gunaProds") await getGunaProds(ctx) vars[from]['recompra'] = false return "1" } - + + /** + * Mandamos nuevamente la lista de categorías. + * @param {*} ctx El objeto del mensaje. + */ + async function terminaCompra(ctx) { + console.log("Entramos a terminaCompra") + vars[from] = [] + sendMessage(client, from, "!Gracias por tu compra, regresa pronto!", response.trigger, step); + return + } /** @@ -448,7 +485,7 @@ const listenMessage = () => client.on('message', async msg => { console.log("############# Encontramos función, ejecutamos la función '" + response.funcion + "'") laFuncion = response.funcion + "(client)" eval(laFuncion) - return + // return } if(response.hasOwnProperty('urlXXXXXXX') && response.hasOwnProperty('values')){ let theURL = response.url; @@ -568,35 +605,35 @@ if(message=='/spam'){ const masivo = require('./spam.json') var saludo; var caritas; - function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); + function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + async function retardo() { + for (sp=0;sp k.messages.message != "") + // console.log(hayHistorialNoBlanks) + // var {keywords} = stepsInitial.find(k => k.key.includes(key)) if(hayHistorial){ let rawdata = fs.readFileSync(`./chats/${from}.json`); let elHistorial = JSON.parse(rawdata); @@ -755,6 +794,10 @@ function traeMensajes(from){ //MOD by CHV - Agregamos para traer el historial de // console.log("Mensajes:"+totalMsjs+", Ultimo:"+JSON.stringify(ultimoMensaje)); // console.log("Anterior:"+JSON.stringify(mensajeAnterior)); } + console.log(histlMsjs) + // var histlMsjsNoBlanks = histlMsjs.find(k => k.message != "") + var histlMsjsNoBlanks = histlMsjs.filter(x => x.message != "") + console.log(histlMsjsNoBlanks) return histlMsjs; } diff --git a/flow/response.json b/flow/response.json index 6fb8226..eff337f 100644 --- a/flow/response.json +++ b/flow/response.json @@ -351,7 +351,7 @@ "pasoRequerido":"soporte" }, "gunaCats":{ - "keywords": ["/guna", "/demoventa", "/demoguna"], + "keywords": ["/guna", "/demoventa", "/demoguna", "⬅️ cambiar categoria"], "replyMessage":[ "Mensaje de getGunaCats" ], @@ -400,7 +400,7 @@ "pasoRequerido":"gunaProdsAgrega" }, "gunaComprarMas":{ - "keywords": ["Agregar productos"], + "keywords": "*agregar productos", "replyMessage":[ "Quiero comprar mas." ], @@ -408,5 +408,15 @@ "media":null, "trigger":null, "pasoRequerido":"gunaProdsCantidad" + }, + "gunaTerminaCompra":{ + "keywords": "*terminar", + "replyMessage":[ + "Termina la compra" + ], + "funcion":"terminaCompra", + "media":null, + "trigger":null, + "pasoRequerido":"gunaProdsCantidad" } } \ No newline at end of file