test: 🔥 a lot test e2e

This commit is contained in:
Leifer Mendez
2023-02-09 20:48:23 +01:00
41 changed files with 1957 additions and 2095 deletions

View File

@@ -142,8 +142,19 @@ class CoreClass {
const nextFlow = (await this.flowClass.find(refToContinue?.ref, true)) ?? []
const filterNextFlow = nextFlow.filter((msg) => msg.refSerialize !== currentPrev?.refSerialize)
const isContinueFlow = filterNextFlow.map((i) => i.keyword).includes(currentPrev?.ref)
if (!isContinueFlow) await sendFlow(filterNextFlow, from, { prev: undefined })
return
if (!isContinueFlow) {
const refToContinueChild = this.flowClass.getRefToContinueChild(currentPrev?.keyword)
const flowStandaloneChild = this.flowClass.getFlowsChild()
const nextChildMessages =
(await this.flowClass.find(refToContinueChild?.ref, true, flowStandaloneChild)) || []
if (nextChildMessages?.length) return await sendFlow(nextChildMessages, from, { prev: undefined })
}
if (!isContinueFlow) {
await sendFlow(filterNextFlow, from, { prev: undefined })
return
}
}
// 📄 [options: fallBack]: esta funcion se encarga de repetir el ultimo mensaje
const fallBack =

View File

@@ -59,6 +59,37 @@ class FlowClass {
findBySerialize = (refSerialize) => this.flowSerialize.find((r) => r.refSerialize === refSerialize)
findIndexByRef = (ref) => this.flowSerialize.findIndex((r) => r.ref === ref)
getRefToContinueChild = (keyword) => {
try {
const flowChilds = this.flowSerialize
.reduce((acc, cur) => {
const merge = [...acc, cur?.options?.nested].flat(2)
return merge
}, [])
.filter((i) => !!i && i?.refSerialize === keyword)
.shift()
return flowChilds
} catch (e) {
return undefined
}
}
getFlowsChild = () => {
try {
const flowChilds = this.flowSerialize
.reduce((acc, cur) => {
const merge = [...acc, cur?.options?.nested].flat(2)
return merge
}, [])
.filter((i) => !!i)
return flowChilds
} catch (e) {
return []
}
}
}
module.exports = FlowClass

View File

@@ -23,6 +23,8 @@ class ProviderClass extends EventEmitter {
if (NODE_ENV !== 'production') console.log('[sendMessage]', { userId, message })
return message
}
getInstance = () => this.vendor
}
module.exports = ProviderClass

View File

@@ -30,7 +30,6 @@ class MongoAdapter {
save = async (ctx) => {
await this.db.collection('history').insert(ctx)
console.log('Guardando DB...', ctx)
this.listHistory.push(ctx)
}
}

View File

@@ -152,57 +152,65 @@ const flowString = addKeyword('hola')
## endFlow()
Esta funcion se utliza para finalizar un flujo con dos o más addAnswer. Un ejemplo de uso sería registrar 3 datos de un usuario en 3 preguntas distinas y
que el usuario pueda finalizar por él mismo el flujo.
Esta funcion se utliza para **finalizar un flujo con dos** o más addAnswer. Un ejemplo de uso sería registrar 3 datos de un usuario en 3 preguntas distinas y
que el usuario **pueda finalizar por él mismo el flujo**.
Como podrás comprobar en el ejemplo siguiente, se puede vincular flowDynamic y todas sus funciones; como por ejemplo botones.
```js
const flowFormulario = addKeyword(['Hola'])
let nombre;
let apellidos;
let telefono;
const flowFormulario = addKeyword(['Hola','⬅️ Volver al Inicio'])
.addAnswer(
['Hola!', 'Escriba su *Nombre* para generar su solicitud'],
['Hola!','Para enviar el formulario necesito unos datos...' ,'Escriba su *Nombre*'],
{ capture: true, buttons: [{ body: '❌ Cancelar solicitud' }] },
async (ctx, { flowDynamic, endFlow }) => {
if (ctx.body == '❌ Cancelar solicitud') {
await flowDynamic([
{
body: '❌ *Su solicitud de cita ha sido cancelada* ❌',
buttons: [{ body: '⬅️ Volver al Inicio' }],
},
])
return endFlow()
}
if (ctx.body == '❌ Cancelar solicitud')
return endFlow({body: '❌ Su solicitud ha sido cancelada ❌', // Aquí terminamos el flow si la condicion se comple
buttons:[{body:'⬅️ Volver al Inicio' }] // Y además, añadimos un botón por si necesitas derivarlo a otro flow
})
nombre = ctx.body
return flowDynamic(`Encantado *${nombre}*, continuamos...`)
}
)
.addAnswer(
['También necesito tus dos apellidos'],
{ capture: true, buttons: [{ body: '❌ Cancelar solicitud' }] },
async (ctx, { flowDynamic, endFlow }) => {
if (ctx.body == '❌ Cancelar solicitud') {
await flowDynamic([
{
body: '❌ *Su solicitud de cita ha sido cancelada* ❌',
buttons: [{ body: '⬅️ Volver al Inicio' }],
},
])
return endFlow()
}
if (ctx.body == '❌ Cancelar solicitud')
return endFlow({body: '❌ Su solicitud ha sido cancelada ❌',
buttons:[{body:'⬅️ Volver al Inicio' }]
})
apellidos = ctx.body
return flowDynamic(`Perfecto *${nombre}*, por último...`)
}
)
.addAnswer(
['Dejeme su número de teléfono y le llamaré lo antes posible.'],
{ capture: true, buttons: [{ body: '❌ Cancelar solicitud' }] },
async (ctx, { flowDynamic, endFlow }) => {
if (ctx.body == '❌ Cancelar solicitud') {
await flowDynamic([
{
body: '❌ *Su solicitud de cita ha sido cancelada* ❌',
buttons: [{ body: '⬅️ Volver al Inicio' }],
},
])
return endFlow()
}
if (ctx.body == '❌ Cancelar solicitud')
return endFlow({body: '❌ Su solicitud ha sido cancelada ❌',
buttons:[{body:'⬅️ Volver al Inicio' }]
})
telefono = ctx.body
await delay(2000)
return flowDynamic(`Estupendo *${nombre}*! te dejo el resumen de tu formulario
\n- Nombre y apellidos: *${nombre} ${apellidos}*
\n- Telefono: *${telefono}*`)
}
)
```
---

View File

@@ -148,6 +148,11 @@ class BaileysProvider extends ProviderClass {
}
}
/**
* Funcion SendRaw envia opciones directamente del proveedor
* @example await sendMessage('+XXXXXXXXXXX', 'Hello World')
*/
/**
* @alpha
* @param {string} number
@@ -204,10 +209,10 @@ class BaileysProvider extends ProviderClass {
* @example await sendMessage('+XXXXXXXXXXX', 'audio.mp3')
*/
sendAudio = async (number, audioUrl, voiceNote = false) => {
sendAudio = async (number, audioUrl) => {
return this.vendor.sendMessage(number, {
audio: { url: audioUrl },
ptt: voiceNote,
ptt: true,
})
}
@@ -273,6 +278,7 @@ class BaileysProvider extends ProviderClass {
* @param {string} message
* @example await sendMessage('+XXXXXXXXXXX', 'Hello World')
*/
sendMessage = async (numberIn, message, { options }) => {
const number = baileyCleanNumber(numberIn)

View File

@@ -225,6 +225,14 @@ class WebWhatsappProvider extends ProviderClass {
return this.sendFile(number, fileDownloaded)
}
/**
* Funcion SendRaw envia opciones directamente del proveedor
* @param {string} number
* @param {string} message
* @example await sendMessage('+XXXXXXXXXXX', 'Hello World')
*/
sendRaw = () => this.vendor.sendMessage
/**
*
* @param {*} userId