Skip to content

Instantly share code, notes, and snippets.

@tsheaff
Created June 25, 2016 15:56
Show Gist options
  • Save tsheaff/304222ab7d9112d4713d6b61e4e31e74 to your computer and use it in GitHub Desktop.
Save tsheaff/304222ab7d9112d4713d6b61e4e31e74 to your computer and use it in GitHub Desktop.
models = require '../models'
sequelize = require 'sequelize'
async = require 'async'
_ = require 'lodash'
fs = require 'fs'
moment = require 'moment-timezone'
Intercom = require 'intercom-client'
IntercomClient = new Intercom.Client(process.env.INTERCOM_APP_ID, process.env.INTERCOM_API_KEY)
emails = fs.readFileSync('./scripts/unsubscribed_emails.txt').toString().split("\n")
unsubscribedEmails = {}
_.map(emails, (email) ->
unsubscribedEmails[email] = true
)
models.User.findAll({attributes: ['id'], where: {email: {$ne: null}}}).nodeify (err, usersResults) ->
if (err or not usersResults)
console.log 'no users found', err
return
console.log "#{usersResults.length} users"
allUserIds = _.map(usersResults, 'id')
queue = async.queue((userIds, done) ->
async.parallel {
stats: (callback) ->
models.Stats.findAll({where: {user_id: {$in: userIds}}}).nodeify (err, stats) ->
return callback() if err
return callback(null, _.keyBy(stats, 'user_id'))
subscriptions: (callback) ->
models.Subscription.findAll({where: {target_id: {$in: userIds}}}).nodeify (err, subscriptions) ->
return callback(null, _.keyBy(subscriptions, 'target_id'))
users: (callback) ->
models.User.findAll({where: {id: {$in: userIds}}}).nodeify (err, users) ->
return callback(null, _.keyBy(users, 'id'))
}, (err, results) ->
intercomUsers = _.map(userIds, (user_id) ->
user = results.users[user_id]
stats = results.stats[user.id]
statsData = if stats then stats.dataValues else {}
custom_attributes = {}
for key in ['current_streak', 'maximum_streak', 'total_sessions', 'total_duration']
custom_attributes[key] = statsData[key] or 0
subscription = results.subscriptions?[user.id]?.clean()
custom_attributes.is_subscribed = subscription?.valid or false
return {
create: {
user_id: user.id
email: user.email
name: user.name
signed_up_at: moment(user.created_at).unix()
unsubscribed_from_emails: Boolean(unsubscribedEmails[user.email])
custom_attributes: custom_attributes
}
}
)
IntercomClient.users.bulk(intercomUsers, (res) ->
console.log('submitted ', intercomUsers.length, ' to intercom')
console.log(' > intercom response is ', res.body)
done()
)
, 30)
queue.drain = ->
console.log 'Done!'
process.exit()
queue.push(_.chunk(allUserIds, 100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment