'use strict'; const assert = require('assert'); const _ = require('lodash'); const { ObjectId } = require('mongoose').Types; const { CrudService } = require('naf-framework-mongoose/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const sd = require('silly-datetime'); class NoticeService extends CrudService { constructor(ctx) { super(ctx, 'notice'); this.model = this.ctx.model.Notice; this.umodel = this.ctx.model.User; this.stumodel = this.ctx.model.Student; this.schmodel = this.ctx.model.School; this.heamodel = this.ctx.model.Headteacher; this.teamodel = this.ctx.model.Teacher; } async create(data) { const { planyearid, planid, termid, classid, noticeid, content, notified } = data; assert(planyearid, '年度计划id为必填项'); assert(planid, '计划id为必填项'); assert(noticeid, '通知人id为必填项'); assert(content, '通知内容为必填项'); const res = await this.model.create(data); if (res) { for (const elm of res.notified) { const user = await this.umodel.findOne({ uid: elm.notifiedid }); if (!user) { continue; } if (user.openid) { const openid = user.openid; const remark = '感谢您的使用'; const date = await this.ctx.service.util.updatedate(); const detail = '尊敬的' + user.name + ',您有一个新的通知,请及时查收'; const tourl = this.ctx.app.config.baseUrl + '/mobiledirtea/messageInfo/index?uid=' + user.uid + '¬iceid=' + res.id; this.ctx.service.weixin.sendTemplateDesign(this.ctx.app.config.REVIEW_TEMPLATE_ID, openid, '您有一个新的通知', detail, date, remark, tourl); } } } } async look(data) { const { noticeid, uid } = data; const notice = await this.model.findById(noticeid); if (notice) { for (const elm of notice.notified) { if (elm.notifiedid === uid) { elm.status = '1'; elm.readtime = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss'); } } await notice.save(); } } async query({ skip, limit, ...info }) { const total = await this.model.count(info); const notices = await this.model.find(info).skip(Number(skip)).limit(Number(limit)); const res = []; for (const _notice of notices) { const notice = _.cloneDeep(JSON.parse(JSON.stringify(_notice))); const { noticeid, content, notified, meta } = notice; const elm = []; for (const notified of notice.notified) { const _notified = _.cloneDeep(JSON.parse(JSON.stringify(notified))); const userinfo = await this.findUserInfo(_notified.notifiedid); elm.push({ ...JSON.parse(JSON.stringify(userinfo)), ..._notified }); } res.push({ noticeid, content, meta, notified: elm }); } return { data: res, total }; } async findUserInfo(userid) { let userinfo; userinfo = await this.heamodel.findById(userid); if (!userinfo) { userinfo = await this.schmodel.findById(userid); } if (!userinfo) { userinfo = await this.teamodel.findById(userid); if (userinfo) { delete userinfo.status; } } if (!userinfo) { userinfo = await this.stumodel.findById(userid); } return userinfo; } } module.exports = NoticeService;