The DTP Sites web app development engine.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

100 lines
2.5 KiB

// user-notification.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0
'use strict';
const path = require('path');
const mongoose = require('mongoose');
const UserNotification = mongoose.model('UserNotification');
const pug = require('pug');
const { SiteService } = require('../../lib/site-lib');
class UserNotificationService extends SiteService {
constructor (dtp) {
super(dtp, module.exports);
this.populateComment = [
{
path: 'author',
select: '_id username username_lc displayName picture',
},
{
path: 'replyTo',
},
];
}
async start ( ) {
this.templates = { };
this.templates.notification = pug.compileFile(path.join(this.dtp.config.root, 'app', 'views', 'notification', 'components', 'notification-standalone.pug'));
}
async create (user, notificationDefinition) {
const NOW = new Date();
const notification = new UserNotification();
notification.created = NOW;
notification.user = user._id;
notification.source = notificationDefinition.source;
notification.message = notificationDefinition.message;
notification.status = 'new';
notification.attachmentType = notificationDefinition.attachmentType;
notification.attachment = notificationDefinition.attachment;
await notification.save();
return notification.toObject();
}
async getNewCountForUser (user) {
const result = await UserNotification.aggregate([
{
$match: {
user: user._id,
status: 'new',
},
},
{
$group: {
_id: { user: 1 },
count: { $sum: 1 },
},
},
{
$project: {
_id: -1,
count: '$count',
},
},
]);
this.log('getNewCountForUser', { result });
return result[0].count;
}
async getForUser (user, pagination) {
const notifications = await UserNotification
.find({ user: user._id })
.sort({ created: -1 })
.skip(pagination.skip)
.limit(pagination.cpp)
.lean();
const newNotifications = notifications.map((notif) => notif.status === 'new');
if (newNotifications.length > 0) {
await UserNotification.updateMany(
{ _id: { $in: newNotifications.map((notif) => notif._id) } },
{ $set: { stats: 'seen' } },
);
}
return notifications;
}
}
module.exports = {
slug: 'user-notification',
name: 'userNotification',
create: (dtp) => { return new UserNotificationService(dtp); },
};