Skip to content

Commit

Permalink
Merge pull request #933 from codigoencasa/dev
Browse files Browse the repository at this point in the history
build: ⚡ improved
  • Loading branch information
leifermendez authored Nov 27, 2023
2 parents 3437d7a + 53dc6c1 commit 77c03ce
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 19 deletions.
2 changes: 1 addition & 1 deletion __test__/0.0.2-goto-flow.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ testSuite(`Debe de continuar el el encadenamiento con procesos async`, async ({
assert.is('datos de json', history[3])
assert.is('Digame su *Nombre y apellidos* para reservar su mesa...', history[4])
assert.is('leifer', history[5])
assert.is(undefined, history[96])
assert.is(undefined, history[6])
})

//Issue https://github.com/codigoencasa/bot-whatsapp/issues/877
Expand Down
68 changes: 68 additions & 0 deletions __test__/0.1.5-case.test.js → __test__/0.1.5-endflow.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const { suite } = require('uvu')
const assert = require('uvu/assert')
const { addKeyword, createBot, createFlow } = require('../packages/bot/index')
const { setup, clear, delay } = require('../__mocks__/env')
const { EVENTS } = require('../packages/bot/lib/bundle.bot.cjs')

const fakeHTTP = async (fakeData = []) => {
await delay(50)
Expand Down Expand Up @@ -164,4 +165,71 @@ suiteCase(`flowDynamic con capture`, async ({ database, provider }) => {
assert.is('Puedes pasar', getHistory[11])
})

suiteCase(`endFlow desde gotoFlow`, async ({ database, provider }) => {
const flow = addKeyword(['hola'])
.addAnswer('Buenas!', null, async (_, { gotoFlow }) => {
return gotoFlow(flowUsuario)
})
.addAnswer('no debe llegar')

const flowUsuario = addKeyword(EVENTS.ACTION)
.addAction({ ref: `1111111111111111` }, async (_, { flowDynamic, endFlow }) => {
try {
const confirmar = {
data: {
estado: '3',
},
}
if (confirmar === 500) {
return gotoFlow(serverError)
}
if (confirmar.data.estado === '3') {
return endFlow(`Final y no mas`)
}

if (confirmar.data) {
await flowDynamic('ya estas! debe finalizar flow no debe enviar mas mensajes')
return endFlow()
}
} catch (error) {
console.error(error)
}
await flowDynamic('⏳ por favor solo espere a que el asistente responda 🍀🤖...')
})
.addAction({ ref: `22222222222` }, async (_, { flowDynamic }) => {
await flowDynamic('ping pong')
console.log(`🌟🌟🌟🌟`)
})

await createBot({
database,
provider,
flow: createFlow([flow, flowUsuario]),
})

await provider.delaySendMessage(100, 'message', {
from: '000',
body: 'hola',
})

await delay(5000)
const getHistory = database.listHistory.map((i) => i.answer)
assert.is('Buenas!', getHistory[0])
assert.is('__capture_only_intended__', getHistory[1])
assert.is('__capture_only_intended__', getHistory[2])
assert.is('Final y no mas', getHistory[3])
assert.is(undefined, getHistory[4])
// assert.is('this is not email value', getHistory[1])
// assert.is(MOCK_VALUES[0], getHistory[2])
// assert.is('[email protected]', getHistory[3])
// assert.is('Gracias por tu email se ha validado de manera correcta', getHistory[4])
// assert.is(MOCK_VALUES[1], getHistory[5])
// assert.is(MOCK_VALUES[2], getHistory[6])
// assert.is('20', getHistory[7])
// assert.is('Ups creo que no eres mayor de edad', getHistory[8])
// assert.is('18', getHistory[9])
// assert.is('Bien tu edad es correcta!', getHistory[10])
// assert.is('Puedes pasar', getHistory[11])
})

suiteCase.run()
1 change: 1 addition & 0 deletions __test__/0.2.0-case.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ suiteCase(`Encadenanos addAction con captures and gotoFlow`, async ({ database,
.addAction({ ref: `1111111111111111111` }, async (ctx, { flowDynamic }) => {
await flowDynamic(`Chao!`)
})

await createBot({
database,
flow: createFlow([flujoPrincipal, flujoSegundario, flujoTercero]),
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bot-whatsapp/root",
"version": "0.1.33",
"version": "0.1.34",
"description": "Bot de wahtsapp open source para MVP o pequeños negocios",
"main": "app.js",
"private": true,
Expand Down
40 changes: 26 additions & 14 deletions packages/bot/core/core.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,21 +174,33 @@ class CoreClass extends EventEmitter {
// 📄 Finalizar flujo
const endFlow =
(flag) =>
async (messages = null) => {
async (messages = null, options = { fromGotoFlow: false, end: false }) => {
flag.endFlow = true
endFlowFlag = true
if (typeof messages === 'string') {

if (typeof messages === 'string' || messages === null) {
await this.sendProviderAndSave(from, createCtxMessage(messages))
clearQueue()
return
}

// Procesos de callback que se deben execute como exepciones
if (Array.isArray(messages)) {
// console.log('options.fromGotoFlow', messages)

// const indexLimit = messages.findIndex((m) => m.ref === inRef)
for (const iteratorCtxMessage of messages) {
await resolveCbEveryCtx(iteratorCtxMessage, {
omitEndFlow: true,
// console.log(`Counter ${indexLimit}`)
// if(indexLimit !== -1 && counterFor === indexLimit) break
const scopeCtx = await resolveCbEveryCtx(iteratorCtxMessage, {
omitEndFlow: options.fromGotoFlow,
idleCtx: !!iteratorCtxMessage?.options?.idle,
triggerKey: iteratorCtxMessage.keyword.startsWith('key_'),
})

if (scopeCtx?.endFlow) break

// options.fromGotoFlow = false
}
}
clearQueue()
Expand Down Expand Up @@ -315,13 +327,10 @@ class CoreClass extends EventEmitter {
const msgParse = this.flowClass.findSerializeByRef(msg?.ref)

const ctxMessage = { ...msgParse, ...msg }

// Enviar el mensaje al proveedor y guardarlo
await this.sendProviderAndSave(from, ctxMessage).then(() => promises.push(ctxMessage))
}

await endFlow(flag)(promises)

await endFlow(flag)(promises, { fromGotoFlow: true, ...{ end: endFlowFlag } })
return
}

Expand Down Expand Up @@ -377,13 +386,16 @@ class CoreClass extends EventEmitter {
`[ATENCION IDLE]: La función "idle" no tendrá efecto a menos que habilites la opción "capture:true". Por favor, asegúrate de configurar "capture:true" o elimina la función "idle"`
)
}

// if(endFlowFlag) return

if (ctxMessage?.options?.idle) {
await cbEveryCtx(ctxMessage?.ref, { ...options, startIdleMs: ctxMessage?.options?.idle })
return
const run = await cbEveryCtx(ctxMessage?.ref, { ...options, startIdleMs: ctxMessage?.options?.idle })
return run
}
if (!ctxMessage?.options?.capture) {
await cbEveryCtx(ctxMessage?.ref, options)
return
const run = await cbEveryCtx(ctxMessage?.ref, options)
return run
}
}

Expand Down Expand Up @@ -414,7 +426,7 @@ class CoreClass extends EventEmitter {
inRef,
fallBack: fallBack(flags),
flowDynamic: flowDynamic(flags, inRef, options),
endFlow: endFlow(flags),
endFlow: endFlow(flags, inRef),
gotoFlow: gotoFlow(flags),
}

Expand Down Expand Up @@ -452,7 +464,7 @@ class CoreClass extends EventEmitter {
}

await runContext()
return
return { ...flags }
}

const exportFunctionsSend = async (cb = () => Promise.resolve()) => {
Expand Down
3 changes: 2 additions & 1 deletion packages/bot/io/flow.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ class FlowClass {

constructor(_flow) {
if (!Array.isArray(_flow)) throw new Error('Esto debe ser un ARRAY')
this.flowRaw = this.addEndsFlows(_flow)
// this.flowRaw = this.addEndsFlows(_flow)
this.flowRaw = _flow

this.allCallbacks = flatObject(_flow)

Expand Down
2 changes: 1 addition & 1 deletion packages/bot/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@bot-whatsapp/bot",
"version": "0.0.204-alpha.0",
"version": "0.0.216-alpha.0",
"description": "",
"main": "./lib/bundle.bot.cjs",
"scripts": {
Expand Down
1 change: 1 addition & 0 deletions starters/apps/base-baileys-json/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "",
"main": "app.js",
"scripts": {
"prestart": "npx eslint . --no-ignore",
"pre-copy": "cd .. && npm run copy.lib base-baileys-json",
"start": "node app.js"
},
Expand Down
2 changes: 1 addition & 1 deletion starters/apps/base-baileys-memory/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "",
"main": "app.js",
"scripts": {
"prestart": "npx eslint .",
"prestart": "npx eslint . --no-ignore",
"pre-copy": "cd .. && npm run copy.lib base-baileys-memory",
"start": "node app.js"
},
Expand Down

0 comments on commit 77c03ce

Please sign in to comment.