All files / lib/models notification.ts

89.23% Statements 58/65
54.55% Branches 6/11
72.73% Functions 8/11
89.23% Lines 58/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200                16x 16x 16x 16x                                                       16x 16x   16x                                                                               16x       16x     16x 16x 16x   16x                       16x 15x   15x 15x 15x 15x                   15x             15x   14x 14x     14x     16x 1x 1x 1x   1x   1x 1x     16x 1x     16x 1x 1x   1x     16x 1x 1x 1x   1x 1x 1x   1x     16x 2x   2x 2x   2x             16x 15x 15x         16x 16x 16x   16x   16x    
import Crowi from 'server/crowi'
import { Types, Document, Model, Schema, Query, model } from 'mongoose'
import Debug from 'debug'
import moment from 'moment'
import ActivityDefine from '../util/activityDefine'
import { ActivityDocument } from './activity'
import { UserDocument } from './user'
 
const STATUS_UNREAD = 'UNREAD'
const STATUS_UNOPENED = 'UNOPENED'
const STATUS_OPENED = 'OPENED'
const STATUSES = [STATUS_UNREAD, STATUS_UNOPENED, STATUS_OPENED]
 
export interface NotificationDocument extends Document {
  _id: Types.ObjectId
  user: Types.ObjectId
  targetModel: string
  target: Types.ObjectId
  action: string
  activities: Types.ObjectId[]
  status: string
  createdAt: Date
}
 
export interface NotificationModel extends Model<NotificationDocument> {
  findLatestNotificationsByUser(user: Types.ObjectId, skip: number, offset: number): Promise<NotificationDocument[]>
  upsertByActivity(user: Types.ObjectId, activity: ActivityDocument, createdAt?: Date | null): Promise<NotificationDocument | null>
  removeActivity(activity: any): any
  removeEmpty(): Query<any>
  read(user: UserDocument): Promise<Query<any>>
  open(user: UserDocument, id: Types.ObjectId): Promise<NotificationDocument | null>
  getUnreadCountByUser(user: Types.ObjectId): Promise<number | undefined>
 
  STATUS_UNREAD: string
  STATUS_UNOPENED: string
  STATUS_OPENED: string
}
 
export default (crowi: Crowi) => {
  const debug = Debug('crowi:models:notification')
  const notificationEvent = crowi.event('Notification')
 
  const notificationSchema = new Schema<NotificationDocument, NotificationModel>({
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      index: true,
      require: true,
    },
    targetModel: {
      type: String,
      require: true,
      enum: ActivityDefine.getSupportTargetModelNames(),
    },
    target: {
      type: Schema.Types.ObjectId,
      refPath: 'targetModel',
      require: true,
    },
    action: {
      type: String,
      require: true,
      enum: ActivityDefine.getSupportActionNames(),
    },
    activities: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Activity',
      },
    ],
    status: {
      type: String,
      default: STATUS_UNREAD,
      enum: STATUSES,
      index: true,
      require: true,
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
  })
  notificationSchema.virtual('actionUsers').get(function(this: NotificationDocument) {
    const Activity = crowi.model('Activity')
    return Activity.getActionUsersFromActivities((this.activities as any) as ActivityDocument[])
  })
  const transform = (doc, ret) => {
    // delete ret.activities
  }
  notificationSchema.set('toObject', { virtuals: true, transform })
  notificationSchema.set('toJSON', { virtuals: true, transform })
  notificationSchema.index({ user: 1, target: 1, action: 1, createdAt: 1 })
 
  notificationSchema.statics.findLatestNotificationsByUser = function(user, limit, offset) {
    limit = limit || 10
 
    return Notification.find({ user })
      .sort({ createdAt: -1 })
      .skip(offset)
      .limit(limit)
      .populate(['user', 'target'])
      .populate({ path: 'activities', populate: { path: 'user' } })
      .exec()
  }
 
  notificationSchema.statics.upsertByActivity = async function(user, activity, createdAt = null) {
    const { _id: activityId, targetModel, target, action } = activity
 
    const now = createdAt || Date.now()
    const lastWeek = moment(now).subtract(7, 'days')
    const query = { user, target, action, createdAt: { $gt: lastWeek } }
    const parameters = {
      user,
      targetModel,
      target,
      action,
      status: STATUS_UNREAD,
      createdAt: now,
      $addToSet: { activities: activityId },
    }
 
    const options = {
      upsert: true,
      new: true,
      setDefaultsOnInsert: true,
      runValidators: true,
    }
 
    const notification = await Notification.findOneAndUpdate(query, parameters, options)
 
    Eif (notification) {
      notificationEvent.emit('update', notification.user)
    }
 
    return notification
  }
 
  notificationSchema.statics.removeActivity = async function(activity) {
    const { _id, target, action } = activity
    const query = { target, action }
    const parameters = { $pull: { activities: _id } }
 
    const result = await Notification.updateMany(query, parameters)
 
    await Notification.removeEmpty()
    return result
  }
 
  notificationSchema.statics.removeEmpty = function() {
    return Notification.remove({ activities: { $size: 0 } })
  }
 
  notificationSchema.statics.read = async function(user) {
    const query = { user, status: STATUS_UNREAD }
    const parameters = { status: STATUS_UNOPENED }
 
    return Notification.updateMany(query, parameters)
  }
 
  notificationSchema.statics.open = async function(user, id) {
    const query = { _id: id, user: user._id }
    const parameters = { status: STATUS_OPENED }
    const options = { new: true }
 
    const notification = await Notification.findOneAndUpdate(query, parameters, options)
    Eif (notification) {
      notificationEvent.emit('update', notification.user)
    }
    return notification
  }
 
  notificationSchema.statics.getUnreadCountByUser = async function(user) {
    const query = { user, status: STATUS_UNREAD }
 
    try {
      const count = await Notification.countDocuments(query)
 
      return count
    } catch (err) {
      debug('Error on getUnreadCountByUser', err)
      throw err
    }
  }
 
  notificationEvent.on('update', user => {
    const io = crowi.getIo()
    Iif (io) {
      io.sockets.emit('notification updated', { user })
    }
  })
 
  notificationSchema.statics.STATUS_UNOPENED = STATUS_UNOPENED
  notificationSchema.statics.STATUS_UNREAD = STATUS_UNREAD
  notificationSchema.statics.STATUS_OPENED = STATUS_OPENED
 
  const Notification = model<NotificationDocument, NotificationModel>('Notification', notificationSchema)
 
  return Notification
}