Commit 1eac633e by sxy

feat: 消息接口

parent 0082ac61
var system = require("../../../system");
const http = require("http");
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class MsgCtl extends CtlBase {
constructor() {
super("msg", CtlBase.getServiceName(MsgCtl));
}
/**
* 创建消息
* @param {
* msgType,
* app_id,
* app_key(跳转链接时需要)
// * company_id(需要给某个交付商发送,暂时不考虑)
* sender (如果不传默认系统发的)
* sender_id
* emergency_level(紧急级别暂时不考虑)
* jump_address (详情跳转地址)
* target:[{id:"",name:''}] 发送给目标人 (非系统消息时必填)
* } pobj
* @param {*} qobj
* @param {*} req
*/
async create(pobj, qobj, req) {
if (!pobj.title) {
return system.getResult(null, "title can not be empty,100290");
}
if (!pobj.content) {
return system.getResult(null, "content can not be empty,100290");
}
if (!pobj.sender || !pobj.sender_id) {
return system.getResult(null, "发送者信息 can not be empty,100290");
}
if (pobj.jump_address && !pobj.app_key) {
return system.getResult(null, "需要跳转时,app_key不能为空");
}
if (!pobj.msgType) {
return system.getResult(null, "msgType can not be empty,100290");
}
if (pobj.msgType !== system.Msg.SYS && !pobj.target) {
return system.getResult(null, "非系统公告,target 不能为空");
}
if (pobj.msgType === system.Msg.SINGLE && Object.prototype.toString.call(pobj.target) !== '[object Object]') {
return system.getResult(null, "单条消息时,target格式是对象");
}
if ((pobj.msgType === system.Msg.SINGLE && pobj.target) && !pobj.target.id) {
return system.getResult(null, "单条消息时,目标用户id不能为空");
}
if (pobj.msgType === system.Msg.MULTI && Object.prototype.toString.call(pobj.target) !== "[object Array]") {
return system.getResult(null, "多条消息时,target格式是数组");
}
if ((pobj.msgType === system.Msg.MULTI && pobj.target) && pobj.target.length <= 0) {
return system.getResult(null, "多条消息时,target数组不能为空");
}
if ((pobj.msgType === system.Msg.MULTI && pobj.target) && pobj.target.length > 0) {
for (let val of pobj.target) {
if (!val.id) {
return system.getResult(null, "目标用户id不能为空");
}
}
}
try {
const rs = await this.service.create(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
/**
* 返回未提醒 消息
* @param {*} pobj
* @param {*} qobj
* @param {*} req
*/
async findRemindMessage(pobj, qobj, req) {
if (!pobj.userid) {
return system.getResult(null, "userid can not be empty,100290");
}
try {
const rs = await this.service.findRemindMessage(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
/**
* 查询 未读消息条数
* @param {*} pobj
* @param {*} qobj
* @param {*} req
*/
async findUnreadCount(pobj, qobj, req) {
if (!pobj.userid) {
return system.getResult(null, "userid can not be empty,100290");
}
pobj.is_read = false;
try {
const rs = await this.service.findUnreadCount(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
/**
* 更新已读未读
* @param {
* all true| false 全部已读未读
* } pobj
* @param {*} qobj
* @param {*} req
*/
async updateStatus(pobj, qobj, req) {
if (!pobj.userid) {
return system.getResult(null, "userid can not be empty,100290");
}
if (!pobj.id && !pobj.all) {
return system.getResult(null, "id can not be empty,100290");
}
try {
const rs = await this.service.updateStatus(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
/**
* 查询系统公告
* @param {*} pobj
* @param {*} qobj
* @param {*} req
*/
async findSystemMsgCount(pobj, qobj, req) {
try {
pobj.type = 'recently';
const rs = await this.service.findSystemMsgCount(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
/**
* 消息列表
* @param {*} pobj
* @param {*} qobj
* @param {*} req
*/
async list(pobj, qobj, req) {
if (!pobj.msgType) {
return system.getResult(null, "msgType can not be empty,100290");
}
if (!pobj.userid) {
return system.getResult(null, "userid can not be empty,100290");
}
try {
const rs = await this.service.list(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
/**
* 各个消息类型条数统计
*/
async groupCount(pobj, qobj, req) {
if (!pobj.userid) {
return system.getResult(null, "userid can not be empty,100290");
}
try {
const rs = await this.service.groupCount(pobj, qobj, req);
return system.getResult(rs);
} catch (err) {
return system.getResult(null, err.message)
}
}
}
module.exports = MsgCtl;
...@@ -16,7 +16,7 @@ class Dao { ...@@ -16,7 +16,7 @@ class Dao {
var u2 = this.preCreate(u); var u2 = this.preCreate(u);
if (t) { if (t) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log( this.model); console.log(this.model);
return this.model.create(u2, { transaction: t }).then(u => { return this.model.create(u2, { transaction: t }).then(u => {
return u; return u;
}); });
...@@ -30,7 +30,7 @@ class Dao { ...@@ -30,7 +30,7 @@ class Dao {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase() return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
} }
async refQuery(qobj) { async refQuery(qobj) {
var w =qobj.refwhere? qobj.refwhere:{}; var w = qobj.refwhere ? qobj.refwhere : {};
if (qobj.levelinfo) { if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level; w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
} }
...@@ -38,8 +38,8 @@ class Dao { ...@@ -38,8 +38,8 @@ class Dao {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode; w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
} }
//如果需要控制数据权限 //如果需要控制数据权限
if(qobj.datapriv){ if (qobj.datapriv) {
w["id"]={ [this.db.Op.in]: qobj.datapriv}; w["id"] = { [this.db.Op.in]: qobj.datapriv };
} }
if (qobj.likestr) { if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" }; w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
...@@ -48,12 +48,12 @@ class Dao { ...@@ -48,12 +48,12 @@ class Dao {
return this.model.findAll({ where: w, attributes: qobj.fields }); return this.model.findAll({ where: w, attributes: qobj.fields });
} }
} }
async bulkDelete(ids,t) { async bulkDelete(ids, t) {
if(t){ if (t) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } },transaction:t}); var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } }, transaction: t });
return en; return en;
}else{ } else {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } }}); var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en return en
} }
...@@ -70,13 +70,13 @@ class Dao { ...@@ -70,13 +70,13 @@ class Dao {
async delete(qobj, t) { async delete(qobj, t) {
var en = null var en = null
if (t != null && t != 'undefined') { if (t != null && t != 'undefined') {
en=await this.model.findOne({ where: {id:qobj.id},transaction:t}); en = await this.model.findOne({ where: { id: qobj.id }, transaction: t });
if (en != null) { if (en != null) {
await en.destroy({ transaction: t }); await en.destroy({ transaction: t });
return en return en
} }
} else { } else {
en=await this.model.findOne({ where: {id:qobj.id}}); en = await this.model.findOne({ where: { id: qobj.id } });
if (en != null) { if (en != null) {
return en.destroy(); return en.destroy();
} }
...@@ -92,9 +92,9 @@ class Dao { ...@@ -92,9 +92,9 @@ class Dao {
} }
orderBy(qobj) { orderBy(qobj) {
//return {"key":"include","value":{model:this.db.models.app}}; //return {"key":"include","value":{model:this.db.models.app}};
if(!qobj.orderInfo || qobj.orderInfo.length==0){ if (!qobj.orderInfo || qobj.orderInfo.length == 0) {
return [["created_at", "DESC"]]; return [["created_at", "DESC"]];
}else{ } else {
return qobj.orderInfo; return qobj.orderInfo;
} }
...@@ -178,10 +178,10 @@ class Dao { ...@@ -178,10 +178,10 @@ class Dao {
qcwhere["attributes"] = aggArray; qcwhere["attributes"] = aggArray;
qcwhere["raw"] = true; qcwhere["raw"] = true;
//提高效率去掉关联和排序,数据记录数量,为聚合 //提高效率去掉关联和排序,数据记录数量,为聚合
let tmpwhere={ let tmpwhere = {
attributes:qcwhere.attributes, attributes: qcwhere.attributes,
raw:true, raw: true,
where:qcwhere.where where: qcwhere.where
} }
var aggResult = await this.model.findOne(tmpwhere); var aggResult = await this.model.findOne(tmpwhere);
return aggResult; return aggResult;
...@@ -192,11 +192,11 @@ class Dao { ...@@ -192,11 +192,11 @@ class Dao {
} }
async findAndCountAll(qobj, t) { async findAndCountAll(qobj, t) {
var qc = this.buildQuery(qobj); var qc = this.buildQuery(qobj);
let findList={} let findList = {}
let count=await this.findCount({where:qc.where}) let count = await this.findCount({ where: qc.where })
var rows = await this.model.findAll(qc); var rows = await this.model.findAll(qc);
findList["count"]=count findList["count"] = count
findList["rows"]=rows findList["rows"] = rows
var aggresult = await this.findAggs(qobj, qc); var aggresult = await this.findAggs(qobj, qc);
var rtn = {}; var rtn = {};
rtn.results = findList; rtn.results = findList;
...@@ -223,16 +223,16 @@ class Dao { ...@@ -223,16 +223,16 @@ class Dao {
} }
async updateByWhere(setObj, whereObj, t) { async updateByWhere(setObj, whereObj, t) {
let inWhereObj={} let inWhereObj = {}
if (t && t != 'undefined') { if (t && t != 'undefined') {
if (whereObj && whereObj != 'undefined') { if (whereObj && whereObj != 'undefined') {
inWhereObj["where"]=whereObj; inWhereObj["where"] = whereObj;
inWhereObj["transaction"] = t; inWhereObj["transaction"] = t;
} else { } else {
inWhereObj["transaction"] = t; inWhereObj["transaction"] = t;
} }
}else{ } else {
inWhereObj["where"]=whereObj; inWhereObj["where"] = whereObj;
} }
return this.model.update(setObj, inWhereObj); return this.model.update(setObj, inWhereObj);
} }
...@@ -278,19 +278,26 @@ class Dao { ...@@ -278,19 +278,26 @@ class Dao {
if (includeObj != null && includeObj.length > 0) { if (includeObj != null && includeObj.length > 0) {
tmpWhere.include = includeObj; tmpWhere.include = includeObj;
tmpWhere.distinct = true; tmpWhere.distinct = true;
}else{ } else {
tmpWhere.raw = true; tmpWhere.raw = true;
} }
return await this.model.findAndCountAll(tmpWhere); return await this.model.findAndCountAll(tmpWhere);
} }
async findOne(obj) { async findOne(obj, attributes = []) {
return this.model.findOne({ "where": obj }); if (attributes.length > 0) {
return this.model.findOne({ "where": obj, attributes, row: true });
} else {
return this.model.findOne({ "where": obj, row: true });
}
} }
async findOneWithTm(obj,t) { async findOneWithTm(obj, t) {
return this.model.findOne({ "where": obj ,transaction:t}); return this.model.findOne({ "where": obj, transaction: t });
} }
async findById(oid) { async findById(oid) {
return this.model.findById(oid); return this.model.findById(oid);
} }
async findAll(obj, include = [], other = {}) {
return this.model.findAll({ "where": obj, include, row: true, ...other });
}
} }
module.exports = Dao; module.exports = Dao;
const Sequelize = require('sequelize'); const Sequelize = require('sequelize');
const settings=require("../../../../config/settings") const settings = require("../../../../config/settings")
const fs=require("fs") const fs = require("fs")
const path=require("path"); const path = require("path");
var glob = require("glob"); var glob = require("glob");
class DbFactory{ const Op = Sequelize.Op
constructor(){ class DbFactory {
const dbConfig=settings.database(); constructor() {
this.db=new Sequelize(dbConfig.dbname, const dbConfig = settings.database();
dbConfig.user, this.db = new Sequelize(dbConfig.dbname,
dbConfig.password, dbConfig.user,
dbConfig.config); dbConfig.password,
this.db.Sequelize=Sequelize; {
this.db.Op=Sequelize.Op; ...dbConfig.config,
operatorsAliases: {
$eq: Op.eq,
$ne: Op.ne,
$gte: Op.gte,
$gt: Op.gt,
$lte: Op.lte,
$lt: Op.lt,
$not: Op.not,
$in: Op.in,
$notIn: Op.notIn,
$is: Op.is,
$like: Op.like,
$notLike: Op.notLike,
$iLike: Op.iLike,
$notILike: Op.notILike,
$regexp: Op.regexp,
$notRegexp: Op.notRegexp,
$iRegexp: Op.iRegexp,
$notIRegexp: Op.notIRegexp,
$between: Op.between,
$notBetween: Op.notBetween,
$overlap: Op.overlap,
$contains: Op.contains,
$contained: Op.contained,
$adjacent: Op.adjacent,
$strictLeft: Op.strictLeft,
$strictRight: Op.strictRight,
$noExtendRight: Op.noExtendRight,
$noExtendLeft: Op.noExtendLeft,
$and: Op.and,
$or: Op.or,
$any: Op.any,
$all: Op.all,
$values: Op.values,
$col: Op.col
}
});
this.db.Sequelize = Sequelize;
this.db.Op = Sequelize.Op;
this.initModels(); this.initModels();
this.initRelations(); this.initRelations();
} }
async initModels(){ async initModels() {
var self=this; var self = this;
var modelpath=path.normalize(path.join(__dirname, '../..'))+"/models/"; var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
var models=glob.sync(modelpath+"/**/*.js"); var models = glob.sync(modelpath + "/**/*.js");
console.log(models.length); console.log(models.length);
models.forEach(function(m){ models.forEach(function (m) {
console.log(m); console.log(m);
self.db.import(m); self.db.import(m);
}); });
console.log("init models...."); console.log("init models....");
} }
async initRelations(){ async initRelations() {
this.db.models.dataauth.belongsTo(this.db.models.user,{constraints: false,}); this.db.models.dataauth.belongsTo(this.db.models.user, { constraints: false, });
/*建立用户和角色之间的关系*/ /*建立用户和角色之间的关系*/
this.db.models.user.belongsToMany(this.db.models.role, {as:"Roles",through: 'p_userrole',constraints: false,}); this.db.models.user.belongsToMany(this.db.models.role, { as: "Roles", through: 'p_userrole', constraints: false, });
this.db.models.role.belongsToMany(this.db.models.user, {as:"Users",through: 'p_userrole',constraints: false,}); this.db.models.role.belongsToMany(this.db.models.user, { as: "Users", through: 'p_userrole', constraints: false, });
/*组织机构自引用*/ /*组织机构自引用*/
//this.db.models.org.belongsTo(this.db.models.org,{constraints: false,}); //this.db.models.org.belongsTo(this.db.models.org,{constraints: false,});
//this.db.models.org.hasMany(this.db.models.org,{constraints: false,}); //this.db.models.org.hasMany(this.db.models.org,{constraints: false,});
//组织机构和角色是多对多关系,建立兼职岗位,给岗位赋予多个角色,从而同步修改用户的角色 //组织机构和角色是多对多关系,建立兼职岗位,给岗位赋予多个角色,从而同步修改用户的角色
//通过岗位接口去修改用户的角色 //通过岗位接口去修改用户的角色
//this.db.models.role.belongsToMany(this.db.models.org,{through: this.db.models.orgrole,constraints: false,}); //this.db.models.role.belongsToMany(this.db.models.org,{through: this.db.models.orgrole,constraints: false,});
//this.db.models.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,}); //this.db.models.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,});
//组织机构和用户是1对多, //组织机构和用户是1对多,
// this.db.models.user.belongsTo(this.db.models.org,{constraints: false,}); // this.db.models.user.belongsTo(this.db.models.org,{constraints: false,});
// this.db.models.org.hasMany(this.db.models.user,{constraints: false,}); // this.db.models.org.hasMany(this.db.models.user,{constraints: false,});
this.db.models.user.belongsTo(this.db.models.app,{constraints: false,}); this.db.models.user.belongsTo(this.db.models.app, { constraints: false, });
this.db.models.role.belongsTo(this.db.models.app, {constraints: false,}); this.db.models.role.belongsTo(this.db.models.app, { constraints: false, });
this.db.models.auth.belongsTo(this.db.models.app, { constraints: false, });
this.db.models.auth.belongsTo(this.db.models.company, { constraints: false, });
this.db.models.auth.belongsTo(this.db.models.role, { constraints: false, });
this.db.models.auth.belongsTo(this.db.models.app,{constraints: false,}); this.db.models.app.belongsTo(this.db.models.user, { as: "creator", constraints: false, });
this.db.models.auth.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.auth.belongsTo(this.db.models.role,{constraints: false,});
this.db.models.app.belongsTo(this.db.models.user,{as:"creator",constraints: false,});
this.db.models.user.belongsTo(this.db.models.company, { constraints: false, });
this.db.models.user.belongsTo(this.db.models.company,{constraints: false,}); this.db.models.company.hasMany(this.db.models.user, { as: 'us', constraints: false, });
this.db.models.company.hasMany(this.db.models.user,{as:'us',constraints: false,});
this.db.models.role.belongsTo(this.db.models.company, {constraints: false,}); this.db.models.role.belongsTo(this.db.models.company, { constraints: false, });
// this.db.models.org.belongsTo(this.db.models.company,{constraints: false,}); // this.db.models.org.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.route.belongsTo(this.db.models.app,{constraints: false,}); this.db.models.route.belongsTo(this.db.models.app, { constraints: false, });
this.db.models.plugin.belongsTo(this.db.models.app,{constraints: false,}); this.db.models.plugin.belongsTo(this.db.models.app, { constraints: false, });
//渠道和渠道路径方法映射
this.db.models.pathtomethod.belongsTo(this.db.models.channel, { constraints: false, });
this.db.models.channel.hasMany(this.db.models.pathtomethod, { as: "pts", constraints: false, });
//产品相关
this.db.models.productprice.belongsTo(this.db.models.product, { constraints: false, });
this.db.models.product.hasMany(this.db.models.productprice, { as: "skus", constraints: false, });
this.db.models.product.belongsTo(this.db.models.company, { constraints: false, });
//产品价格引用定价策略
this.db.models.productprice.belongsTo(this.db.models.pricestrategy, { constraints: false, });
this.db.models.productprice.belongsTo(this.db.models.company, { constraints: false, });
//成本项目属于productprice
this.db.models.productcost.belongsTo(this.db.models.productprice, { constraints: false, });
this.db.models.productprice.hasMany(this.db.models.productcost, { as: "costs", constraints: false, });
//渠道和渠道路径方法映射 // 消息 -> 用户消息关联 1:n
this.db.models.pathtomethod.belongsTo(this.db.models.channel,{constraints: false,}); this.db.models.msg.hasMany(this.db.models.msguser, { constraints: false });
this.db.models.channel.hasMany(this.db.models.pathtomethod,{as:"pts",constraints: false,}); this.db.models.msguser.belongsTo(this.db.models.msg, { constraints: false });
//产品相关
this.db.models.productprice.belongsTo(this.db.models.product,{constraints: false,});
this.db.models.product.hasMany(this.db.models.productprice,{as:"skus",constraints: false,});
this.db.models.product.belongsTo(this.db.models.company,{constraints: false,});
//产品价格引用定价策略
this.db.models.productprice.belongsTo(this.db.models.pricestrategy,{constraints: false,});
this.db.models.productprice.belongsTo(this.db.models.company,{constraints: false,});
//成本项目属于productprice
this.db.models.productcost.belongsTo(this.db.models.productprice,{constraints: false,});
this.db.models.productprice.hasMany(this.db.models.productcost,{as:"costs",constraints: false,});
} }
//async getCon(){,用于使用替换table模型内字段数据使用 //async getCon(){,用于使用替换table模型内字段数据使用
getCon(){ getCon() {
var that=this; var that = this;
// await this.db.authenticate().then(()=>{ // await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.'); // console.log('Connection has been established successfully.');
// }).catch(err => { // }).catch(err => {
...@@ -92,7 +137,7 @@ class DbFactory{ ...@@ -92,7 +137,7 @@ class DbFactory{
// throw err; // throw err;
// }); // });
//同步模型 //同步模型
if(settings.env=="dev"){ if (settings.env == "dev") {
//console.log(pa); //console.log(pa);
// pconfigObjs.forEach(p=>{ // pconfigObjs.forEach(p=>{
...@@ -109,7 +154,7 @@ class DbFactory{ ...@@ -109,7 +154,7 @@ class DbFactory{
return this.db; return this.db;
} }
} }
module.exports=DbFactory; module.exports = DbFactory;
// const dbf=new DbFactory(); // const dbf=new DbFactory();
// dbf.getCon().then((db)=>{ // dbf.getCon().then((db)=>{
// //console.log(db); // //console.log(db);
......
const system = require("../../../system");
const Dao = require("../../dao.base");
class MsguserDao extends Dao {
constructor() {
super(Dao.getModelName(MsguserDao));
}
}
module.exports = MsguserDao;
const system = require("../../../system"); const system = require("../../../system");
const settings = require("../../../../config/settings"); const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig(); const appconfig = system.getSysConfig();
module.exports = (db, DataTypes) => { module.exports = (db, DataTypes) => {
return db.define("msghistory", { return db.define("msg", {
msgType:{ msgType: {
type:DataTypes.ENUM, type: DataTypes.ENUM,
allowNull: false, allowNull: false,
values: Object.keys(appconfig.pdict.msgType), values: Object.keys(appconfig.pdict.msgType),
}, },
app_id:DataTypes.INTEGER, app_id: {
company_id:DataTypes.INTEGER, type: DataTypes.INTEGER,
sender:DataTypes.STRING, allowNull: true
senderId:DataTypes.INTEGER, },
target:DataTypes.STRING, app_key: {
targetId:DataTypes.INTEGER, type: DataTypes.STRING,
content: { allowNull: true
type: DataTypes.TEXT('long'), },
allowNull: false, company_id: {
},//需要在后台补充 type: DataTypes.INTEGER,
isRead:{ allowNull: true
type:DataTypes.BOOLEAN, },
defaultValue: false, sender: {
type: DataTypes.STRING,
allowNull: true
},
sender_id: {
type: DataTypes.INTEGER,
allowNull: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
emergency_level: {
type: DataTypes.INTEGER,
defaultValue: 0
},
content: {
type: DataTypes.TEXT('long'),
allowNull: false,
},
jump_address: {
type: DataTypes.STRING,
allowNull: true
},
other: {
allowNull: true,
type: DataTypes.JSON
},
is_undo: {
type: DataTypes.BOOLEAN,
defaultValue: false
} }
},{ }, {
paranoid: false,//假的删除 paranoid: false,//假的删除
underscored: true, underscored: true,
version: true, version: true,
freezeTableName: true, freezeTableName: true,
//freezeTableName: true, //freezeTableName: true,
// define the table's name // define the table's name
tableName: 'msg_history', tableName: 'msg_history',
validate: { validate: {
}, },
indexes:[ indexes: [
// Create a unique index on email // Create a unique index on email
// { // {
// unique: true, // unique: true,
// fields: ['email'] // fields: ['email']
// }, // },
// //
// // Creates a gin index on data with the jsonb_path_ops operator // // Creates a gin index on data with the jsonb_path_ops operator
// { // {
// fields: ['data'], // fields: ['data'],
// using: 'gin', // using: 'gin',
// operator: 'jsonb_path_ops' // operator: 'jsonb_path_ops'
// }, // },
// //
// // By default index name will be [table]_[fields] // // By default index name will be [table]_[fields]
// // Creates a multi column partial index // // Creates a multi column partial index
// { // {
// name: 'public_by_author', // name: 'public_by_author',
// fields: ['author', 'status'], // fields: ['author', 'status'],
// where: { // where: {
// status: 'public' // status: 'public'
// } // }
// }, // },
// //
// // A BTREE index with a ordered field // // A BTREE index with a ordered field
// { // {
// name: 'title_index', // name: 'title_index',
// method: 'BTREE', // method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}] // fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// } // }
] ]
}); });
} }
module.exports = (db, DataTypes) => { module.exports = (db, DataTypes) => {
return db.define("msgnotice", { return db.define("msguser", {
fromuser: DataTypes.STRING,//需要在后台补充 user_id: {
fromId:DataTypes.INTEGER, type: DataTypes.INTEGER,
touser: DataTypes.STRING,//需要在后台补充 allowNull: false
toId:DataTypes.INTEGER, },
isAccepted:DataTypes.BOOLEAN, user: {
lastMsgId:DataTypes.INTEGER type: DataTypes.STRING,
},{ allowNull: true
paranoid: true,//假的删除 },
underscored: true, is_read: {
version: true, type: DataTypes.BOOLEAN,
freezeTableName: true, defaultValue: false
//freezeTableName: true, },
// define the table's name is_remind: {
tableName: 'msg_notice', type: DataTypes.BOOLEAN,
validate: { defaultValue: false
},
msg_id: {
type: DataTypes.INTEGER,
defaultValue: false
}
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msg_history_p_user_relationships',
validate: {
}, },
indexes:[ indexes: [
// Create a unique index on email // Create a unique index on email
// { // {
// unique: true, // unique: true,
// fields: ['email'] // fields: ['email']
// }, // },
// //
// // Creates a gin index on data with the jsonb_path_ops operator // // Creates a gin index on data with the jsonb_path_ops operator
// { // {
// fields: ['data'], // fields: ['data'],
// using: 'gin', // using: 'gin',
// operator: 'jsonb_path_ops' // operator: 'jsonb_path_ops'
// }, // },
// //
// // By default index name will be [table]_[fields] // // By default index name will be [table]_[fields]
// // Creates a multi column partial index // // Creates a multi column partial index
// { // {
// name: 'public_by_author', // name: 'public_by_author',
// fields: ['author', 'status'], // fields: ['author', 'status'],
// where: { // where: {
// status: 'public' // status: 'public'
// } // }
// }, // },
// //
// // A BTREE index with a ordered field // // A BTREE index with a ordered field
// { // {
// name: 'title_index', // name: 'title_index',
// method: 'BTREE', // method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}] // fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// } // }
] ]
}); });
} }
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const moment = require("moment");
class MsgService extends ServiceBase {
constructor() {
super("msg", ServiceBase.getDaoName(MsgService));
this.msguserDao = system.getObject("db.msg.msguserDao");
}
async create(pobj, qobj, req) {
let {
msgType, app_id, app_key, sender, sender_id, title,
content, jump_address, other, target
} = pobj;
let msg = {
msgType,
app_id,
app_key,
sender: sender,
sender_id: sender_id,
title,
content,
jump_address,
other
}
return this.db.transaction(async (t) => {
const msgData = await this.dao.create(msg, t);
if (msgType !== system.Msg.SYS && Object.prototype.toString.call(target) === '[object Object]') {
await this.msguserDao.create({
user_id: target.id,
user: target.name,
msg_id: msgData.id
}, t);
}
if (msgType !== system.Msg.SYS && Object.prototype.toString.call(target) === "[object Array]") {
let msgusers = [];
for (let val of target) {
msgusers.push({
user_id: val.id,
user: val.name,
msg_id: msgData.id
})
}
await this.msguserDao.bulkCreate(msgusers, t);
}
return 'SUCCESS'
})
}
async findRemindMessage(pobj, qobj, req) {
let { userid } = pobj;
const msgData = await this.msguserDao.findAll({
user_id: userid,
is_remind: false
}, [
{
model: this.db.models.msg,
where: {
is_undo: false
},
}
]);
const ids = msgData.map(item => item.id)
if (ids.length > 0) {
this.msguserDao.updateByWhere({
is_remind: true
}, {
id: {
$in: ids
}
});
}
return msgData;
}
async findUnreadCount(pobj, qobj, req) {
let { userid, is_read } = pobj;
const msgCount = await this.msguserDao.findCount({
where: {
user_id: userid,
is_read
}, include: [
{
model: this.db.models.msg,
where: {
is_undo: false
},
attributes: ["id"]
}
]
});
return { count: msgCount };
}
async updateStatus(pobj, qobj, req) {
let { id, userid, all } = pobj;
let where = {
is_read: false,
user_id: userid
};
if (!all) {
where.id = id
}
await this.msguserDao.updateByWhere({
is_read: true
}, where);
return "SUCESS"
}
async findSystemMsgCount(pobj, qobj, req) {
let { type } = pobj;
let where = {
msgType: system.Msg.SYS,
is_undo: false,
}
if (type === "recently") {
// 查询 三天内的
where.created_at = {
$between: [
moment().subtract('days', 3).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')
]
}
}
const msgCount = await this.dao.findCount({
where
});
return { count: msgCount };
}
async groupCount(pobj, qobj, req) {
let { userid } = pobj;
let [read, unRead, system] = await Promise.all(
[
this.findUnreadCount({ userid, is_read: true }),
this.findUnreadCount({ userid, is_read: false }),
this.findSystemMsgCount({ type: "all" })
]
);
return {
read: read.count, unRead: unRead.count, system: system.count
}
}
async list(pobj, qobj, req) {
let { userid, msgType, pageSize = 10, pageNo = 1 } = pobj;
let msgData = [];
let other = {
limit: pageSize,
offset: (pageNo - 1) * pageSize,
order: [["created_at", "DESC"]]
};
if (["read", "unread"].includes(msgType)) {
msgData = await this.msguserDao.findAll({
user_id: userid,
is_read: msgType === "read"
}, [
{
model: this.db.models.msg,
where: {
is_undo: false
}
}
], other);
}
if (msgType === "system") {
msgData = await this.dao.findAll({
msgType: system.Msg.SYS,
is_undo: false,
}, [], other);
msgData = msgData.map(item => {
return {
msg: item
}
})
}
return msgData;
}
}
module.exports = MsgService;
...@@ -275,6 +275,13 @@ Date.prototype.Format = function (fmt) { //author: meizz ...@@ -275,6 +275,13 @@ Date.prototype.Format = function (fmt) { //author: meizz
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt; return fmt;
} }
System.Msg = {
// "sys": "系统", "single": "单点", "multi": "群发"
SYS: "sys",
SINGLE: "single",
MULTI: "multi"
}
/* /*
编码说明, 编码说明,
1000----1999 为请求参数验证和app权限验证 1000----1999 为请求参数验证和app权限验证
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment