'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const assert = require('assert'); const { trimData } = require('naf-core').Util; const { ObjectId } = require('mongoose').Types; // 通知 class PatentnoticeService extends CrudService { constructor(ctx) { super(ctx, 'patentnotice'); this.model = this.ctx.model.Patent.Patentnotice; this.personalModel = this.ctx.model.User.Personal; this.adminModel = this.ctx.model.User.Admin; } async query(query, { skip = 0, limit = 0 } = {}) { const nq = await this.resetQuery(_.cloneDeep(query)); const data = await this.model .find(nq) .skip(parseInt(skip)) .limit(parseInt(limit)) .sort({ 'meta.createdAt': -1 }); return data; } async count(query) { const nq = await this.resetQuery(_.cloneDeep(query)); const res = await this.model.count(nq); return res; } async resetQuery(condition) { const { to_id } = condition; if (to_id) { condition.to_id = { $elemMatch: { $in: [ ObjectId(to_id) ] } }; } return condition; } /** * 根据send_id,和to_type,查询范围内的用户数据 * to_type=0:都查 * ...=1:只查机构用户 * ...=2:只查平台用户 * ...=3:机构给自己的平台用户发送信息 * ...=4:给指定用户发送消息 * @param {Object} body 数据 */ async create(body) { let object = {}; // 最后insert的数据集 // 先判断是不是3,如果不是3,就说明是管理员发送的 const { send_id, send_name, to_type, to_id, to_name, content, notice_file } = body; const admin = await this.adminModel.findById(send_id); // 获取自己的信息 if (!admin) { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到发送人信息'); } if (to_type === '3') { // 获取自己下的用户 const data = await this.getOrgUser(admin.code); // 整理->添加 object = { send_id, send_name, to_type, to_id: data.map(i => i._id), content, notice_file }; } else if (to_type === '4') { object = { send_id, send_name, to_type, to_id, to_name, content, notice_file }; } else { // 获取该管理员下的机构用户 const org = await this.adminModel.find( { pid: admin._id }, { id: 1, code: 1 } ); if (org.length <= 0) { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到相关机构信息'); } // 然后进行数据整合 if (to_type === '1') { // 将机构用户整理->添加 const ids = org.map(i => i._id); object = { send_id, send_name, to_type, to_id: ids, content, notice_file }; } else { // 再用机构的信息去查机构下的用户,整理->添加 const p1 = await this.getOrgUser(admin.code); const p2 = await this.getOrgUser(org.map(i => i.code)); let ids = [ ...p1.map(i => i._id), ...p2.map(i => i._id) ]; if (to_type === '0') { ids = [ ...ids, ...org.map(i => i._id) ]; } object = { send_id, send_name, to_type, to_id: ids, content, notice_file }; } } return await this.model.create(object); } /** * 获取指定code/codes(多个)的用户信息 * @param {String/Array} code */ async getOrgUser(code) { const data = await this.personalModel.find({ code }, { id: 1 }); return data; } } module.exports = PatentnoticeService;