Commit d8e663e4 by Sxy

fix: 代码规范

parent 3576ff32
...@@ -5,7 +5,7 @@ ARG webenv ...@@ -5,7 +5,7 @@ ARG webenv
ADD center-manage /apps/center-manage/ ADD center-manage /apps/center-manage/
ADD web/$webenv /apps/center-manage/app/front/entry/public/ ADD web/$webenv /apps/center-manage/app/front/entry/public/
WORKDIR /apps/center-manage/ WORKDIR /apps/center-manage/
RUN cnpm install -S RUN cnpm install -S --production
CMD ["node","/apps/center-manage/main.js"] CMD ["node","/apps/center-manage/main.js"]
......
module.exports = {
root: true,
extends: [
// 'plugin:vue/essential',
'@tencent/eslint-config-tencent',
// '@vue/standard'
],
rules: {
// allow async-await
'generator-star-spacing': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'vue/no-parsing-error': [2, {
'x-invalid-end-tag': false,
}],
'no-undef': 'off',
camelcase: 'off',
},
parserOptions: {
parser: 'babel-eslint',
},
env: {
jquery: true,
node: true,
},
};
const system = require("../system"); const system = require('../system');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
const settings = require("../../config/settings"); const settings = require('../../config/settings');
class APIBase{ class APIBase {
constructor() { constructor() {
this.cacheManager = system.getObject("db.common.cacheManager"); this.cacheManager = system.getObject('db.common.cacheManager');
this.logClient=system.getObject("util.logClient"); this.logClient = system.getObject('util.logClient');
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
return u;
}
async setContextParams(pobj, qobj, req) {
const 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'];
} }
getUUID() { const app = await this.cacheManager.AppCache.cache(req.xctx.appkey);
var uuid = uuidv4(); req.xctx.appid = app.id;
var u = uuid.replace(/\-/g, ""); pobj.app_id = app.id;// 传递参数对象里注入app_id
return u;
// 平台注册时,companyid,companykey都为空
// 自由注册时,companykey不能为空
// if(!req.xctx.companyid && !req.xctx.companykey){
// return [-200,"请求头缺少应用x-app-key"]
// }
if (!req.xctx.companyid && req.xctx.companykey) {
const 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 setContextParams(pobj, qobj, req) { }
let custtags = req.headers["x-consumetag"]?req.headers["x-consumetag"].split("|"):null; async doexec(gname, methodname, pobj, query, req) {
//当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值 try {
req.xctx = { const xarg = await this.setContextParams(pobj, query, req);
appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色 if (xarg && xarg[0] < 0) {
companyid: custtags?custtags[0].split("_")[1]:null, return system.getResultFail(...xarg);
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 { const rtn = await this[methodname](pobj, query, req);
let xarg=await this.setContextParams(pobj, query, req); this.logClient.log(pobj, req, rtn);
if(xarg && xarg[0]<0){ return rtn;
return system.getResultFail(...xarg); } catch (e) {
} this.logClient.log(pobj, req, null, e.stack);
console.log(e.stack, 'api调用异常--error...................');
var rtn = await this[methodname](pobj, query, req); const rtnerror = system.getResultFail(-200, '出现异常,请联系管理员');
this.logClient.log(pobj,req,rtn) return rtnerror;
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; module.exports = APIBase;
const system = require("../system"); const system = require('../system');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
class DocBase { class DocBase {
constructor() { constructor() {
this.apiDoc = { this.apiDoc = {
group: "逻辑分组", group: '逻辑分组',
groupDesc: "", groupDesc: '',
name: "", name: '',
desc: "请对当前类进行描述", desc: '请对当前类进行描述',
exam: "概要示例", exam: '概要示例',
methods: [] methods: [],
}; };
this.initClassDoc(); this.initClassDoc();
} }
initClassDoc() { initClassDoc() {
this.descClass(); this.descClass();
this.descMethods(); this.descMethods();
} }
descClass() { descClass() {
var classDesc = this.classDesc(); const classDesc = this.classDesc();
this.apiDoc.group = classDesc.groupName; this.apiDoc.group = classDesc.groupName;
this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc); this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc);
this.apiDoc.name = classDesc.name; this.apiDoc.name = classDesc.name;
this.apiDoc.desc = this.examDescHtml(classDesc.desc); this.apiDoc.desc = this.examDescHtml(classDesc.desc);
this.apiDoc.exam = this.examHtml(); this.apiDoc.exam = this.examHtml();
} }
examDescHtml(desc) { examDescHtml(desc) {
// var tmpDesc = desc.replace(/\\/g, "<br/>"); // var tmpDesc = desc.replace(/\\/g, "<br/>");
return desc; return desc;
} }
examHtml() { examHtml() {
var exam = this.exam(); let exam = this.exam();
exam = exam.replace(/\\/g, "<br/>"); exam = exam.replace(/\\/g, '<br/>');
return exam; return exam;
} }
exam() { exam() {
throw new Error("请在子类中定义类操作示例"); throw new Error('请在子类中定义类操作示例');
} }
classDesc() { classDesc() {
throw new Error(` throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构 请重写classDesc对当前的类进行描述,返回如下数据结构
{ {
groupName:"auth", groupName:"auth",
...@@ -46,19 +46,21 @@ class DocBase { ...@@ -46,19 +46,21 @@ class DocBase {
exam:"", exam:"",
} }
`); `);
}
descMethods() {
const methoddescs = this.methodDescs();
for (const methoddesc of methoddescs) {
for (const paramdesc of methoddesc.paramdescs) {
this.descMethod(
methoddesc.methodDesc, methoddesc.methodName
, paramdesc.paramDesc, paramdesc.paramName, paramdesc.paramType,
paramdesc.defaultValue, methoddesc.rtnTypeDesc, methoddesc.rtnType,
);
}
} }
descMethods() { }
var methoddescs = this.methodDescs(); methodDescs() {
for (var methoddesc of methoddescs) { throw new Error(`
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对当前的类的所有方法进行描述,返回如下数据结构 请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[ [
{ {
...@@ -83,35 +85,32 @@ class DocBase { ...@@ -83,35 +85,32 @@ class DocBase {
} }
] ]
`); `);
}
descMethod(methodDesc, methodName, paramDesc, paramName, paramType, defaultValue, rtnTypeDesc, rtnType) {
const mobj = this.apiDoc.methods.filter((m) => {
if (m.name == methodName) {
return true;
}
return false;
})[0];
const 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,
rtnType,
});
} }
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; module.exports = DocBase;
var APIBase = require("../../api.base"); const APIBase = require('../../api.base');
var system = require("../../../system"); const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
class AccessAuthAPI extends APIBase { class AccessAuthAPI extends APIBase {
constructor() { constructor() {
super(); super();
this.userSve = system.getObject("service.auth.userSve"); this.userSve = system.getObject('service.auth.userSve');
} }
//不从平台应用列表入口登录时 // 不从平台应用列表入口登录时
//先要调用平台登录接口 // 先要调用平台登录接口
//返回token,利用这个token再去登录某个具体APP // 返回token,利用这个token再去登录某个具体APP
//会话存储具体APP的用户信息 // 会话存储具体APP的用户信息
//每个前端应用打开时,先检查是否存在token // 每个前端应用打开时,先检查是否存在token
//如果存在,就去访问获取用户信息,---调用本接口--即刻 // 如果存在,就去访问获取用户信息,---调用本接口--即刻
//进入或登录某个具体应用 // 进入或登录某个具体应用
//前提是已经具备了统一管理的账号,并且已经在统一管理账号登录,客户端具备了token // 前提是已经具备了统一管理的账号,并且已经在统一管理账号登录,客户端具备了token
//进入某个具体应用时,需要指定 x-appkey请求头 // 进入某个具体应用时,需要指定 x-appkey请求头
// //
async loginToApp(p,q,req){ async loginToApp(p, q, req) {
let appkey=req.xctx.appkey; const { appkey } = req.xctx;
}
} async getBizUserForBizChance(p, q, req) {
async getBizUserForBizChance(p,q,req){ const s = await this.userSve.getBizUserForBizChance(p.clientMobile, p.spName, p.productCatName, p.regionName);
let s= await this.userSve.getBizUserForBizChance(p.clientMobile,p.spName,p.productCatName,p.regionName) return system.getResult(s);
return system.getResult(s) }
} async getBizUserForDelivery(p, q, req) {
async getBizUserForDelivery(p,q,req){ const s = await this.userSve.getBizUserForDelivery(p.clientMobile, p.spName, p.productCatName, p.skucode, p.regionName);
let s= await this.userSve.getBizUserForDelivery(p.clientMobile,p.spName,p.productCatName,p.skucode,p.regionName) return system.getResult(s);
return system.getResult(s) }
} classDesc() {
classDesc() { return {
return { groupName: 'auth',
groupName: "auth", groupDesc: '认证相关的包',
groupDesc: "认证相关的包", name: 'AccessAuthAPI',
name: "AccessAuthAPI", desc: '关于认证的类',
desc: "关于认证的类", exam: `
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey post http://p.apps.com/api/auth/accessAuth/getAccessKey
{ {
appKey:xxxxx, appKey:xxxxx,
secret:yyyyyy secret:yyyyyy
} }
`, `,
}; };
} }
methodDescs() { methodDescs() {
return [ return [
{ {
methodDesc: "生成访问token,访问地址:http://......../api/auth/accessAuth/getAccessKey,访问token需要放置到后续API方法调用的请求头中", methodDesc: '生成访问token,访问地址:http://......../api/auth/accessAuth/getAccessKey,访问token需要放置到后续API方法调用的请求头中',
methodName: "getAccessKey", methodName: 'getAccessKey',
paramdescs: [ paramdescs: [
{ {
paramDesc: "访问appkey", paramDesc: '访问appkey',
paramName: "appkey", paramName: 'appkey',
paramType: "string", paramType: 'string',
defaultValue: "", defaultValue: '',
}, },
{ {
paramDesc: "访问secret", paramDesc: '访问secret',
paramName: "secret", paramName: 'secret',
paramType: "string", paramType: 'string',
defaultValue: "", defaultValue: '',
} },
], ],
rtnTypeDesc: "返回JSON对象字符串", rtnTypeDesc: '返回JSON对象字符串',
rtnType: "json object {accessKey: xxxxxx, app: {xxx:xxx}},注意app,是当前app信息,详细见后面示例" rtnType: 'json object {accessKey: xxxxxx, app: {xxx:xxx}},注意app,是当前app信息,详细见后面示例',
}, },
]; ];
} }
exam() { exam() {
return `` return ``;
} }
} }
module.exports = AccessAuthAPI; module.exports = AccessAuthAPI;
var APIBase = require("../../api.base"); const APIBase = require('../../api.base');
var system = require("../../../system"); const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
class RoleAuthAPI extends APIBase { class RoleAuthAPI extends APIBase {
constructor() { constructor() {
super(); super();
this.authS=system.getObject("service.auth.authSve"); this.authS = system.getObject('service.auth.authSve');
} }
async findAuthsByRole(p,q,req){ async findAuthsByRole(p, q, req) {
var tmpRoles=p.roles; const tmpRoles = p.roles;
var appid=p.appid; const { appid } = p;
var comid=p.companyid; const comid = p.companyid;
var auths=await this.authS.findAuthsByRole(tmpRoles,appid,comid); const auths = await this.authS.findAuthsByRole(tmpRoles, appid, comid);
return system.getResult(auths); return system.getResult(auths);
} }
exam(){ exam() {
return ` return `
xxxxxxxxx xxxxxxxxx
yyyyyyyyy yyyyyyyyy
zzzzzzzzz zzzzzzzzz
ooooooo ooooooo
`; `;
} }
classDesc() { classDesc() {
return { return {
groupName: "auth", groupName: 'auth',
groupDesc: "角色授权相关的API", groupDesc: '角色授权相关的API',
name: "RoleAuthAPI", name: 'RoleAuthAPI',
desc: "角色授权相关的API", desc: '角色授权相关的API',
exam: "", 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"
}
];
}
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; module.exports = RoleAuthAPI;
\ No newline at end of file
var APIBase = require("../../api.base"); const APIBase = require('../../api.base');
var system = require("../../../system"); const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
class AppAPI extends APIBase { class AppAPI extends APIBase {
constructor() { constructor() {
super(); super();
this.appS = system.getObject("service.common.appSve"); this.appS = system.getObject('service.common.appSve');
} }
async create(pobj,q,req){ async create(pobj, q, req) {
// console.log("oooooooooooooooooooooooooooooooooooooooooooooooo") // console.log("oooooooooooooooooooooooooooooooooooooooooooooooo")
// console.log(req.xctx) // console.log(req.xctx)
let rtn=this.appS.create(pobj,q,req); const rtn = this.appS.create(pobj, q, req);
return system.getResult(rtn); return system.getResult(rtn);
} }
async del(pobj,q,req){ async del(pobj, q, req) {
let rtn=this.appS.delete(pobj,q,req); const rtn = this.appS.delete(pobj, q, req);
return system.getResult(rtn); return system.getResult(rtn);
} }
classDesc() { classDesc() {
return { return {
groupName: "auth", groupName: 'auth',
groupDesc: "认证相关的包", groupDesc: '认证相关的包',
name: "AccessAuthAPI", name: 'AccessAuthAPI',
desc: "关于认证的类", desc: '关于认证的类',
exam: ` exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey post http://p.apps.com/api/auth/accessAuth/getAccessKey
{ {
appKey:xxxxx, appKey:xxxxx,
secret:yyyyyy secret:yyyyyy
} }
`, `,
}; };
} }
methodDescs() { methodDescs() {
return [ return [
]; ];
} }
exam() { exam() {
return `` return ``;
} }
} }
module.exports = AppAPI; module.exports = AppAPI;
var APIBase = require("../../api.base"); const APIBase = require('../../api.base');
var system = require("../../../system"); const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
class ChannelAPI extends APIBase { class ChannelAPI extends APIBase {
constructor() { constructor() {
super(); super();
this.channelS=system.getObject("service.common.channelSve") this.channelS = system.getObject('service.common.channelSve');
} }
async getChannels(hostname){ async getChannels(hostname) {
let cacheManager = system.getObject("db.common.cacheManager"); const cacheManager = system.getObject('db.common.cacheManager');
let channels=await cacheManager["ChannelCache"].cache(hostname) const channels = await cacheManager.ChannelCache.cache(hostname);
return channels; return channels;
} }
async channelHandle(channelobj,path,data){ async channelHandle(channelobj, path, data) {
let rtn=await this.channelS.channelHandle(channelobj,path,data) const rtn = await this.channelS.channelHandle(channelobj, path, data);
return rtn; return rtn;
} }
classDesc() { classDesc() {
return { return {
groupName: "auth", groupName: 'auth',
groupDesc: "认证相关的包", groupDesc: '认证相关的包',
name: "AccessAuthAPI", name: 'AccessAuthAPI',
desc: "关于认证的类", desc: '关于认证的类',
exam: ` exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey post http://p.apps.com/api/auth/accessAuth/getAccessKey
{ {
appKey:xxxxx, appKey:xxxxx,
secret:yyyyyy secret:yyyyyy
} }
`, `,
}; };
} }
methodDescs() { methodDescs() {
return [ return [
]; ];
} }
exam() { exam() {
return `` return ``;
} }
} }
module.exports = ChannelAPI; module.exports = ChannelAPI;
var APIBase = require("../../api.base"); const APIBase = require('../../api.base');
var system = require("../../../system"); const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
class ProductAPI extends APIBase { class ProductAPI extends APIBase {
constructor() { constructor() {
super(); super();
this.productpriceS = system.getObject("service.product.productpriceSve") this.productpriceS = system.getObject('service.product.productpriceSve');
} }
/** /**
* *
* @param {*} p productname-产品名称/sp名称 * @param {*} p productname-产品名称/sp名称
* @param {*} q * @param {*} q
* @param {*} req * @param {*} req
* 返回值[ * 返回值[
* label:'', * label:'',
* code:'' * code:''
* ] * ]
*/ */
async findRegionsByProductName(p, q, req) { async findRegionsByProductName(p, q, req) {
let pname = p.productname; const pname = p.productname;
let sp = p.sp; const { sp } = p;
let rs = await this.productpriceS.findRegionsByProductName(pname, sp) const rs = await this.productpriceS.findRegionsByProductName(pname, sp);
return system.getResult(rs); return system.getResult(rs);
} }
async findProductInfoForFt(p, q, req) { async findProductInfoForFt(p, q, req) {
let pname = p.productname; const pname = p.productname;
let region = p.region; const { region } = p;
let rs = await this.productpriceS.findProductInfoForFt(pname, region) const rs = await this.productpriceS.findProductInfoForFt(pname, region);
return system.getResult(rs); return system.getResult(rs);
} }
classDesc() { classDesc() {
return { return {
groupName: "auth", groupName: 'auth',
groupDesc: "认证相关的包", groupDesc: '认证相关的包',
name: "AccessAuthAPI", name: 'AccessAuthAPI',
desc: "关于认证的类", desc: '关于认证的类',
exam: ` exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey post http://p.apps.com/api/auth/accessAuth/getAccessKey
{ {
appKey:xxxxx, appKey:xxxxx,
secret:yyyyyy secret:yyyyyy
} }
`, `,
}; };
} }
methodDescs() { methodDescs() {
return [ return [
]; ];
} }
exam() { exam() {
return `` return ``;
} }
} }
module.exports = ProductAPI; module.exports = ProductAPI;
var APIBase = require("../../api.base"); const APIBase = require('../../api.base');
var system = require("../../../system"); const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const crypto = require('crypto'); const crypto = require('crypto');
var fs=require("fs"); const fs = require('fs');
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5'; const accesskey = '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd'; const accessKeyId = 'LTAI4GC5tSKvqsH2hMqj6pvd';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com"; const url = 'https://gsb-zc.oss-cn-beijing.aliyuncs.com';
class OSSAPI extends APIBase{ class OSSAPI extends APIBase {
constructor(){ constructor() {
super() super();
} }
async getOssConfig(){ async getOssConfig() {
var policyText = { const policyText = {
"expiration":"2119-12-31T16:00:00.000Z", expiration: '2119-12-31T16:00:00.000Z',
"conditions":[ conditions: [
["content-length-range",0,1048576000], ['content-length-range', 0, 1048576000],
["starts-with","$key","zc"] ['starts-with', '$key', 'zc'],
] ],
}; };
var b = new Buffer(JSON.stringify(policyText)); const b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64'); const policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64 const signature = crypto.createHmac('sha1', accesskey).update(policyBase64)
.digest()
.toString('base64'); // base64
var data={ const data = {
OSSAccessKeyId:accessKeyId, OSSAccessKeyId: accessKeyId,
policy:policyBase64, policy: policyBase64,
Signature:signature, Signature: signature,
Bucket:'gsb-zc', Bucket: 'gsb-zc',
success_action_status:201, success_action_status: 201,
url:url url,
}; };
return system.getResult(data); return system.getResult(data);
};
async upfile(srckey, dest) {
const oss = System.getObject('util.ossClient');
const result = await oss.upfile(srckey, `/tmp/${dest}`);
return result;
};
async downfile(srckey) {
const oss = System.getObject('util.ossClient');
var downfile = await oss.downfile(srckey).then(() => {
downfile = `/tmp/${srckey}`;
return downfile;
});
return downfile;
}; };
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; module.exports = OSSAPI;
const system = require("../system"); const system = require('../system');
const settings = require("../../config/settings"); const settings = require('../../config/settings');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
class CtlBase { class CtlBase {
constructor(gname, sname) { constructor(gname, sname) {
this.serviceName = sname; this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname); this.service = system.getObject(`service.${gname}.${sname}`);
this.cacheManager = system.getObject("db.common.cacheManager"); this.cacheManager = system.getObject('db.common.cacheManager');
this.logClient = system.getObject("util.logClient"); this.logClient = system.getObject('util.logClient');
} }
getUUID() { getUUID() {
var uuid = uuidv4(); const uuid = uuidv4();
var u = uuid.replace(/\-/g, ""); const u = uuid.replace(/\-/g, '');
return u; return u;
} }
static getServiceName(ClassObj) { static getServiceName(ClassObj) {
return `${ClassObj.name.substring(0, ClassObj.name.lastIndexOf('Ctl')).toLowerCase()}Sve`;
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
} }
async update(pobj, qobj, req) { async update(pobj, qobj, req) {
const up = await this.service.update(pobj); const up = await this.service.update(pobj);
...@@ -30,8 +29,8 @@ class CtlBase { ...@@ -30,8 +29,8 @@ class CtlBase {
return system.getResult(up); return system.getResult(up);
} }
async findAndCountAll(pobj, qobj, req) { async findAndCountAll(pobj, qobj, req) {
//设置查询条件 // 设置查询条件
console.log(pobj) console.log(pobj);
const rs = await this.service.findAndCountAll(pobj); const rs = await this.service.findAndCountAll(pobj);
return system.getResult(rs); return system.getResult(rs);
} }
...@@ -39,61 +38,61 @@ class CtlBase { ...@@ -39,61 +38,61 @@ class CtlBase {
return this.service.findOne(obj); return this.service.findOne(obj);
} }
async refQuery(pobj, qobj, req) { async refQuery(pobj, qobj, req) {
//pobj.refwhere.app_id=pobj.app_id;//角色过滤按照公司过滤 // pobj.refwhere.app_id=pobj.app_id;//角色过滤按照公司过滤
pobj.refwhere.company_id = pobj.company_id; pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj); const rtn = await this.service.refQuery(pobj);
return rtn return rtn;
} }
async setContextParams(pobj, qobj, req) { async setContextParams(pobj, qobj, req) {
let custtags = req.headers["x-consumetag"] ? req.headers["x-consumetag"].split("|") : null; const custtags = req.headers['x-consumetag'] ? req.headers['x-consumetag'].split('|') : null;
let lastindex = custtags ? custtags.length - 1 : 0; const lastindex = custtags ? custtags.length - 1 : 0;
//当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值 // 当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值
req.xctx = { req.xctx = {
appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色 appkey: req.headers.xappkey, // 用于系统管理区分应用,比如角色
fromappkey: req.headers["xfromappkey"],//来源APP,如果没有来源与appkey相同 fromappkey: req.headers.xfromappkey, // 来源APP,如果没有来源与appkey相同
companyid: custtags ? custtags[0].split("_")[1] : null, companyid: custtags ? custtags[0].split('_')[1] : null,
fromcompanykey: req.headers["xfromcompanykey"],//专用于自由用户注册,自由用户用于一定属于某个存在的公司 fromcompanykey: req.headers.xfromcompanykey, // 专用于自由用户注册,自由用户用于一定属于某个存在的公司
password: custtags ? custtags[lastindex].split("_")[1] : null, password: custtags ? custtags[lastindex].split('_')[1] : null,
username: req.headers["x-consumer-username"], username: req.headers['x-consumer-username'],
userid: req.headers["x-consumer-custom-id"], userid: req.headers['x-consumer-custom-id'],
credid: req.headers["x-credential-identifier"], credid: req.headers['x-credential-identifier'],
regrole: req.headers["xregrole"], regrole: req.headers.xregrole,
bizpath: req.headers["xbizpath"], bizpath: req.headers.xbizpath,
codename: req.headers["xcodename"], codename: req.headers.xcodename,
codetitle: req.headers["xcodetitle"] ? decodeURI(req.headers["xcodetitle"]) : '', codetitle: req.headers.xcodetitle ? decodeURI(req.headers.xcodetitle) : '',
opath: req.headers['xopath'], opath: req.headers.xopath,
ptags: req.headers['xptags'], ptags: req.headers.xptags,
} };
//添加组织结构路径,如果是上级,取上级 // 添加组织结构路径,如果是上级,取上级
if (req.xctx.ptags && req.xctx.ptags != "") { if (req.xctx.ptags && req.xctx.ptags != '') {
pobj.opath = req.xctx.ptags pobj.opath = req.xctx.ptags;
} else { } else {
if (!pobj.opath || pobj.opath == "") {//解决当前保存用户功能 if (!pobj.opath || pobj.opath == '') { // 解决当前保存用户功能
pobj.opath = req.xctx.opath pobj.opath = req.xctx.opath;
} }
} }
if (!req.xctx.appkey) { if (!req.xctx.appkey) {
return [-200, "请求头缺少应用x-app-key"] return [-200, '请求头缺少应用x-app-key'];
} else { }
let app = await this.cacheManager["AppCache"].cache(req.xctx.fromappkey); const app = await this.cacheManager.AppCache.cache(req.xctx.fromappkey);
req.xctx.appid = app.id; req.xctx.appid = app.id;
if (!pobj.app_id) { if (!pobj.app_id) {
pobj.app_id = app.id;//传递参数对象里注入app_id pobj.app_id = app.id;// 传递参数对象里注入app_id
}
} }
//平台注册时,companyid,companykey都为空
//自由注册时,companykey不能为空 // 平台注册时,companyid,companykey都为空
// 自由注册时,companykey不能为空
// if(!req.xctx.companyid && !req.xctx.companykey){ // if(!req.xctx.companyid && !req.xctx.companykey){
// return [-200,"请求头缺少应用x-app-key"] // return [-200,"请求头缺少应用x-app-key"]
// } // }
if (!req.xctx.companyid && req.xctx.fromcompanykey && req.xctx.fromcompanykey != "null" && req.xctx.fromcompanykey != "undefined") { 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); const comptmp = await this.cacheManager.CompanyCache.cache(req.xctx.fromcompanykey);
req.xctx.companyid = comptmp.id; req.xctx.companyid = comptmp.id;
} }
if (req.xctx.companyid) {//在请求传递数据对象注入公司id if (req.xctx.companyid) { // 在请求传递数据对象注入公司id
pobj.company_id = req.xctx.companyid; pobj.company_id = req.xctx.companyid;
} }
if (req.xctx.userid) {//在请求传递数据对象注入公司id if (req.xctx.userid) { // 在请求传递数据对象注入公司id
pobj.userid = req.xctx.userid; pobj.userid = req.xctx.userid;
pobj.username = req.xctx.username; pobj.username = req.xctx.username;
} }
...@@ -102,17 +101,17 @@ class CtlBase { ...@@ -102,17 +101,17 @@ class CtlBase {
async doexec(methodname, pobj, query, req) { async doexec(methodname, pobj, query, req) {
try { try {
let xarg = await this.setContextParams(pobj, query, req); const xarg = await this.setContextParams(pobj, query, req);
if (xarg && xarg[0] < 0) { if (xarg && xarg[0] < 0) {
return system.getResultFail(...xarg); return system.getResultFail(...xarg);
} }
var rtn = await this[methodname](pobj, query, req); const rtn = await this[methodname](pobj, query, req);
this.logClient.log(pobj, req, rtn, null) this.logClient.log(pobj, req, rtn, null);
return rtn; return rtn;
} catch (e) { } catch (e) {
this.logClient.log(pobj, req, null, e.stack) this.logClient.log(pobj, req, null, e.stack);
console.log(e.stack, "出现异常,请联系管理员......."); console.log(e.stack, '出现异常,请联系管理员.......');
return system.getResultFail(-200, e.message ? e.message : "出现异常,请联系管理员"); return system.getResultFail(-200, e.message ? e.message : '出现异常,请联系管理员');
} }
} }
} }
...@@ -133,4 +132,4 @@ module.exports = CtlBase; ...@@ -133,4 +132,4 @@ module.exports = CtlBase;
} }
} }
logs-sytxpublic-msgq-service--日志服务 logs-sytxpublic-msgq-service--日志服务
*/ */
\ No newline at end of file
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings=require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class AuthCtl extends CtlBase{ class AuthCtl extends CtlBase {
constructor(){ constructor() {
super("auth",CtlBase.getServiceName(AuthCtl)); super('auth', CtlBase.getServiceName(AuthCtl));
} }
async saveAuths(pobj,query,req){ async saveAuths(pobj, query, req) {
var auths=pobj.auths; const { auths } = pobj;
var xrtn=await this.service.saveAuths(auths,pobj.app_id,pobj.company_id); const xrtn = await this.service.saveAuths(auths, pobj.app_id, pobj.company_id);
return system.getResult(xrtn); return system.getResult(xrtn);
} }
async findAuthsByRoles(pobj,query,req){ async findAuthsByRoles(pobj, query, req) {
var roleids=pobj.roleids; const { roleids } = pobj;
var xrtn=await this.service.findAuthsByRole(roleids,pobj.app_id,pobj.company_id); const xrtn = await this.service.findAuthsByRole(roleids, pobj.app_id, pobj.company_id);
return system.getResult(xrtn); return system.getResult(xrtn);
} }
} }
module.exports=AuthCtl; module.exports = AuthCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings=require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
const logCtl = system.getObject("web.common.oplogCtl"); const logCtl = system.getObject('web.common.oplogCtl');
class DataauthCtl extends CtlBase{ class DataauthCtl extends CtlBase {
constructor(){ constructor() {
super("auth",CtlBase.getServiceName(DataauthCtl)); 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){ async saveauth(qobj, querybij, req) {
var uid=qobj.uid; const { arys } = qobj;
var refmodel=qobj.modelname; const { uid } = qobj;
var authtmp=await this.service.findOne({user_id:uid,modelname:refmodel,app_id:req.appid}); const refmodel = qobj.modelname;
if(authtmp){ const u = await this.service.saveauth({
var auths= authtmp.auths; user_id: uid,
var arys=auths.split(","); modelname: refmodel,
auths: arys.join(','),
app_id: req.appid,
});
return system.getResult(u);
}
async fetchInitAuth(qobj, querybij, req) {
const { uid } = qobj;
const refmodel = qobj.modelname;
const authtmp = await this.service.findOne({ user_id: uid, modelname: refmodel, app_id: req.appid });
if (authtmp) {
const { auths } = authtmp;
const arys = auths.split(',');
return system.getResult(arys); return system.getResult(arys);
}else{
return system.getResultSuccess([]);
} }
return system.getResultSuccess([]);
} }
} }
module.exports=DataauthCtl; module.exports = DataauthCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings=require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
const logCtl = system.getObject("web.common.oplogCtl"); const logCtl = system.getObject('web.common.oplogCtl');
class OrgCtl extends CtlBase{ class OrgCtl extends CtlBase {
constructor(){ constructor() {
super("auth",CtlBase.getServiceName(OrgCtl)); super('auth', CtlBase.getServiceName(OrgCtl));
// this.compSvr=system.getObject("service.common.companySve"); // this.compSvr=system.getObject("service.common.companySve");
} }
//检查是否已经存在主要岗位 // 检查是否已经存在主要岗位
async checkMainPosition(p,q,req){ async checkMainPosition(p, q, req) {
return this.service.checkMainPosition(p,q,req); return this.service.checkMainPosition(p, q, req);
} }
async changePos(p,q,req){ async changePos(p, q, req) {
var toorgid=p.orgid; const toorgid = p.orgid;
var uid=p.uid; const { uid } = p;
var rtn= await this.service.changePos(toorgid,uid); const rtn = await this.service.changePos(toorgid, uid);
return system.getResult(rtn); return system.getResult(rtn);
} }
async create(p,q,req){ async create(p, q, req) {
return super.create(p, q, req);
return super.create(p,q,req); }
} async delete(p, q, req) {
async delete(p,q,req){ return super.delete(p, q, req);
return super.delete(p,q,req); }
} async update(p, q, req) {
async update(p,q,req){ return super.update(p, q, req);
return super.update(p,q,req); }
} async initOrgs(p, q, req) {
async initOrgs(p,q,req){ let { tocompany } = req.session;
var tocompany=req.session.tocompany; const cmkey = p.comkey;
var cmkey=p.comkey; if (cmkey) {
if(cmkey){ tocompany = await this.compSvr.findOne({ companykey: cmkey });
tocompany =await this.compSvr.findOne({companykey:cmkey});
} }
//按照公司名称查询,是否存在节点,不存在,就创建根节点 // 按照公司名称查询,是否存在节点,不存在,就创建根节点
//如果存在就按照名称查询出当前和她的字节点 // 如果存在就按照名称查询出当前和她的字节点
var rtn=await this.service.initOrgs(tocompany,req.appid); const 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); return system.getResult(rtn);
} }
async findOrgById(p, q, req) {
const rtn = await this.service.findOrgById(p.id);
return system.getResult(rtn);
}
} }
module.exports=OrgCtl; module.exports = OrgCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
const logCtl = system.getObject("web.common.oplogCtl"); const logCtl = system.getObject('web.common.oplogCtl');
var cacheBaseComp = null; const cacheBaseComp = null;
class RoleCtl extends CtlBase { class RoleCtl extends CtlBase {
constructor() { constructor() {
super("auth", CtlBase.getServiceName(RoleCtl)); super('auth', CtlBase.getServiceName(RoleCtl));
this.redisClient = system.getObject("util.redisClient"); this.redisClient = system.getObject('util.redisClient');
} }
async initNewInstance(pobj, queryobj, req) { async initNewInstance(pobj, queryobj, req) {
var rtn = {}; const rtn = {};
rtn.roles = []; rtn.roles = [];
return system.getResultSuccess(rtn); return system.getResultSuccess(rtn);
} }
async create(pobj, queryobj, req) { async create(pobj, queryobj, req) {
let r = await super.create(pobj, queryobj, req) const r = await super.create(pobj, queryobj, req);
return system.getResult(r); return system.getResult(r);
} }
......
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class UserCtl extends CtlBase { class UserCtl extends CtlBase {
constructor() { constructor() {
super("auth", CtlBase.getServiceName(UserCtl)); super('auth', CtlBase.getServiceName(UserCtl));
this.captchaSve = system.getObject("service.auth.captchaSve"); this.captchaSve = system.getObject('service.auth.captchaSve');
} }
async logout(pobj, qobj, req) { async logout(pobj, qobj, req) {
let rtn = await this.service.logout(pobj) const rtn = await this.service.logout(pobj);
return system.getResult(rtn) return system.getResult(rtn);
} }
async pmgetUserByCode(pobj, qobj, req) { async pmgetUserByCode(pobj, qobj, req) {
let code = pobj.code const { code } = pobj;
let rtn = await this.service.pmgetUserByCode(code) const rtn = await this.service.pmgetUserByCode(code);
return system.getResult(rtn) return system.getResult(rtn);
} }
async loginApp(pobj, qobj, req) { async loginApp(pobj, qobj, req) {
let appkey = pobj.fromAppKey const appkey = pobj.fromAppKey;
let uname = pobj.username const uname = pobj.username;
let rtn = await this.service.loginApp(appkey, uname) const rtn = await this.service.loginApp(appkey, uname);
return system.getResult(rtn); return system.getResult(rtn);
} }
async resetPassword(pobj, qobj, req) { async resetPassword(pobj, qobj, req) {
try { try {
await this.service.resetPassword(req.xctx.username, pobj.onepassword) await this.service.resetPassword(req.xctx.username, pobj.onepassword);
return system.getResult({}); return system.getResult({});
} catch (err) { } catch (err) {
return system.getResult(null, err.message) return system.getResult(null, err.message);
} }
} }
async allowOrNot(pobj, qobj, req) { async allowOrNot(pobj, qobj, req) {
await this.service.updateByWhere({ isEnabled: !pobj.isEnabled }, { company_id: pobj.company_id }) await this.service.updateByWhere({ isEnabled: !pobj.isEnabled }, { company_id: pobj.company_id });
return system.getResult({}); return system.getResult({});
} }
async allowOrNotToOne(pobj, qobj, req) { async allowOrNotToOne(pobj, qobj, req) {
if (!pobj.isEnabled) { if (!pobj.isEnabled) {
await this.service.cacheManager["LoginTimesCache"].invalidate(pobj.userName) await this.service.cacheManager.LoginTimesCache.invalidate(pobj.userName);
} }
const userData = await this.service.findOne({ id: pobj.curid, company_id: pobj.company_id }); const userData = await this.service.findOne({ id: pobj.curid, company_id: pobj.company_id });
if (!userData) { if (!userData) {
throw new Error("没有权限") throw new Error('没有权限');
} }
await this.service.updateByWhere({ isEnabled: !pobj.isEnabled }, { id: pobj.curid }) await this.service.updateByWhere({ isEnabled: !pobj.isEnabled }, { id: pobj.curid });
return system.getResult({}); return system.getResult({});
} }
async initNewInstance(queryobj, req) { async initNewInstance(queryobj, req) {
var rtn = {}; const rtn = {};
rtn.roles = []; rtn.roles = [];
return system.getResultSuccess(rtn); return system.getResultSuccess(rtn);
} }
//获取验证码,发送给指定手机 // 获取验证码,发送给指定手机
// async sendVCode(pobj, qobj, req) { // async sendVCode(pobj, qobj, req) {
// var mobile = pobj.mobile; // var mobile = pobj.mobile;
// let v = await this.smsS.sendVCode(mobile); // let v = await this.smsS.sendVCode(mobile);
...@@ -61,115 +61,113 @@ class UserCtl extends CtlBase { ...@@ -61,115 +61,113 @@ class UserCtl extends CtlBase {
async exit(pobj, qobj, req) { async exit(pobj, qobj, req) {
} }
//应用的自由用户注册,无需验证,需要前端头设置公司KEY // 应用的自由用户注册,无需验证,需要前端头设置公司KEY
async pmregisterByFreeUser(p, q, req) { async pmregisterByFreeUser(p, q, req) {
//检查是否有用户名和密码 // 检查是否有用户名和密码
if (!pobj.userName || !pobj.password) { if (!pobj.userName || !pobj.password) {
return system.getResult(null, "请检查用户名和密码是否存在") return system.getResult(null, '请检查用户名和密码是否存在');
} }
//p.company_id = req.xctx.companyid;//控制基类里已经添加 // p.company_id = req.xctx.companyid;//控制基类里已经添加
if (!p.company_id) { if (!p.company_id) {
return system.getResultFail(-201, "自有用户创建需要提供公司KEY"); return system.getResultFail(-201, '自有用户创建需要提供公司KEY');
} }
let rtn = await this.service.pmregisterByFreeUser(p, q); const rtn = await this.service.pmregisterByFreeUser(p, q);
return rtn; return rtn;
} }
async create(p, q, req) { async create(p, q, req) {
//检查是否有用户名和密码 // 检查是否有用户名和密码
if (!p.userName) { if (!p.userName) {
return system.getResult(null, "请检查用户名和密码是否存在") return system.getResult(null, '请检查用户名和密码是否存在');
} }
let rtn = await this.service.registerByTantent(p, q); const rtn = await this.service.registerByTantent(p, q);
return system.getResult(rtn); return system.getResult(rtn);
} }
//登录后的租户创建属于租户的用户 // 登录后的租户创建属于租户的用户
//需要在控制器里取出公司ID // 需要在控制器里取出公司ID
//和租户绑定同一家公司 // 和租户绑定同一家公司
//按照用户名和密码进行注册 // 按照用户名和密码进行注册
//控制器端检查用户名和密码非空 // 控制器端检查用户名和密码非空
async registerByTantent(p, q, req) { async registerByTantent(p, q, req) {
//检查是否有用户名和密码 // 检查是否有用户名和密码
if (!pobj.userName) { if (!pobj.userName) {
return system.getResult(null, "请检查用户名和密码是否存在") return system.getResult(null, '请检查用户名和密码是否存在');
} }
let rtn = await this.service.registerByTantent(p, q); const rtn = await this.service.registerByTantent(p, q);
return rtn; return rtn;
} }
//租户用户名和密码的租户注册 // 租户用户名和密码的租户注册
async pmregister(pobj, qobj, req) { async pmregister(pobj, qobj, req) {
//平台注册设置平台的应用ID // 平台注册设置平台的应用ID
pobj.app_id = settings.pmappid; pobj.app_id = settings.pmappid;
//检查是否有用户名和密码 // 检查是否有用户名和密码
if (!pobj.userName || !pobj.password) { if (!pobj.userName || !pobj.password) {
return system.getResult(null, "请检查用户名和密码是否存在") return system.getResult(null, '请检查用户名和密码是否存在');
} }
var rtn = await this.service.pmregister(pobj); const rtn = await this.service.pmregister(pobj);
return system.getResult(rtn); return system.getResult(rtn);
} }
async pmlogin(pobj, qobj, req) { async pmlogin(pobj, qobj, req) {
//平台注册设置平台的应用ID // 平台注册设置平台的应用ID
let verifyres = await this.captchaSve.apiValidator({ key: pobj.key, code: pobj.code }); const verifyres = await this.captchaSve.apiValidator({ key: pobj.key, code: pobj.code });
if (verifyres.status !== 0) if (verifyres.status !== 0) return verifyres;
return verifyres; const rtn = await this.service.pmlogin(pobj, qobj, req);
let rtn = await this.service.pmlogin(pobj, qobj, req); let msg = null;
let msg = null if (!rtn) { // 登录错误
if (!rtn) {//登录错误 const times = await this.service.cacheManager.LoginTimesCache.incrAsync(pobj.userName);
let times = await this.service.cacheManager["LoginTimesCache"].incrAsync(pobj.userName);
if (times >= 4) { if (times >= 4) {
await this.service.updateByWhere({ isEnabled: false }, { userName: pobj.userName }) await this.service.updateByWhere({ isEnabled: false }, { userName: pobj.userName });
msg = "登录超过4次失败,您的账户已被锁定,请联系管理员解锁." msg = '登录超过4次失败,您的账户已被锁定,请联系管理员解锁.';
} }
} else { } else {
await this.service.cacheManager["LoginTimesCache"].invalidate(pobj.userName) await this.service.cacheManager.LoginTimesCache.invalidate(pobj.userName);
} }
return system.getResult(rtn, msg); return system.getResult(rtn, msg);
} }
/** /**
* 重置密码 * 重置密码
* @param {*} pobj * @param {*} pobj
* @param {*} qobj * @param {*} qobj
* @param {*} req * @param {*} req
*/ */
async unlockUser(pobj, qobj, req) { async unlockUser(pobj, qobj, req) {
try { try {
const userData = await this.service.findOne({ userName: pobj.userName, company_id: pobj.company_id }); const userData = await this.service.findOne({ userName: pobj.userName, company_id: pobj.company_id });
if (!userData) { if (!userData) {
throw new Error("没有权限") throw new Error('没有权限');
} }
await this.service.unlockUser(pobj.userName) await this.service.unlockUser(pobj.userName);
return system.getResult({}); return system.getResult({});
} catch (err) { } catch (err) {
return system.getResult(null, err.message) return system.getResult(null, err.message);
} }
} }
async getUserInfo(pobj, qobj, req) { async getUserInfo(pobj, qobj, req) {
let uname = req.xctx.username; const uname = req.xctx.username;
let rtn = await this.service.getUserInfo(uname); const rtn = await this.service.getUserInfo(uname);
return system.getResult(rtn); return system.getResult(rtn);
} }
//按照电话创建自由用户 // 按照电话创建自由用户
async pmloginByVCodeForFreeUser(p, q, req) { async pmloginByVCodeForFreeUser(p, q, req) {
if (!pobj.mobile || !pobj.vcode) { if (!pobj.mobile || !pobj.vcode) {
return system.getResult(null, "请检查手机号和验证码是否存在") return system.getResult(null, '请检查手机号和验证码是否存在');
} }
p.companykey = req.xctx.companykey; p.companykey = req.xctx.companykey;
if (!p.companykey) { if (!p.companykey) {
return system.getResult(null, "自有用户创建需要提供公司KEY"); return system.getResult(null, '自有用户创建需要提供公司KEY');
} }
let rtn = await this.service.pmloginByVCodeForFreeUser(p, q); const rtn = await this.service.pmloginByVCodeForFreeUser(p, q);
return rtn; return rtn;
} }
async pmloginByVCode(pobj, qobj, req) { async pmloginByVCode(pobj, qobj, req) {
let rtn = await this.service.pmloginByVCode(pobj, qobj); const rtn = await this.service.pmloginByVCode(pobj, qobj);
return system.getResult(rtn); return system.getResult(rtn);
} }
async pmSendVCode(pobj, qobj, req) { async pmSendVCode(pobj, qobj, req) {
let rtn = await this.service.sendVCode(pobj, qobj); const rtn = await this.service.sendVCode(pobj, qobj);
return system.getResult(rtn); return system.getResult(rtn);
} }
} }
module.exports = UserCtl; module.exports = UserCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
var cacheBaseComp = null; const cacheBaseComp = null;
class AppCtl extends CtlBase { class AppCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(AppCtl)); super('common', CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve"); this.userCtl = system.getObject('service.auth.userSve');
this.comS = system.getObject("service.common.companySve"); this.comS = system.getObject('service.common.companySve');
} }
async findAndCountAll(pobj, qobj, req) { async findAndCountAll(pobj, qobj, req) {
let comtemp = await this.comS.findById(pobj.company_id) const comtemp = await this.comS.findById(pobj.company_id);
pobj.myappstrs = comtemp.appids pobj.myappstrs = comtemp.appids;
let rtn = await super.findAndCountAll(pobj, qobj, req) const rtn = await super.findAndCountAll(pobj, qobj, req);
return rtn return rtn;
} }
async findAllApps(p, q, req) { async findAllApps(p, q, req) {
var rtns = await this.service.findAllApps(p.userid); const rtns = await this.service.findAllApps(p.userid);
return system.getResult(rtns); return system.getResult(rtns);
} }
async getApp(p, q, req) { async getApp(p, q, req) {
let app = await this.cacheManager["AppCache"].cache(p.appkey, null); const app = await this.cacheManager.AppCache.cache(p.appkey, null);
return system.getResult({ funcJson: JSON.parse(app.functionJSON) }); return system.getResult({ funcJson: JSON.parse(app.functionJSON) });
} }
async buildFrontRouter(p, q, req) { async buildFrontRouter(p, q, req) {
let appkey = p.appkeyForRoute const appkey = p.appkeyForRoute;
let app = await this.cacheManager["AppCache"].cache(appkey, null); const app = await this.cacheManager.AppCache.cache(appkey, null);
let funcJSONOBJ = JSON.parse(app.functionJSON) const funcJSONOBJ = JSON.parse(app.functionJSON);
if (!funcJSONOBJ || funcJSONOBJ.length === 0) { if (!funcJSONOBJ || funcJSONOBJ.length === 0) {
return system.getResultError("请先建立功能数据") return system.getResultError('请先建立功能数据');
} }
let rtn = await this.service.buildFrontRouter(funcJSONOBJ, app.id) const rtn = await this.service.buildFrontRouter(funcJSONOBJ, app.id);
return system.getResult(rtn) return system.getResult(rtn);
} }
async getFuncs(p, q, req) { async getFuncs(p, q, req) {
let appkey = p.appkey const { appkey } = p;
let app = await this.cacheManager["AppCache"].cache(appkey, null); const app = await this.cacheManager.AppCache.cache(appkey, null);
return system.getResult({ funcJson: JSON.parse(app.functionJSON) }) return system.getResult({ funcJson: JSON.parse(app.functionJSON) });
//return system.getResult({funcJson:[]}) // return system.getResult({funcJson:[]})
} }
async saveFuncTree(p, q, req) { async saveFuncTree(p, q, req) {
let rtn = await this.service.saveFuncTree(p) const rtn = await this.service.saveFuncTree(p);
return system.getResult(rtn) return system.getResult(rtn);
} }
async create(pobj, queryobj, req) { async create(pobj, queryobj, req) {
pobj.creator_id = pobj.userid;//设置创建者 pobj.creator_id = pobj.userid;// 设置创建者
return super.create(pobj, queryobj, req) return super.create(pobj, queryobj, req);
} }
async update(pobj, queryobj, req) { async update(pobj, queryobj, req) {
return super.update(pobj, queryobj, req); return super.update(pobj, queryobj, req);
} }
async initNewInstance(pobj, queryobj, req) { async initNewInstance(pobj, queryobj, req) {
var rtn = {}; const rtn = {};
rtn.appkey = this.getUUID(); rtn.appkey = this.getUUID();
rtn.secret = this.getUUID(); rtn.secret = this.getUUID();
return system.getResult(rtn); return system.getResult(rtn);
} }
async resetPass(pobj, queryobj, req) { async resetPass(pobj, queryobj, req) {
pobj.password = await super.encryptPasswd(settings.defaultpwd); pobj.password = await super.encryptPasswd(settings.defaultpwd);
var rtn = this.service.resetPass(pobj); const rtn = this.service.resetPass(pobj);
return system.getResult(rtn); return system.getResult(rtn);
} }
async createAdminUser(pobj, queryobj, req) { async createAdminUser(pobj, queryobj, req) {
pobj.password = settings.defaultpwd; pobj.password = settings.defaultpwd;
var rtn = this.service.createAdminUser(pobj); const rtn = this.service.createAdminUser(pobj);
return system.getResult(rtn); return system.getResult(rtn);
} }
async create(pobj, queryobj, req) { async create(pobj, queryobj, req) {
//设置创建者,需要同时创建app管理员、默认密码、电话 // 设置创建者,需要同时创建app管理员、默认密码、电话
pobj.creator_id = pobj.userid; pobj.creator_id = pobj.userid;
// pobj.password=super.encryptPasswd(settings.defaultpwd); // pobj.password=super.encryptPasswd(settings.defaultpwd);
//构造默认的应用相关的URL // 构造默认的应用相关的URL
pobj.authUrl = settings.protocalPrefix + pobj.domainName + "/auth"; pobj.authUrl = `${settings.protocalPrefix + pobj.domainName}/auth`;
// pobj.uiconfigUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/config/fetchAppConfig"; // pobj.uiconfigUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/config/fetchAppConfig";
// pobj.opCacheUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/opCacheData"; // pobj.opCacheUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/opCacheData";
// pobj.notifyCacheCountUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/recvNotificationForCacheCount"; // pobj.notifyCacheCountUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/recvNotificationForCacheCount";
var app = await super.create(pobj, queryobj, req); const app = await super.create(pobj, queryobj, req);
return system.getResult(app); return system.getResult(app);
} }
async fetchApiCallData(pobj, queryobj, req) { async fetchApiCallData(pobj, queryobj, req) {
var curappkey = pobj.curappkey; const { curappkey } = pobj;
//检索出作为访问时的app呼出调用数据 // 检索出作为访问时的app呼出调用数据
var rtn = await this.service.fetchApiCallData(curappkey); const rtn = await this.service.fetchApiCallData(curappkey);
return system.getResultSuccess(rtn); return system.getResultSuccess(rtn);
} }
//接受缓存计数通知接口 // 接受缓存计数通知接口
async recvNotificationForCacheCount(p, q, req) { async recvNotificationForCacheCount(p, q, req) {
return this.service.recvNotificationForCacheCount(p); return this.service.recvNotificationForCacheCount(p);
} }
......
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class ArticleCtl extends CtlBase { class ArticleCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(ArticleCtl)); super('common', CtlBase.getServiceName(ArticleCtl));
} }
async create (p, q, req) { async create(p, q, req) {
p.creator_id = p.userid p.creator_id = p.userid;
p.creator = p.username p.creator = p.username;
let rtn = await this.service.create(p, q, req) const rtn = await this.service.create(p, q, req);
return system.getResult(rtn) return system.getResult(rtn);
} }
} }
module.exports = ArticleCtl; module.exports = ArticleCtl;
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class AttachmentCtl extends CtlBase { class AttachmentCtl extends CtlBase {
constructor() { constructor() {
super("common",CtlBase.getServiceName(AttachmentCtl)); super('common', CtlBase.getServiceName(AttachmentCtl));
} }
} }
module.exports = AttachmentCtl; module.exports = AttachmentCtl;
var system = require("../../../system") const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
class CachSearchesCtl extends CtlBase { class CachSearchesCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(CachSearchesCtl)); super('common', CtlBase.getServiceName(CachSearchesCtl));
} }
async initNewInstance(queryobj, qobj) { async initNewInstance(queryobj, qobj) {
return system.getResultSuccess({}); return system.getResultSuccess({});
...@@ -15,11 +15,11 @@ class CachSearchesCtl extends CtlBase { ...@@ -15,11 +15,11 @@ class CachSearchesCtl extends CtlBase {
return await this.service.findAndCountAllCache(pobj); return await this.service.findAndCountAllCache(pobj);
} }
async delCache(queryobj, qobj, req) { async delCache(queryobj, qobj, req) {
var param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl }; const param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param); return await this.service.delCache(param);
} }
async clearAllCache(queryobj, qobj, req) { async clearAllCache(queryobj, qobj, req) {
var param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl }; const param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param); return await this.service.clearAllCache(param);
} }
} }
......
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class ChannelCtl extends CtlBase { class ChannelCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(ChannelCtl)); super('common', CtlBase.getServiceName(ChannelCtl));
} }
async refQuery(pobj, qobj, req) { async refQuery(pobj, qobj, req) {
let rtn = await this.service.refQuery(pobj); const rtn = await this.service.refQuery(pobj);
return rtn return rtn;
} }
async authorizeUser(pobj, qobj, req) { async authorizeUser(pobj, qobj, req) {
if (!pobj.channelId) { if (!pobj.channelId) {
return system.getResult(null, "channelId can not be empty,100290"); return system.getResult(null, 'channelId can not be empty,100290');
} }
await this.service.authorizeUser(pobj); await this.service.authorizeUser(pobj);
return system.getResult("SUCCESS"); return system.getResult('SUCCESS');
} }
} }
module.exports = ChannelCtl; module.exports = ChannelCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class CompanyCtl extends CtlBase { class CompanyCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(CompanyCtl)); super('common', CtlBase.getServiceName(CompanyCtl));
this.userSve = system.getObject("service.auth.userSve"); this.userSve = system.getObject('service.auth.userSve');
} }
async update(p, q, req) { async update(p, q, req) {
if (p.company_id != 1) { if (p.company_id != 1) {
if (p.company_id != p.id) { if (p.company_id != p.id) {
throw new Error("没有权限"); throw new Error('没有权限');
} }
}
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)
} }
const u = await super.update(p, q, req);
// 缓存失效
await this.cacheManager.CompanyCache.invalidate(p.companykey);
const company = await this.cacheManager.CompanyCache.cache(p.companykey);
return system.getResult(company);
}
async getMyApps(p, q, req) { async getMyApps(p, q, req) {
let userfind = await this.cacheManager["UserCache"].cache(p.username) const userfind = await this.cacheManager.UserCache.cache(p.username);
let isSuper = userfind.isSuper const { isSuper } = userfind;
if (userfind.company.appids && userfind.company.appids != "") { if (userfind.company.appids && userfind.company.appids != '') {
let appsarray = userfind.company.appids.split(",") const appsarray = userfind.company.appids.split(',');
let appidsquery = appsarray.map(astr => { const appidsquery = appsarray.map(astr => astr.split('|')[0]);
return astr.split("|")[0] const apps = await this.service.getMyApps(appidsquery, isSuper);
}) return system.getResult(apps);
let apps = await this.service.getMyApps(appidsquery, isSuper)
return system.getResult(apps)
} else {
return []
}
} }
return [];
}
async bindApps(p, q, req) { async bindApps(p, q, req) {
let appids = p.appids const { appids } = p;
let cmpid = p.postcmpid const cmpid = p.postcmpid;
let appids2 = appids.map(item => { const appids2 = appids.map(item => `${item.appid}|${item.title}`);
return item.appid + "|" + item.title const appidstrs = appids2.join(',');
}) await this.service.bindApps(appidstrs, cmpid);
let appidstrs = appids2.join(",") return system.getResult(appids);
await this.service.bindApps(appidstrs, cmpid) }
return system.getResult(appids)
}
async setOrgs(p, q, req) { async setOrgs(p, q, req) {
//let companynew=await this.service.findById(p.company_id) // let companynew=await this.service.findById(p.company_id)
let orgs = await this.service.setOrgs(p) const orgs = await this.service.setOrgs(p);
return system.getResult(orgs) return system.getResult(orgs);
} }
async getOrgs(p, q, req) { async getOrgs(p, q, req) {
//let companynew=await this.cacheManager["CompanyCache"].cache(req.xctx.fromcompanykey) // let companynew=await this.cacheManager["CompanyCache"].cache(req.xctx.fromcompanykey)
let companynew = await this.service.findById(p.company_id); const companynew = await this.service.findById(p.company_id);
const userData = await this.userSve.findById(p.userid); const userData = await this.userSve.findById(p.userid);
let orgjsonstr = companynew.orgJson; const orgjsonstr = companynew.orgJson;
let rtnjson = null; let rtnjson = null;
if (orgjsonstr && orgjsonstr != "") { if (orgjsonstr && orgjsonstr != '') {
rtnjson = JSON.parse(companynew.orgJson); rtnjson = JSON.parse(companynew.orgJson);
} else { } else {
rtnjson = []; rtnjson = [];
}
if (userData) {
this.service.formatOrgs(rtnjson);
if (userData.isAdmin || userData.isSuper) {
return system.getResult({ orgJson: rtnjson });
} else {
return system.getResult({ orgJson: this.service.buildOrgs(rtnjson, userData.ptags) });
}
} else {
return system.getResult({ orgJson: [] });
}
} }
if (userData) {
async getWatchOrgNodes(p, q, req) { this.service.formatOrgs(rtnjson);
return await this.service.getWatchOrgNodes(p.company_id); if (userData.isAdmin || userData.isSuper) {
return system.getResult({ orgJson: rtnjson });
}
return system.getResult({ orgJson: this.service.buildOrgs(rtnjson, userData.ptags) });
} }
return system.getResult({ orgJson: [] });
}
async refQuery(pobj, qobj, req) { async getWatchOrgNodes(p, q, req) {
let rtn = await this.service.refQuery(pobj); return await this.service.getWatchOrgNodes(p.company_id);
return rtn }
}
async refQuery(pobj, qobj, req) {
const rtn = await this.service.refQuery(pobj);
return rtn;
}
} }
module.exports = CompanyCtl; module.exports = CompanyCtl;
var system = require("../../../system") const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
var cacheBaseComp = null; const cacheBaseComp = null;
class MetaCtl extends CtlBase { class MetaCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(MetaCtl)); super('common', CtlBase.getServiceName(MetaCtl));
} }
} }
module.exports = MetaCtl; module.exports = MetaCtl;
var system = require("../../../system") const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
const uuidv4 = require('uuid/v4'); const uuidv4 = require('uuid/v4');
var moment = require("moment"); const moment = require('moment');
class OplogCtl extends CtlBase { class OplogCtl extends CtlBase {
constructor() { constructor() {
super("common",CtlBase.getServiceName(OplogCtl)); super('common', CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve"); // this.appS=system.getObject("service.appSve");
} }
async initNewInstance(qobj) { async initNewInstance(qobj) {
var u = uuidv4(); const u = uuidv4();
var aid = u.replace(/\-/g, ""); const aid = u.replace(/\-/g, '');
var rd = { name: "", appid: aid } const rd = { name: '', appid: aid };
return system.getResult(rd); return system.getResult(rd);
} }
async debug(obj) { async debug(obj) {
obj.logLevel = "debug"; obj.logLevel = 'debug';
return this.create(obj); return this.create(obj);
} }
async info(obj) { async info(obj) {
obj.logLevel = "info"; obj.logLevel = 'info';
return this.create(obj); return this.create(obj);
} }
async warn(obj) { async warn(obj) {
obj.logLevel = "warn"; obj.logLevel = 'warn';
return this.create(obj); return this.create(obj);
} }
async error(obj) { async error(obj) {
obj.logLevel = "error"; obj.logLevel = 'error';
return this.create(obj); return this.create(obj);
} }
async fatal(obj) { async fatal(obj) {
obj.logLevel = "fatal"; obj.logLevel = 'fatal';
return this.create(obj); return this.create(obj);
} }
...@@ -41,17 +41,17 @@ class OplogCtl extends CtlBase { ...@@ -41,17 +41,17 @@ class OplogCtl extends CtlBase {
prefix:业务前缀 prefix:业务前缀
*/ */
async getBusUid_Ctl(prefix) { async getBusUid_Ctl(prefix) {
prefix = (prefix || ""); prefix = (prefix || '');
if (prefix) { if (prefix) {
prefix = prefix.toUpperCase(); prefix = prefix.toUpperCase();
} }
var prefixlength = prefix.length; const prefixlength = prefix.length;
var subLen = 8 - prefixlength; const subLen = 8 - prefixlength;
var uidStr = ""; let uidStr = '';
if (subLen > 0) { if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60); uidStr = await this.getUidInfo_Ctl(subLen, 60);
} }
var timStr = moment().format("YYYYMMDDHHmm"); const timStr = moment().format('YYYYMMDDHHmm');
return prefix + timStr + uidStr; return prefix + timStr + uidStr;
} }
/* /*
...@@ -59,13 +59,13 @@ prefix:业务前缀 ...@@ -59,13 +59,13 @@ prefix:业务前缀
radix:参与计算的长度,最大为62 radix:参与计算的长度,最大为62
*/ */
async getUidInfo_Ctl(len, radix) { async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36 const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');// 长度62,到yz长度为长36
var uuid = [], i; const uuid = []; let i;
radix = radix || chars.length; radix = radix || chars.length;
if (len) { if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]; for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else { } else {
var r; let r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4'; uuid[14] = '4';
for (i = 0; i < 36; i++) { for (i = 0; i < 36; i++) {
......
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class PathtomethodCtl extends CtlBase { class PathtomethodCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(PathtomethodCtl)); super('common', CtlBase.getServiceName(PathtomethodCtl));
this.appS=system.getObject("service.common.appSve") this.appS = system.getObject('service.common.appSve');
} }
} }
module.exports = PathtomethodCtl; module.exports = PathtomethodCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings=require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
var cacheBaseComp = null; const cacheBaseComp = null;
class PConfigCtl extends CtlBase { class PConfigCtl extends CtlBase {
constructor() { constructor() {
super("common",CtlBase.getServiceName(PConfigCtl)); super('common', CtlBase.getServiceName(PConfigCtl));
this.userCtl = system.getObject("service.auth.userSve"); this.userCtl = system.getObject('service.auth.userSve');
} }
async initNewInstance(pobj,queryobj, req) { async initNewInstance(pobj, queryobj, req) {
var rtn = {}; const rtn = {};
return system.getResult(rtn); return system.getResult(rtn);
} }
async create(pobj,queryobj, req) { async create(pobj, queryobj, req) {
pobj.app_id=req.appid; pobj.app_id = req.appid;
pobj.appkey=req.appkey; pobj.appkey = req.appkey;
var rtn=await super.create(pobj,queryobj, req); const rtn = await super.create(pobj, queryobj, req);
return system.getResult(rtn); return system.getResult(rtn);
} }
async update(pobj,queryobj, req) { async update(pobj, queryobj, req) {
pobj.app_id=req.appid; pobj.app_id = req.appid;
pobj.appkey=req.appkey; pobj.appkey = req.appkey;
var rtn=await super.update(pobj); const rtn = await super.update(pobj);
return system.getResult(rtn); return system.getResult(rtn);
} }
} }
......
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class PushCtl extends CtlBase { class PushCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(PushCtl)); super('common', CtlBase.getServiceName(PushCtl));
} }
async findAndCountAll(pobj, qobj, req) { async findAndCountAll(pobj, qobj, req) {
let query = { const query = {
pageSize: pobj.pageInfo.pageSize, pageSize: pobj.pageInfo.pageSize,
pageIndex: pobj.pageInfo.pageNo pageIndex: pobj.pageInfo.pageNo,
}; };
let search = pobj.search; const { search } = pobj;
if (search.messageBody) if (search.messageBody) query.messageBody = search.messageBody;
query.messageBody = search.messageBody;
if (search.identify_code) if (search.identify_code) query.identifyCode = search.identify_code;
query.identifyCode = search.identify_code;
if (search.request_id) if (search.request_id) query.requestIdInfo = search.request_id;
query.requestIdInfo = search.request_id;
let actionType; let actionType;
switch (pobj.bizpath) { switch (pobj.bizpath) {
case "/sysmag/pushfail": case '/sysmag/pushfail':
actionType = "getPushFailureList"; actionType = 'getPushFailureList';
break; break;
case "/sysmag/pusherror": case '/sysmag/pusherror':
actionType = "getPushErrorList"; actionType = 'getPushErrorList';
break break;
} }
let rtn = await system.postJsonTypeReq(settings.pushUrl(), { let rtn = await system.postJsonTypeReq(settings.pushUrl(), {
"actionType": actionType, actionType,
"actionBody": query 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 || [],
},
}); });
if (rtn.statusCode === 200) { }
rtn = rtn.data; return system.getResultFail(rtn && rtn.message || '请联系管理员');
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)
}
} }
return system.getResultFail(rtn);
}
async repush(pobj, qobj, req) { async repush(pobj, qobj, req) {
let rtn = await system.postJsonTypeReq(settings.pushUrl(), { const rtn = await system.postJsonTypeReq(settings.pushUrl(), {
"actionType": "pushAgainFailureLog", actionType: 'pushAgainFailureLog',
"actionBody": { actionBody: {
id: pobj.id id: pobj.id,
} },
}); });
if (rtn.statusCode === 200) { if (rtn.statusCode === 200) {
return rtn.data; return rtn.data;
} else {
return system.getResultFail(rtn)
}
} }
return system.getResultFail(rtn);
}
} }
module.exports = PushCtl; module.exports = PushCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
var cacheBaseComp = null; const cacheBaseComp = null;
class RouteCtl extends CtlBase { class RouteCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(RouteCtl)); super('common', CtlBase.getServiceName(RouteCtl));
this.appS=system.getObject("service.common.appSve") this.appS = system.getObject('service.common.appSve');
} }
async create(p,q,req){ async create(p, q, req) {
let appid=p.app_id; const appid = p.app_id;
let apptmp= await this.appS.findById(appid) const apptmp = await this.appS.findById(appid);
let routedata={ const routedata = {
name:p.name, name: p.name,
hosts:p.shosts.split(","), hosts: p.shosts.split(','),
paths:p.spaths.split(","), paths: p.spaths.split(','),
isstrip:false, isstrip: false,
app_id:appid, app_id: appid,
shosts:p.shosts, shosts: p.shosts,
spaths:p.spaths spaths: p.spaths,
} };
let rtn= await this.service.create(apptmp.name, routedata, req); const rtn = await this.service.create(apptmp.name, routedata, req);
return system.getResult(rtn) return system.getResult(rtn);
} }
} }
module.exports = RouteCtl; module.exports = RouteCtl;
var system = require("../../../system") const system = require('../../../system');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
class SocketNotifyCtl{ class SocketNotifyCtl {
constructor(){ constructor() {
} }
setSocketServer(s){ setSocketServer(s) {
this.socketServer=s; this.socketServer = s;
} }
//异步推送消息到客户端 // 异步推送消息到客户端
notifyClientMsg(user,msg){ notifyClientMsg(user, msg) {
var uk= this.buildPrivateChannel(user); const uk = this.buildPrivateChannel(user);
var msgHandler=this.socketServer.users[uk]; const msgHandler = this.socketServer.users[uk];
msgHandler.notifyClient(uk,msg); msgHandler.notifyClient(uk, msg);
} }
buildPrivateChannel(user){ buildPrivateChannel(user) {
var ukchannel= user.app_id+"¥"+user.id; const ukchannel = `${user.app_id}${user.id}`;
return ukchannel; return ukchannel;
} }
buildMsgTarget(user){ buildMsgTarget(user) {
var ukchannel= user.app_id+"¥"+user.id; const ukchannel = `${user.app_id}${user.id}`;
var nickName=user.nickName; const { nickName } = user;
var imgUrl=user.imgUrl; const { imgUrl } = user;
var rtn=ukchannel+"¥"+nickName+"¥"+imgUrl; const rtn = `${ukchannel}${nickName}${imgUrl}`;
return rtn; return rtn;
} }
} }
module.exports=SocketNotifyCtl; module.exports = SocketNotifyCtl;
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class TreearchCtl extends CtlBase { class TreearchCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(TreearchCtl)); super('common', CtlBase.getServiceName(TreearchCtl));
} }
async getTreeArchByCode (p, q, req) { async getTreeArchByCode(p, q, req) {
let code = p.code; const { code } = p;
let archName = p.archName; const { archName } = p;
let rtn = await this.service.getTreeArchByCode(archName, code) const rtn = await this.service.getTreeArchByCode(archName, code);
return system.getResult(rtn) return system.getResult(rtn);
} }
async getRegions (p, q, req) { async getRegions(p, q, req) {
let regionjson = await this.service.getRegions(); const regionjson = await this.service.getRegions();
return system.getResult({ regionJson: regionjson }) return system.getResult({ regionJson: regionjson });
} }
async getSysArchJSON (p, q, req) { async getSysArchJSON(p, q, req) {
let sysArchJSON = await this.service.getSysArchJSON(); const sysArchJSON = await this.service.getSysArchJSON();
return system.getResult({ sysArchJSON: sysArchJSON }) return system.getResult({ sysArchJSON });
} }
async saveSysArchJSON (p, q, req) { async saveSysArchJSON(p, q, req) {
let sysArchJSON = await this.service.saveSysArchJSON(p.sysArchJSON, p); const sysArchJSON = await this.service.saveSysArchJSON(p.sysArchJSON, p);
return system.getResult({ sysArchJSON: sysArchJSON }) return system.getResult({ sysArchJSON });
} }
async saveRegions (p, q, req) { async saveRegions(p, q, req) {
let regionjson = await this.service.saveRegions(p.regionJson); const regionjson = await this.service.saveRegions(p.regionJson);
return system.getResult({ regionJson: regionjson }) return system.getResult({ regionJson: regionjson });
} }
async getProductcats (p, q, req) { async getProductcats(p, q, req) {
let productcatJson = await this.service.getProductcats(); const productcatJson = await this.service.getProductcats();
return system.getResult({ productcatJson: productcatJson }) return system.getResult({ productcatJson });
} }
async saveProductcats (p, q, req) { async saveProductcats(p, q, req) {
let productcatJson = await this.service.saveProductcats(p.productcatJson); const productcatJson = await this.service.saveProductcats(p.productcatJson);
return system.getResult({ productcatJson: productcatJson }) return system.getResult({ productcatJson });
} }
} }
module.exports = TreearchCtl; module.exports = TreearchCtl;
var system=require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
const crypto = require('crypto'); const crypto = require('crypto');
var fs=require("fs"); const fs = require('fs');
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5'; const accesskey = '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd'; const accessKeyId = 'LTAI4GC5tSKvqsH2hMqj6pvd';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com"; const url = 'https://gsb-zc.oss-cn-beijing.aliyuncs.com';
class UploadCtl extends CtlBase{ class UploadCtl extends CtlBase {
constructor(){ constructor() {
super("common",CtlBase.getServiceName(UploadCtl)); super('common', CtlBase.getServiceName(UploadCtl));
this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 '{fileName}'"; this.cmdPdf2HtmlPattern = 'docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 \'{fileName}\'';
this.restS=system.getObject("util.execClient"); this.restS = system.getObject('util.execClient');
this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'"; this.cmdInsertToFilePattern = 'sed -i \'s/id="page-container"/id="page-container" contenteditable="true"/\'';
//sed -i 's/1111/&BBB/' /tmp/input.txt // sed -i 's/1111/&BBB/' /tmp/input.txt
//sed 's/{position}/{content}/g' {path} // sed 's/{position}/{content}/g' {path}
} }
async getOssConfig(){ async getOssConfig() {
var policyText = { const policyText = {
"expiration":"2119-12-31T16:00:00.000Z", expiration: '2119-12-31T16:00:00.000Z',
"conditions":[ conditions: [
["content-length-range",0,1048576000], ['content-length-range', 0, 1048576000],
["starts-with","$key","zc"] ['starts-with', '$key', 'zc'],
] ],
}; };
var b = new Buffer(JSON.stringify(policyText)); const b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64'); const policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64 const signature = crypto.createHmac('sha1', accesskey).update(policyBase64)
.digest()
.toString('base64'); // base64
var data={ const data = {
OSSAccessKeyId:accessKeyId, OSSAccessKeyId: accessKeyId,
policy:policyBase64, policy: policyBase64,
Signature:signature, Signature: signature,
Bucket:'gsb-zc', Bucket: 'gsb-zc',
success_action_status:201, success_action_status: 201,
url:url url,
}; };
return data; return data;
};
async upfile(srckey, dest) {
const oss = system.getObject('util.ossClient');
const result = await oss.upfile(srckey, `/tmp/${dest}`);
return result;
};
async downfile(srckey) {
const oss = system.getObject('util.ossClient');
var downfile = await oss.downfile(srckey).then(() => {
downfile = `/tmp/${srckey}`;
return downfile;
});
return downfile;
};
async pdf2html(obj) {
const srckey = obj.key;
const downfile = await this.downfile(srckey);
const cmd = this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
const rtn = await this.restS.exec(cmd);
const path = `/tmp/${srckey.split('.pdf')[0]}.html`;
const a = await this.insertToFile(path);
fs.unlink(`/tmp/${srckey}`);
const result = await this.upfile(`${srckey.split('.pdf')[0]}.html`, `${srckey.split('.pdf')[0]}.html`);
return result.url;
};
async insertToFile(path) {
const cmd = `${this.cmdInsertToFilePattern} ${path}`;
return await this.restS.exec(cmd);
}; };
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; module.exports = UploadCtl;
var system = require("../../../system"); const system = require('../../../system');
const http = require("http"); const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class logCtl extends CtlBase { class logCtl extends CtlBase {
constructor() { constructor() {
super("common", CtlBase.getServiceName(logCtl)); super('common', CtlBase.getServiceName(logCtl));
this.logClient = system.getObject("util.logClient"); this.logClient = system.getObject('util.logClient');
}
async findAndCountAll(pobj, qobj, req) {
try {
const 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)) {
status = 'SUCCESS';
} else {
status = 'FAIL';
}
if (errorInfo && errorInfo !== 'null') {
status = 'FAIL';
}
return {
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);
} }
}
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)) {
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; module.exports = logCtl;
var system = require("../../../system") const system = require('../../../system');
const http = require("http") const http = require('http');
const querystring = require('querystring'); const querystring = require('querystring');
var settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
var cacheBaseComp = null; const cacheBaseComp = null;
class PricecatCtl extends CtlBase { class PricecatCtl extends CtlBase {
constructor() { constructor() {
super("product", CtlBase.getServiceName(PricecatCtl)); super('product', CtlBase.getServiceName(PricecatCtl));
this.pricestrategyService=system.getObject("service.product.pricestrategySve") this.pricestrategyService = system.getObject('service.product.pricestrategySve');
} }
async buildPriceStrategy(p,q,req){ async buildPriceStrategy(p, q, req) {
let pricetypes=p.pricetypes const { pricetypes } = p;
let rtn=await this.pricestrategyService.buildPriceStrategy(pricetypes) const rtn = await this.pricestrategyService.buildPriceStrategy(pricetypes);
if(rtn){ if (rtn) {
if(rtn.status==-1){ if (rtn.status == -1) {
return system.getResult(null,rtn.msg) return system.getResult(null, rtn.msg);
}else{ }
return system.getResult({}) return system.getResult({});
} }
} return system.getResult({});
return system.getResult({})
} }
} }
module.exports = PricecatCtl; module.exports = PricecatCtl;
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class PricestrategyCtl extends CtlBase { class PricestrategyCtl extends CtlBase {
constructor() { constructor() {
super("product", CtlBase.getServiceName(PricestrategyCtl)); super('product', CtlBase.getServiceName(PricestrategyCtl));
} }
async refQuery(pobj, qobj, req) { async refQuery(pobj, qobj, req) {
let rtn=await this.service.refQuery(pobj); const rtn = await this.service.refQuery(pobj);
return rtn return rtn;
} }
} }
module.exports = PricestrategyCtl; module.exports = PricestrategyCtl;
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class ProductCtl extends CtlBase { class ProductCtl extends CtlBase {
constructor() { constructor() {
super("product", CtlBase.getServiceName(ProductCtl)); super('product', CtlBase.getServiceName(ProductCtl));
// this.pricestrategyService=system.getObject("service.product.pricestrategySve") // this.pricestrategyService=system.getObject("service.product.pricestrategySve")
} }
async create(p,q,req){ async create(p, q, req) {
let pn=await this.service.create(p) const pn = await this.service.create(p);
return system.getResult(pn) return system.getResult(pn);
} }
} }
module.exports = ProductCtl; module.exports = ProductCtl;
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class ProductcostCtl extends CtlBase { class ProductcostCtl extends CtlBase {
constructor() { constructor() {
super("product", CtlBase.getServiceName(ProductcostCtl)); super('product', CtlBase.getServiceName(ProductcostCtl));
// this.pricestrategyService=system.getObject("service.product.pricestrategySve") // this.pricestrategyService=system.getObject("service.product.pricestrategySve")
} }
} }
......
var system = require("../../../system") const system = require('../../../system');
const CtlBase = require("../../ctl.base"); const CtlBase = require('../../ctl.base');
class ProductpriceCtl extends CtlBase { class ProductpriceCtl extends CtlBase {
constructor() { constructor() {
super("product", CtlBase.getServiceName(ProductpriceCtl)); super('product', CtlBase.getServiceName(ProductpriceCtl));
// this.pricestrategyService=system.getObject("service.product.pricestrategySve") // this.pricestrategyService=system.getObject("service.product.pricestrategySve")
} }
async updownProduct(p,q,req){ async updownProduct(p, q, req) {
let updownid=p.curid const updownid = p.curid;
let rtn=await this.service.updownProduct(updownid) const rtn = await this.service.updownProduct(updownid);
return system.getResult(rtn) return system.getResult(rtn);
} }
} }
module.exports = ProductpriceCtl; module.exports = ProductpriceCtl;
const system = require("../../../system"); const system = require('../../../system');
const settings = require("../../../../config/settings"); const settings = require('../../../../config/settings');
function exp(db, DataTypes) { function exp(db, DataTypes) {
var base = { const base = {
code: { code: {
type: DataTypes.STRING(50), type: DataTypes.STRING(50),
unique: true unique: true,
}, },
name: DataTypes.STRING(1000), name: DataTypes.STRING(1000),
}; };
......
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
const appconfig = system.getSysConfig(); const appconfig = system.getSysConfig();
function exp(db, DataTypes) { function exp(db, DataTypes) {
var base = { const base = {
//继承的表引用用户信息user_id // 继承的表引用用户信息user_id
code: DataTypes.STRING(100), code: DataTypes.STRING(100),
name: DataTypes.STRING(500), name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者 creator: DataTypes.STRING(100), // 创建者
updator: DataTypes.STRING(100),//更新者 updator: DataTypes.STRING(100), // 更新者
auditor: DataTypes.STRING(100),//审核者 auditor: DataTypes.STRING(100), // 审核者
opNotes: DataTypes.STRING(500),//操作备注 opNotes: DataTypes.STRING(500), // 操作备注
auditStatusName: { auditStatusName: {
type:DataTypes.STRING(50), type: DataTypes.STRING(50),
defaultValue:"待审核", defaultValue: '待审核',
}, },
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过" auditStatus: { // 审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM, type: DataTypes.ENUM,
values: Object.keys(appconfig.pdict.audit_status), values: Object.keys(appconfig.pdict.audit_status),
set: function (val) { set(val) {
this.setDataValue("auditStatus", val); this.setDataValue('auditStatus', val);
this.setDataValue("auditStatusName", appconfig.pdict.audit_status[val]); this.setDataValue('auditStatusName', appconfig.pdict.audit_status[val]);
}, },
defaultValue:"dsh", defaultValue: 'dsh',
}, },
sourceTypeName: DataTypes.STRING(50), sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单" sourceType: { // 来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM, type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type), values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) { set(val) {
this.setDataValue("sourceType", val); this.setDataValue('sourceType', val);
this.setDataValue("sourceTypeName", appconfig.pdict.source_type[val]); this.setDataValue('sourceTypeName', appconfig.pdict.source_type[val]);
} },
}, },
sourceOrderNo: DataTypes.STRING(100),//来源单号 sourceOrderNo: DataTypes.STRING(100), // 来源单号
}; };
return base; return base;
} }
......
const system = require("../system") const system = require('../system');
const settings = require("../../config/settings.js"); const settings = require('../../config/settings.js');
class CacheBase { class CacheBase {
constructor() { constructor() {
this.db = system.getObject("db.common.connection").getCon(); this.db = system.getObject('db.common.connection').getCon();
this.redisClient = system.getObject("util.redisClient"); this.redisClient = system.getObject('util.redisClient');
this.desc = this.desc(); this.desc = this.desc();
this.prefix = this.prefix(); this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "sadd_base:cachekey"; this.cacheCacheKeyPrefix = 'sadd_base:cachekey';
this.isdebug = this.isdebug(); this.isdebug = this.isdebug();
} }
isdebug() { isdebug() {
return false; return false;
} }
desc() { desc() {
throw new Error("子类需要定义desc方法,返回缓存描述"); throw new Error('子类需要定义desc方法,返回缓存描述');
} }
prefix() { prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀"); throw new Error('子类需要定义prefix方法,返回本缓存的前缀');
} }
async cache(inputkey, val, ex, ...items) { async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey; const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey); const cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) { if (!cacheValue || cacheValue == 'undefined' || cacheValue == 'null' || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items); const objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) { if (!objvalstr) {
return null; return null;
} }
...@@ -31,25 +31,23 @@ class CacheBase { ...@@ -31,25 +31,23 @@ class CacheBase {
} else { } else {
await this.redisClient.set(cachekey, objvalstr); await this.redisClient.set(cachekey, objvalstr);
} }
//缓存当前应用所有的缓存key及其描述 // 缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]); this.redisClient.sadd(this.cacheCacheKeyPrefix, [`${cachekey}|${this.desc}`]);
return JSON.parse(objvalstr); return JSON.parse(objvalstr);
} else {
// this.redisClient.setWithEx(cachekey, cacheValue, ex);
return JSON.parse(cacheValue);
} }
// this.redisClient.setWithEx(cachekey, cacheValue, ex);
return JSON.parse(cacheValue);
} }
async getCache(inputkey, ex) { async getCache(inputkey, ex) {
const cachekey = this.prefix + inputkey; const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey); const cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null") { if (!cacheValue || cacheValue == 'undefined' || cacheValue == 'null') {
return null; return null;
} else {
if (ex) {
this.redisClient.set(cachekey, cacheValue, ex);
}
return JSON.parse(cacheValue);
} }
if (ex) {
this.redisClient.set(cachekey, cacheValue, ex);
}
return JSON.parse(cacheValue);
} }
async invalidate(inputkey) { async invalidate(inputkey) {
const cachekey = this.prefix + inputkey; const cachekey = this.prefix + inputkey;
...@@ -57,7 +55,7 @@ class CacheBase { ...@@ -57,7 +55,7 @@ class CacheBase {
return 0; return 0;
} }
async buildCacheVal(cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串"); throw new Error('子类中实现构建缓存值的方法,返回字符串');
} }
async incrCache(inputkey) { async incrCache(inputkey) {
const cachekey = this.prefix + inputkey; const cachekey = this.prefix + inputkey;
......
const CacheBase=require("../cache.base"); const CacheBase = require('../cache.base');
const system=require("../../system"); const system = require('../../system');
//缓存首次登录的赠送的宝币数量 // 缓存首次登录的赠送的宝币数量
class CacheLocker extends CacheBase{ class CacheLocker extends CacheBase {
constructor(){ constructor() {
super(); super();
this.prefix="locker_"; this.prefix = 'locker_';
} }
desc(){ desc() {
} }
prefix(){ prefix() {
} }
async init(tradekey){ async init(tradekey) {
const key=this.prefix+tradekey; const key = this.prefix + tradekey;
return this.redisClient.rpushWithEx(key,"1",1800); return this.redisClient.rpushWithEx(key, '1', 1800);
} }
async enter(tradekey){ async enter(tradekey) {
const key=this.prefix+tradekey; const key = this.prefix + tradekey;
return this.redisClient.rpop(key); return this.redisClient.rpop(key);
} }
async release(tradekey){ async release(tradekey) {
const key=this.prefix+tradekey; const key = this.prefix + tradekey;
return this.redisClient.rpushWithEx(key,"1",1800); return this.redisClient.rpushWithEx(key, '1', 1800);
} }
} }
module.exports=CacheLocker; module.exports = CacheLocker;
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class AppCache extends CacheBase{ class AppCache extends CacheBase {
constructor(){ constructor() {
super(); super();
this.prefix="g_centerappkey:"; this.prefix = 'g_centerappkey:';
this.appDao=system.getObject("db.common.appDao"); 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;
} }
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; module.exports = AppCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class ChannelCache extends CacheBase { class ChannelCache extends CacheBase {
constructor() { constructor() {
super(); super();
this.channelDao = system.getObject("db.common.channelDao"); this.channelDao = system.getObject('db.common.channelDao');
} }
isdebug() { isdebug() {
return true; return true;
} }
desc() { desc() {
return "缓存本地应用对象"; return '缓存本地应用对象';
} }
prefix() { prefix() {
return "g_channel_cm:" return 'g_channel_cm:';
} }
async buildCacheVal(cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
const configValue = await this.channelDao.model.findOne( const configValue = await this.channelDao.model.findOne({
{ where: { routehost: inputkey },
where: { routehost: inputkey }, include: [{ model: this.db.models.pathtomethod, as: 'pts' }],
include: [{ model: this.db.models.pathtomethod, as: "pts" }] });
});
if (configValue) { if (configValue) {
return JSON.stringify(configValue); return JSON.stringify(configValue);
} }
return null; return null;
} }
} }
module.exports = ChannelCache; module.exports = ChannelCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class ClientBindBizUserCache extends CacheBase{ class ClientBindBizUserCache extends CacheBase {
constructor(){ constructor() {
super(); super();
} }
isdebug(){ isdebug() {
return settings.env=="dev"; return settings.env == 'dev';
} }
desc(){ desc() {
return "缓存本地应用对象"; return '缓存本地应用对象';
} }
prefix(){ prefix() {
return "g_client2bizuser_cm:" return 'g_client2bizuser_cm:';
} }
async buildCacheVal(cachekey,inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
return JSON.stringify(val); return JSON.stringify(val);
} }
} }
module.exports=ClientBindBizUserCache; module.exports = ClientBindBizUserCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class CodeCache extends CacheBase{ class CodeCache extends CacheBase {
constructor(){ constructor() {
super(); super();
this.userDao=system.getObject("db.auth.userDao"); this.userDao = system.getObject('db.auth.userDao');
} }
isdebug(){ isdebug() {
return false return false;
// return settings.env=="dev"; // 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; 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; module.exports = CodeCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class CompanyCache extends CacheBase{ class CompanyCache extends CacheBase {
constructor(){ constructor() {
super(); super();
this.prefix="g_centercompanykey:"; this.prefix = 'g_centercompanykey:';
this.companyDao=system.getObject("db.common.companyDao"); 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;
} }
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; module.exports = CompanyCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class LoginErrorCache extends CacheBase { class LoginErrorCache extends CacheBase {
constructor() { constructor() {
super(); super();
} }
isdebug() { isdebug() {
return settings.env == "dev"; return settings.env == 'dev';
} }
desc() { desc() {
return "缓存登录错误信息"; return '缓存登录错误信息';
} }
prefix() { prefix() {
return "g_login_error:" return 'g_login_error:';
} }
async buildCacheVal(cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (val) { if (val) {
return val; return val;
}
return null;
} }
return null;
}
} }
module.exports = LoginErrorCache; module.exports = LoginErrorCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class LoginTimesCache extends CacheBase { class LoginTimesCache extends CacheBase {
constructor() { constructor() {
super(); super();
} }
isdebug() { isdebug() {
return false; return false;
} }
desc() { desc() {
return "缓存登录错误次数信息"; return '缓存登录错误次数信息';
} }
prefix() { prefix() {
return "g_login_times_:" return 'g_login_times_:';
} }
async buildCacheVal(cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (val) { if (val) {
return val; return val;
}
return null;
} }
return null;
}
async incrAsync(key) { async incrAsync(key) {
let cachekey = this.prefix + key const cachekey = this.prefix + key;
let cache = await this.getCache(key); const cache = await this.getCache(key);
if (!cache) { if (!cache) {
await this.cache(key, "0", 60) await this.cache(key, '0', 60);
}
return this.redisClient.incr(cachekey)
} }
return this.redisClient.incr(cachekey);
}
} }
module.exports = LoginTimesCache; module.exports = LoginTimesCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
class MagCache extends CacheBase { class MagCache extends CacheBase {
constructor() { constructor() {
super(); super();
this.prefix = "magCache"; this.prefix = 'magCache';
} }
desc() { desc() {
return "管理当前缓存的key"; return '管理当前缓存的key';
} }
prefix() { prefix() {
return "g_magcache:"; return 'g_magcache:';
} }
async getCacheSmembersByKey(key) { async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key); return this.redisClient.smembers(key);
} }
async delCacheBySrem(key, value) { async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value) return this.redisClient.srem(key, value);
} }
async keys(p) { async keys(p) {
return this.redisClient.keys(p); return this.redisClient.keys(p);
...@@ -28,7 +28,7 @@ class MagCache extends CacheBase { ...@@ -28,7 +28,7 @@ class MagCache extends CacheBase {
return this.redisClient.delete(k); return this.redisClient.delete(k);
} }
async clearAll() { async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............"); console.log('xxxxxxxxxxxxxxxxxxxclearAll............');
return this.redisClient.flushall(); return this.redisClient.flushall();
} }
} }
......
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class TxCache extends CacheBase { class TxCache extends CacheBase {
constructor() { constructor() {
super(); super();
//this.userDao = system.getObject("db.auth.userDao"); // this.userDao = system.getObject("db.auth.userDao");
} }
isdebug() { isdebug() {
return settings.env == "dev"; return settings.env == 'dev';
} }
desc() { desc() {
return "缓存缓存腾讯队列信息"; return '缓存缓存腾讯队列信息';
} }
prefix() { prefix() {
return "g_txInfo_cm:" return 'g_txInfo_cm:';
} }
async buildCacheVal(cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (val) { if (val) {
return val; return val;
}
return null;
} }
return null;
}
} }
module.exports = TxCache; module.exports = TxCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
class UserCache extends CacheBase { class UserCache extends CacheBase {
constructor() { constructor() {
super(); super();
this.userDao = system.getObject("db.auth.userDao"); this.userDao = system.getObject('db.auth.userDao');
this.channelDao = system.getObject("db.common.channelDao"); this.channelDao = system.getObject('db.common.channelDao');
} }
isdebug() { isdebug() {
return settings.env == "localhost"; return settings.env == 'localhost';
} }
desc() { desc() {
return "缓存本地应用对象"; return '缓存本地应用对象';
} }
prefix() { prefix() {
return "g_userlocal_cm:" return 'g_userlocal_cm:';
} }
async buildCacheVal(cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
const configValue = await this.userDao.model.findAll({ const configValue = await this.userDao.model.findAll({
where: { userName: inputkey, app_id: settings.pmappid, isEnabled: true }, 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','tx_uin'], attributes: ['id', 'userName', 'nickName', 'headUrl', 'jwtkey', 'jwtsecret', 'created_at', 'isSuper', 'isAdmin', 'isAllocated', 'mail', 'mobile', 'opath', 'ptags', 'tx_uin'],
include: [ include: [
{ model: this.db.models.company, attributes: ['id', 'name', 'companykey', 'appids', "code"], raw: true }, { model: this.db.models.company, attributes: ['id', 'name', 'companykey', 'appids', 'code'], raw: true },
{ model: this.db.models.role, as: "Roles", attributes: ["id", "code"], } { model: this.db.models.role, as: 'Roles', attributes: ['id', 'code'] },
], ],
}); });
if (configValue && configValue[0]) { if (configValue && configValue[0]) {
let data = JSON.parse(JSON.stringify(configValue[0])); const data = JSON.parse(JSON.stringify(configValue[0]));
let channelDatas = await this.channelDao.findAll({}); let channelDatas = await this.channelDao.findAll({});
channelDatas = JSON.parse(JSON.stringify(channelDatas)); channelDatas = JSON.parse(JSON.stringify(channelDatas));
channelDatas.forEach(item => { channelDatas.forEach((item) => {
if (item.userids && item.userids.split(",").includes(data.id.toString())) { if (item.userids && item.userids.split(',').includes(data.id.toString())) {
data.channel = { data.channel = {
id: item.id, id: item.id,
code: item.code, code: item.code,
name: item.name name: item.name,
} };
} }
}); });
// 获取渠道信息 // 获取渠道信息
...@@ -45,4 +45,4 @@ class UserCache extends CacheBase { ...@@ -45,4 +45,4 @@ class UserCache extends CacheBase {
return null; return null;
} }
} }
module.exports = UserCache; module.exports = UserCache;
\ No newline at end of file
const CacheBase = require("../cache.base"); const CacheBase = require('../cache.base');
const system = require("../../system"); const system = require('../../system');
const settings = require("../../../config/settings"); const settings = require('../../../config/settings');
//缓存首次登录的赠送的宝币数量 // 缓存首次登录的赠送的宝币数量
class VCodeCache extends CacheBase { class VCodeCache extends CacheBase {
constructor() { constructor() {
super(); super();
this.smsUtil = system.getObject("util.smsClient"); this.smsUtil = system.getObject('util.smsClient');
} }
// isdebug() { // isdebug() {
// return settings.env == "dev"; // return settings.env == "dev";
// } // }
desc () { desc() {
return "缓存给手机发送的验证码60妙"; return '缓存给手机发送的验证码60妙';
} }
prefix () { prefix() {
return "g_vcode_cm:" return 'g_vcode_cm:';
} }
async buildCacheVal (cachekey, inputkey, val, ex, ...items) { async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
//inputkey采用appkey_mobile的形式 // inputkey采用appkey_mobile的形式
var mobile = inputkey; const mobile = inputkey;
var tmplCode = val; const tmplCode = val;
var signName = items ? items[0] : ""; const signName = items ? items[0] : '';
var vcode = await this.smsUtil.getUidStr(6, 10); const vcode = await this.smsUtil.getUidStr(6, 10);
if (!tmplCode && !signName) { if (!tmplCode && !signName) {
console.log("=============================") console.log('=============================');
this.smsUtil.sendMsg(mobile, vcode); this.smsUtil.sendMsg(mobile, vcode);
} //tmplCode为发送短信编码,需在阿里开通,signName为短信头描述信息,二者没有传递则用默认的发送验证码 } // tmplCode为发送短信编码,需在阿里开通,signName为短信头描述信息,二者没有传递则用默认的发送验证码
else { else {
this.smsUtil.aliSendMsg(mobile, tmplCode, signName, JSON.stringify({ code: vcode })); this.smsUtil.aliSendMsg(mobile, tmplCode, signName, JSON.stringify({ code: vcode }));
} }
return JSON.stringify({ vcode: vcode }); return JSON.stringify({ vcode });
} }
} }
module.exports = VCodeCache; module.exports = VCodeCache;
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class AuthDao extends Dao{ class AuthDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(AuthDao)); super(Dao.getModelName(AuthDao));
} }
extraWhere(qobj,qw,qc){ extraWhere(qobj, qw, qc) {
qc.raw=true; qc.raw = true;
return qw; return qw;
} }
} }
module.exports=AuthDao; module.exports = AuthDao;
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class DataauthDao extends Dao{ class DataauthDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(DataauthDao)); super(Dao.getModelName(DataauthDao));
} }
extraWhere(qobj,qw,qc){ extraWhere(qobj, qw, qc) {
qc.raw=true; qc.raw = true;
return qw; return qw;
} }
} }
module.exports=DataauthDao; module.exports = DataauthDao;
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class OrgDao extends Dao{ class OrgDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(OrgDao)); super(Dao.getModelName(OrgDao));
} }
extraWhere(qobj,qw,qc){ extraWhere(qobj, qw, qc) {
qc.raw=true; qc.raw = true;
return qw; return qw;
} }
} }
module.exports=OrgDao; module.exports = OrgDao;
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class RoleDao extends Dao{ class RoleDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(RoleDao)); super(Dao.getModelName(RoleDao));
} }
async findOne(paramappid,t){ async findOne(paramappid, t) {
var app= await this.model.findOne({where:{appid:paramappid}},{transaction:t}); const app = await this.model.findOne({ where: { appid: paramappid } }, { transaction: t });
return app; return app;
} }
extraWhere(obj,w,qc,linkAttrs){ extraWhere(obj, w, qc, linkAttrs) {
// if(obj.codepath && obj.codepath!=""){ // if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询 // // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj); // // console.log(obj);
// // w["app_id"]=obj.appid; // // w["app_id"]=obj.appid;
// // } // // }
// } // }
//w["app_id"]=obj.app_id;//不考虑应用的区别 // w["app_id"]=obj.app_id;//不考虑应用的区别
w["company_id"]=obj.company_id; w.company_id = obj.company_id;
return w; return w;
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.app,}]};
} }
async preUpdate(u){ extraModelFilter() {
return { key: 'include', value: [{ model: this.db.models.app }] };
}
async preUpdate(u) {
return u; return u;
} }
async update(obj){ async update(obj) {
var obj2=await this.preUpdate(obj); const obj2 = await this.preUpdate(obj);
await this.model.update(obj2,{where:{id:obj2.id}}); await this.model.update(obj2, { where: { id: obj2.id } });
var role=await this.model.findOne({where:{id:obj2.id}}); const role = await this.model.findOne({ where: { id: obj2.id } });
return role; return role;
} }
async preCreate(u){ async preCreate(u) {
return u; return u;
} }
async create(u,t){ async create(u, t) {
var self=this; const self = this;
var u2= await this.preCreate(u); const u2 = await this.preCreate(u);
if(t){ if (t) {
var role= await this.model.create(u2,{transaction: t}); var role = await this.model.create(u2, { transaction: t });
return role; return role;
}else{ }
var role= await this.model.create(u2); var role = await this.model.create(u2);
return role; return role;
}
} }
} }
module.exports=RoleDao; module.exports = RoleDao;
const system = require("../../../system"); const system = require('../../../system');
const Dao = require("../../dao.base"); const Dao = require('../../dao.base');
class UserDao extends Dao { class UserDao extends Dao {
constructor() { constructor() {
super(Dao.getModelName(UserDao)); super(Dao.getModelName(UserDao));
} }
async getAuths(userid) { async getAuths(userid) {
var self = this; const self = this;
return this.model.findOne({ return this.model.findOne({
where: { id: userid }, where: { id: userid },
include: [{ model: self.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"] }, 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.role, as: 'Roles', attributes: ['id', 'code'], include: [
{ model: self.db.models.product, as: "Products", attributes: ["id", "code"] } { model: self.db.models.product, as: 'Products', attributes: ['id', 'code'] },
] ],
}, },
], ],
}); });
} }
async getUserByUsername(username, appkey, t) { async getUserByUsername(username, appkey, t) {
var app = await this.appDao.findOne(appkey); const app = await this.appDao.findOne(appkey);
var tUser = await this.model.findOne({ const tUser = await this.model.findOne({
where: { userName: username, app_id: app.id }, where: { userName: username, app_id: app.id },
include: [{ model: this.db.models.app, raw: true }, 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", // {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"]}, // "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{ model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true }, { 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.role, as: 'Roles', attributes: ['id', 'code'], include: [
{ model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true } { model: this.db.models.product, as: 'Products', attributes: ['id', 'code'], raw: true },
] ],
}, },
] ],
}, { transaction: t }); }, { transaction: t });
// if(tUser!=null){ // if(tUser!=null){
// tUser=tUser.get({plain:true}); // tUser=tUser.get({plain:true});
...@@ -39,19 +39,19 @@ class UserDao extends Dao { ...@@ -39,19 +39,19 @@ class UserDao extends Dao {
return tUser; return tUser;
} }
async getUserByOpenId(popenid, appkey, t) { async getUserByOpenId(popenid, appkey, t) {
var app = await this.appDao.findOne(appkey); const app = await this.appDao.findOne(appkey);
var tUser = await this.model.findOne({ let tUser = await this.model.findOne({
where: { openId: popenid }, where: { openId: popenid },
include: [{ model: this.db.models.app, raw: true }, 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", // {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"]}, // "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{ model: this.db.models.account, attributes: ["id", "isSuper", "referrerOnlyCode"], raw: true }, { 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.role, as: 'Roles', attributes: ['id', 'code'], include: [
{ model: this.db.models.product, as: "Products", attributes: ["id", "code"], raw: true } { model: this.db.models.product, as: 'Products', attributes: ['id', 'code'], raw: true },
] ],
}, },
] ],
}, { transaction: t }); }, { transaction: t });
if (tUser != null) { if (tUser != null) {
tUser = tUser.get({ plain: true }); tUser = tUser.get({ plain: true });
...@@ -66,64 +66,63 @@ class UserDao extends Dao { ...@@ -66,64 +66,63 @@ class UserDao extends Dao {
return user; return user;
} }
async setApp(user, app, t) { async setApp(user, app, t) {
//按照APPId,获取app对象 // 按照APPId,获取app对象
var user = await user.setApp(app, { transaction: t }); var user = await user.setApp(app, { transaction: t });
return user; return user;
} }
extraModelFilter() { 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.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return { return {
"key": "include", "value": [ key: 'include', value: [
// {model:this.db.models.app,}, // {model:this.db.models.app,},
{ model: this.db.models.company, }, { model: this.db.models.company },
{ model: this.db.models.role, as: "Roles", attributes: ["id", "name"] }] { model: this.db.models.role, as: 'Roles', attributes: ['id', 'name'] }],
}; };
} }
extraWhere(obj, w, qc, linkAttrs) { extraWhere(obj, w, qc, linkAttrs) {
console.log("----=========") console.log('----=========');
console.log(obj) console.log(obj);
if (obj.bizpath && obj.bizpath != "") { if (obj.bizpath && obj.bizpath != '') {
if (obj.bizpath.indexOf("tanents_info") > 0) {//说明是超级管理员的查询 if (obj.bizpath.indexOf('tanents_info') > 0) { // 说明是超级管理员的查询
w["isAdmin"] = true; w.isAdmin = true;
} else { } else {
w["isAdmin"] = false; w.isAdmin = false;
w["company_id"] = obj.company_id; w.company_id = obj.company_id;
// 为空说明是管理员,不需设置组织结构过滤 // 为空说明是管理员,不需设置组织结构过滤
if (obj.opath && obj.opath != "") { if (obj.opath && obj.opath != '') {
w["opath"] = { [this.db.Op.like]: `%${obj.opath}%` } w.opath = { [this.db.Op.like]: `%${obj.opath}%` };
} }
} }
} }
if (linkAttrs.length > 0) { if (linkAttrs.length > 0) {
var search = obj.search; const { search } = obj;
var lnkKey = linkAttrs[0]; const lnkKey = linkAttrs[0];
var strq = "$" + lnkKey.replace("~", ".") + "$"; const strq = `$${lnkKey.replace('~', '.')}$`;
w[strq] = { [this.db.Op.like]: "%" + search[lnkKey] + "%" }; w[strq] = { [this.db.Op.like]: `%${search[lnkKey]}%` };
} }
qc.attributes = { qc.attributes = {
exclude: ["password", "jwtkey", "jwtsecret"] exclude: ['password', 'jwtkey', 'jwtsecret'],
} };
return w; return w;
} }
async preUpdate(u) { async preUpdate(u) {
if (u.roles && u.roles.length >= 0) { if (u.roles && u.roles.length >= 0) {
var roles = await this.db.models.role.findAll({ where: { id: { [this.db.Op.in]: u.roles } } }); const roles = await this.db.models.role.findAll({ where: { id: { [this.db.Op.in]: u.roles } } });
u.roles = roles u.roles = roles;
} }
return u; return u;
} }
async update(obj) { async update(obj) {
var obj2 = await this.preUpdate(obj); const obj2 = await this.preUpdate(obj);
await this.model.update(obj2, { where: { id: obj2.id } }); await this.model.update(obj2, { where: { id: obj2.id } });
var user = await this.model.findOne({ where: { id: obj2.id } }); const user = await this.model.findOne({ where: { id: obj2.id } });
if (obj2.roles) { if (obj2.roles) {
user.setRoles(obj2.roles); user.setRoles(obj2.roles);
} }
return user; return user;
} }
async findAndCountAll(qobj, t) { async findAndCountAll(qobj, t) {
var users = await super.findAndCountAll(qobj, t); const users = await super.findAndCountAll(qobj, t);
return users; return users;
} }
async preCreate(u) { async preCreate(u) {
...@@ -135,40 +134,34 @@ class UserDao extends Dao { ...@@ -135,40 +134,34 @@ class UserDao extends Dao {
return u; return u;
} }
async create(u, t) { async create(u, t) {
var self = this; const self = this;
var u2 = await this.preCreate(u); const u2 = await this.preCreate(u);
if (t) { if (t) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
console.log(u2); console.log(u2);
return this.model.create(u2, { transaction: t }).then(user => { return this.model.create(u2, { transaction: t }).then(user => user);
return user;
});
} else {
return this.model.create(u2).then(user => {
return user;
});
} }
return this.model.create(u2).then(user => user);
} }
//修改用户(user表)公司的唯一码 // 修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId, company_only_code, result) { async putUserCompanyOnlyCode(userId, company_only_code, result) {
var customerObj = { companyOnlyCode: company_only_code }; const customerObj = { companyOnlyCode: company_only_code };
var putSqlWhere = { where: { id: userId } }; const putSqlWhere = { where: { id: userId } };
this.updateByWhere(customerObj, putSqlWhere); this.updateByWhere(customerObj, putSqlWhere);
return result; return result;
} }
} }
module.exports = UserDao; module.exports = UserDao;
// var u=new UserDao(); // var u=new UserDao();
// var roledao=system.getObject("db.roleDao"); // var roledao=system.getObject("db.roleDao");
// (async ()=>{ // (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}}); // var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}}); // var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role); // console.log(role);
// for(var i=0;i<users.length;i++){ // for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]); // await users[i].setRoles([role]);
// console.log(i); // console.log(i);
// } // }
// //
// })(); // })();
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class AppDao extends Dao{ class AppDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(AppDao)); super(Dao.getModelName(AppDao));
} }
extraWhere(obj,w,qc,linkAttrs){ extraWhere(obj, w, qc, linkAttrs) {
if(obj.bizpath && obj.bizpath!=""){ if (obj.bizpath && obj.bizpath != '') {
if(obj.bizpath.indexOf("my_app")>0){//说明是租户查询自己创建的应用 if (obj.bizpath.indexOf('my_app') > 0) { // 说明是租户查询自己创建的应用
let appstrs=obj.myappstrs const appstrs = obj.myappstrs;
let appsarray=appstrs.split(",") const appsarray = appstrs.split(',');
let appidsquery=appsarray.map(astr=>{ const appidsquery = appsarray.map(astr => astr.split('|')[0]);
return astr.split("|")[0] w.id = { [this.db.Op.in]: appidsquery };
}) }
w["id"]= {[this.db.Op.in]:appidsquery}; }
} if (linkAttrs.length > 0) {
} const { search } = obj;
if(linkAttrs.length>0){ const lnkKey = linkAttrs[0];
var search=obj.search; const strq = `$${lnkKey.replace('~', '.')}$`;
var lnkKey=linkAttrs[0]; w[strq] = { [this.db.Op.like]: `%${search[lnkKey]}%` };
var strq="$"+lnkKey.replace("~",".")+"$"; }
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"}; return w;
}
return w;
} }
} }
module.exports=AppDao; module.exports = AppDao;
// var u=new UserDao(); // var u=new UserDao();
// var roledao=system.getObject("db.roleDao"); // var roledao=system.getObject("db.roleDao");
// (async ()=>{ // (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}}); // var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}}); // var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role); // console.log(role);
// for(var i=0;i<users.length;i++){ // for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]); // await users[i].setRoles([role]);
// console.log(i); // console.log(i);
// } // }
// //
// })(); // })();
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class ArticleDao extends Dao{ class ArticleDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(ArticleDao)); super(Dao.getModelName(ArticleDao));
} }
orderBy(qobj) { orderBy(qobj) {
//return {"key":"include","value":{model:this.db.models.app}}; // return {"key":"include","value":{model:this.db.models.app}};
if(!qobj.orderInfo || qobj.orderInfo.length==0){ if (!qobj.orderInfo || qobj.orderInfo.length == 0) {
return [["created_at", "ASC"]]; return [['created_at', 'ASC']];
}else{
return qobj.orderInfo;
} }
return qobj.orderInfo;
} }
} }
module.exports=ArticleDao; module.exports = ArticleDao;
// var u=new UserDao(); // var u=new UserDao();
// var roledao=system.getObject("db.roleDao"); // var roledao=system.getObject("db.roleDao");
// (async ()=>{ // (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}}); // var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}}); // var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role); // console.log(role);
// for(var i=0;i<users.length;i++){ // for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]); // await users[i].setRoles([role]);
// console.log(i); // console.log(i);
// } // }
// //
// })(); // })();
const fs=require("fs"); const fs = require('fs');
const settings=require("../../../../config/settings"); const settings = require('../../../../config/settings');
class CacheManager{ class CacheManager {
constructor(){ constructor() {
//await this.buildCacheMap(); // await this.buildCacheMap();
this.buildCacheMap(); this.buildCacheMap();
} }
buildCacheMap(){ buildCacheMap() {
var self=this; const self = this;
self.doc={}; self.doc = {};
var cachePath=settings.basepath+"/app/base/db/cache/"; const cachePath = `${settings.basepath}/app/base/db/cache/`;
const files=fs.readdirSync(cachePath); const files = fs.readdirSync(cachePath);
if(files){ if (files) {
files.forEach(function(r){ files.forEach((r) => {
var classObj=require(cachePath+"/"+r); const classObj = require(`${cachePath}/${r}`);
self[classObj.name]=new classObj(); self[classObj.name] = new classObj();
var refTmp=self[classObj.name]; const refTmp = self[classObj.name];
if(refTmp.prefix){ if (refTmp.prefix) {
self.doc[refTmp.prefix]=refTmp.desc; self.doc[refTmp.prefix] = refTmp.desc;
} } else {
else{ console.log(`请在${classObj.name}缓存中定义prefix`);
console.log("请在"+classObj.name+"缓存中定义prefix"); }
} });
}); }
}
} }
} }
module.exports=CacheManager; module.exports = CacheManager;
// var cm= new CacheManager(); // var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){ // cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{ // cm["InitGiftCache"].cacheGlobalVal().then(x=>{
......
const Sequelize = require('sequelize'); const Sequelize = require('sequelize');
const settings = require("../../../../config/settings") const settings = require('../../../../config/settings');
const fs = require("fs") const fs = require('fs');
const path = require("path"); const path = require('path');
var glob = require("glob"); const glob = require('glob');
const Op = Sequelize.Op const { Op } = Sequelize;
class DbFactory { class DbFactory {
constructor() { constructor() {
const dbConfig = settings.database(); const dbConfig = settings.database();
this.db = new Sequelize(dbConfig.dbname, this.db = new Sequelize(
dbConfig.dbname,
dbConfig.user, dbConfig.user,
dbConfig.password, dbConfig.password,
{ {
...@@ -46,100 +47,99 @@ class DbFactory { ...@@ -46,100 +47,99 @@ class DbFactory {
$any: Op.any, $any: Op.any,
$all: Op.all, $all: Op.all,
$values: Op.values, $values: Op.values,
$col: Op.col $col: Op.col,
} },
}); },
);
this.db.Sequelize = Sequelize; this.db.Sequelize = Sequelize;
this.db.Op = Sequelize.Op; this.db.Op = Sequelize.Op;
this.initModels(); this.initModels();
this.initRelations(); this.initRelations();
} }
async initModels() { async initModels() {
var self = this; const self = this;
var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/"; const modelpath = `${path.normalize(path.join(__dirname, '../..'))}/models/`;
var models = glob.sync(modelpath + "/**/*.js"); const models = glob.sync(`${modelpath}/**/*.js`);
console.log(models.length); console.log(models.length);
models.forEach(function (m) { models.forEach((m) => {
console.log(m); console.log(m);
self.db.import(m); self.db.import(m);
}); });
console.log("init models...."); console.log('init models....');
} }
async initRelations() { async initRelations() {
this.db.models.dataauth.belongsTo(this.db.models.user, { constraints: false, }); this.db.models.dataauth.belongsTo(this.db.models.user, { constraints: false });
/*建立用户和角色之间的关系*/ /* 建立用户和角色之间的关系*/
this.db.models.user.belongsToMany(this.db.models.role, { as: "Roles", through: 'p_userrole', constraints: false, }); this.db.models.user.belongsToMany(this.db.models.role, { as: 'Roles', through: 'p_userrole', constraints: false });
this.db.models.role.belongsToMany(this.db.models.user, { as: "Users", through: 'p_userrole', constraints: false, }); this.db.models.role.belongsToMany(this.db.models.user, { as: 'Users', through: 'p_userrole', constraints: false });
/*组织机构自引用*/ /* 组织机构自引用*/
//this.db.models.org.belongsTo(this.db.models.org,{constraints: false,}); // this.db.models.org.belongsTo(this.db.models.org,{constraints: false,});
//this.db.models.org.hasMany(this.db.models.org,{constraints: false,}); // this.db.models.org.hasMany(this.db.models.org,{constraints: false,});
//组织机构和角色是多对多关系,建立兼职岗位,给岗位赋予多个角色,从而同步修改用户的角色 // 组织机构和角色是多对多关系,建立兼职岗位,给岗位赋予多个角色,从而同步修改用户的角色
//通过岗位接口去修改用户的角色 // 通过岗位接口去修改用户的角色
//this.db.models.role.belongsToMany(this.db.models.org,{through: this.db.models.orgrole,constraints: false,}); // this.db.models.role.belongsToMany(this.db.models.org,{through: this.db.models.orgrole,constraints: false,});
//this.db.models.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,}); // this.db.models.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,});
//组织机构和用户是1对多, // 组织机构和用户是1对多,
// this.db.models.user.belongsTo(this.db.models.org,{constraints: false,}); // this.db.models.user.belongsTo(this.db.models.org,{constraints: false,});
// this.db.models.org.hasMany(this.db.models.user,{constraints: false,}); // this.db.models.org.hasMany(this.db.models.user,{constraints: false,});
this.db.models.user.belongsTo(this.db.models.app, { constraints: false, }); this.db.models.user.belongsTo(this.db.models.app, { constraints: false });
this.db.models.role.belongsTo(this.db.models.app, { constraints: false, }); this.db.models.role.belongsTo(this.db.models.app, { constraints: false });
this.db.models.auth.belongsTo(this.db.models.app, { constraints: false, }); this.db.models.auth.belongsTo(this.db.models.app, { constraints: false });
this.db.models.auth.belongsTo(this.db.models.company, { constraints: false, }); this.db.models.auth.belongsTo(this.db.models.company, { constraints: false });
this.db.models.auth.belongsTo(this.db.models.role, { constraints: false, }); this.db.models.auth.belongsTo(this.db.models.role, { constraints: false });
this.db.models.app.belongsTo(this.db.models.user, { as: "creator", constraints: false, }); this.db.models.app.belongsTo(this.db.models.user, { as: 'creator', constraints: false });
this.db.models.user.belongsTo(this.db.models.company, { constraints: false, }); this.db.models.user.belongsTo(this.db.models.company, { constraints: false });
this.db.models.company.hasMany(this.db.models.user, { as: 'us', constraints: false, }); this.db.models.company.hasMany(this.db.models.user, { as: 'us', constraints: false });
this.db.models.role.belongsTo(this.db.models.company, { constraints: false, }); this.db.models.role.belongsTo(this.db.models.company, { constraints: false });
// this.db.models.org.belongsTo(this.db.models.company,{constraints: false,}); // this.db.models.org.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.route.belongsTo(this.db.models.app, { constraints: false, }); this.db.models.route.belongsTo(this.db.models.app, { constraints: false });
this.db.models.plugin.belongsTo(this.db.models.app, { constraints: false, }); this.db.models.plugin.belongsTo(this.db.models.app, { constraints: false });
//渠道和渠道路径方法映射 // 渠道和渠道路径方法映射
this.db.models.pathtomethod.belongsTo(this.db.models.channel, { constraints: false, }); this.db.models.pathtomethod.belongsTo(this.db.models.channel, { constraints: false });
this.db.models.channel.hasMany(this.db.models.pathtomethod, { as: "pts", 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.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.hasMany(this.db.models.productprice, { as: 'skus', constraints: false });
this.db.models.product.belongsTo(this.db.models.company, { 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.pricestrategy, { constraints: false });
this.db.models.productprice.belongsTo(this.db.models.company, { constraints: false, }); this.db.models.productprice.belongsTo(this.db.models.company, { constraints: false });
//成本项目属于productprice // 成本项目属于productprice
this.db.models.productcost.belongsTo(this.db.models.productprice, { constraints: false, }); this.db.models.productcost.belongsTo(this.db.models.productprice, { constraints: false });
this.db.models.productprice.hasMany(this.db.models.productcost, { as: "costs", constraints: false, }); this.db.models.productprice.hasMany(this.db.models.productcost, { as: 'costs', constraints: false });
// 消息 -> 用户消息关联 1:n // 消息 -> 用户消息关联 1:n
this.db.models.msg.hasMany(this.db.models.msguser, { constraints: false }); this.db.models.msg.hasMany(this.db.models.msguser, { constraints: false });
this.db.models.msguser.belongsTo(this.db.models.msg, { constraints: false }); this.db.models.msguser.belongsTo(this.db.models.msg, { constraints: false });
} }
//async getCon(){,用于使用替换table模型内字段数据使用 // async getCon(){,用于使用替换table模型内字段数据使用
getCon() { getCon() {
var that = this; const that = this;
// await this.db.authenticate().then(()=>{ // await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.'); // console.log('Connection has been established successfully.');
// }).catch(err => { // }).catch(err => {
// console.error('Unable to connect to the database:', err); // console.error('Unable to connect to the database:', err);
// throw err; // throw err;
// }); // });
//同步模型 // 同步模型
if (settings.env == "dev") { if (settings.env == 'dev') {
//console.log(pa); // console.log(pa);
// pconfigObjs.forEach(p=>{ // pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true})); // console.log(p.get({plain:true}));
// }); // });
......
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class MsgHistoryDao extends Dao{ class MsgHistoryDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(MsgHistoryDao)); super(Dao.getModelName(MsgHistoryDao));
} }
extraWhere(obj,w){ extraWhere(obj, w) {
if(obj.ukstr && obj.ukstr!=""){ if (obj.ukstr && obj.ukstr != '') {
// w={[this.db.Op.or]:[ // w={[this.db.Op.or]:[
// {[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]}, // {[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
// {[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]}, // {[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
// ] // ]
// }; // };
w[this.db.Op.or]=[ w[this.db.Op.or] = [
{[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]}, { [this.db.Op.and]: [{ sender: obj.ukstr }, { target: obj.extra }] },
{[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]}, { [this.db.Op.and]: [{ sender: obj.extra }, { target: obj.ukstr }] },
]; ];
} }
return w; return w;
} }
orderBy(){ orderBy() {
//return {"key":"include","value":{model:this.db.models.app}}; // return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]]; return [['id', 'DESC']];
} }
} }
module.exports=MsgHistoryDao; module.exports = MsgHistoryDao;
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class MsgNoticeDao extends Dao{ class MsgNoticeDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(MsgNoticeDao)); super(Dao.getModelName(MsgNoticeDao));
} }
async saveNotice(msg, t) { async saveNotice(msg, t) {
var noticeFrom = await super.findOne({fromId : msg.senderId, toId : msg.targetId}); let noticeFrom = await super.findOne({ fromId: msg.senderId, toId: msg.targetId });
if(noticeFrom) { if (noticeFrom) {
var set = {lastMsgId:msg.id}; var set = { lastMsgId: msg.id };
if(msg.businessLicense_id) { if (msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id; set.businessLicense_id = msg.businessLicense_id;
} }
await super.updateByWhere(set, {where:{id:noticeFrom.id}}, t); await super.updateByWhere(set, { where: { id: noticeFrom.id } }, t);
} else { } else {
noticeFrom = { noticeFrom = {
fromuser: msg.sender, fromuser: msg.sender,
fromId:msg.senderId, fromId: msg.senderId,
touser: msg.target, touser: msg.target,
toId:msg.targetId, toId: msg.targetId,
isAccepted:true, isAccepted: true,
lastMsgId:msg.id, lastMsgId: msg.id,
businessLicense_id : msg.businessLicense_id || 0 businessLicense_id: msg.businessLicense_id || 0,
}; };
await super.create(noticeFrom, t); await super.create(noticeFrom, t);
} }
var noticeTo = await super.findOne({fromId : msg.targetId, toId : msg.senderId}); let noticeTo = await super.findOne({ fromId: msg.targetId, toId: msg.senderId });
if(noticeTo) { if (noticeTo) {
var set = {lastMsgId:msg.id}; var set = { lastMsgId: msg.id };
if(msg.businessLicense_id) { if (msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id; set.businessLicense_id = msg.businessLicense_id;
} }
await super.updateByWhere(set, {where:{id:noticeTo.id}}, t); await super.updateByWhere(set, { where: { id: noticeTo.id } }, t);
} else { } else {
noticeTo = { noticeTo = {
fromuser: msg.target, fromuser: msg.target,
fromId:msg.targetId, fromId: msg.targetId,
touser: msg.sender, touser: msg.sender,
toId:msg.senderId, toId: msg.senderId,
isAccepted:true, isAccepted: true,
lastMsgId:msg.id, lastMsgId: msg.id,
businessLicense_id : msg.businessLicense_id || 0 businessLicense_id: msg.businessLicense_id || 0,
}; };
await super.create(noticeTo, t); await super.create(noticeTo, t);
} }
} }
orderBy(){ orderBy() {
//return {"key":"include","value":{model:this.db.models.app}}; // return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]]; return [['id', 'DESC']];
} }
} }
module.exports=MsgNoticeDao; module.exports = MsgNoticeDao;
const system = require("../../../system"); const system = require('../../../system');
const Dao = require("../../dao.base"); const Dao = require('../../dao.base');
class MsguserDao extends Dao { class MsguserDao extends Dao {
constructor() { constructor() {
super(Dao.getModelName(MsguserDao)); super(Dao.getModelName(MsguserDao));
} }
} }
module.exports = MsguserDao; module.exports = MsguserDao;
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class PricecatDao extends Dao{ class PricecatDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(PricecatDao)); super(Dao.getModelName(PricecatDao));
} }
orderBy(qobj) { orderBy(qobj) {
//return {"key":"include","value":{model:this.db.models.app}}; // return {"key":"include","value":{model:this.db.models.app}};
if(!qobj.orderInfo || qobj.orderInfo.length==0){ if (!qobj.orderInfo || qobj.orderInfo.length == 0) {
return [["seq", "ASC"]]; return [['seq', 'ASC']];
}else{
return qobj.orderInfo;
} }
return qobj.orderInfo;
} }
} }
module.exports=PricecatDao; module.exports = PricecatDao;
// var u=new UserDao(); // var u=new UserDao();
// var roledao=system.getObject("db.roleDao"); // var roledao=system.getObject("db.roleDao");
// (async ()=>{ // (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}}); // var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}}); // var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role); // console.log(role);
// for(var i=0;i<users.length;i++){ // for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]); // await users[i].setRoles([role]);
// console.log(i); // console.log(i);
// } // }
// //
// })(); // })();
const system = require("../../../system"); const system = require('../../../system');
const Dao = require("../../dao.base"); const Dao = require('../../dao.base');
class ProductDao extends Dao { class ProductDao extends Dao {
constructor() { constructor() {
super(Dao.getModelName(ProductDao)); super(Dao.getModelName(ProductDao));
} }
extraWhere(obj,w,qc,linkAttrs){ extraWhere(obj, w, qc, linkAttrs) {
if(obj.bizpath && obj.bizpath!=""){ if (obj.bizpath && obj.bizpath != '') {
if(obj.bizpath.indexOf("productdef")>0){//说明是租户查询自己创建的应用 if (obj.bizpath.indexOf('productdef') > 0) { // 说明是租户查询自己创建的应用
w["company_id"]= obj.company_id; w.company_id = obj.company_id;
} }
} }
if(linkAttrs.length>0){ if (linkAttrs.length > 0) {
var search=obj.search; const { search } = obj;
var lnkKey=linkAttrs[0]; const lnkKey = linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$"; const strq = `$${lnkKey.replace('~', '.')}$`;
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"}; w[strq] = { [this.db.Op.like]: `%${search[lnkKey]}%` };
} }
return w; return w;
} }
extraModelFilter() { 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.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return { return {
"key": "include", "value": [ key: 'include', value: [
{ model: this.db.models.productprice, as: "skus", attributes: ["id", "pricestrategy_id"] }] { model: this.db.models.productprice, as: 'skus', attributes: ['id', 'pricestrategy_id'] }],
} };
} }
} }
module.exports = ProductDao; module.exports = ProductDao;
\ No newline at end of file
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class ProductcostDao extends Dao{ class ProductcostDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(ProductcostDao)); super(Dao.getModelName(ProductcostDao));
} }
extraModelFilter(){ 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.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[ return { key: 'include', value: [
{model:this.db.models.productprice,attributes:["id","lowpriceref"]}]}; { model: this.db.models.productprice, attributes: ['id', 'lowpriceref'] }] };
} }
} }
module.exports=ProductcostDao; module.exports = ProductcostDao;
// var u=new UserDao(); // var u=new UserDao();
// var roledao=system.getObject("db.roleDao"); // var roledao=system.getObject("db.roleDao");
// (async ()=>{ // (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}}); // var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}}); // var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role); // console.log(role);
// for(var i=0;i<users.length;i++){ // for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]); // await users[i].setRoles([role]);
// console.log(i); // console.log(i);
// } // }
// //
// })(); // })();
const system=require("../../../system"); const system = require('../../../system');
const Dao=require("../../dao.base"); const Dao = require('../../dao.base');
class ProductpriceDao extends Dao{ class ProductpriceDao extends Dao {
constructor(){ constructor() {
super(Dao.getModelName(ProductpriceDao)); super(Dao.getModelName(ProductpriceDao));
} }
extraWhere(obj,w,qc,linkAttrs){ extraWhere(obj, w, qc, linkAttrs) {
if(obj.bizpath && obj.bizpath!=""){ if (obj.bizpath && obj.bizpath != '') {
if(obj.bizpath.indexOf("platformprice")>0){//说明是租户查询自己创建的应用 if (obj.bizpath.indexOf('platformprice') > 0) { // 说明是租户查询自己创建的应用
w["company_id"]= obj.company_id; w.company_id = obj.company_id;
} }
} }
if(linkAttrs.length>0){ if (linkAttrs.length > 0) {
var search=obj.search; const { search } = obj;
var lnkKey=linkAttrs[0]; const lnkKey = linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$"; const strq = `$${lnkKey.replace('~', '.')}$`;
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"}; w[strq] = { [this.db.Op.like]: `%${search[lnkKey]}%` };
} }
return w; return w;
} }
extraModelFilter(){ 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.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[ return { key: 'include', value: [
{model:this.db.models.pricestrategy,attributes:["id","optionunion"]}, { model: this.db.models.pricestrategy, attributes: ['id', 'optionunion'] },
{model:this.db.models.product,attributes:["id","name"]}]}; { model: this.db.models.product, attributes: ['id', 'name'] }] };
} }
} }
module.exports=ProductpriceDao; module.exports = ProductpriceDao;
// var u=new UserDao(); // var u=new UserDao();
// var roledao=system.getObject("db.roleDao"); // var roledao=system.getObject("db.roleDao");
// (async ()=>{ // (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}}); // var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}}); // var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role); // console.log(role);
// for(var i=0;i<users.length;i++){ // for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]); // await users[i].setRoles([role]);
// console.log(i); // console.log(i);
// } // }
// //
// })(); // })();
const system = require("../system"); const system = require('../system');
const settings = require("../../config/settings.js"); const settings = require('../../config/settings.js');
const reclient = system.getObject("util.redisClient"); const reclient = system.getObject('util.redisClient');
const md5 = require("MD5"); const md5 = require('MD5');
//获取平台配置兑换率 // 获取平台配置兑换率
//初次登录的赠送数量 // 初次登录的赠送数量
//创建一笔交易 // 创建一笔交易
//同时增加账户数量,增加系统平台账户 // 同时增加账户数量,增加系统平台账户
var dbf = system.getObject("db.common.connection"); const dbf = system.getObject('db.common.connection');
var db = dbf.getCon(); const db = dbf.getCon();
db.sync({ force: true }).then(async () => { db.sync({ force: true }).then(async () => {
// const apps = await system.getObject("service.common.appSve"); // const apps = await system.getObject("service.common.appSve");
// const usS = await system.getObject("service.auth.userSve"); // const usS = await system.getObject("service.auth.userSve");
...@@ -27,8 +27,7 @@ db.sync({ force: true }).then(async () => { ...@@ -27,8 +27,7 @@ db.sync({ force: true }).then(async () => {
// await appnew.save() // await appnew.save()
// 创建role
//创建role
// if(settings.env=="prod"){ // if(settings.env=="prod"){
// reclient.flushall(()=>{ // reclient.flushall(()=>{
// console.log("clear caches ok....."); // console.log("clear caches ok.....");
...@@ -40,4 +39,3 @@ db.sync({ force: true }).then(async () => { ...@@ -40,4 +39,3 @@ db.sync({ force: true }).then(async () => {
}); });
module.exports = { module.exports = {
"config": { config: {
"pdict": { pdict: {
"app_type": { "api": "API服务","web": "PCWEB","app":"移动APP","xcx":"小程序","access":"接入"}, app_type: { api: 'API服务', web: 'PCWEB', app: '移动APP', xcx: '小程序', access: '接入' },
"data_priv": { "auth.role": "角色", "auth.user": "用户" }, data_priv: { 'auth.role': '角色', 'auth.user': '用户' },
"noticeType": {"sms": "短信", "email": "邮件","wechat":"微信"}, noticeType: { sms: '短信', email: '邮件', wechat: '微信' },
"authType": {"add": "新增", "edit": "编辑","delete":"删除","export":"导出","show":"查看"}, authType: { add: '新增', edit: '编辑', delete: '删除', export: '导出', show: '查看' },
"mediaType": {"vd": "视频", "ad": "音频","qt":"其它"}, mediaType: { vd: '视频', ad: '音频', qt: '其它' },
"usageType": {"kt": "课堂","taxkt":"财税课堂", "qt": "其它"}, usageType: { kt: '课堂', taxkt: '财税课堂', qt: '其它' },
"opstatus": {"0": "失败", "1": "成功"}, opstatus: { 0: '失败', 1: '成功' },
"sex": {"male": "男", "female": "女"}, sex: { male: '男', female: '女' },
"logLevel": {"debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4}, logLevel: { debug: 0, info: 1, warn: 2, error: 3, fatal: 4 },
"msgType": { "sys": "系统", "single": "单点", "multi": "群发"}, msgType: { sys: '系统', single: '单点', multi: '群发' },
"node_type":{"org":"组织","arc":"文档"} node_type: { org: '组织', arc: '文档' },
} },
} },
} };
const fs=require("fs"); const fs = require('fs');
const path=require("path"); const path = require('path');
const appPath=path.normalize(__dirname+"/app"); const appPath = path.normalize(`${__dirname}/app`);
const bizsPath=path.normalize(__dirname+"/bizs"); const bizsPath = path.normalize(`${__dirname}/bizs`);
var appJsons={ const appJsons = {
config:require(appPath+"/"+"platform.js").config config: require(`${appPath}/` + 'platform.js').config,
} };
module.exports=appJsons; module.exports = appJsons;
module.exports = (db, DataTypes) => { module.exports = (db, DataTypes) => db.define('auth', {
return db.define("auth", { rolecode: DataTypes.STRING,
rolecode: DataTypes.STRING, bizcode: DataTypes.STRING,
bizcode: DataTypes.STRING, codepath: DataTypes.STRING,
codepath: DataTypes.STRING, authstrs: DataTypes.STRING,
authstrs: DataTypes.STRING }, {
},{ paranoid: true, // 假的删除
paranoid: true,//假的删除 underscored: true,
underscored: true, version: true,
version: true, freezeTableName: true,
freezeTableName: true, // freezeTableName: true,
//freezeTableName: true, // define the table's name
// define the table's name tableName: 'p_auths',
tableName: 'p_auths', validate: {
validate: { },
} });
});
}
module.exports = (db, DataTypes) => { module.exports = (db, DataTypes) => db.define('dataauth', {
return db.define("dataauth", { modelname: DataTypes.STRING,
modelname: DataTypes.STRING, auths: DataTypes.STRING,
auths: DataTypes.STRING, }, {
},{ paranoid: true, // 假的删除
paranoid: true,//假的删除 underscored: true,
underscored: true, version: true,
version: true, freezeTableName: true,
freezeTableName: true, // freezeTableName: true,
//freezeTableName: true, // define the table's name
// define the table's name tableName: 'p_dataauths',
tableName: 'p_dataauths', validate: {
validate: { },
} });
});
}
const system=require("../../../system"); const system = require('../../../system');
const settings=require("../../../../config/settings"); const settings = require('../../../../config/settings');
const appconfig=system.getSysConfig(); const appconfig = system.getSysConfig();
module.exports = (db, DataTypes) => { module.exports = (db, DataTypes) => db.define('org', {
return db.define("org", { code: {
code: { type: DataTypes.STRING(64),
type:DataTypes.STRING(64), allowNull: false,
allowNull: false, },
}, name: {
name: { type: DataTypes.STRING(64),
type:DataTypes.STRING(64), allowNull: false,
allowNull: false, },
}, isLeaf: {
isLeaf:{ type: DataTypes.BOOLEAN,
type:DataTypes.BOOLEAN, defaultValue: true,
defaultValue: true },
}, orgpath: {
orgpath: { type: DataTypes.STRING,
type:DataTypes.STRING, allowNull: false,
allowNull: false, },
}, nodeType: { // 默认为组织
nodeType: {//默认为组织 type: DataTypes.ENUM,
type:DataTypes.ENUM, allowNull: false,
allowNull: false, values: Object.keys(appconfig.pdict.node_type),
values: Object.keys(appconfig.pdict.node_type), defaultValue: 'org',
defaultValue:'org' },
}, isPosition: { // 是否是岗位
isPosition:{//是否是岗位 type: DataTypes.BOOLEAN,
type:DataTypes.BOOLEAN, defaultValue: false,
defaultValue: false },
}, isMain: { // 是否是主岗
isMain:{//是否是主岗 type: DataTypes.BOOLEAN,
type:DataTypes.BOOLEAN, defaultValue: false,
defaultValue: false },
}, }, {
},{ paranoid: true, // 假的删除
paranoid: true,//假的删除 underscored: true,
underscored: true, version: true,
version: true, freezeTableName: true,
freezeTableName: true, // freezeTableName: true,
//freezeTableName: true, // define the table's name
// define the table's name tableName: 'p_org',
tableName: 'p_org', validate: {
validate: { },
} });
});
}
\ No newline at end of file
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