Commit 77b4cb5b by 蒋勇

d

parent 03b8df99
#!/bin/bash #!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang2/node105:v2 FROM registry.cn-beijing.aliyuncs.com/hantang2/node105:v2
MAINTAINER jy "jiangyong@gongsibao.com" MAINTAINER jy "jiangyong@gongsibao.com"
ADD center-manage /apps/center-manage/ ADD im-center /apps/im-center/
WORKDIR /apps/center-manage/ WORKDIR /apps/im-center/
RUN cnpm install -S RUN cnpm install -S
CMD ["node","/apps/center-manage/main.js"] CMD ["node","/apps/im-center/main.js"]
......
node_modules/
app/config/localsettings.js
*.sh
\ No newline at end of file
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
const system = require("../system");
const uuidv4 = require('uuid/v4');
const settings = require("../../config/settings");
class APIBase{
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
this.logClient=system.getObject("util.logClient");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async setContextParams(pobj, qobj, req) {
let custtags = req.headers["x-consumetag"]?req.headers["x-consumetag"].split("|"):null;
//当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值
req.xctx = {
appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色
companyid: custtags?custtags[0].split("_")[1]:null,
password: custtags?custtags[1].split("_")[1]:null,
username: req.headers["x-consumer-username"],
credid: req.headers["x-credential-identifier"],
companykey:req.headers["x-company-key"],//专用于自由用户注册,自由用户用于一定属于某个存在的公司
codename:req.headers["xcodename"],
codetitle:req.headers["xcodetitle"]?decodeURI(req.headers["xcodetitle"]):'',
}
if(!req.xctx.appkey){
return [-200,"请求头缺少应用x-app-key"]
}else{
let app=await this.cacheManager["AppCache"].cache(req.xctx.appkey);
req.xctx.appid=app.id;
pobj.app_id=app.id;//传递参数对象里注入app_id
}
//平台注册时,companyid,companykey都为空
//自由注册时,companykey不能为空
// if(!req.xctx.companyid && !req.xctx.companykey){
// return [-200,"请求头缺少应用x-app-key"]
// }
if(!req.xctx.companyid && req.xctx.companykey){
let comptmp=await this.cacheManager["CompanyCache"].cache(req.xctx.companykey);
req.xctx.companyid=comptmp.id;
}
if(req.xctx.companyid){//在请求传递数据对象注入公司id
pobj.company_id=req.xctx.companyid;
}
}
async doexec(gname, methodname, pobj, query, req) {
try {
let xarg=await this.setContextParams(pobj, query, req);
if(xarg && xarg[0]<0){
return system.getResultFail(...xarg);
}
var rtn = await this[methodname](pobj, query, req);
this.logClient.log(pobj,req,rtn)
return rtn;
} catch (e) {
this.logClient.log(pobj,req,null,e.stack)
console.log(e.stack, "api调用异常--error...................");
var rtnerror = system.getResultFail(-200, "出现异常,请联系管理员");
return rtnerror;
}
}
}
module.exports = APIBase;
const system = require("../system");
const uuidv4 = require('uuid/v4');
class DocBase {
constructor() {
this.apiDoc = {
group: "逻辑分组",
groupDesc: "",
name: "",
desc: "请对当前类进行描述",
exam: "概要示例",
methods: []
};
this.initClassDoc();
}
initClassDoc() {
this.descClass();
this.descMethods();
}
descClass() {
var classDesc = this.classDesc();
this.apiDoc.group = classDesc.groupName;
this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc);
this.apiDoc.name = classDesc.name;
this.apiDoc.desc = this.examDescHtml(classDesc.desc);
this.apiDoc.exam = this.examHtml();
}
examDescHtml(desc) {
// var tmpDesc = desc.replace(/\\/g, "<br/>");
return desc;
}
examHtml() {
var exam = this.exam();
exam = exam.replace(/\\/g, "<br/>");
return exam;
}
exam() {
throw new Error("请在子类中定义类操作示例");
}
classDesc() {
throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构
{
groupName:"auth",
groupDesc:"认证相关的包"
desc:"关于认证的类",
exam:"",
}
`);
}
descMethods() {
var methoddescs = this.methodDescs();
for (var methoddesc of methoddescs) {
for (var paramdesc of methoddesc.paramdescs) {
this.descMethod(methoddesc.methodDesc, methoddesc.methodName
, paramdesc.paramDesc, paramdesc.paramName, paramdesc.paramType,
paramdesc.defaultValue, methoddesc.rtnTypeDesc, methoddesc.rtnType);
}
}
}
methodDescs() {
throw new Error(`
请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[
{
methodDesc:"生成访问token",
methodName:"getAccessKey",
paramdescs:[
{
paramDesc:"访问appkey",
paramName:"appkey",
paramType:"string",
defaultValue:"x",
},
{
paramDesc:"访问secret",
paramName:"secret",
paramType:"string",
defaultValue:null,
}
],
rtnTypeDesc:"xxxx",
rtnType:"xxx"
}
]
`);
}
descMethod(methodDesc, methodName, paramDesc, paramName, paramType, defaultValue, rtnTypeDesc, rtnType) {
var mobj = this.apiDoc.methods.filter((m) => {
if (m.name == methodName) {
return true;
} else {
return false;
}
})[0];
var param = {
pname: paramName,
ptype: paramType,
pdesc: paramDesc,
pdefaultValue: defaultValue,
};
if (mobj != null) {
mobj.params.push(param);
} else {
this.apiDoc.methods.push(
{
methodDesc: methodDesc ? methodDesc : "",
name: methodName,
params: [param],
rtnTypeDesc: rtnTypeDesc,
rtnType: rtnType
}
);
}
}
}
module.exports = DocBase;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class AccessAuthAPI extends APIBase {
constructor() {
super();
this.userSve = system.getObject("service.auth.userSve");
}
//不从平台应用列表入口登录时
//先要调用平台登录接口
//返回token,利用这个token再去登录某个具体APP
//会话存储具体APP的用户信息
//每个前端应用打开时,先检查是否存在token
//如果存在,就去访问获取用户信息,---调用本接口--即刻
//进入或登录某个具体应用
//前提是已经具备了统一管理的账号,并且已经在统一管理账号登录,客户端具备了token
//进入某个具体应用时,需要指定 x-appkey请求头
//
async loginToApp(p,q,req){
let appkey=req.xctx.appkey;
}
async getBizUserForBizChance(p,q,req){
let s= await this.userSve.getBizUserForBizChance(p.clientMobile,p.spName,p.productCatName,p.regionName)
return system.getResult(s)
}
async getBizUserForDelivery(p,q,req){
let s= await this.userSve.getBizUserForDelivery(p.clientMobile,p.spName,p.productCatName,p.skucode,p.regionName)
return system.getResult(s)
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
{
methodDesc: "生成访问token,访问地址:http://......../api/auth/accessAuth/getAccessKey,访问token需要放置到后续API方法调用的请求头中",
methodName: "getAccessKey",
paramdescs: [
{
paramDesc: "访问appkey",
paramName: "appkey",
paramType: "string",
defaultValue: "",
},
{
paramDesc: "访问secret",
paramName: "secret",
paramType: "string",
defaultValue: "",
}
],
rtnTypeDesc: "返回JSON对象字符串",
rtnType: "json object {accessKey: xxxxxx, app: {xxx:xxx}},注意app,是当前app信息,详细见后面示例"
},
];
}
exam() {
return ``
}
}
module.exports = AccessAuthAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class RoleAuthAPI extends APIBase {
constructor() {
super();
this.authS=system.getObject("service.auth.authSve");
}
async findAuthsByRole(p,q,req){
var tmpRoles=p.roles;
var appid=p.appid;
var comid=p.companyid;
var auths=await this.authS.findAuthsByRole(tmpRoles,appid,comid);
return system.getResult(auths);
}
exam(){
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "角色授权相关的API",
name: "RoleAuthAPI",
desc: "角色授权相关的API",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "按照角色获取权限,访问地址:/api/auth/roleAuth/findAuthsByRole",
methodName: "findAuthsByRole",
paramdescs: [
{
paramDesc: "应用的ID",
paramName: "appid",
paramType: "int",
defaultValue: "x",
},
{
paramDesc: "角色列表",
paramName: "roles",
paramType: "array",
defaultValue: null,
}
],
rtnTypeDesc: "逗号分隔的",
rtnType: "string"
}
];
}
}
module.exports = RoleAuthAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class AppAPI extends APIBase {
constructor() {
super();
this.appS = system.getObject("service.common.appSve");
}
async create(pobj,q,req){
// console.log("oooooooooooooooooooooooooooooooooooooooooooooooo")
// console.log(req.xctx)
let rtn=this.appS.create(pobj,q,req);
return system.getResult(rtn);
}
async del(pobj,q,req){
let rtn=this.appS.delete(pobj,q,req);
return system.getResult(rtn);
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
];
}
exam() {
return ``
}
}
module.exports = AppAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class ChannelAPI extends APIBase {
constructor() {
super();
this.channelS=system.getObject("service.common.channelSve")
}
async getChannels(hostname){
let cacheManager = system.getObject("db.common.cacheManager");
let channels=await cacheManager["ChannelCache"].cache(hostname)
return channels;
}
async channelHandle(channelobj,path,data){
let rtn=await this.channelS.channelHandle(channelobj,path,data)
return rtn;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
];
}
exam() {
return ``
}
}
module.exports = ChannelAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class ProductAPI extends APIBase {
constructor() {
super();
this.productpriceS = system.getObject("service.product.productpriceSve")
}
/**
*
* @param {*} p productname-产品名称/sp名称
* @param {*} q
* @param {*} req
* 返回值[
* label:'',
* code:''
* ]
*/
async findRegionsByProductName (p, q, req) {
let pname = p.productname;
let sp = p.sp;
let rs = await this.productpriceS.findRegionsByProductName(pname, sp)
return system.getResult(rs);
}
async findCostBySkuCode (p, q, req) {
let skucode = p.skucode;
let rs = await this.productpriceS.findCostBySkuCode(skucode)
return system.getResult({ cost: rs });
}
classDesc () {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs () {
return [
];
}
exam () {
return ``
}
}
module.exports = ProductAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class OSSAPI extends APIBase{
constructor(){
super()
}
async getOssConfig(){
var policyText = {
"expiration":"2119-12-31T16:00:00.000Z",
"conditions":[
["content-length-range",0,1048576000],
["starts-with","$key","zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64
var data={
OSSAccessKeyId:accessKeyId,
policy:policyBase64,
Signature:signature,
Bucket:'gsb-zc',
success_action_status:201,
url:url
};
return system.getResult(data);
};
async upfile(srckey,dest){
var oss=System.getObject("util.ossClient");
var result=await oss.upfile(srckey,"/tmp/"+dest);
return result;
};
async downfile(srckey){
var oss=System.getObject("util.ossClient");
var downfile=await oss.downfile(srckey).then(function(){
downfile="/tmp/"+srckey;
return downfile;
});
return downfile;
};
}
module.exports=OSSAPI;
const system = require("../system");
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
class CtlBase {
constructor(gname, sname) {
this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname);
this.cacheManager = system.getObject("db.common.cacheManager");
this.logClient = system.getObject("util.logClient");
}
getUUID () {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
static getServiceName (ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async update (pobj, qobj, req) {
const up = await this.service.update(pobj);
return system.getResult(up);
}
async create (pobj, qobj, req) {
const up = await this.service.create(pobj);
return system.getResult(up);
}
async delete (pobj, qobj, req) {
const up = await this.service.delete(pobj);
return system.getResult(up);
}
async findAndCountAll (pobj, qobj, req) {
//设置查询条件
console.log(pobj)
const rs = await this.service.findAndCountAll(pobj);
return system.getResult(rs);
}
async refQuery (pobj, qobj, req) {
//pobj.refwhere.app_id=pobj.app_id;//角色过滤按照公司过滤
pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj);
return rtn
}
async setContextParams (pobj, qobj, req) {
let custtags = req.headers["x-consumetag"] ? req.headers["x-consumetag"].split("|") : null;
let lastindex = custtags ? custtags.length - 1 : 0;
//当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值
req.xctx = {
appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色
fromappkey: req.headers["xfromappkey"],//来源APP,如果没有来源与appkey相同
companyid: custtags ? custtags[0].split("_")[1] : null,
fromcompanykey: req.headers["xfromcompanykey"],//专用于自由用户注册,自由用户用于一定属于某个存在的公司
password: custtags ? custtags[lastindex].split("_")[1] : null,
username: req.headers["x-consumer-username"],
userid: req.headers["x-consumer-custom-id"],
credid: req.headers["x-credential-identifier"],
regrole: req.headers["xregrole"],
bizpath: req.headers["xbizpath"],
codename: req.headers["xcodename"],
codetitle: req.headers["xcodetitle"] ? decodeURI(req.headers["xcodetitle"]) : '',
opath: req.headers['xopath'],
ptags: req.headers['xptags'],
}
//添加组织结构路径,如果是上级,取上级
if (req.xctx.ptags && req.xctx.ptags != "") {
pobj.opath = req.xctx.ptags
} else {
if (!pobj.opath || pobj.opath == "") {
pobj.opath = req.xctx.opath
}
}
if (!req.xctx.appkey) {
return [-200, "请求头缺少应用x-app-key"]
} else {
let app = await this.cacheManager["AppCache"].cache(req.xctx.fromappkey);
req.xctx.appid = app.id;
if (!pobj.app_id) {
pobj.app_id = app.id;//传递参数对象里注入app_id
}
}
//平台注册时,companyid,companykey都为空
//自由注册时,companykey不能为空
// if(!req.xctx.companyid && !req.xctx.companykey){
// return [-200,"请求头缺少应用x-app-key"]
// }
if (!req.xctx.companyid && req.xctx.fromcompanykey && req.xctx.fromcompanykey != "null" && req.xctx.fromcompanykey != "undefined") {
let comptmp = await this.cacheManager["CompanyCache"].cache(req.xctx.fromcompanykey);
req.xctx.companyid = comptmp.id;
}
if (req.xctx.companyid) {//在请求传递数据对象注入公司id
pobj.company_id = req.xctx.companyid;
}
if (req.xctx.userid) {//在请求传递数据对象注入公司id
pobj.userid = req.xctx.userid;
pobj.username = req.xctx.username;
}
pobj.bizpath = req.xctx.bizpath;
}
async doexec (methodname, pobj, query, req) {
try {
let xarg = await this.setContextParams(pobj, query, req);
if (xarg && xarg[0] < 0) {
return system.getResultFail(...xarg);
}
var rtn = await this[methodname](pobj, query, req);
this.logClient.log(pobj, req, rtn, null)
return rtn;
} catch (e) {
this.logClient.log(pobj, req, null, e.stack)
console.log(e.stack, "出现异常,请联系管理员.......");
return system.getResultFail(-200, e.message ? e.message : "出现异常,请联系管理员");
}
}
}
module.exports = CtlBase;
/*
地址:http://192.168.1.128:401/api/queueAction/producer/springBoard
请求方式:post
参数:
{
"actionType": "produceLogsData",// Y 功能名称
"actionBody": {
"opTitle": "",// N 操作的业务标题
"identifyCode": "logs001",// Y 操作的业务标识
"messageBody": {//日志的描述信息
"opUrl": "http://192.168.1.189:4012/api/test/testApi/springBoard",// N 操作的业务Url
"message": ""// Y 日志消息描述
}
}
}
logs-sytxpublic-msgq-service--日志服务
*/
\ No newline at end of file
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class AuthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(AuthCtl));
}
async saveAuths(pobj,query,req){
var auths=pobj.auths;
var xrtn=await this.service.saveAuths(auths,pobj.app_id,pobj.company_id);
return system.getResult(xrtn);
}
async findAuthsByRoles(pobj,query,req){
var roleids=pobj.roleids;
var xrtn=await this.service.findAuthsByRole(roleids,pobj.app_id,pobj.company_id);
return system.getResult(xrtn);
}
}
module.exports=AuthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class DataauthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(DataauthCtl));
}
async saveauth(qobj,querybij,req){
var arys=qobj.arys;
var uid=qobj.uid;
var refmodel=qobj.modelname;
var u=await this.service.saveauth({
user_id:uid,
modelname:refmodel,
auths:arys.join(","),
app_id:req.appid,
});
return system.getResult(u);
}
async fetchInitAuth(qobj,querybij,req){
var uid=qobj.uid;
var refmodel=qobj.modelname;
var authtmp=await this.service.findOne({user_id:uid,modelname:refmodel,app_id:req.appid});
if(authtmp){
var auths= authtmp.auths;
var arys=auths.split(",");
return system.getResult(arys);
}else{
return system.getResultSuccess([]);
}
}
}
module.exports=DataauthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class OrgCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(OrgCtl));
// this.compSvr=system.getObject("service.common.companySve");
}
//检查是否已经存在主要岗位
async checkMainPosition(p,q,req){
return this.service.checkMainPosition(p,q,req);
}
async changePos(p,q,req){
var toorgid=p.orgid;
var uid=p.uid;
var rtn= await this.service.changePos(toorgid,uid);
return system.getResult(rtn);
}
async create(p,q,req){
return super.create(p,q,req);
}
async delete(p,q,req){
return super.delete(p,q,req);
}
async update(p,q,req){
return super.update(p,q,req);
}
async initOrgs(p,q,req){
var tocompany=req.session.tocompany;
var cmkey=p.comkey;
if(cmkey){
tocompany =await this.compSvr.findOne({companykey:cmkey});
}
//按照公司名称查询,是否存在节点,不存在,就创建根节点
//如果存在就按照名称查询出当前和她的字节点
var rtn=await this.service.initOrgs(tocompany,req.appid);
return system.getResult(rtn);
}
async findOrgById(p,q,req){
var rtn=await this.service.findOrgById(p.id);
return system.getResult(rtn);
}
}
module.exports=OrgCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class RoleCtl extends CtlBase {
constructor() {
super("auth",CtlBase.getServiceName(RoleCtl));
this.redisClient=system.getObject("util.redisClient");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
async create(pobj,queryobj, req) {
let r=await super.create(pobj,queryobj, req)
return system.getResult(r);
}
}
module.exports = RoleCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
}
async logout (pobj, qobj, req) {
let rtn = await this.service.logout(pobj)
return system.getResult(rtn)
}
async pmgetUserByCode (pobj, qobj, req) {
let code = pobj.code
let rtn = await this.service.pmgetUserByCode(code)
return system.getResult(rtn)
}
async loginApp (pobj, qobj, req) {
let appkey = pobj.fromAppKey
let uname = pobj.username
let rtn = await this.service.loginApp(appkey, uname)
return system.getResult(rtn);
}
async resetPassword (pobj, qobj, req) {
await this.service.resetPassword(req.xctx.username, pobj.onepassword)
return system.getResult({});
}
async allowOrNot (pobj, qobj, req) {
await this.service.updateByWhere({ isEnabled: !pobj.isEnabled }, { company_id: pobj.company_id })
return system.getResult({});
}
async allowOrNotToOne (pobj, qobj, req) {
await this.service.updateByWhere({ isEnabled: !pobj.isEnabled }, { id: pobj.curid })
return system.getResult({});
}
async initNewInstance (queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
//获取验证码,发送给指定手机
// async sendVCode(pobj, qobj, req) {
// var mobile = pobj.mobile;
// let v = await this.smsS.sendVCode(mobile);
// return system.getResult({ vcodestr: v });
// }
async exit (pobj, qobj, req) {
}
//应用的自由用户注册,无需验证,需要前端头设置公司KEY
async pmregisterByFreeUser (p, q, req) {
//检查是否有用户名和密码
if (!pobj.userName || !pobj.password) {
return system.getResult(null, "请检查用户名和密码是否存在")
}
//p.company_id = req.xctx.companyid;//控制基类里已经添加
if (!p.company_id) {
return system.getResultFail(-201, "自有用户创建需要提供公司KEY");
}
let rtn = await this.service.pmregisterByFreeUser(p, q);
return rtn;
}
async create (p, q, req) {
//检查是否有用户名和密码
if (!p.userName) {
return system.getResult(null, "请检查用户名和密码是否存在")
}
let rtn = await this.service.registerByTantent(p, q);
return system.getResult(rtn);
}
//登录后的租户创建属于租户的用户
//需要在控制器里取出公司ID
//和租户绑定同一家公司
//按照用户名和密码进行注册
//控制器端检查用户名和密码非空
async registerByTantent (p, q, req) {
//检查是否有用户名和密码
if (!pobj.userName) {
return system.getResult(null, "请检查用户名和密码是否存在")
}
let rtn = await this.service.registerByTantent(p, q);
return rtn;
}
//租户用户名和密码的租户注册
async pmregister (pobj, qobj, req) {
//平台注册设置平台的应用ID
pobj.app_id = settings.pmappid;
//检查是否有用户名和密码
if (!pobj.userName || !pobj.password) {
return system.getResult(null, "请检查用户名和密码是否存在")
}
var rtn = await this.service.pmregister(pobj);
return system.getResult(rtn);
}
async pmlogin (pobj, qobj, req) {
//平台注册设置平台的应用ID
let rtn = await this.service.pmlogin(pobj, qobj, req);
return system.getResult(rtn);
}
async getUserInfo (pobj, qobj, req) {
let uname = req.xctx.username;
let rtn = await this.service.getUserInfo(uname);
return system.getResult(rtn);
}
//按照电话创建自由用户
async pmloginByVCodeForFreeUser (p, q, req) {
if (!pobj.mobile || !pobj.vcode) {
return system.getResult(null, "请检查手机号和验证码是否存在")
}
p.companykey = req.xctx.companykey;
if (!p.companykey) {
return system.getResult(null, "自有用户创建需要提供公司KEY");
}
let rtn = await this.service.pmloginByVCodeForFreeUser(p, q);
return rtn;
}
async pmloginByVCode (pobj, qobj, req) {
let rtn = await this.service.pmloginByVCode(pobj, qobj);
return system.getResult(rtn);
}
async pmSendVCode (pobj, qobj, req) {
let rtn = await this.service.sendVCode(pobj, qobj);
return system.getResult(rtn);
}
}
module.exports = UserCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class AppCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve");
this.comS = system.getObject("service.common.companySve");
}
async findAndCountAll(pobj, qobj, req) {
let comtemp = await this.comS.findById(pobj.company_id)
pobj.myappstrs = comtemp.appids
let rtn = await super.findAndCountAll(pobj, qobj, req)
return rtn
}
async findAllApps(p, q, req) {
var rtns = await this.service.findAllApps(p.userid);
return system.getResult(rtns);
}
async getApp(p, q, req) {
let app = await this.cacheManager["AppCache"].cache(p.appkey, null);
return system.getResult({ funcJson: JSON.parse(app.functionJSON) });
}
async buildFrontRouter(p, q, req) {
let appkey = p.appkeyForRoute
let app = await this.cacheManager["AppCache"].cache(appkey, null);
let funcJSONOBJ = JSON.parse(app.functionJSON)
if (!funcJSONOBJ || funcJSONOBJ.length === 0) {
return system.getResultError("请先建立功能数据")
}
let rtn = await this.service.buildFrontRouter(funcJSONOBJ, app.id)
return system.getResult(rtn)
}
async getFuncs(p, q, req) {
let appkey = p.appkey
let app = await this.cacheManager["AppCache"].cache(appkey, null);
return system.getResult({ funcJson: JSON.parse(app.functionJSON) })
//return system.getResult({funcJson:[]})
}
async saveFuncTree(p, q, req) {
let rtn = await this.service.saveFuncTree(p)
return system.getResult(rtn)
}
async create(pobj, queryobj, req) {
pobj.creator_id = pobj.userid;//设置创建者
return super.create(pobj, queryobj, req)
}
async update(pobj, queryobj, req) {
return super.update(pobj, queryobj, req);
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
rtn.appkey = this.getUUID();
rtn.secret = this.getUUID();
return system.getResult(rtn);
}
async resetPass(pobj, queryobj, req) {
pobj.password = await super.encryptPasswd(settings.defaultpwd);
var rtn = this.service.resetPass(pobj);
return system.getResult(rtn);
}
async createAdminUser(pobj, queryobj, req) {
pobj.password = settings.defaultpwd;
var rtn = this.service.createAdminUser(pobj);
return system.getResult(rtn);
}
async create(pobj, queryobj, req) {
//设置创建者,需要同时创建app管理员、默认密码、电话
pobj.creator_id = pobj.userid;
// pobj.password=super.encryptPasswd(settings.defaultpwd);
//构造默认的应用相关的URL
pobj.authUrl = settings.protocalPrefix + pobj.domainName + "/auth";
// pobj.uiconfigUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/config/fetchAppConfig";
// pobj.opCacheUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/opCacheData";
// pobj.notifyCacheCountUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/recvNotificationForCacheCount";
var app = await super.create(pobj, queryobj, req);
return system.getResult(app);
}
async fetchApiCallData(pobj, queryobj, req) {
var curappkey = pobj.curappkey;
//检索出作为访问时的app呼出调用数据
var rtn = await this.service.fetchApiCallData(curappkey);
return system.getResultSuccess(rtn);
}
//接受缓存计数通知接口
async recvNotificationForCacheCount(p, q, req) {
return this.service.recvNotificationForCacheCount(p);
}
}
module.exports = AppCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class ArticleCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(ArticleCtl));
}
async create (p, q, req) {
p.creator_id = p.userid
p.creator = p.username
let rtn = await this.service.create(p, q, req)
return system.getResult(rtn)
}
}
module.exports = ArticleCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class AttachmentCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(AttachmentCtl));
}
}
module.exports = AttachmentCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
class CachSearchesCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CachSearchesCtl));
}
async initNewInstance(queryobj, qobj) {
return system.getResultSuccess({});
}
async findAndCountAll(pobj, gobj, req) {
pobj.opCacheUrl = req.session.app.opCacheUrl;
pobj.appid = req.appid;
return await this.service.findAndCountAllCache(pobj);
}
async delCache(queryobj, qobj, req) {
var param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param);
}
async clearAllCache(queryobj, qobj, req) {
var param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param);
}
}
module.exports = CachSearchesCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class ChannelCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(ChannelCtl));
}
async refQuery(pobj, qobj, req) {
let rtn = await this.service.refQuery(pobj);
return rtn
}
async authorizeUser(pobj, qobj, req) {
if (!pobj.channelId) {
return system.getResult(null, "channelId can not be empty,100290");
}
await this.service.authorizeUser(pobj);
return system.getResult("SUCCESS");
}
}
module.exports = ChannelCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class CompanyCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CompanyCtl));
}
async update (p, q, req) {
let u = await super.update(p, q, req)
//缓存失效
await this.cacheManager["CompanyCache"].invalidate(p.companykey)
let company = await this.cacheManager["CompanyCache"].cache(p.companykey)
return system.getResult(company)
}
async getMyApps (p, q, req) {
let userfind = await this.cacheManager["UserCache"].cache(p.username)
let isSuper = userfind.isSuper
if (userfind.company.appids && userfind.company.appids != "") {
let appsarray = userfind.company.appids.split(",")
let appidsquery = appsarray.map(astr => {
return astr.split("|")[0]
})
let apps = await this.service.getMyApps(appidsquery, isSuper)
return system.getResult(apps)
} else {
return []
}
}
async bindApps (p, q, req) {
let appids = p.appids
let cmpid = p.postcmpid
let appids2 = appids.map(item => {
return item.appid + "|" + item.title
})
let appidstrs = appids2.join(",")
await this.service.bindApps(appidstrs, cmpid)
return system.getResult(appids)
}
async setOrgs (p, q, req) {
//let companynew=await this.service.findById(p.company_id)
let orgs = await this.service.setOrgs(p)
return system.getResult(orgs)
}
async getOrgs (p, q, req) {
//let companynew=await this.cacheManager["CompanyCache"].cache(req.xctx.fromcompanykey)
let companynew = await this.service.findById(p.company_id)
let orgjsonstr = companynew.orgJson
let rtnjson = null
if (orgjsonstr && orgjsonstr != "") {
rtnjson = JSON.parse(companynew.orgJson)
} else {
rtnjson = []
}
return system.getResult({ orgJson: rtnjson })
}
async getWatchOrgNodes (p, q, req) {
let wns = await this.service.getWatchOrgNodes(p.company_id)
return wns
}
async refQuery (pobj, qobj, req) {
let rtn = await this.service.refQuery(pobj);
return rtn
}
}
module.exports = CompanyCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class MetaCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(MetaCtl));
}
}
module.exports = MetaCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
class OplogCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve");
}
async initNewInstance(qobj) {
var u = uuidv4();
var aid = u.replace(/\-/g, "");
var rd = { name: "", appid: aid }
return system.getResult(rd);
}
async debug(obj) {
obj.logLevel = "debug";
return this.create(obj);
}
async info(obj) {
obj.logLevel = "info";
return this.create(obj);
}
async warn(obj) {
obj.logLevel = "warn";
return this.create(obj);
}
async error(obj) {
obj.logLevel = "error";
return this.create(obj);
}
async fatal(obj) {
obj.logLevel = "fatal";
return this.create(obj);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
}
module.exports = OplogCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class PathtomethodCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(PathtomethodCtl));
this.appS=system.getObject("service.common.appSve")
}
}
module.exports = PathtomethodCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class PConfigCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(PConfigCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
return system.getResult(rtn);
}
async create(pobj,queryobj, req) {
pobj.app_id=req.appid;
pobj.appkey=req.appkey;
var rtn=await super.create(pobj,queryobj, req);
return system.getResult(rtn);
}
async update(pobj,queryobj, req) {
pobj.app_id=req.appid;
pobj.appkey=req.appkey;
var rtn=await super.update(pobj);
return system.getResult(rtn);
}
}
module.exports = PConfigCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class PushCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(PushCtl));
}
async findAndCountAll(pobj, qobj, req) {
let query = {
pageSize: pobj.pageInfo.pageSize,
pageIndex: pobj.pageInfo.pageNo
};
let search = pobj.search;
if (search.messageBody)
query.messageBody = search.messageBody;
if (search.identify_code)
query.identifyCode = search.identify_code;
if (search.request_id)
query.requestIdInfo = search.request_id;
let actionType;
switch (pobj.bizpath) {
case "/sysmag/pushfail":
actionType = "getPushFailureList";
break;
case "/sysmag/pusherror":
actionType = "getPushErrorList";
break
}
let rtn = await system.postJsonTypeReq(settings.pushUrl(), {
"actionType": actionType,
"actionBody": query
});
if (rtn.statusCode === 200) {
rtn = rtn.data;
if (rtn && rtn.status === 1) {
return system.getResult({
results: {
count: rtn.totalCount,
rows: rtn && rtn.data || []
}
});
} else {
return system.getResultFail(rtn && rtn.message || '请联系管理员');
}
} else {
return system.getResultFail(rtn)
}
}
async repush(pobj, qobj, req) {
let rtn = await system.postJsonTypeReq(settings.pushUrl(), {
"actionType": "pushAgainFailureLog",
"actionBody": {
id: pobj.id
}
});
if (rtn.statusCode === 200) {
return rtn.data;
} else {
return system.getResultFail(rtn)
}
}
}
module.exports = PushCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class RouteCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(RouteCtl));
this.appS=system.getObject("service.common.appSve")
}
async create(p,q,req){
let appid=p.app_id;
let apptmp= await this.appS.findById(appid)
let routedata={
name:p.name,
hosts:p.shosts.split(","),
paths:p.spaths.split(","),
isstrip:false,
app_id:appid,
shosts:p.shosts,
spaths:p.spaths
}
let rtn= await this.service.create(apptmp.name, routedata, req);
return system.getResult(rtn)
}
}
module.exports = RouteCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
class SocketNotifyCtl{
constructor(){
}
setSocketServer(s){
this.socketServer=s;
}
//异步推送消息到客户端
notifyClientMsg(user,msg){
var uk= this.buildPrivateChannel(user);
var msgHandler=this.socketServer.users[uk];
msgHandler.notifyClient(uk,msg);
}
buildPrivateChannel(user){
var ukchannel= user.app_id+"¥"+user.id;
return ukchannel;
}
buildMsgTarget(user){
var ukchannel= user.app_id+"¥"+user.id;
var nickName=user.nickName;
var imgUrl=user.imgUrl;
var rtn=ukchannel+"¥"+nickName+"¥"+imgUrl;
return rtn;
}
}
module.exports=SocketNotifyCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class TreearchCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(TreearchCtl));
}
async getTreeArchByCode (p, q, req) {
let code = p.code;
let archName = p.archName;
let rtn = await this.service.getTreeArchByCode(archName, code)
return system.getResult(rtn)
}
async getRegions (p, q, req) {
let regionjson = await this.service.getRegions();
return system.getResult({ regionJson: regionjson })
}
async getSysArchJSON (p, q, req) {
let sysArchJSON = await this.service.getSysArchJSON();
return system.getResult({ sysArchJSON: sysArchJSON })
}
async saveSysArchJSON (p, q, req) {
let sysArchJSON = await this.service.saveSysArchJSON(p.sysArchJSON, p);
return system.getResult({ sysArchJSON: sysArchJSON })
}
async saveRegions (p, q, req) {
let regionjson = await this.service.saveRegions(p.regionJson);
return system.getResult({ regionJson: regionjson })
}
async getProductcats (p, q, req) {
let productcatJson = await this.service.getProductcats();
return system.getResult({ productcatJson: productcatJson })
}
async saveProductcats (p, q, req) {
let productcatJson = await this.service.saveProductcats(p.productcatJson);
return system.getResult({ productcatJson: productcatJson })
}
}
module.exports = TreearchCtl;
var system=require("../../../system")
const CtlBase = require("../../ctl.base");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class UploadCtl extends CtlBase{
constructor(){
super("common",CtlBase.getServiceName(UploadCtl));
this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 '{fileName}'";
this.restS=system.getObject("util.execClient");
this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'";
//sed -i 's/1111/&BBB/' /tmp/input.txt
//sed 's/{position}/{content}/g' {path}
}
async getOssConfig(){
var policyText = {
"expiration":"2119-12-31T16:00:00.000Z",
"conditions":[
["content-length-range",0,1048576000],
["starts-with","$key","zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64
var data={
OSSAccessKeyId:accessKeyId,
policy:policyBase64,
Signature:signature,
Bucket:'gsb-zc',
success_action_status:201,
url:url
};
return data;
};
async upfile(srckey,dest){
var oss=system.getObject("util.ossClient");
var result=await oss.upfile(srckey,"/tmp/"+dest);
return result;
};
async downfile(srckey){
var oss=system.getObject("util.ossClient");
var downfile=await oss.downfile(srckey).then(function(){
downfile="/tmp/"+srckey;
return downfile;
});
return downfile;
};
async pdf2html(obj){
var srckey=obj.key;
var downfile=await this.downfile(srckey);
var cmd=this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
var rtn=await this.restS.exec(cmd);
var path="/tmp/"+srckey.split(".pdf")[0]+".html";
var a=await this.insertToFile(path);
fs.unlink("/tmp/"+srckey);
var result=await this.upfile(srckey.split(".pdf")[0]+".html",srckey.split(".pdf")[0]+".html");
return result.url;
};
async insertToFile(path){
var cmd=this.cmdInsertToFilePattern+" "+path;
return await this.restS.exec(cmd);
};
}
module.exports=UploadCtl;
var system = require("../../../system");
const http = require("http");
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class logCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(logCtl));
this.logClient = system.getObject("util.logClient");
}
async findAndCountAll(pobj, qobj, req) {
try {
let rtn = await this.logClient.logList(pobj);
return system.getResult({
results: {
count: rtn.totalCount,
rows: rtn && rtn.list && rtn.list.map(item => {
let { opTitle, identifyCode, messageBody, resultInfo, errorInfo, requestId, created_at } = item;
messageBody = messageBody ? JSON.parse(messageBody) : {}
resultInfo = resultInfo ? JSON.parse(resultInfo) : {}
let status;
if (resultInfo && (resultInfo.status === 0 || !resultInfo.status || resultInfo.status === 1)) {
status = "SUCCESS"
} else {
status = "FAIL"
}
if (errorInfo && errorInfo !== "null") {
status = "FAIL"
}
return {
opTitle: opTitle,
url: `${messageBody.gname}/${messageBody.qname}/${messageBody.method}`,
user: messageBody.param && messageBody.param.username || '',
ip: messageBody.param && messageBody.param.clientIp,
created_at,
requestId,
status,
info: {
opTitle, identifyCode, messageBody, resultInfo, errorInfo, requestId, created_at
}
}
}) || []
}
});
} catch (err) {
return system.getResult(null, err.message);
}
}
}
module.exports = logCtl;
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 !== 0 && !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)
}
}
async createSysMessage(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");
}
try {
const rs = await this.service.create({
...pobj,
msgType: system.Msg.SYS,
sender: pobj.username,
sender_id: pobj.userid,
company_id: pobj.company_id
}, 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;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class PricecatCtl extends CtlBase {
constructor() {
super("product", CtlBase.getServiceName(PricecatCtl));
this.pricestrategyService=system.getObject("service.product.pricestrategySve")
}
async buildPriceStrategy(p,q,req){
let pricetypes=p.pricetypes
let rtn=await this.pricestrategyService.buildPriceStrategy(pricetypes)
if(rtn){
if(rtn.status==-1){
return system.getResult(null,rtn.msg)
}else{
return system.getResult({})
}
}
return system.getResult({})
}
}
module.exports = PricecatCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class PricestrategyCtl extends CtlBase {
constructor() {
super("product", CtlBase.getServiceName(PricestrategyCtl));
}
async refQuery(pobj, qobj, req) {
let rtn=await this.service.refQuery(pobj);
return rtn
}
}
module.exports = PricestrategyCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class ProductCtl extends CtlBase {
constructor() {
super("product", CtlBase.getServiceName(ProductCtl));
// this.pricestrategyService=system.getObject("service.product.pricestrategySve")
}
async create(p,q,req){
let pn=await this.service.create(p)
return system.getResult(pn)
}
}
module.exports = ProductCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class ProductcostCtl extends CtlBase {
constructor() {
super("product", CtlBase.getServiceName(ProductcostCtl));
// this.pricestrategyService=system.getObject("service.product.pricestrategySve")
}
}
module.exports = ProductcostCtl;
var system = require("../../../system")
const CtlBase = require("../../ctl.base");
class ProductpriceCtl extends CtlBase {
constructor() {
super("product", CtlBase.getServiceName(ProductpriceCtl));
// this.pricestrategyService=system.getObject("service.product.pricestrategySve")
}
async updownProduct(p,q,req){
let updownid=p.curid
let rtn=await this.service.updownProduct(updownid)
return system.getResult(rtn)
}
}
module.exports = ProductpriceCtl;
const system = require("../../../system");
const settings = require("../../../../config/settings");
function exp(db, DataTypes) {
var base = {
code: {
type: DataTypes.STRING(50),
unique: true
},
name: DataTypes.STRING(1000),
};
return base;
}
module.exports = exp;
const system = require("../../system");
const settings = require("../../../config/settings");
const appconfig = system.getSysConfig();
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(appconfig.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", appconfig.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", appconfig.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
constructor() {
this.db = system.getObject("db.common.connection").getCon();
this.redisClient = system.getObject("util.redisClient");
this.desc = this.desc();
this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "sadd_base:cachekey";
this.isdebug = this.isdebug();
}
isdebug() {
return false;
}
desc() {
throw new Error("子类需要定义desc方法,返回缓存描述");
}
prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀");
}
async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) {
return null;
}
if (ex) {
await this.redisClient.setWithEx(cachekey, objvalstr, ex);
} else {
await this.redisClient.set(cachekey, objvalstr);
}
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
return JSON.parse(objvalstr);
} else {
// this.redisClient.setWithEx(cachekey, cacheValue, ex);
return JSON.parse(cacheValue);
}
}
async getCache(inputkey, ex) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null") {
return null;
} else {
if (ex) {
this.redisClient.set(cachekey, cacheValue, ex);
}
return JSON.parse(cacheValue);
}
}
async invalidate(inputkey) {
const cachekey = this.prefix + inputkey;
this.redisClient.delete(cachekey);
return 0;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串");
}
}
module.exports = CacheBase;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class CacheLocker extends CacheBase{
constructor(){
super();
this.prefix="locker_";
}
desc(){
}
prefix(){
}
async init(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
async enter(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpop(key);
}
async release(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
}
module.exports=CacheLocker;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class AliCache extends CacheBase {
constructor() {
super();
//this.userDao = system.getObject("db.auth.userDao");
}
isdebug() {
return settings.env == "dev";
}
desc() {
return "缓存缓存阿里队列信息";
}
prefix() {
return "g_aliInfo_cm:"
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (val) {
return val;
}
return null;
}
}
module.exports = AliCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class AppCache extends CacheBase{
constructor(){
super();
this.prefix="g_centerappkey:";
this.appDao=system.getObject("db.common.appDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存本地应用对象";
}
prefix(){
return "g_applocal_cm:"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue=await this.appDao.findOne({appkey:inputkey});
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports=AppCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class ChannelCache extends CacheBase {
constructor() {
super();
this.channelDao = system.getObject("db.common.channelDao");
}
isdebug () {
return true;
}
desc () {
return "缓存本地应用对象";
}
prefix () {
return "g_channel_cm:"
}
async buildCacheVal (cachekey, inputkey, val, ex, ...items) {
const configValue = await this.channelDao.model.findOne(
{
where: { routehost: inputkey },
include: [{ model: this.db.models.pathtomethod, as: "pts" }]
});
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports = ChannelCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class ClientBindBizUserCache extends CacheBase{
constructor(){
super();
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存本地应用对象";
}
prefix(){
return "g_client2bizuser_cm:"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
return JSON.stringify(val);
}
}
module.exports=ClientBindBizUserCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class CodeCache extends CacheBase{
constructor(){
super();
this.userDao=system.getObject("db.auth.userDao");
}
isdebug(){
return false
// return settings.env=="dev";
}
desc(){
return "缓存code子系统用户登录信息对象";
}
prefix(){
return "g_code_userlocal_cm:"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
if (val) {
return JSON.stringify(val);
}
return null;
}
}
module.exports=CodeCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class CompanyCache extends CacheBase{
constructor(){
super();
this.prefix="g_centercompanykey:";
this.companyDao=system.getObject("db.common.companyDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存统一公司对象";
}
prefix(){
return "gc_companylocal_cm:"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue=await this.companyDao.findOne({companykey:inputkey});
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports=CompanyCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class LoopDistributionUserCache extends CacheBase {
constructor() {
super();
this.userDao = system.getObject("db.auth.userDao");
this.channelDao = system.getObject("db.common.channelDao");
}
isdebug() {
return settings.env == "dev";
}
desc() {
return "缓存阿里订单轮循环分配的业务员信息";
}
prefix() {
return "g_loopDistributionUserInfo_cm:"
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (val) {
return val;
}
return null;
}
}
module.exports = LoopDistributionUserCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "管理当前缓存的key";
}
prefix() {
return "g_magcache:";
}
async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key);
}
async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value)
}
async keys(p) {
return this.redisClient.keys(p);
}
async get(k) {
return this.redisClient.get(k);
}
async del(k) {
return this.redisClient.delete(k);
}
async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............");
return this.redisClient.flushall();
}
}
module.exports = MagCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class TxCache extends CacheBase {
constructor() {
super();
//this.userDao = system.getObject("db.auth.userDao");
}
isdebug() {
return settings.env == "dev";
}
desc() {
return "缓存缓存腾讯队列信息";
}
prefix() {
return "g_txInfo_cm:"
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (val) {
return val;
}
return null;
}
}
module.exports = TxCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class UserCache extends CacheBase {
constructor() {
super();
this.userDao = system.getObject("db.auth.userDao");
this.channelDao = system.getObject("db.common.channelDao");
}
isdebug () {
return settings.env == "dev";
}
desc () {
return "缓存本地应用对象";
}
prefix () {
return "g_userlocal_cm:"
}
async buildCacheVal (cachekey, inputkey, val, ex, ...items) {
const configValue = await this.userDao.model.findAll({
where: { userName: inputkey, app_id: settings.pmappid, isEnabled: true },
attributes: ['id', 'userName', 'nickName', 'headUrl', 'jwtkey', 'jwtsecret', 'created_at', 'isSuper', 'isAdmin', 'isAllocated', 'mail', 'mobile', 'opath', 'ptags'],
include: [
{ model: this.db.models.company, attributes: ['id', 'name', 'companykey', 'appids', "code"], raw: true },
{ model: this.db.models.role, as: "Roles", attributes: ["id", "code"], }
],
});
if (configValue && configValue[0]) {
let data = JSON.parse(JSON.stringify(configValue[0]));
if (data.company.id != 1 && data.company.appids) {
let tmpids = data.company.appids.split(",")
let tmpid = tmpids[0]
if (tmpid && tmpid != "" && tmpids.length == 1) {
let app = await this.db.models.app.findById(tmpid)
data.defaultAppkey = app.appkey
}
}
let channelDatas = await this.channelDao.findAll({});
channelDatas = JSON.parse(JSON.stringify(channelDatas));
channelDatas.forEach(item => {
if (item.userids && item.userids.split(",").includes(data.id.toString())) {
data.channel = {
id: item.id,
code: item.code,
name: item.name
}
}
});
// 获取渠道信息
return JSON.stringify(data);
}
return null;
}
}
module.exports = UserCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class VCodeCache extends CacheBase {
constructor() {
super();
this.smsUtil = system.getObject("util.smsClient");
}
// isdebug() {
// return settings.env == "dev";
// }
desc () {
return "缓存给手机发送的验证码60妙";
}
prefix () {
return "g_vcode_cm:"
}
async buildCacheVal (cachekey, inputkey, val, ex, ...items) {
//inputkey采用appkey_mobile的形式
var mobile = inputkey;
var tmplCode = val;
var signName = items ? items[0] : "";
var vcode = await this.smsUtil.getUidStr(6, 10);
if (!tmplCode && !signName) {
console.log("=====================================", mobile, vcode)
this.smsUtil.sendMsg(mobile, vcode);
} //tmplCode为发送短信编码,需在阿里开通,signName为短信头描述信息,二者没有传递则用默认的发送验证码
else {
this.smsUtil.aliSendMsg(mobile, tmplCode, signName, JSON.stringify({ code: vcode }));
}
return JSON.stringify({ vcode: vcode });
}
}
module.exports = VCodeCache;
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
var db = system.getObject("db.common.connection").getCon();
this.db = db;
console.log("........set dao model..........");
console.log(this.modelName)
this.model = db.models[this.modelName];
console.log(this.modelName);
}
preCreate (u) {
return u;
}
async create (u, t) {
var u2 = this.preCreate(u);
if (t) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(this.model);
return this.model.create(u2, { transaction: t }).then(u => {
return u;
});
} else {
return this.model.create(u2).then(u => {
return u;
});
}
}
static getModelName (ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery (qobj) {
var w = qobj.refwhere ? qobj.refwhere : {};
if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
}
if (qobj.parentinfo) {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
}
//如果需要控制数据权限
if (qobj.datapriv) {
w["id"] = { [this.db.Op.in]: qobj.datapriv };
}
if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
return this.model.findAll({ where: w, attributes: qobj.fields });
} else {
return this.model.findAll({ where: w, attributes: qobj.fields });
}
}
async bulkDelete (ids, t) {
if (t) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } }, transaction: t });
return en;
} else {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en
}
}
async bulkDeleteByWhere (whereParam, t) {
var en = null;
if (t != null && t != 'undefined') {
whereParam.transaction = t;
return await this.model.destroy(whereParam);
} else {
return await this.model.destroy(whereParam);
}
}
async delete (qobj, t) {
var en = null
if (t != null && t != 'undefined') {
en = await this.model.findOne({ where: { id: qobj.id }, transaction: t });
if (en != null) {
await en.destroy({ transaction: t });
return en
}
} else {
en = await this.model.findOne({ where: { id: qobj.id } });
if (en != null) {
return en.destroy();
}
}
return null;
}
extraModelFilter (pobj) {
//return {"key":"include","value":{model:this.db.models.app}};
return null;
}
extraWhere (obj, where) {
return where;
}
orderBy (qobj) {
//return {"key":"include","value":{model:this.db.models.app}};
if (!qobj.orderInfo || qobj.orderInfo.length == 0) {
return [["created_at", "DESC"]];
} else {
return qobj.orderInfo;
}
}
buildQuery (qobj) {
var linkAttrs = [];
const pageNo = qobj.pageInfo.pageNo;
const pageSize = qobj.pageInfo.pageSize;
const search = qobj.search;
var qc = {};
//设置分页查询条件
qc.limit = pageSize;
qc.offset = (pageNo - 1) * pageSize;
//默认的查询排序
qc.order = this.orderBy(qobj);
//构造where条件
qc.where = {};
if (search) {
Object.keys(search).forEach(k => {
console.log(search[k], ":search[k]search[k]search[k]");
if (search[k] && search[k] != 'undefined' && search[k] != "") {
if ((k.indexOf("Date") >= 0 || k.indexOf("_at") >= 0)) {
if (search[k] != "" && search[k]) {
var stdate = new Date(search[k][0]);
var enddate = new Date(search[k][1]);
qc.where[k] = { [this.db.Op.between]: [stdate, enddate] };
}
}
else if (k.indexOf("id") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("channelCode") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("Type") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("Status") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("status") >= 0) {
qc.where[k] = search[k];
}
else {
if (k.indexOf("~") >= 0) {
linkAttrs.push(k);
} else {
qc.where[k] = { [this.db.Op.like]: "%" + search[k] + "%" };
}
}
}
});
}
this.extraWhere(qobj, qc.where, qc, linkAttrs);
var extraFilter = this.extraModelFilter(qobj);
if (extraFilter) {
qc[extraFilter.key] = extraFilter.value;
}
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
console.log(qc);
return qc;
}
buildaggs (qobj) {
var aggsinfos = [];
if (qobj.aggsinfo) {
qobj.aggsinfo.sum.forEach(aggitem => {
var t1 = [this.db.fn('SUM', this.db.col(aggitem.field)), aggitem.field + "~" + "sum"];
aggsinfos.push(t1);
});
qobj.aggsinfo.avg.forEach(aggitem => {
var t2 = [this.db.fn('AVG', this.db.col(aggitem.field)), aggitem.field + "~" + "avg"];
aggsinfos.push(t2);
});
}
return aggsinfos;
}
async findAggs (qobj, qcwhere) {
var aggArray = this.buildaggs(qobj);
if (aggArray.length != 0) {
qcwhere["attributes"] = {};
qcwhere["attributes"] = aggArray;
qcwhere["raw"] = true;
//提高效率去掉关联和排序,数据记录数量,为聚合
let tmpwhere = {
attributes: qcwhere.attributes,
raw: true,
where: qcwhere.where
}
var aggResult = await this.model.findOne(tmpwhere);
return aggResult;
} else {
return {};
}
}
convertAggResult (aggresult) {
return aggresult
}
async findAndCountAll (qobj, t) {
var qc = this.buildQuery(qobj);
let findList = {}
let count = await this.findCount({ where: qc.where })
var rows = await this.model.findAll(qc);
findList["count"] = count
findList["rows"] = rows
var aggresult = await this.findAggs(qobj, qc);
let convertAggResult = this.convertAggResult(aggresult);
var rtn = {};
rtn.results = findList;
rtn.aggresult = convertAggResult;
return rtn;
}
preUpdate (obj) {
return obj;
}
async update (obj, tm) {
var obj2 = this.preUpdate(obj);
if (tm != null && tm != 'undefined') {
await this.model.update(obj2, { where: { id: obj2.id }, transaction: tm });
let n = await this.model.findOne({ where: { id: obj2.id }, transaction: tm });
return n
} else {
await this.model.update(obj2, { where: { id: obj2.id } });
let n = await this.model.findById(obj2.id)
return n
}
}
async bulkCreate (ids, t) {
if (t != null && t != 'undefined') {
return await this.model.bulkCreate(ids, { transaction: t });
} else {
return await this.model.bulkCreate(ids);
}
}
async updateByWhere (setObj, whereObj, t) {
let inWhereObj = {}
if (t && t != 'undefined') {
if (whereObj && whereObj != 'undefined') {
inWhereObj["where"] = whereObj;
inWhereObj["transaction"] = t;
} else {
inWhereObj["transaction"] = t;
}
} else {
inWhereObj["where"] = whereObj;
}
return this.model.update(setObj, inWhereObj);
}
async customExecAddOrPutSql (sql, paras = null) {
return this.db.query(sql, paras);
}
async customQuery (sql, paras, t) {
var tmpParas = null;//||paras=='undefined'?{type: this.db.QueryTypes.SELECT }:{ replacements: paras, type: this.db.QueryTypes.SELECT };
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' ? { type: this.db.QueryTypes.SELECT } : { replacements: paras, type: this.db.QueryTypes.SELECT };
}
return this.db.query(sql, tmpParas);
}
async findCount (whereObj = null) {
return this.model.count(whereObj, { logging: false }).then(c => {
return c;
});
}
async findSum (fieldName, whereObj = null) {
return this.model.sum(fieldName, whereObj);
}
async getPageList (pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
var tmpWhere = {};
tmpWhere.limit = pageSize;
tmpWhere.offset = (pageIndex - 1) * pageSize;
if (whereObj != null) {
tmpWhere.where = whereObj;
}
if (orderObj != null && orderObj.length > 0) {
tmpWhere.order = orderObj;
}
if (attributesObj != null && attributesObj.length > 0) {
tmpWhere.attributes = attributesObj;
}
if (includeObj != null && includeObj.length > 0) {
tmpWhere.include = includeObj;
tmpWhere.distinct = true;
} else {
tmpWhere.raw = true;
}
return await this.model.findAndCountAll(tmpWhere);
}
async findOne (obj, attributes = []) {
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) {
return this.model.findOne({ "where": obj, transaction: t });
}
async 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;
const system=require("../../../system");
const Dao=require("../../dao.base");
class AuthDao extends Dao{
constructor(){
super(Dao.getModelName(AuthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=AuthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class DataauthDao extends Dao{
constructor(){
super(Dao.getModelName(DataauthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=DataauthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OrgDao extends Dao{
constructor(){
super(Dao.getModelName(OrgDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=OrgDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class RoleDao extends Dao{
constructor(){
super(Dao.getModelName(RoleDao));
}
async findOne(paramappid,t){
var app= await this.model.findOne({where:{appid:paramappid}},{transaction:t});
return app;
}
extraWhere(obj,w,qc,linkAttrs){
// if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj);
// // w["app_id"]=obj.appid;
// // }
// }
//w["app_id"]=obj.app_id;//不考虑应用的区别
w["company_id"]=obj.company_id;
return w;
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.app,}]};
}
async preUpdate(u){
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
await this.model.update(obj2,{where:{id:obj2.id}});
var role=await this.model.findOne({where:{id:obj2.id}});
return role;
}
async preCreate(u){
return u;
}
async create(u,t){
var self=this;
var u2= await this.preCreate(u);
if(t){
var role= await this.model.create(u2,{transaction: t});
return role;
}else{
var role= await this.model.create(u2);
return role;
}
}
}
module.exports=RoleDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class UserDao extends Dao {
constructor() {
super(Dao.getModelName(UserDao));
}
async getAuths(userid) {
var self = this;
return this.model.findOne({
where: { id: userid },
include: [{ model: self.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"] },
{
model: self.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
{ model: self.db.models.product, as: "Products", attributes: ["id", "code"] }
]
},
],
});
}
async getUserByUsername(username, appkey, t) {
var app = await this.appDao.findOne(appkey);
var tUser = await this.model.findOne({
where: { userName: username, app_id: app.id },
include: [{ model: this.db.models.app, raw: true },
// {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
// "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{ model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true },
{
model: this.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
{ model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true }
]
},
]
}, { transaction: t });
// if(tUser!=null){
// tUser=tUser.get({plain:true});
// tUser.partnerinfo=await this.partnerinfoDao.model.findOne({where:{onlyCode:tUser.onlyCode},raw:true});
// }
return tUser;
}
async getUserByOpenId(popenid, appkey, t) {
var app = await this.appDao.findOne(appkey);
var tUser = await this.model.findOne({
where: { openId: popenid },
include: [{ model: this.db.models.app, raw: true },
// {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
// "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{ model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true },
{
model: this.db.models.role, as: "Roles", attributes: ["id", "code"], include: [
{ model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true }
]
},
]
}, { transaction: t });
if (tUser != null) {
tUser = tUser.get({ plain: true });
tUser.partnerinfo = await this.partnerinfoDao.model.findOne({ where: { onlyCode: tUser.onlyCode }, raw: true });
}
// console.log("tUser.partnerinfo...................................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>999sy");
// console.log(tUser);
return tUser;
}
async setAccount(user, account, t) {
var user = await user.setAccount(account, { transaction: t });
return user;
}
async setApp(user, app, t) {
//按照APPId,获取app对象
var user = await user.setApp(app, { transaction: t });
return user;
}
extraModelFilter() {
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {
"key": "include", "value": [
// {model:this.db.models.app,},
{ model: this.db.models.company, },
{ model: this.db.models.role, as: "Roles", attributes: ["id", "name"] }]
};
}
extraWhere(obj, w, qc, linkAttrs) {
console.log("----=========")
console.log(obj)
if (obj.bizpath && obj.bizpath != "") {
if (obj.bizpath.indexOf("tanents_info") > 0) {//说明是超级管理员的查询
w["isAdmin"] = true;
} else {
w["isAdmin"] = false;
w["company_id"] = obj.company_id;
// 为空说明是管理员,不需设置组织结构过滤
if (obj.opath && obj.opath != "") {
w["opath"] = { [this.db.Op.like]: `%${obj.opath}%` }
}
}
}
if (linkAttrs.length > 0) {
var search = obj.search;
var lnkKey = linkAttrs[0];
var strq = "$" + lnkKey.replace("~", ".") + "$";
w[strq] = { [this.db.Op.like]: "%" + search[lnkKey] + "%" };
}
return w;
}
async preUpdate(u) {
if (u.roles && u.roles.length >= 0) {
var roles = await this.db.models.role.findAll({ where: { id: { [this.db.Op.in]: u.roles } } });
u.roles = roles
}
return u;
}
async update(obj) {
var obj2 = await this.preUpdate(obj);
await this.model.update(obj2, { where: { id: obj2.id } });
var user = await this.model.findOne({ where: { id: obj2.id } });
if (obj2.roles) {
user.setRoles(obj2.roles);
}
return user;
}
async findAndCountAll(qobj, t) {
var users = await super.findAndCountAll(qobj, t);
return users;
}
async preCreate(u) {
// var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(roles);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// u.roles=roles
return u;
}
async create(u, t) {
var self = this;
var u2 = await this.preCreate(u);
if (t) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(u2);
return this.model.create(u2, { transaction: t }).then(user => {
return user;
});
} else {
return this.model.create(u2).then(user => {
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId, company_only_code, result) {
var customerObj = { companyOnlyCode: company_only_code };
var putSqlWhere = { where: { id: userId } };
this.updateByWhere(customerObj, putSqlWhere);
return result;
}
}
module.exports = UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const Dao=require("../../dao.base");
class AppDao extends Dao{
constructor(){
super(Dao.getModelName(AppDao));
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.bizpath && obj.bizpath!=""){
if(obj.bizpath.indexOf("my_app")>0){//说明是租户查询自己创建的应用
let appstrs=obj.myappstrs
let appsarray=appstrs.split(",")
let appidsquery=appsarray.map(astr=>{
return astr.split("|")[0]
})
w["id"]= {[this.db.Op.in]:appidsquery};
}
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
}
module.exports=AppDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const Dao=require("../../dao.base");
class ArticleDao extends Dao{
constructor(){
super(Dao.getModelName(ArticleDao));
}
orderBy(qobj) {
//return {"key":"include","value":{model:this.db.models.app}};
if(!qobj.orderInfo || qobj.orderInfo.length==0){
return [["created_at", "ASC"]];
}else{
return qobj.orderInfo;
}
}
}
module.exports=ArticleDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const fs=require("fs");
const settings=require("../../../../config/settings");
class CacheManager{
constructor(){
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap(){
var self=this;
self.doc={};
var cachePath=settings.basepath+"/app/base/db/cache/";
const files=fs.readdirSync(cachePath);
if(files){
files.forEach(function(r){
var classObj=require(cachePath+"/"+r);
self[classObj.name]=new classObj();
var refTmp=self[classObj.name];
if(refTmp.prefix){
self.doc[refTmp.prefix]=refTmp.desc;
}
else{
console.log("请在"+classObj.name+"缓存中定义prefix");
}
});
}
}
}
module.exports=CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const Sequelize = require('sequelize');
const settings = require("../../../../config/settings")
const fs = require("fs")
const path = require("path");
var glob = require("glob");
const Op = Sequelize.Op
class DbFactory {
constructor() {
const dbConfig = settings.database();
this.db = new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
{
...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.initRelations();
}
async initModels() {
var self = this;
var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
var models = glob.sync(modelpath + "/**/*.js");
console.log(models.length);
models.forEach(function (m) {
console.log(m);
self.db.import(m);
});
console.log("init models....");
}
async initRelations() {
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.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.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.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,});
//组织机构和用户是1对多,
// 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.user.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.app.belongsTo(this.db.models.user, { as: "creator", 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.role.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.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.msg.hasMany(this.db.models.msguser, { constraints: false });
this.db.models.msguser.belongsTo(this.db.models.msg, { constraints: false });
}
//async getCon(){,用于使用替换table模型内字段数据使用
getCon() {
var that = this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// throw err;
// });
//同步模型
if (settings.env == "dev") {
//console.log(pa);
// pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true}));
// });
// await this.db.models.user.create({nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
// .then(function(user){
// var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
// acc.save().then(a=>{
// user.setAccount(a);
// });
// });
}
return this.db;
}
}
module.exports = DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class MsgHistoryDao extends Dao{
constructor(){
super(Dao.getModelName(MsgHistoryDao));
}
extraWhere(obj,w){
if(obj.ukstr && obj.ukstr!=""){
// w={[this.db.Op.or]:[
// {[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
// {[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
// ]
// };
w[this.db.Op.or]=[
{[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
{[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
];
}
return w;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]];
}
}
module.exports=MsgHistoryDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MsgNoticeDao extends Dao{
constructor(){
super(Dao.getModelName(MsgNoticeDao));
}
async saveNotice(msg, t) {
var noticeFrom = await super.findOne({fromId : msg.senderId, toId : msg.targetId});
if(noticeFrom) {
var set = {lastMsgId:msg.id};
if(msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
await super.updateByWhere(set, {where:{id:noticeFrom.id}}, t);
} else {
noticeFrom = {
fromuser: msg.sender,
fromId:msg.senderId,
touser: msg.target,
toId:msg.targetId,
isAccepted:true,
lastMsgId:msg.id,
businessLicense_id : msg.businessLicense_id || 0
};
await super.create(noticeFrom, t);
}
var noticeTo = await super.findOne({fromId : msg.targetId, toId : msg.senderId});
if(noticeTo) {
var set = {lastMsgId:msg.id};
if(msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
await super.updateByWhere(set, {where:{id:noticeTo.id}}, t);
} else {
noticeTo = {
fromuser: msg.target,
fromId:msg.targetId,
touser: msg.sender,
toId:msg.senderId,
isAccepted:true,
lastMsgId:msg.id,
businessLicense_id : msg.businessLicense_id || 0
};
await super.create(noticeTo, t);
}
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]];
}
}
module.exports=MsgNoticeDao;
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 Dao=require("../../dao.base");
class PricecatDao extends Dao{
constructor(){
super(Dao.getModelName(PricecatDao));
}
orderBy(qobj) {
//return {"key":"include","value":{model:this.db.models.app}};
if(!qobj.orderInfo || qobj.orderInfo.length==0){
return [["seq", "ASC"]];
}else{
return qobj.orderInfo;
}
}
}
module.exports=PricecatDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system = require("../../../system");
const Dao = require("../../dao.base");
class ProductDao extends Dao {
constructor() {
super(Dao.getModelName(ProductDao));
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.bizpath && obj.bizpath!=""){
if(obj.bizpath.indexOf("productdef")>0){//说明是租户查询自己创建的应用
w["company_id"]= obj.company_id;
}
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
extraModelFilter() {
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {
"key": "include", "value": [
{ model: this.db.models.productprice, as: "skus", attributes: ["id", "pricestrategy_id"] }]
}
}
}
module.exports = ProductDao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class ProductcostDao extends Dao{
constructor(){
super(Dao.getModelName(ProductcostDao));
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[
{model:this.db.models.productprice,attributes:["id","lowpriceref"]}]};
}
}
module.exports=ProductcostDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const Dao=require("../../dao.base");
class ProductpriceDao extends Dao{
constructor(){
super(Dao.getModelName(ProductpriceDao));
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.bizpath && obj.bizpath!=""){
if(obj.bizpath.indexOf("platformprice")>0){//说明是租户查询自己创建的应用
w["company_id"]= obj.company_id;
}
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[
{model:this.db.models.pricestrategy,attributes:["id","optionunion"]},
{model:this.db.models.product,attributes:["id","name"]}]};
}
}
module.exports=ProductpriceDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system = require("../system");
const settings = require("../../config/settings.js");
const reclient = system.getObject("util.redisClient");
const md5 = require("MD5");
//获取平台配置兑换率
//初次登录的赠送数量
//创建一笔交易
//同时增加账户数量,增加系统平台账户
var dbf = system.getObject("db.common.connection");
var db = dbf.getCon();
db.sync({ force: true }).then(async () => {
// const apps = await system.getObject("service.common.appSve");
// const usS = await system.getObject("service.auth.userSve");
// let appnew = await apps.create({
// "name": "center-app",
// "domainName": "t9.com",
// "backend": "192.168.1.148",
// "isSystem": true,
// "title": "center-app"
// });
// let Role = db.models["role"];
// await Role.create({ code: "ta", name: "租户", isSystem: true, app_id: appnew.id, company_id: settings.pmcompanyid })
// await Role.create({ code: "pr", name: "个人", isSystem: true, app_id: appnew.id, company_id: settings.pmcompanyid })
// let usuper = await usS.pmregister({ userName: "sm", password: "951753", isSuper: true, isAdmin: true, isSystem: true, isEnabled: true, nickName: "superman", app_id: appnew.id, company_id: settings.id })
// appnew.creator_id = usuper.user.id
// await appnew.save()
//创建role
// if(settings.env=="prod"){
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
// }
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
});
module.exports = {
"config": {
"pdict": {
"app_type": { "api": "API服务","web": "PCWEB","app":"移动APP","xcx":"小程序","access":"接入"},
"data_priv": { "auth.role": "角色", "auth.user": "用户" },
"noticeType": {"sms": "短信", "email": "邮件","wechat":"微信"},
"authType": {"add": "新增", "edit": "编辑","delete":"删除","export":"导出","show":"查看"},
"mediaType": {"vd": "视频", "ad": "音频","qt":"其它"},
"usageType": {"kt": "课堂","taxkt":"财税课堂", "qt": "其它"},
"opstatus": {"0": "失败", "1": "成功"},
"sex": {"male": "男", "female": "女"},
"logLevel": {"debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4},
"msgType": { "sys": "系统", "single": "单点", "multi": "群发"},
"node_type":{"org":"组织","arc":"文档"}
}
}
}
const fs=require("fs");
const path=require("path");
const appPath=path.normalize(__dirname+"/app");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
config:require(appPath+"/"+"platform.js").config
}
module.exports=appJsons;
module.exports = (db, DataTypes) => {
return db.define("auth", {
rolecode: DataTypes.STRING,
bizcode: DataTypes.STRING,
codepath: DataTypes.STRING,
authstrs: DataTypes.STRING
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_auths',
validate: {
}
});
}
module.exports = (db, DataTypes) => {
return db.define("dataauth", {
modelname: DataTypes.STRING,
auths: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_dataauths',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("org", {
code: {
type:DataTypes.STRING(64),
allowNull: false,
},
name: {
type:DataTypes.STRING(64),
allowNull: false,
},
isLeaf:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
orgpath: {
type:DataTypes.STRING,
allowNull: false,
},
nodeType: {//默认为组织
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(appconfig.pdict.node_type),
defaultValue:'org'
},
isPosition:{//是否是岗位
type:DataTypes.BOOLEAN,
defaultValue: false
},
isMain:{//是否是主岗
type:DataTypes.BOOLEAN,
defaultValue: false
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_org',
validate: {
}
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("orgrole", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_orgrole',
validate: {
},
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("role", {
name: DataTypes.STRING,
code: DataTypes.STRING,
description: DataTypes.STRING,
isSystem: {//是否系统数据,0否,1是
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_role',
validate: {
}
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("user", {
userName: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
},
nickName: {
type: DataTypes.STRING,
allowNull: true,
},
sex: {
type: DataTypes.ENUM,
allowNull: true,
values: Object.keys(appconfig.pdict.sex),
},
mobile: DataTypes.STRING,
mail: {
type: DataTypes.STRING,
allowNull: true,
},
headUrl: DataTypes.STRING,
isAdmin: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
isAllocated: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
isSuper: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
isSystem: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
center_id: DataTypes.STRING,
jwtkey: DataTypes.STRING,
jwtsecret: DataTypes.STRING,
isEnabled: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
opath: DataTypes.STRING,//作业务时,需要在业务表冗余当前处理人的opath
ptags: DataTypes.STRING,//权限标签,逗号分隔,可以按照标签查看opath中含有标签的数据
skilltags: DataTypes.STRING,// 技能标签
regiontags: {
type: DataTypes.STRING,
allowNull: true,
},// 区域标签
openid: {
type: DataTypes.STRING,
allowNull: true,
},
unid: {
type: DataTypes.STRING,
allowNull: true,
},
isDelivery: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
isSalesman: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
isAllArea: {
type: DataTypes.BOOLEAN,
defaultValue: false
}
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_user',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("app", {
appkey:{
type: DataTypes.STRING,
allowNull: true,
},
title:{
type: DataTypes.STRING,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
domainName: DataTypes.STRING,//域名
backend:DataTypes.STRING,//域名
backport:DataTypes.INTEGER,//后台端口
homePage: DataTypes.STRING,//首页
functionJSON: DataTypes.TEXT,//功能清单地址--前端通过loadJson下载数据
docUrl: DataTypes.STRING,//接口文档地址
configUrl: DataTypes.STRING,//基础信息配置信息地址
logoUrl: DataTypes.STRING,//应用Logo
bkimageUrl: DataTypes.STRING,//应用背景图
showimgUrl: DataTypes.STRING,//应用显示图标
detailimgUrl: DataTypes.STRING,//应用详情介绍地址
opCacheUrl: DataTypes.STRING,//操作缓存地址
description: DataTypes.STRING,//应用描述
isSystem: {
type: DataTypes.BOOLEAN,
defaultValue: false
},//是否启用
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否启用
isPublish: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
appType: {
type: DataTypes.ENUM,
allowNull: true,
values: Object.keys(appconfig.pdict.app_type),
},
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_app',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("article", {
title: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
desc: {//概述
type: DataTypes.STRING,
allowNull: true,
},//和us
listimg: {//简图
type: DataTypes.STRING,
allowNull: true,
},//和us
isPubed:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
htmlcontent: {
type: DataTypes.STRING,
allowNull: true,
},//和user的from相同,在注册user时,去创建
tags: {
type: DataTypes.STRING,
allowNull: true,
},//和user的from相同,在注册user时,去创建
archpath:{//文档路径
type: DataTypes.STRING,
allowNull: false,
},
seq:{
type: DataTypes.INTEGER,
allowNull: true,
defaultValue:0
},
creator_id:{
type: DataTypes.INTEGER,
allowNull: false,
},
creator:{
type: DataTypes.STRING,
allowNull: false,
}
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_article',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("attachment", {
name: DataTypes.STRING,
urlstr:DataTypes.STRING,
description: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_attachments',
validate: {
}
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("channel", {
code: {
type: DataTypes.STRING,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
routehost: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
userids: {
type: DataTypes.STRING,
allowNull: true,
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_channel',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("company", {
code:{//存放简码
type: DataTypes.STRING,
allowNull: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
companykey: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from
address: {
type: DataTypes.STRING,
allowNull: true,
},//和user的from
mail: {
type: DataTypes.STRING,
allowNull: true,
},//和user的from
phone: {
type: DataTypes.STRING,
allowNull: true,
},
licenseUrl: {
type: DataTypes.STRING,
allowNull: true,
},
orgJson: DataTypes.TEXT,//功能清
appids:DataTypes.STRING,
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_company',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("pathtomethod", {
path:{
type: DataTypes.STRING,
allowNull: false,
},
method: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
desc:{
type: DataTypes.STRING,
allowNull: false,
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_pathtomethod',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("plugin", {
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_plugin',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("region", {
code: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
level: {
type: DataTypes.INTEGER,
allowNull: false,
},//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'fh_regions',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("route", {
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
center_id: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
shosts:{
type: DataTypes.STRING,
allowNull: false,
},
spaths:{
type: DataTypes.STRING,
allowNull: false,
}
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_route',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("treearch", {
regionJSON: DataTypes.TEXT,//功能清单地址--前端通过loadJson下载数据
productcatJSON:DataTypes.TEXT,
sysArchJSON:DataTypes.TEXT,//系统的文档树
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_treearchs',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("msg", {
msgType: {
type: DataTypes.ENUM,
allowNull: false,
values: Object.keys(appconfig.pdict.msgType),
},
app_id: {
type: DataTypes.INTEGER,
allowNull: true
},
app_key: {
type: DataTypes.STRING,
allowNull: true
},
company_id: {
type: DataTypes.INTEGER,
allowNull: true
},
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,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msg_history',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("msguser", {
user_id: {
type: DataTypes.INTEGER,
allowNull: false
},
user: {
type: DataTypes.STRING,
allowNull: true
},
is_read: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
is_remind: {
type: DataTypes.BOOLEAN,
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: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
//定价类型
return db.define("pricecat", {
seq:{
type: DataTypes.INTEGER,
allowNull: false,
},
code:{
type: DataTypes.STRING,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
options: {
type: DataTypes.STRING,
allowNull: false,
}//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_pricecat',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
//定价类型
return db.define("pricestrategy", {
codeunion:{
type: DataTypes.STRING,
allowNull: false,
},
nameunion: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
optionunion: {
type: DataTypes.STRING,
allowNull: false,
}//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_pricestrategy',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
//定价类型
return db.define("product", {
sptags:{//交付商标签
type: DataTypes.STRING,
allowNull: true,
},
channeltags:{//渠道标签
type: DataTypes.STRING,
allowNull: true,
},
industrytags:{//行业标签
type: DataTypes.STRING,
allowNull: true,
},
code:{
type: DataTypes.STRING,
allowNull: false,
},
regionpath:{
type: DataTypes.STRING,
allowNull: false,
},
productcatpath:{
type: DataTypes.STRING,
allowNull: false,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
desc: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_product',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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