2015-01-15 14:04:48 -05:00
|
|
|
log = require 'winston'
|
|
|
|
mongoose = require 'mongoose'
|
|
|
|
utils = require '../lib/utils'
|
2014-12-15 14:45:12 -05:00
|
|
|
AnalyticsLogEvent = require './AnalyticsLogEvent'
|
2015-01-02 16:31:43 -05:00
|
|
|
Campaign = require '../campaigns/Campaign'
|
|
|
|
Level = require '../levels/Level'
|
2014-12-15 14:45:12 -05:00
|
|
|
Handler = require '../commons/Handler'
|
|
|
|
|
|
|
|
class AnalyticsLogEventHandler extends Handler
|
|
|
|
modelClass: AnalyticsLogEvent
|
|
|
|
jsonSchema: require '../../app/schemas/models/analytics_log_event'
|
|
|
|
editableProperties: [
|
2015-01-14 20:51:04 -05:00
|
|
|
'e'
|
|
|
|
'p'
|
2014-12-15 14:45:12 -05:00
|
|
|
'event'
|
|
|
|
'properties'
|
|
|
|
]
|
|
|
|
|
|
|
|
hasAccess: (req) ->
|
2014-12-17 00:45:17 -05:00
|
|
|
req.method in ['POST'] or req.user?.isAdmin()
|
2014-12-15 14:45:12 -05:00
|
|
|
|
|
|
|
makeNewInstance: (req) ->
|
|
|
|
instance = super(req)
|
2015-01-14 20:51:04 -05:00
|
|
|
instance.set('u', req.user._id)
|
|
|
|
# TODO: Remove 'user' after we stop querying for it (probably 30 days, ~2/16/15)
|
2014-12-15 14:45:12 -05:00
|
|
|
instance.set('user', req.user._id)
|
|
|
|
instance
|
|
|
|
|
2014-12-31 14:49:17 -05:00
|
|
|
getByRelationship: (req, res, args...) ->
|
2015-01-14 20:51:04 -05:00
|
|
|
return @logEvent(req, res) if args[1] is 'log_event'
|
2015-01-14 16:03:02 -05:00
|
|
|
# TODO: Remove these APIs
|
|
|
|
# return @getLevelCompletionsBySlug(req, res) if args[1] is 'level_completions'
|
|
|
|
# return @getCampaignCompletionsBySlug(req, res) if args[1] is 'campaign_completions'
|
2014-12-31 14:49:17 -05:00
|
|
|
super(arguments...)
|
|
|
|
|
2015-01-14 20:51:04 -05:00
|
|
|
logEvent: (req, res) ->
|
|
|
|
# Converts strings to string IDs where possible, and logs the event
|
2015-01-15 17:21:30 -05:00
|
|
|
user = req.user?._id
|
2015-01-14 20:51:04 -05:00
|
|
|
event = req.query.event or req.body.event
|
|
|
|
properties = req.query.properties or req.body.properties
|
|
|
|
@sendSuccess res # Return request immediately
|
2015-02-04 16:54:35 -05:00
|
|
|
AnalyticsLogEvent.logEvent user, event, properties
|
2015-01-14 20:51:04 -05:00
|
|
|
|
2015-01-05 13:28:56 -05:00
|
|
|
getLevelCompletionsBySlug: (req, res) ->
|
2014-12-31 14:49:17 -05:00
|
|
|
# Returns an array of per-day level starts and finishes
|
|
|
|
# Parameters:
|
2015-01-01 15:26:19 -05:00
|
|
|
# slug - level slug
|
2014-12-31 14:49:17 -05:00
|
|
|
# startDay - Inclusive, optional, e.g. '2014-12-14'
|
|
|
|
# endDay - Exclusive, optional, e.g. '2014-12-16'
|
2014-12-31 15:25:18 -05:00
|
|
|
|
2015-01-08 19:01:47 -05:00
|
|
|
# TODO: An uncached call can take over 50s locally
|
|
|
|
# TODO: mapReduce() was slower than find()
|
2014-12-31 14:49:17 -05:00
|
|
|
|
2015-01-01 15:26:19 -05:00
|
|
|
levelSlug = req.query.slug or req.body.slug
|
2014-12-31 14:49:17 -05:00
|
|
|
startDay = req.query.startDay or req.body.startDay
|
|
|
|
endDay = req.query.endDay or req.body.endDay
|
|
|
|
|
2015-01-01 15:26:19 -05:00
|
|
|
return @sendSuccess res, [] unless levelSlug?
|
2014-12-31 14:49:17 -05:00
|
|
|
|
2015-01-08 19:01:47 -05:00
|
|
|
# log.warn "level_completions levelSlug='#{levelSlug}' startDay=#{startDay} endDay=#{endDay}"
|
|
|
|
|
2014-12-31 14:49:17 -05:00
|
|
|
# Cache results for 1 day
|
|
|
|
@levelCompletionsCache ?= {}
|
|
|
|
@levelCompletionsCachedSince ?= new Date()
|
|
|
|
if (new Date()) - @levelCompletionsCachedSince > 86400 * 1000 # Dumb cache expiration
|
|
|
|
@levelCompletionsCache = {}
|
2015-01-01 15:01:43 -05:00
|
|
|
@levelCompletionsCachedSince = new Date()
|
2015-01-01 15:26:19 -05:00
|
|
|
cacheKey = levelSlug
|
2014-12-31 14:49:17 -05:00
|
|
|
cacheKey += 's' + startDay if startDay?
|
|
|
|
cacheKey += 'e' + endDay if endDay?
|
|
|
|
return @sendSuccess res, levelCompletions if levelCompletions = @levelCompletionsCache[cacheKey]
|
|
|
|
|
2015-01-08 19:01:47 -05:00
|
|
|
levelDateMap = {}
|
|
|
|
|
2014-12-31 14:49:17 -05:00
|
|
|
# Build query
|
2015-01-08 19:01:47 -05:00
|
|
|
queryParams = {$and: [
|
2015-01-08 20:00:02 -05:00
|
|
|
{$or: [{"event" : 'Started Level'}, {"event" : 'Saw Victory'}]}
|
2015-01-08 19:01:47 -05:00
|
|
|
]}
|
2015-01-14 14:09:01 -05:00
|
|
|
queryParams["$and"].push _id: {$gte: utils.objectIdFromTimestamp(startDay + "T00:00:00.000Z")} if startDay?
|
|
|
|
queryParams["$and"].push _id: {$lt: utils.objectIdFromTimestamp(endDay + "T00:00:00.000Z")} if endDay?
|
2015-01-08 19:01:47 -05:00
|
|
|
|
|
|
|
# Query stream is better for large results
|
|
|
|
# http://mongoosejs.com/docs/api.html#query_Query-stream
|
|
|
|
stream = AnalyticsLogEvent.find(queryParams).select('created event properties user').stream()
|
|
|
|
stream.on 'data', (item) =>
|
2014-12-31 14:49:17 -05:00
|
|
|
# Build per-level-day started and finished counts
|
2015-01-08 19:01:47 -05:00
|
|
|
created = item.get('created').toISOString().substring(0, 10)
|
|
|
|
event = item.get('event')
|
|
|
|
properties = item.get('properties')
|
|
|
|
if properties.level? then level = properties.level.toLowerCase().replace new RegExp(' ', 'g'), '-'
|
|
|
|
else if properties.levelID? then level = properties.levelID
|
|
|
|
else return
|
|
|
|
user = item.get('user')
|
|
|
|
|
|
|
|
# log.warn "level_completions data " + " " + created + " " + event + " " + level
|
|
|
|
|
|
|
|
levelDateMap[level] ?= {}
|
|
|
|
levelDateMap[level][created] ?= {}
|
|
|
|
levelDateMap[level][created]['finished'] ?= {}
|
|
|
|
levelDateMap[level][created]['started'] ?= {}
|
|
|
|
if event is 'Saw Victory' then levelDateMap[level][created]['finished'][user] = true
|
|
|
|
else levelDateMap[level][created]['started'][user] = true
|
|
|
|
.on 'error', (err) =>
|
|
|
|
return @sendDatabaseError res, err
|
|
|
|
.on 'close', () =>
|
2014-12-31 14:49:17 -05:00
|
|
|
# Build list of level completions
|
2015-01-01 15:26:19 -05:00
|
|
|
# Cache every level, since we had to grab all this data anyway
|
|
|
|
completions = {}
|
2014-12-31 14:49:17 -05:00
|
|
|
for level of levelDateMap
|
2015-01-01 15:26:19 -05:00
|
|
|
completions[level] = []
|
2014-12-31 14:49:17 -05:00
|
|
|
for created, item of levelDateMap[level]
|
2015-02-04 16:54:35 -05:00
|
|
|
completions[level].push
|
2014-12-31 14:49:17 -05:00
|
|
|
level: level
|
|
|
|
created: created
|
2015-01-08 19:01:47 -05:00
|
|
|
started: Object.keys(item.started).length
|
|
|
|
finished: Object.keys(item.finished).length
|
2015-01-01 15:26:19 -05:00
|
|
|
cacheKey = level
|
|
|
|
cacheKey += 's' + startDay if startDay?
|
|
|
|
cacheKey += 'e' + endDay if endDay?
|
|
|
|
@levelCompletionsCache[cacheKey] = completions[level]
|
2015-01-08 19:01:47 -05:00
|
|
|
unless levelSlug of completions then completions[levelSlug] = []
|
2015-01-01 15:26:19 -05:00
|
|
|
@sendSuccess res, completions[levelSlug]
|
2014-12-31 14:49:17 -05:00
|
|
|
|
2015-01-05 13:28:56 -05:00
|
|
|
getCampaignCompletionsBySlug: (req, res) ->
|
|
|
|
# Returns a dictionary of per-campaign level starts, finishes, and drop-offs
|
2015-01-01 15:01:43 -05:00
|
|
|
# Drop-off: last started or finished level event
|
|
|
|
# Parameters:
|
|
|
|
# slugs - array of campaign slugs
|
|
|
|
# startDay - Inclusive, optional, e.g. '2014-12-14'
|
|
|
|
# endDay - Exclusive, optional, e.g. '2014-12-16'
|
|
|
|
|
2015-01-07 17:49:21 -05:00
|
|
|
# TODO: Must be a better way to organize this series of database calls (campaigns, levels, analytics)
|
2015-01-08 19:01:47 -05:00
|
|
|
# TODO: An uncached call can take over 50s locally
|
2015-01-01 15:01:43 -05:00
|
|
|
# TODO: Returns all the campaigns
|
|
|
|
# TODO: Calculate overall campaign stats
|
2015-01-02 16:31:43 -05:00
|
|
|
# TODO: Assumes db campaign levels are in progression order. Should build this based on actual progression.
|
2015-01-07 17:49:21 -05:00
|
|
|
# TODO: Remove earliest duplicate event so our dropped counts will be more accurate.
|
2015-01-01 15:01:43 -05:00
|
|
|
|
2015-01-02 16:31:43 -05:00
|
|
|
campaignSlug = req.query.slug or req.body.slug
|
2015-01-01 15:01:43 -05:00
|
|
|
startDay = req.query.startDay or req.body.startDay
|
|
|
|
endDay = req.query.endDay or req.body.endDay
|
|
|
|
|
2015-01-08 19:01:47 -05:00
|
|
|
# log.warn "campaign_completions campaignSlug='#{campaignSlug}' startDay=#{startDay} endDay=#{endDay}"
|
|
|
|
|
2015-01-02 16:31:43 -05:00
|
|
|
return @sendSuccess res, [] unless campaignSlug?
|
2015-01-01 15:01:43 -05:00
|
|
|
|
|
|
|
# Cache results for 1 day
|
|
|
|
@campaignDropOffsCache ?= {}
|
|
|
|
@campaignDropOffsCachedSince ?= new Date()
|
|
|
|
if (new Date()) - @campaignDropOffsCachedSince > 86400 * 1000 # Dumb cache expiration
|
|
|
|
@campaignDropOffsCache = {}
|
|
|
|
@campaignDropOffsCachedSince = new Date()
|
2015-01-02 16:31:43 -05:00
|
|
|
cacheKey = campaignSlug
|
2015-01-01 15:01:43 -05:00
|
|
|
cacheKey += 's' + startDay if startDay?
|
|
|
|
cacheKey += 'e' + endDay if endDay?
|
|
|
|
return @sendSuccess res, campaignDropOffs if campaignDropOffs = @campaignDropOffsCache[cacheKey]
|
|
|
|
|
2015-01-07 17:49:21 -05:00
|
|
|
getCompletions = (campaigns, userProgression) =>
|
2015-01-02 16:31:43 -05:00
|
|
|
# Calculate campaign drop off rates
|
|
|
|
# Input:
|
|
|
|
# campaigns - per-campaign dictionary of ordered level slugs
|
2015-01-07 17:49:21 -05:00
|
|
|
# userProgression - per-user event lists
|
|
|
|
|
|
|
|
# Remove duplicate user events
|
|
|
|
for user of userProgression
|
|
|
|
userProgression[user] = _.uniq userProgression[user], false, (val, index, arr) -> val.event + val.level
|
|
|
|
|
|
|
|
# Order user progression by created
|
|
|
|
for user of userProgression
|
|
|
|
userProgression[user].sort (a,b) -> if a.created < b.created then return -1 else 1
|
|
|
|
|
|
|
|
# Per-level start/drop/finish/drop
|
|
|
|
levelProgression = {}
|
|
|
|
for user of userProgression
|
|
|
|
for i in [0...userProgression[user].length]
|
|
|
|
event = userProgression[user][i].event
|
|
|
|
level = userProgression[user][i].level
|
|
|
|
levelProgression[level] ?=
|
|
|
|
started: 0
|
|
|
|
startDropped: 0
|
|
|
|
finished: 0
|
|
|
|
finishDropped: 0
|
|
|
|
if event is 'Started Level'
|
|
|
|
levelProgression[level].started++
|
|
|
|
levelProgression[level].startDropped++ if i is userProgression[user].length - 1
|
|
|
|
else if event is 'Saw Victory'
|
|
|
|
levelProgression[level].finished++
|
|
|
|
levelProgression[level].finishDropped++ if i is userProgression[user].length - 1
|
|
|
|
|
|
|
|
# Put in campaign order
|
|
|
|
completions = {}
|
|
|
|
for level of levelProgression
|
|
|
|
for campaign of campaigns
|
|
|
|
if level in campaigns[campaign]
|
|
|
|
started = levelProgression[level].started
|
|
|
|
startDropped = levelProgression[level].startDropped
|
|
|
|
finished = levelProgression[level].finished
|
|
|
|
finishDropped = levelProgression[level].finishDropped
|
|
|
|
completions[campaign] ?=
|
|
|
|
levels: []
|
|
|
|
# overall:
|
|
|
|
# started: 0,
|
|
|
|
# startDropped: 0,
|
|
|
|
# finished: 0,
|
|
|
|
# finishDropped: 0
|
|
|
|
completions[campaign].levels.push
|
|
|
|
level: level
|
|
|
|
started: started
|
|
|
|
startDropped: startDropped
|
|
|
|
finished: finished
|
|
|
|
finishDropped: finishDropped
|
|
|
|
break
|
|
|
|
|
|
|
|
# Sort level data by campaign order
|
|
|
|
for campaign of completions
|
|
|
|
completions[campaign].levels.sort (a, b) ->
|
|
|
|
if campaigns[campaign].indexOf(a.level) < campaigns[campaign].indexOf(b.level) then return -1 else 1
|
|
|
|
|
|
|
|
# Return all campaign data for simplicity
|
|
|
|
# Cache other individual campaigns too, since we have them
|
|
|
|
@campaignDropOffsCache[cacheKey] = completions
|
|
|
|
for campaign of completions
|
|
|
|
cacheKey = campaign
|
|
|
|
cacheKey += 's' + startDay if startDay?
|
|
|
|
cacheKey += 'e' + endDay if endDay?
|
|
|
|
@campaignDropOffsCache[cacheKey] = completions
|
2015-01-08 19:01:47 -05:00
|
|
|
unless campaignSlug of completions then completions[campaignSlug] = levels: []
|
2015-01-07 17:49:21 -05:00
|
|
|
@sendSuccess res, completions
|
|
|
|
|
|
|
|
getUserEventData = (campaigns) =>
|
|
|
|
# Gather user start and finish event data
|
|
|
|
# Input:
|
|
|
|
# campaigns - per-campaign dictionary of ordered level slugs
|
|
|
|
# Output:
|
|
|
|
# userProgression - per-user event lists
|
|
|
|
|
|
|
|
userProgression = {}
|
2015-01-01 15:01:43 -05:00
|
|
|
|
2015-01-02 16:31:43 -05:00
|
|
|
queryParams = {$and: [{$or: [ {"event" : 'Started Level'}, {"event" : 'Saw Victory'}]}]}
|
2015-01-14 14:09:01 -05:00
|
|
|
queryParams["$and"].push _id: {$gte: utils.objectIdFromTimestamp(startDay + "T00:00:00.000Z")} if startDay?
|
|
|
|
queryParams["$and"].push _id: {$lt: utils.objectIdFromTimestamp(endDay + "T00:00:00.000Z")} if endDay?
|
2015-01-01 15:01:43 -05:00
|
|
|
|
2015-01-07 17:49:21 -05:00
|
|
|
# Query stream is better for large results
|
|
|
|
# http://mongoosejs.com/docs/api.html#query_Query-stream
|
|
|
|
stream = AnalyticsLogEvent.find(queryParams).select('created event properties user').stream()
|
|
|
|
stream.on 'data', (item) =>
|
|
|
|
created = item.get('created')
|
|
|
|
event = item.get('event')
|
|
|
|
if event is 'Saw Victory'
|
|
|
|
level = item.get('properties.level').toLowerCase().replace new RegExp(' ', 'g'), '-'
|
|
|
|
else
|
|
|
|
level = item.get('properties.levelID')
|
|
|
|
return unless level?
|
|
|
|
user = item.get('user')
|
|
|
|
userProgression[user] ?= []
|
|
|
|
userProgression[user].push
|
|
|
|
created: created
|
|
|
|
event: event
|
|
|
|
level: level
|
|
|
|
.on 'error', (err) =>
|
|
|
|
return @sendDatabaseError res, err
|
|
|
|
.on 'close', () =>
|
|
|
|
getCompletions campaigns, userProgression
|
2015-01-02 16:31:43 -05:00
|
|
|
|
|
|
|
getLevelData = (campaigns, campaignLevelIDs) =>
|
|
|
|
# Get level data and replace levelIDs with level slugs in campaigns
|
|
|
|
# Input:
|
|
|
|
# campaigns - per-campaign dictionary of ordered levelIDs
|
|
|
|
# campaignLevelIDs - dictionary of all campaign levelIDs
|
|
|
|
# Output:
|
|
|
|
# campaigns - per-campaign dictionary of ordered level slugs
|
|
|
|
|
|
|
|
Level.find({original: {$in: campaignLevelIDs}, "version.isLatestMajor": true, "version.isLatestMinor": true}).exec (err, documents) =>
|
|
|
|
if err? then return @sendDatabaseError res, err
|
|
|
|
|
|
|
|
levelSlugMap = {}
|
|
|
|
for doc in documents
|
|
|
|
levelID = doc.get('original')
|
|
|
|
levelSlug = doc.get('name').toLowerCase().replace new RegExp(' ', 'g'), '-'
|
|
|
|
levelSlugMap[levelID] = levelSlug
|
|
|
|
|
|
|
|
# Replace levelIDs with level slugs
|
|
|
|
for campaign of campaigns
|
|
|
|
mapFn = (item) -> levelSlugMap[item]
|
|
|
|
campaigns[campaign] = _.map campaigns[campaign], mapFn, @
|
|
|
|
|
2015-01-07 17:49:21 -05:00
|
|
|
getUserEventData campaigns
|
2015-01-02 16:31:43 -05:00
|
|
|
|
|
|
|
getCampaignData = () =>
|
2015-02-04 16:54:35 -05:00
|
|
|
# Get campaign data
|
2015-01-02 16:31:43 -05:00
|
|
|
# Output:
|
|
|
|
# campaigns - per-campaign dictionary of ordered levelIDs
|
|
|
|
# campaignLevelIDs - dictionary of all campaign levelIDs
|
|
|
|
|
|
|
|
Campaign.find().exec (err, documents) =>
|
|
|
|
if err? then return @sendDatabaseError res, err
|
|
|
|
|
|
|
|
campaigns = {}
|
|
|
|
levelCampaignMap = {}
|
|
|
|
campaignLevelIDs = []
|
|
|
|
for doc in documents
|
2015-01-08 19:01:47 -05:00
|
|
|
slug = doc.get('slug')
|
2015-01-02 16:31:43 -05:00
|
|
|
levels = doc.get('levels')
|
2015-01-08 19:01:47 -05:00
|
|
|
campaigns[slug] = []
|
|
|
|
levelCampaignMap[slug] = {}
|
2015-01-02 16:31:43 -05:00
|
|
|
for levelID of levels
|
2015-01-08 19:01:47 -05:00
|
|
|
campaigns[slug].push levelID
|
2015-01-02 16:31:43 -05:00
|
|
|
campaignLevelIDs.push levelID
|
2015-01-08 19:01:47 -05:00
|
|
|
levelCampaignMap[levelID] = slug
|
2015-01-02 16:31:43 -05:00
|
|
|
|
|
|
|
getLevelData campaigns, campaignLevelIDs
|
|
|
|
|
|
|
|
getCampaignData()
|
2015-01-01 15:01:43 -05:00
|
|
|
|
2014-12-15 14:45:12 -05:00
|
|
|
module.exports = new AnalyticsLogEventHandler()
|