codecombat/server/routes/mail.coffee

35 lines
1.2 KiB
CoffeeScript
Raw Normal View History

2014-01-24 14:48:00 -05:00
mail = require '../commons/mail'
map = _.invert mail.MAILCHIMP_GROUP_MAP
User = require '../users/User.coffee'
errors = require '../commons/errors'
request = require 'request'
config = require '../../server_config'
2014-01-24 14:48:00 -05:00
module.exports.setupRoutes = (app) ->
app.all config.mail.mailchimpWebhook, (req, res) ->
2014-01-24 14:48:00 -05:00
post = req.body
return res.end() unless post.type in ['unsubscribe', 'profile']
return res.end() unless post.data.email
2014-01-24 15:39:05 -05:00
User.findOne {'mailChimp.euid':post.data.id}, (err, user) ->
2014-01-24 15:23:14 -05:00
return errors.serverError(res) if err
return errors.notFound(res) if not user
2014-01-24 15:39:05 -05:00
handleProfileUpdate(user, post) if post.type is 'profile'
handleUnsubscribe(user) if post.type is 'unsubscribe'
2014-01-24 15:23:14 -05:00
user.updatedMailChimp = true # so as not to echo back to mailchimp
user.save (err) ->
return errors.serverError(res) if err
2014-01-24 15:23:14 -05:00
res.end()
2014-01-24 15:39:05 -05:00
handleProfileUpdate = (user, post) ->
groups = post.data.merges.INTERESTS.split(', ')
2014-01-24 15:23:14 -05:00
groups = (map[g] for g in groups when map[g])
user.set 'emailSubscriptions', groups
mailChimpInfo = user.get 'mailChimp'
2014-01-24 15:39:05 -05:00
mailChimpInfo.email = post.data.email
2014-01-24 15:23:14 -05:00
user.set 'mailChimp', mailChimpInfo
2014-01-24 14:48:00 -05:00
2014-01-24 15:39:05 -05:00
handleUnsubscribe = (user) ->
2014-01-24 15:23:14 -05:00
user.set 'emailSubscriptions', []