Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix increment custom metric #66

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 40 additions & 31 deletions custom solutions/Increment Custom Metric/increment-custom-metric.js
Original file line number Diff line number Diff line change
@@ -1,55 +1,64 @@
/**
* Increments a metric in the bot_analytics table
* @title Increment Metric in bot_analytics
* Increments a metric
* @title Increment Metric
* @category Custom
* @author Botpress
* @param metric {string} the name of the metric to increment
* @param n {int} how much to increment it
*/

async function getNewLeads(botId, date, metric) {
var new_leads = await bp.database.raw(
`SELECT * FROM bot_analytics WHERE
botId='${botId}' AND
date = '${date}' AND
channel = '${event.channel}' AND
metric = '${metric}' AND
subMetric = 'n/a'`
)
let new_leads = await bp.database
.select('*')
.from('bot_analytics')
.where({
botId: botId,
date: date,
channel: event.channel,
metric: metric,
subMetric: 'n/a'
})

try {
bp.logger.info('New leads: ' + new_leads[0])
return new_leads[0]
} catch (error) {
bp.logger.error('Something happened! ' + error)
return undefined
}
}

const myAction = async (metric, n) => {
const incrementMetric = async (metric, n) => {
let date = event.createdOn.toISOString().split('T')[0]
bp.logger.info(date)

var new_leads = await getNewLeads(event.botId, date, metric)
if (new_leads) {
new_leads = { ...new_leads, value: new_leads.value + n } // Increment the value
await bp.database.raw(
//Update the database
`UPDATE bot_analytics
SET value = ${new_leads.value}
WHERE botId='${event.botId}' AND
date = '${date}' AND
channel = '${event.channel}' AND
metric = '${metric}' AND
subMetric = 'n/a'`
)

await bp
.database('bot_analytics')
.where({
botId: event.botId,
date: date,
channel: event.channel,
metric: metric,
subMetric: 'n/a'
})
.update({
value: new_leads.value
})
} else {
await bp.database.insertAndRetrieve('bot_analytics', {
botId: event.botId,
date: date,
channel: event.channel,
metric: metric,
subMetric: 'n/a',
value: 1
})
await bp.database
.insert({
botId: event.botId,
date: date,
channel: event.channel,
metric: metric,
subMetric: 'n/a',
value: 1
})
.into('bot_analytics')
}
}

return myAction(args.metric, parseInt(args.n))
return incrementMetric(args.metric, parseInt(args.n))