module.exports = {
  find: function (req, res) {
    var total

    Activity.query(function (qb) {
      qb.where('reader_id', req.session.userId)
      qb.limit(req.param('limit') || 10)
      qb.offset(req.param('offset') || 0)
      qb.select(bookshelf.knex.raw('activity.*, count(*) over () as total'))
      qb.orderBy('created_at', 'desc')

      qb.whereRaw('(comment.active = true or comment.id is null)')
      .leftJoin('comment', function () {
        this.on('comment.id', '=', 'activity.comment_id')
      })

      qb.whereRaw('(post.active = true or post.id is null)')
      .leftJoin('post', function () {
        this.on('post.id', '=', 'activity.post_id')
      })
    })
    .fetchAll({withRelated: [
      {actor: qb => qb.column('id', 'name', 'avatar_url')},
      {comment: qb => qb.column('id', 'comment_text', 'created_at')},
      {'comment.thanks': qb => qb.where('thanked_by_id', req.session.userId)},
      {post: qb => qb.column('id', 'name', 'user_id', 'type', 'description')},
      {'post.communities': qb => qb.column('community.id', 'slug')},
      {'post.relatedUsers': qb => qb.column('users.id', 'name', 'avatar_url')}
    ]})
    .tap(activities => total = (activities.length > 0 ? activities.first().get('total') : 0))
    .then(activities => {
      if (req.param('paginate')) {
        return {total, items: activities}
      } else {
        return activities
      }
    })
    .tap(() => req.param('resetCount') && User.query()
      .where('id', req.session.userId)
      .update({new_notification_count: 0}))
    .then(res.ok, res.serverError)
  },

  markAllRead: function (req, res) {
    Activity.query().where({reader_id: req.session.userId}).update({unread: false})
    .then(function () {
      res.ok({})
    })
    .catch(res.serverError.bind(res))
  },

  update: function (req, res) {
    Activity.find(req.param('activityId')).then(function (activity) {
      activity.attributes = _.pick(req.allParams(), 'unread')
      return activity.save()
    })
    .then(function () {
      res.ok({})
    })
    .catch(res.serverError.bind(res))
  }

}

@@ -839,16 +839,27 @@
 ated_at'
+, 'post_id'
 )%7D,%0A    
@@ -1657,16 +1657,21 @@
 .query()
+%0A    
 .where(%7B
@@ -1701,16 +1701,21 @@
 userId%7D)
+%0A    
 .update(
@@ -1741,35 +1741,21 @@
   .then(
-function () %7B%0A     
+() =%3E
  res.ok(
@@ -1749,38 +1749,32 @@
 () =%3E res.ok(%7B%7D)
-%0A    %7D
 )%0A    .catch(res
@@ -1781,34 +1781,24 @@
 .serverError
-.bind(res)
 )%0A  %7D,%0A%0A  up
@@ -1871,50 +1871,24 @@
 d'))
-.then(function (activity) %7B%0A      activity
+%0A    .tap(a =%3E a
 .att
@@ -1934,43 +1934,32 @@
 ad')
+)
 %0A    
-  return activity
+.tap(a =%3E a
 .save()
-%0A    %7D
 )%0A  
@@ -1966,35 +1966,21 @@
   .then(
-function () %7B%0A     
+() =%3E
  res.ok(
@@ -1982,22 +1982,16 @@
 s.ok(%7B%7D)
-%0A    %7D
 )%0A    .c
@@ -2014,18 +2014,8 @@
 rror
-.bind(res)
 )%0A  

add post_id to comments in ActivityController