usual.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. const _ = require('lodash');
  3. const assert = require('assert');
  4. const Service = require('egg').Service;
  5. const columns = require('../public/query');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const moment = require('moment');
  8. //
  9. class UsualService extends Service {
  10. constructor(ctx) {
  11. super(ctx, 'usual');
  12. this.http = this.ctx.service.util.httpUtil;
  13. this.fetchService = this.ctx.service.fetch;
  14. this.createService = this.ctx.service.create;
  15. this.updateService = this.ctx.service.update;
  16. this.wxService = this.ctx.service.wx;
  17. this.prefix = '/db';
  18. }
  19. async reserve({ id }) {
  20. assert(id, '缺少预约安排信息');
  21. const data = await this.http.$post(`${this.prefix}/reserve`, { query: { id } });
  22. if (data && data.code) {
  23. throw new BusinessError(ErrorCode.SERVICE_FAULT, data.message);
  24. }
  25. let result = true;
  26. if (data <= 0) result = false;
  27. return { data: result };
  28. }
  29. /**
  30. * 发送消息
  31. * @param {Object} body 参数
  32. * @property {Array} user_ids 用户列表
  33. * @property {String} content 消息内容
  34. */
  35. async sendMessage({ user_ids, content }) {
  36. if (!this.ctx.user) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未获取发送人信息,无法发送信息');
  37. // 找到对应的用户,且用户存在openid的数据
  38. const templateId = 'vQi6KbytlFvyT6rLjeAwih5Ji6qMY2nBGXeMvNXrUkw';
  39. const time = moment().format('YYYY-MM-DD HH:mm:ss');
  40. const { wxServer } = this.app.config;
  41. if (!wxServer) throw new BusinessError(ErrorCode.SERVICE_FAULT, '未设置已读地址');
  42. const data = { templateId, data: { keyword2: { value: content }, keyword3: { value: time } } };
  43. const warningMessage = { send_id: this.ctx.user.id, send_name: this.ctx.user.name };
  44. for (const id of user_ids) {
  45. const user = await this.fetchService.index({ table: 'security_guard_base' }, { id });
  46. if (!user) continue;
  47. const { gopenid: openid, unionid, id: receive_id, name: receive_name } = user.data;
  48. // 发送消息
  49. const msgData = {
  50. ...warningMessage,
  51. send_time: time,
  52. receive_id,
  53. receive_name,
  54. content,
  55. };
  56. const msg = await this.createService.index({ table: 'warning_message' }, msgData);
  57. if (!msg.data) throw new BusinessError(ErrorCode.SERVICE_FAULT, '创建消息失败');
  58. const sendObject = { ...data, openid, unionid, url: `${wxServer}/api/usual/readMessage/${msg.data.id}` };
  59. await this.wxService.sendTemplate(sendObject);
  60. }
  61. }
  62. async readMessage({ id }) {
  63. await this.updateService.index({ table: 'warning_message' }, { id }, { is_read: '1' });
  64. }
  65. }
  66. module.exports = UsualService;