patentnotice.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const { trimData } = require('naf-core').Util;
  7. // 通知
  8. class PatentnoticeService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'patentnotice');
  11. this.model = this.ctx.model.Patent.Patentnotice;
  12. this.personalModel = this.ctx.model.Personal;
  13. this.adminModel = this.ctx.model.Admin;
  14. }
  15. async query(query, { skip = 0, limit = 0 } = 0) {
  16. query = await this.resetQuery(query);
  17. const data = await this.model.find(query).skip(parseInt(skip)).limit(parseInt(limit))
  18. .sort({ 'meta.createdAt': -1 });
  19. return data;
  20. }
  21. async count(query) {
  22. query = await this.resetQuery(query);
  23. const res = await this.model.countDocuments(trimData(query)).exec();
  24. return res;
  25. }
  26. async resetQuery(condition) {
  27. const { to_id } = condition;
  28. if (to_id) {
  29. condition.to_id = { $elemMatch: { $in: [ to_id ] } };
  30. }
  31. return condition;
  32. }
  33. /**
  34. * 根据send_id,和to_type,查询范围内的用户数据
  35. * to_type=1:只查机构用户
  36. * ...=2:只查平台用户
  37. * ...=0:都查
  38. * @param {Object} body 数据
  39. */
  40. async create(body) {
  41. const arr = []; // 最后insert的数据集
  42. const { send_id, to_type, content, send_name } = body;
  43. const admin = await this.adminModel.findById(send_id);
  44. if (!admin) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到管理员信息');
  45. const org = await this.personalModel.find({ pid: admin._id }, { id: 1, code: 1 });
  46. if (org.length <= 0) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到相关机构信息');
  47. if (to_type === '1') {
  48. const ids = org.map(i => i._id);
  49. for (const id of ids) {
  50. const obj = { send_id, send_name, to_type, to_id: id, content };
  51. arr.push(obj);
  52. }
  53. } else {
  54. const p1 = await this.personalModel.find({ code: admin.code }, { id: 1 });
  55. const p2 = await this.personalModel.find({ code: org.map(i => i.code) }, { id: 1 });
  56. let ids = [ ...p1.map(i => i._id), ...p2.map(i => i._id) ];
  57. if (to_type === 0) {
  58. ids = [ ...ids, ...org.map(i => i._id) ];
  59. }
  60. for (const id of ids) {
  61. const obj = { send_id, send_name, to_type, to_id: id, content };
  62. arr.push(obj);
  63. }
  64. }
  65. return await this.model.insertMany(arr);
  66. }
  67. }
  68. module.exports = PatentnoticeService;