lrf 8 місяців тому
батько
коміт
fbb7e7e9c5

+ 49 - 16
src/controller/system/message.controller.ts

@@ -1,12 +1,12 @@
-import { Body, Controller, Del, Get, Inject, Param, Post, Query } from "@midwayjs/core";
-import { ApiQuery, ApiTags } from "@midwayjs/swagger";
-import { BaseController } from "../../frame/BaseController";
-import { Validate } from "@midwayjs/validate";
-import { omit, pick } from "lodash";
-import { ServiceError, ErrorCode } from "../../error/service.error";
-import { FVO_region, CVO_region } from "../../interface/system/region.interface";
-import { MessageService } from "../../service/system/message.service";
-
+import { Body, Controller, Del, Get, Inject, Param, Post, Query } from '@midwayjs/core';
+import { ApiQuery, ApiTags } from '@midwayjs/swagger';
+import { BaseController } from '../../frame/BaseController';
+import { Validate } from '@midwayjs/validate';
+import { get, omit, pick } from 'lodash';
+import { ServiceError, ErrorCode } from '../../error/service.error';
+import { MessageService } from '../../service/system/message.service';
+import { Context } from '@midwayjs/koa';
+import { MessageUserType } from '../../public/var';
 
 const namePrefix = '消息';
 @ApiTags(['消息'])
@@ -16,22 +16,28 @@ export class RegionController implements BaseController {
   @Inject()
   service: MessageService;
 
+  @Inject()
+  ctx: Context;
+
   @Get('/')
   @ApiTags('列表查询')
   @ApiQuery({ name: 'query' })
   async index(@Query() query: object) {
     const qobj = omit(query, ['skip', 'limit']);
     const others = pick(query, ['skip', 'limit']);
-    const result = await this.service.query(qobj, others);
-    return result;
+    let { data, total } = await this.service.query(qobj, others);
+    // 如果query中有'to.user',那就把to中其他的人的数据都删掉
+    if (qobj['to.user']) {
+      data = await this.service.deleteOtherUserInfo(data, qobj['to.user']);
+    }
+    return { data, total };
   }
 
   @Get('/:id')
   @ApiTags('单查询')
   async fetch(@Param('id') id: number) {
     const data = await this.service.fetch({ id });
-    const result = new FVO_region(data);
-    return result;
+    return data;
   }
 
   @Post('/', { routerName: `创建${namePrefix}` })
@@ -39,8 +45,24 @@ export class RegionController implements BaseController {
   @Validate()
   async create(@Body() data: object) {
     const dbData = await this.service.create(data);
-    const result = new CVO_region(dbData);
-    return result;
+    // 需要让mq发送消息,触发前端接收消息
+    const to = get(dbData, 'to', []);
+    for (const i of to) {
+      await this.service.toSendMq(get(i, 'user'), MessageUserType.USER, get(dbData, 'id'));
+    }
+    return dbData;
+  }
+
+  @Post('/remind/:id', { routerName: `重提示${namePrefix}` })
+  @ApiTags('重提示')
+  async remind(@Param('id') id: number) {
+    const message = await this.service.fetch({ id });
+    if (!message) return;
+    const to = get(message, 'to', []);
+    for (const i of to) {
+      await this.service.toSendMq(get(i, 'user'), MessageUserType.USER, id);
+    }
+    return;
   }
 
   @Post('/:id', { routerName: `修改${namePrefix}` })
@@ -61,4 +83,15 @@ export class RegionController implements BaseController {
     return result;
   }
 
-}
+  @Get('/checkNotRead')
+  @ApiTags('列表查询')
+  @ApiQuery({ name: 'query' })
+  async checkNotRead() {
+    const qobj = { 'to.is_read': '0' };
+    const user = get(this.ctx, 'user');
+    if (!user) return 0;
+    qobj['to.user'] = get(user, 'id');
+    const result = await this.service.query(qobj, { selects: ['id'] });
+    return get(result, 'total');
+  }
+}

+ 1 - 5
src/event/dbSubscriber.ts

@@ -3,12 +3,8 @@ import { EntitySubscriberInterface, InsertEvent, UpdateEvent, RemoveEvent } from
 import Axios from 'axios';
 import { Config } from '@midwayjs/core';
 import { get, toLower } from 'lodash';
+import { Methods } from '../public/var';
 
-enum Methods {
-  CREATE = 'CREATE',
-  UPDATE = 'UPDATE',
-  DELETE = 'DELETE',
-}
 
 /**
  * 数据库监听类

+ 24 - 13
src/frame/BaseServiceV2.ts

@@ -1,6 +1,6 @@
 import { App, Inject, MidwayWebRouterService } from '@midwayjs/core';
 import { Application, Context } from '@midwayjs/koa';
-import { compact, flattenDeep, get, head, isArray, isNull, isObject, isFinite, isString, isUndefined, last, uniq } from 'lodash';
+import { compact, flattenDeep, get, head, isArray, isNull, isObject, isFinite, isString, isUndefined, last, uniq, cloneDeep } from 'lodash';
 import { Opera } from './dbOpera';
 import { Opera as operaModel } from '../entityLogs/opera.entity';
 import dayjs = require('dayjs');
@@ -192,11 +192,11 @@ export abstract class BaseServiceV2 {
           let jorootCol = head(jokeys);
           let jolastKey = last(jokeys);
           let jopath = jokeys.filter(f => f !== jorootCol && f !== jolastKey);
-          str = `"${jorootCol}" `
+          str = `"${jorootCol}" `;
           for (const jok of jopath) {
-            str = `${str} -> ${jok}`
+            str = `${str} -> ${jok}`;
           }
-          str = `${str} ->> '${jolastKey}' = :${valueStr}`
+          str = `${str} ->> '${jolastKey}' = :${valueStr}`;
           params = { [`${valueStr}`]: value };
           break;
         case this.Opera.JsonArrayObject:
@@ -205,21 +205,32 @@ export abstract class BaseServiceV2 {
            * x:根子段;后面,数组中依次往下的属性名
            */
           const keys = key.split('.');
-          let newValue = value;
-          if (isFinite(parseInt(newValue))) newValue = parseInt(value);
+          let numberValue;
+          if (isFinite(parseInt(value))) numberValue = parseInt(value);
           let rootCol = head(keys);
           let lastKey = last(keys);
           let path = keys.filter(f => f !== rootCol && f !== lastKey);
-          let obj = {};
-          let mid = obj;
-          for (const k of path) {
-            mid[k] = {};
-            mid = mid[k];
-          }
-          mid[lastKey] = newValue;
+          const getObject = (path, lastKey, value) => {
+            let obj = {};
+            let mid = obj;
+            for (const k of path) {
+              mid[k] = {};
+              mid = mid[k];
+            }
+            mid[lastKey] = value;
+            return obj;
+          };
+          const obj = getObject(path, lastKey, value);
           let newVal = JSON.stringify([obj]);
           str = `"${rootCol}" @> :${valueStr}`;
           params = { [`${valueStr}`]: newVal };
+          if (numberValue) {
+            const numObj = getObject(path, lastKey, numberValue);
+            let numVal = JSON.stringify([numObj]);
+            const valueStrNum = `${valueStr}Num`;
+            str = `${str} OR "${rootCol}" @> :${valueStrNum}`;
+            params[valueStrNum] = numVal;
+          }
           break;
         case this.Opera.Equal:
         default:

+ 10 - 0
src/public/var.ts

@@ -0,0 +1,10 @@
+export enum Methods {
+  CREATE = 'CREATE',
+  UPDATE = 'UPDATE',
+  DELETE = 'DELETE',
+}
+
+export enum MessageUserType {
+  ADMIN = 'ADMIN',
+  USER = 'USER',
+}

+ 43 - 6
src/service/system/message.service.ts

@@ -1,14 +1,51 @@
-import { Provide } from "@midwayjs/core";
-import { InjectEntityModel } from "@midwayjs/typeorm";
-import { Repository } from "typeorm";
-import { Message } from "../../entity/system/message.entity";
-import { BaseServiceV2 } from "../../frame/BaseServiceV2";
+import { Config, Provide } from '@midwayjs/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository } from 'typeorm';
+import { Message } from '../../entity/system/message.entity';
+import { BaseServiceV2 } from '../../frame/BaseServiceV2';
+import { MessageUserType } from '../../public/var';
+import Axios from 'axios';
+import { get, omit } from 'lodash';
 
 @Provide()
 export class MessageService extends BaseServiceV2 {
   @InjectEntityModel(Message)
   model: Repository<Message>;
+  @Config('modulesConfig.mq')
+  mqServiceHttpPrefix: any;
   getQueryColumnsOpera() {
-    return { 'to.user': this.Opera.JsonArrayObject };
+    return { 'to.user': this.Opera.JsonArrayObject, 'to.is_read': this.Opera.JsonArrayObject };
+  }
+  /**
+   * 发送mq消息
+   * @param target mq接收人
+   * @param userType 用户类型
+   * @param data_id 消息数据id
+   */
+  async toSendMq(target, userType: MessageUserType, data_id) {
+    const url = `${this.mqServiceHttpPrefix}/send`;
+    const body = { target, userType, data_id };
+    try {
+      await Axios.post(url, body, { responseType: 'json' });
+    } catch (error) {
+      console.log(error);
+    }
+  }
+
+  /**
+   * 剃除非当前用户外的数据
+   * @param data 消息数据列表
+   * @param user 用户id
+   */
+  deleteOtherUserInfo(data, user) {
+    const nd = [];
+    for (const i of data) {
+      let to = get(i, 'to', []);
+      const ndo = omit(i, ['to']);
+      to = to.filter(f => f.user === user || f.user === parseInt(user));
+      ndo.to = to;
+      nd.push(ndo);
+    }
+    return nd;
   }
 }