Commit 50841017 by 蒋勇

init bigdata

parents
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
const system = require("../system");
const uuidv4 = require('uuid/v4');
const DocBase = require("./doc.base");
const settings = require("../../config/settings");
class APIBase extends DocBase {
constructor() {
super();
this.redisClient = system.getObject("util.redisClient");
this.cacheManager = system.getObject("db.common.cacheManager");
this.apitradeSvr = system.getObject("service.common.apitradeSve");
this.logCtl = system.getObject("web.common.oplogCtl");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
/**
* 白名单验证
* @param {*} gname 组名
* @param {*} methodname 方法名
*/
async isCheckWhiteList(gname, methodname) {
var fullname = gname + "." + methodname;
var lst = [
"auth.getAccessKey",
"meta.getBaseComp",
"meta.doc",
"meta.clearAllCache"
];
var x = lst.indexOf(fullname);
return x >= 0;
}
async checkAcck(gname, methodname, pobj, query, req) {
var apptocheck = null;
var isCheckWhite = await this.isCheckWhiteList(gname, methodname);
if (!isCheckWhite) {//在验证请单里面,那么就检查访问token
var ak = req.headers["accesskey"];
try {
apptocheck = await this.cacheManager["ApiAccessKeyCache"].cache(ak, null, null, null);
} catch (e) {
this.logCtl.error({
optitle: "获取访问token异常_error",
op: pobj.classname + "/" + methodname,
content: e.stack,
clientIp: pobj.clientIp
});
}
}
return { app: apptocheck, ispass: isCheckWhite || apptocheck };
}
async doexec(gname, methodname, pobj, query, req) {
var requestid = req.headers["request-id"] || this.getUUID();
try {
//检查访问token
var isPassResult = await this.checkAcck(gname, methodname, pobj, query, req);
if (!isPassResult.ispass) {
var tmpResult = system.getResultFail(system.tokenFail, "访问token失效,请重新获取");
tmpResult.requestid = "";
return tmpResult;
}
// //检查appkey
// let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(pobj.appKey);
// if(key==null){
// return system.getResultFail(system.appKeyError,"appKey授权有误");
// }
req.app = isPassResult.app;
var rtn = await this[methodname](pobj, query, req);
if (isPassResult.app) {
if (methodname && methodname.indexOf("apiAccessCount") < 0) {
this.apitradeSvr.create({
srcappkey: isPassResult.app.appkey,
tradeType: "consume",
op: req.classname + "/" + methodname,
params: JSON.stringify(pobj),
clientIp: req.clientIp,
agent: req.uagent + ";reqid=" + requestid,
destappkey: settings.appKey,
});
}
}
rtn.requestid = requestid;
return rtn;
} catch (e) {
console.log(e.stack, "api调用异常--error...................");
this.logCtl.error({
optitle: "api调用异常--error",
op: req.classname + "/" + methodname + ";reqid=" + requestid,
content: e.stack,
clientIp: req.clientIp
});
var rtnerror = system.getResultFail(-200, "出现异常,请联系管理员");
rtnerror.requestid = requestid;
return rtnerror;
}
}
}
module.exports = APIBase;
const system = require("../system");
const uuidv4 = require('uuid/v4');
class DocBase {
constructor() {
this.apiDoc = {
group: "逻辑分组",
groupDesc: "",
name: "",
desc: "请对当前类进行描述",
exam: "概要示例",
methods: []
};
this.initClassDoc();
}
initClassDoc() {
this.descClass();
this.descMethods();
}
descClass() {
var classDesc = this.classDesc();
this.apiDoc.group = classDesc.groupName;
this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc);
this.apiDoc.name = classDesc.name;
this.apiDoc.desc = this.examDescHtml(classDesc.desc);
this.apiDoc.exam = this.examHtml();
}
examDescHtml(desc) {
// var tmpDesc = desc.replace(/\\/g, "<br/>");
return desc;
}
examHtml() {
var exam = this.exam();
exam = exam.replace(/\\/g, "<br/>");
return exam;
}
exam() {
throw new Error("请在子类中定义类操作示例");
}
classDesc() {
throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构
{
groupName:"auth",
groupDesc:"认证相关的包"
desc:"关于认证的类",
exam:"",
}
`);
}
descMethods() {
var methoddescs = this.methodDescs();
for (var methoddesc of methoddescs) {
for (var paramdesc of methoddesc.paramdescs) {
this.descMethod(methoddesc.methodDesc, methoddesc.methodName
, paramdesc.paramDesc, paramdesc.paramName, paramdesc.paramType,
paramdesc.defaultValue, methoddesc.rtnTypeDesc, methoddesc.rtnType);
}
}
}
methodDescs() {
throw new Error(`
请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[
{
methodDesc:"生成访问token",
methodName:"getAccessKey",
paramdescs:[
{
paramDesc:"访问appkey",
paramName:"appkey",
paramType:"string",
defaultValue:"x",
},
{
paramDesc:"访问secret",
paramName:"secret",
paramType:"string",
defaultValue:null,
}
],
rtnTypeDesc:"xxxx",
rtnType:"xxx"
}
]
`);
}
descMethod(methodDesc, methodName, paramDesc, paramName, paramType, defaultValue, rtnTypeDesc, rtnType) {
var mobj = this.apiDoc.methods.filter((m) => {
if (m.name == methodName) {
return true;
} else {
return false;
}
})[0];
var param = {
pname: paramName,
ptype: paramType,
pdesc: paramDesc,
pdefaultValue: defaultValue,
};
if (mobj != null) {
mobj.params.push(param);
} else {
this.apiDoc.methods.push(
{
methodDesc: methodDesc ? methodDesc : "",
name: methodName,
params: [param],
rtnTypeDesc: rtnTypeDesc,
rtnType: rtnType
}
);
}
}
}
module.exports = DocBase;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class RoleAuthAPI extends APIBase {
constructor() {
super();
this.authS=system.getObject("service.auth.authSve");
}
async findAuthsByRole(p,q,req){
var tmpRoles=p.roles;
var appid=p.appid;
var comid=p.companyid;
var auths=await this.authS.findAuthsByRole(tmpRoles,appid,comid);
return system.getResult(auths);
}
exam(){
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "角色授权相关的API",
name: "RoleAuthAPI",
desc: "角色授权相关的API",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "按照角色获取权限,访问地址:/api/auth/roleAuth/findAuthsByRole",
methodName: "findAuthsByRole",
paramdescs: [
{
paramDesc: "应用的ID",
paramName: "appid",
paramType: "int",
defaultValue: "x",
},
{
paramDesc: "角色列表",
paramName: "roles",
paramType: "array",
defaultValue: null,
}
],
rtnTypeDesc: "逗号分隔的",
rtnType: "string"
}
];
}
}
module.exports = RoleAuthAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var glob = require("glob");
var settings = require("../../../../config/settings");
var cacheBaseComp = null;
class BaseCompAPI extends APIBase {
constructor() {
super();
this.cachsearchesSve = system.getObject("service.common.cachsearchesSve");
}
async clearAllCache(pobj, gobj, req) {
return await this.cachsearchesSve.clearAllCache(pobj);
}
async getBaseComp() {
if (cacheBaseComp) {
return cacheBaseComp;
}
var vuePath = settings.basepath + "/app/front/vues/base";
var baseComps = [];
var rs = glob.sync(vuePath + "/**/*.vue");
if (rs) {
rs.forEach(function (r) {
var comp = "";
if (settings.env == "dev") {
delete require.cache[r];
comp = require(r).replace(/\n/g, "");
} else {
comp = require(r).replace(/\n/g, "");
}
baseComps.push(comp);
});
}
// cacheBaseComp = escape(JSON.stringify(baseComps));
return system.getResult({ basecom: baseComps });
}
exam() {
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "meta",
groupDesc: "元数据相关的包",
name: "BaseCompAPI",
desc: "关于认证的类",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "baseComp",
methodName: "baseComp",
paramdescs: [
{
paramDesc: "访问appkey",
paramName: "appkey",
paramType: "string",
defaultValue: "x",
},
{
paramDesc: "访问secret",
paramName: "secret",
paramType: "string",
defaultValue: null,
}
],
rtnTypeDesc: "xxxx",
rtnType: "xxx"
}
];
}
}
module.exports = BaseCompAPI;
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
class CtlBase {
constructor(gname, sname) {
this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname);
this.cacheManager = system.getObject("db.common.cacheManager");
this.redisClient = system.getObject("util.redisClient");
// this.md5 = require("MD5");
this.appS = system.getObject("service.common.appSve");
this.comS=system.getObject("service.common.companySve");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async encryptPasswd(passwd) {
if (!passwd) {
throw new Error("请输入密码");
}
var rtn = await this.service.getEncryptStr(passwd);
return rtn;
}
notify(req, msg) {
if (req.session) {
req.session.bizmsg = msg;
}
}
async findOne(queryobj, qobj) {
var rd = await this.service.findOne(qobj);
return system.getResult(rd);
}
async findAndCountAll(obj, queryobj, req) {
obj.codepath = req.codepath;
obj.appid = req.appid;
if (req.session.user) {
obj.uid = req.session.user.id;
obj.appid = req.session.user.app_id;
obj.account_id = req.session.user.account_id;
}
var apps = await this.service.findAndCountAll(obj);
return system.getResult(apps);
}
async refQuery(qobj,queryobj,req) {
if(qobj.refwhere){
qobj.refwhere.app_id=req.appid;
qobj.refwhere.company_id=req.tanentid;
}else{
qobj.refwhere = { app_id: req.appid,company_id:req.tanentid};
}
var rd = await this.service.refQuery(qobj);
return system.getResult(rd);
}
async bulkDelete(queryobj, ids) {
var rd = await this.service.bulkDelete(ids);
return system.getResult(rd);
}
async delete(qobj, queryobj) {
var rd = await this.service.delete(qobj);
return system.getResult(rd);
}
async create(qobj, queryobj, req) {
if (req && req.session && req.session.app) {
qobj.app_id = req.appid;
if (req.codepath) {
qobj.codepath = req.codepath;
}
if (qobj.app_id == settings.platformid) {
qobj.company_id = settings.platformcompanyid;
}
}
if (req && req.tanentid) {//设置默认的公司id
qobj.company_id = req.tanentid;
// qobj.owner_id=req.tanentid;
}
var rd = await this.service.create(qobj,queryobj,req);
return system.getResult(rd);
}
async update(qobj, queryobj, req) {
if (req && req.session && req.session.user) {
qobj.onlyCode = req.session.user.unionId;
}
if (req.codepath) {
qobj.codepath = req.codepath;
}
var rd = await this.service.update(qobj);
return system.getResult(rd);
}
static getServiceName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async initNewInstance(queryobj, req) {
return system.getResult({});
}
async findById(oid) {
var rd = await this.service.findById(oid);
return system.getResult(rd);
}
async timestampConvertDate(time) {
if (time == null) {
return "";
}
var date = new Date(Number(time * 1000));
var y = 1900 + date.getYear();
var m = "0" + (date.getMonth() + 1);
var d = "0" + date.getDate();
return y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
}
async universalTimeConvertLongDate(time) {
if (time == null) {
return "";
}
var d = new Date(time);
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}
async universalTimeConvertShortDate(time) {
if (time == null) {
return "";
}
var d = new Date(time);
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
}
async setContextParams(pobj, qobj, req) {
req.appid = req.session.app ? req.session.app.id : null;
req.appkey = req.session.app ? req.session.app.appkey : null;
pobj.userid = req.session.user ? req.session.user.id : null;
var tocompany = req.session.tocompany;
if (!req.session.app) {
var appkey = qobj.appKey;
var tokey = qobj.toKey;
if (appkey) {
var app = await this.appS.getApp(appkey);
var toapp = await this.appS.getApp(tokey);
req.session.app = app;
req.session.toapp = toapp;
req.appid = app.id;
req.appkey = app.appkey;
}else{//如果空,并且没有参数appkey
var app = await this.appS.getApp(settings.appKey);
req.session.app = app;
req.appid = app.id;
req.appkey = app.appkey;
}
}
if(!tocompany && qobj.companyKey){
//说明是自主登录后,跳转到目标平台进行管理操作
tocompany=await this.comS.findOne({companykey:qobj.companyKey});
req.session.tocompany=tocompany;
}
//只要当前APP支持saas,并且非平台那么就设置
if (req.session.app && req.session.app.id != settings.platformid) {
if (req.session.app.isSaas && tocompany) {
req.tanentid = tocompany.id;
pobj.tanentid = tocompany.id;
} else {
req.tanentid = null;
pobj.tanentid = null;
}
} else {
req.tanentid = settings.platformcompanyid;
pobj.tanentid = settings.platformcompanyid;
}
}
async doexec(methodname, pobj, query, req) {
try {
await this.setContextParams(pobj, query, req);
// //检查appkey
// let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(pobj.appKey);
// if(key==null){
// return system.getResultFail(system.tokenFail,"appKey授权有误");
// }
var rtn = await this[methodname](pobj, query, req);
// await this. apitradeSvr .create({
// appkey: pobj.appKey,
// tradeType: "consume",
// op: pobj.classname + "/" + methodname,
// params: JSON.stringify(pobj),
// clientIp: pobj.clientIp,
// agent: pobj.agent,
// });
return rtn;
} catch (e) {
console.log(e.stack, "出现异常,请联系管理员.......");
// this.logCtl.error({
// optitle: "api调用出错",
// op: pobj.classname + "/" + methodname,
// content: e.stack,
// clientIp: pobj.clientIp
// });
return system.getResultFail(-200, "出现异常,请联系管理员");
}
}
}
module.exports = CtlBase;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class AuthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(AuthCtl));
}
async saveAuths(qobj,query,req){
var auths=qobj.aus;
var xrtn=await this.service.saveAuths(auths,req.appid,req.tanentid);
return system.getResult(xrtn);
}
async findAuthsByRole(qobj,query,req){
var rolecodestrs=qobj.rolecode;
var xrtn=await this.service.findAuthsByRole(rolecodestrs,req.appid,req.tanentid);
return system.getResult(xrtn);
}
}
module.exports=AuthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class DataauthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(DataauthCtl));
}
async saveauth(qobj,querybij,req){
var arys=qobj.arys;
var uid=qobj.uid;
var refmodel=qobj.modelname;
var u=await this.service.saveauth({
user_id:uid,
modelname:refmodel,
auths:arys.join(","),
app_id:req.appid,
});
return system.getResult(u);
}
async fetchInitAuth(qobj,querybij,req){
var uid=qobj.uid;
var refmodel=qobj.modelname;
var authtmp=await this.service.findOne({user_id:uid,modelname:refmodel,app_id:req.appid});
if(authtmp){
var auths= authtmp.auths;
var arys=auths.split(",");
return system.getResult(arys);
}else{
return system.getResultSuccess([]);
}
}
}
module.exports=DataauthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class OrgCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(OrgCtl));
}
//检查是否已经存在主要岗位
async checkMainPosition(p,q,req){
return this.service.checkMainPosition(p,q,req);
}
async changePos(p,q,req){
var toorgid=p.orgid;
var uid=p.uid;
var rtn= await this.service.changePos(toorgid,uid);
return system.getResult(rtn);
}
async create(p,q,req){
return super.create(p,q,req);
}
async delete(p,q,req){
return super.delete(p,q,req);
}
async update(p,q,req){
return super.update(p,q,req);
}
async initOrgs(p,q,req){
var tocompany=req.session.tocompany;
//按照公司名称查询,是否存在节点,不存在,就创建根节点
//如果存在就按照名称查询出当前和她的字节点
var rtn=await this.service.initOrgs(tocompany,req.appid);
return system.getResult(rtn);
}
async findOrgById(p,q,req){
var rtn=await this.service.findOrgById(p.id);
return system.getResult(rtn);
}
}
module.exports=OrgCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class RoleCtl extends CtlBase {
constructor() {
super("auth",CtlBase.getServiceName(RoleCtl));
//this.loginS=system.getObject("service.userSve");
this.roleS=system.getObject("service.auth.roleSve");
this.redisClient=system.getObject("util.redisClient");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
}
module.exports = RoleCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
//this.loginS=system.getObject("service.userSve");
this.acS = system.getObject("service.auth.accountSve");
this.companyS = system.getObject("service.common.companySve");
}
async initNewInstance(queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
//获取验证码,发送给指定手机
async fetchVcode(pobj, qobj, req) {
var mobile = pobj.u;
//生成一个验证码,发送
// var vcode = await this.service.getUidStr(6, 10);
// await this.smsS.sendMsg(mobile, vcode);
return system.getResult({ vcodestr: "123" });
}
async checkLogin(gobj, qobj, req) {
//当前如果缓存中存在user,还是要检查当前user所在的域名,如果不和来访一致,则退出重新登录
if (req.session.user) {
var x = null;
if (req.session.user.Roles) {
x = req.session.user.Roles.map(r => { return r.code });
}
var tmp = {
id: req.session.user.id,
userName: req.session.user.userName,
nickName: req.session.user.nickName,
mobile: req.session.user.mobile,
isAdmin: req.session.user.isAdmin,
isSuper:req.session.user.isSuper,
created_at: req.session.user.created_at,
email: req.session.user.email,
headUrl: req.session.user.headUrl,
roles: x ? x.join(",") : "",
owner:req.session.user?req.session.user.owner:null,
tanentor_id:req.session.user?req.session.user.tanentor_id:null,
}
return system.getResult(tmp, "操作成功", req);
} else {
req.session.user = null;
//req.session.destroy();
return system.getResult(null, "操作失败", req);
}
}
async exit(pobj, qobj, req) {
if(req.session.app.id==settings.platformid){
req.session.user = null;
req.session.tocompany=null;
req.session.destroy();
return system.getResultSuccess({ "env": settings.env });
}else{
req.session.user=req.session.originalUID;
req.session.app=req.session.originalAPP;
return system.getResultSuccess({ "env": settings.env });
}
}
/**
*
* //用户重名检查--account
*
* 先按照username和password检查,是否存在account,
* 如果不存在account(第一次注册),检查查询字符串中是否存在appkey,
* 如果不存在说明是平台用户注册,就从会话中取出app_id
*
* 如果存在(已经注册过)
* 检查查询字符串appkey,如果存在,那么就按照appkey和userName和password去查看是否存在用户
* 如果存在,提示已经有同名用户存在;
* 如果不存在,那么就创建app下的用户
* 如果不存在,就按照会话中app_id去查看是否存在用户
*
*/
//重名检查,检查是否有
async checkSameName(pobj, qobj, req) {
var uname = pobj.uname;
//按照appid查询出app
var rtn = await this.service.checkSameName(uname, req.appid);
return system.getResult(rtn);
}
/**
* 查询某一个应用管理员信息
* @param {*} pobj
* @param {*} qobj
* @param {*} req
*/
async findAppAdmin(pobj, qobj, req) {
var appid = pobj.appid;
var user = await this.service.findOne({ isAdmin: true, app_id: appid });
return system.getResult(user);
}
async register(pobj, qobj, req) {
var appid = req.session.app.id;
var jumpUrl = req.session.app.authUrl;
var fmuser = pobj.u;
fmuser.app_id = req.appid;
if (!fmuser.userName) {
return system.getResult(null, "用户名不能为空");
}
if (!fmuser.mobile) {
return system.getResult(null, "手机号不能为空");
}
if (!fmuser.password) {
return system.getResult(null, "密码不能为空");
}
if (appid == settings.platformid){//如果是开放平台应用注册,设置所属公司
fmuser.owner_id=settings.platformid;
}else{//否则 todo
if(!fmuser.owner_id && req.session.tocompany){
fmuser.owner_id=req.tanentid;
}
}
var ruser = await this.service.register(fmuser);
if (ruser) {
if (appid != settings.platformid) {//说明是委托注册或登录
// this.redisClient.setWithEx(req.session.id,ruser,3600);
await this.cacheManager["OpenCodeCache"].cache(req.session.id, ruser, 30);
jumpUrl = jumpUrl + "?code=" + req.session.id;
} else {
//登录
req.session.user = ruser;
//设置系统默认公司
var pcompany=await this.companyS.findById(settings.platformcompanyid);
req.session.company=pcompany;
}
return system.getResultSuccess({ user: ruser, jumpUrl: jumpUrl });
} else {
return system.getResult(null, "用户已存在, 请修改并重试");
}
}
//管理员新增用户,设置默认密码
async create(pobj, queryobj, req) {
pobj.appid = req.appid;
pobj.owner_id=req.tanentid;
//新增用户时,获取当前用户的租户id
pobj.tanentor_id=req.session.user.tanentor_id;
var rtn=await this.service.createUser(pobj);
return system.getResult(rtn);
}
/**
* inuser 当前的req.session.app不是平台时,退出按钮关闭的是
* req.session.inuser
* @param {*} req
*/
async authByCode(req) {
var opencode = req.query.code;
var user = await this.service.authByCode(opencode);
if (user) {
req.session.originalUID=req.session.user;
req.session.originalAPP=req.session.app;
req.session.user = user;//防止覆盖租户的session
req.session.tocompany=user.owner;//从应用中导航到平台管理,平台完成登录
} else {
req.session.user = null;
}
return user;
}
// async bindCompany(p,q,req){
// var cmpinfo=p.u;
// var cmp=await this.service.bindCompany(cmpinfo,req.session.user.id);
// req.session.company=cmp;
// return system.getResult(cmp);
// }
//非开放平台登录方法
async goLoginForApp(p,q,req){
var app=p;
var appid=app.id;
var jumpUrl = app.authUrl;
var usercurrent=req.session.user;
var pobj={};
pobj.u={
userName:usercurrent.userName,
password:usercurrent.password,
mobile:usercurrent.mobile,
app_id:appid,
isNavto:true,
owner_id:req.session.tocompany?req.session.tocompany.id:null
}
var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
if (existedUser != null) {
await this.cacheManager["OpenCodeCache"].cache(req.session.id, existedUser, 60);
jumpUrl = jumpUrl + "?code=" + req.session.id;
return system.getResult({ user: existedUser, jumpUrl: jumpUrl });
}else {
return system.getResultFail(-1, "账号或密码有误.");
}
}
async login(pobj, qobj, req) {
var appid = req.session.app.id;
var jumpUrl = req.session.app.authUrl;
if (req.session.toapp) {
jumpUrl = req.session.toapp.authUrl;
pobj.u.isNavto=true;
//state为p_app表中appkey
} else{
pobj.u.isNavto=false;
}
pobj.u.app_id = appid;
if(!pobj.u.owner_id){//说明不是从平台界面,利用go进入,所以是自主登录
pobj.u.owner_id=pobj.tanentid;
}
var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
if (existedUser != null) {
if (appid != settings.platformid) {//非平台应用
await this.cacheManager["OpenCodeCache"].cache(req.session.id, existedUser, 60);
jumpUrl = jumpUrl + "?code=" + req.session.id;
if (req.session.toapp) {
jumpUrl = jumpUrl + "&srcKey=" + req.session.app.appkey;
}
} else {
req.session.user = existedUser;
//查询出companys信息,缓存当前的compnay,todo 放到service
var pcompany=await this.companyS.findById(settings.platformcompanyid);
req.session.company=pcompany;
//设置平台登录后默认要去往的租户公司
//查看用户身上是否有tanentor_id值,如果没有,说明是平台租户
var maproleids= existedUser.Roles.map((r)=>r.id);
var istanentorpassrole=maproleids.indexOf(settings.passroleid)>=0 || maproleids.indexOf(settings.commonroleid)>=0;
if(istanentorpassrole && !existedUser.isAdmin && !existedUser.isSuper){
var coms=existedUser.companies;
if(coms && coms.length>1){//因为平台默认公司的存在
var comfinds=coms.find((item)=>{
return item.usercompany.isCurrent==true;
});
if(comfinds){
req.session.tocompany=comfinds;
}
}
}else{
req.session.tocompany=existedUser.owner;
}
}
if (!existedUser.isEnabled) {
return system.getResultFail(system.waitAuditApp, "您的账户处于待审核等待启用状态.");
}
return system.getResult({ user: existedUser, jumpUrl: jumpUrl });
} else {
return system.getResultFail(-1, "账号或密码有误.");
}
}
}
module.exports = UserCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class AppCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async findAllApps() {
var rtns = await this.service.findAllApps();
return system.getResult(rtns);
}
async update(pobj, queryobj, req){
return super.update(pobj, queryobj, req);
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
rtn.appkey = this.getUUID();
rtn.secret = this.getUUID();
return system.getResult(rtn);
}
async resetPass(pobj, queryobj, req) {
pobj.password = await super.encryptPasswd(settings.defaultpwd);
var rtn = this.service.resetPass(pobj);
return system.getResult(rtn);
}
async createAdminUser(pobj, queryobj, req) {
pobj.password = settings.defaultpwd;
var rtn = this.service.createAdminUser(pobj);
return system.getResult(rtn);
}
async create(pobj, queryobj, req) {
//设置创建者,需要同时创建app管理员、默认密码、电话
pobj.creator_id = req.session.user.id;
// pobj.password=super.encryptPasswd(settings.defaultpwd);
//构造默认的应用相关的URL
pobj.authUrl=settings.protocalPrefix+pobj.domainName+"/auth";
pobj.docUrl=settings.protocalPrefix+pobj.domainName+"/web/common/metaCtl/getApiDoc";
pobj.uiconfigUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/config/fetchAppConfig";
pobj.opCacheUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/opCache/opCacheData";
pobj.notifyCacheCountUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/opCache/recvNotificationForCacheCount";
var app = await super.create(pobj,queryobj, req);
return system.getResult(app);
}
async fetchApiCallData(pobj, queryobj, req){
var curappkey=pobj.curappkey;
//检索出作为访问时的app呼出调用数据
var rtn= await this.service.fetchApiCallData(curappkey);
return system.getResultSuccess(rtn);
}
//接受缓存计数通知接口
async recvNotificationForCacheCount(p,q,req){
return this.service.recvNotificationForCacheCount(p);
}
}
module.exports = AppCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
class CachSearchesCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CachSearchesCtl));
}
async initNewInstance(queryobj, qobj) {
return system.getResultSuccess({});
}
async findAndCountAll(pobj, gobj, req) {
pobj.opCacheUrl = req.session.app.opCacheUrl;
pobj.appid = req.appid;
return await this.service.findAndCountAllCache(pobj);
}
async delCache(queryobj, qobj, req) {
var param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param);
}
async clearAllCache(queryobj, qobj, req) {
var param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param);
}
}
module.exports = CachSearchesCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class CompanyCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CompanyCtl));
this.userS=system.getObject("service.auth.userSve");
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
return system.getResult(rtn);
}
//to do租户在创建公司的时候,需要同时维护平台下面,用户所属租户是当前租户的公司
//当删除公司时,需要同时删除公司关联的APP,还有用户关联的公司
async create(p,q,req){
var user=await this.userS.findOne({id:p.userid});
var uuidstr=this.getUUID();
p.companykey=uuidstr;
var company=await this.service.create(p,user);
req.session.tocompany=company;
return system.getResult(company);
}
async update(p,q,req){
//修改重新刷新页面,初始化页面的公司信息
var rtn=await super.update(p,q,req);
req.session.company=p;
return system.getResult(rtn);
}
async buyApp(p,q,req){
var cmpid=req.session.tocompany.id;
var user=req.session.user;
var cmpfind=await this.service.buyApp(p,cmpid,user);
req.session.tocompany=cmpfind;
return system.getResult(cmpfind.apps);
}
//设置当前用户选择的公司为当前公司
async settocompany(p,q,req){
p.isCurrent=true;
req.session.tocompany=p;
var cmp= await this.service.settocompany(p);
return system.getResult(cmp);
}
async findAndCountAll(p,q,req){
var comps=await this.service.findAndCountAll(p,q,req);
var rtns=[];
for(var cmp of comps){
if(cmp.id!=settings.platformcompanyid){
var rtntmp={
id:cmp.id,
name:cmp.name,
description:cmp.description,
logoUrl:cmp.logoUrl,
isCurrent:cmp.usercompany.isCurrent,
apps:cmp.apps?cmp.apps:[]
}
rtns.push(rtntmp);
}
}
var rtn = {};
rtn.results = {count:rtns.length,rows:rtns};
rtn.aggresult = {};
return system.getResult(rtn);
}
}
module.exports = CompanyCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
class OplogCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve");
}
async initNewInstance(qobj) {
var u = uuidv4();
var aid = u.replace(/\-/g, "");
var rd = { name: "", appid: aid }
return system.getResult(rd);
}
async debug(obj) {
obj.logLevel = "debug";
return this.create(obj);
}
async info(obj) {
obj.logLevel = "info";
return this.create(obj);
}
async warn(obj) {
obj.logLevel = "warn";
return this.create(obj);
}
async error(obj) {
obj.logLevel = "error";
return this.create(obj);
}
async fatal(obj) {
obj.logLevel = "fatal";
return this.create(obj);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
}
module.exports = OplogCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class PConfigCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(PConfigCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
return system.getResult(rtn);
}
async create(pobj,queryobj, req) {
pobj.app_id=req.appid;
pobj.appkey=req.appkey;
var rtn=await super.create(pobj,queryobj, req);
return system.getResult(rtn);
}
async update(pobj,queryobj, req) {
pobj.app_id=req.appid;
pobj.appkey=req.appkey;
var rtn=await super.update(pobj);
return system.getResult(rtn);
}
}
module.exports = PConfigCtl;
var system=require("../../../system")
const CtlBase = require("../../ctl.base");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='DHmRtFlw2Zr3KaRwUFeiu7FWATnmla';
var accessKeyId='LTAIyAUK8AD04P5S';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class UploadCtl extends CtlBase{
constructor(){
super("common",CtlBase.getServiceName(UploadCtl));
this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 '{fileName}'";
this.restS=system.getObject("util.execClient");
this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'";
//sed -i 's/1111/&BBB/' /tmp/input.txt
//sed 's/{position}/{content}/g' {path}
}
async getOssConfig(){
var policyText = {
"expiration":"2119-12-31T16:00:00.000Z",
"conditions":[
["content-length-range",0,1048576000],
["starts-with","$key","zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64
var data={
OSSAccessKeyId:accessKeyId,
policy:policyBase64,
Signature:signature,
Bucket:'gsb-zc',
success_action_status:201,
url:url
};
return data;
};
async upfile(srckey,dest){
var oss=system.getObject("util.ossClient");
var result=await oss.upfile(srckey,"/tmp/"+dest);
return result;
};
async downfile(srckey){
var oss=system.getObject("util.ossClient");
var downfile=await oss.downfile(srckey).then(function(){
downfile="/tmp/"+srckey;
return downfile;
});
return downfile;
};
async pdf2html(obj){
var srckey=obj.key;
var downfile=await this.downfile(srckey);
var cmd=this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
var rtn=await this.restS.exec(cmd);
var path="/tmp/"+srckey.split(".pdf")[0]+".html";
var a=await this.insertToFile(path);
fs.unlink("/tmp/"+srckey);
var result=await this.upfile(srckey.split(".pdf")[0]+".html",srckey.split(".pdf")[0]+".html");
return result.url;
};
async insertToFile(path){
var cmd=this.cmdInsertToFilePattern+" "+path;
return await this.restS.exec(cmd);
};
}
module.exports=UploadCtl;
const system = require("../../../system");
const settings = require("../../../../config/settings");
function exp(db, DataTypes) {
var base = {
code: {
type: DataTypes.STRING(50),
unique: true
},
name: DataTypes.STRING(1000),
};
return base;
}
module.exports = exp;
const system = require("../../system");
const settings = require("../../../config/settings");
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", uiconfig.config.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", uiconfig.config.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
constructor() {
this.redisClient = system.getObject("util.redisClient");
this.desc = this.desc();
this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "sadd_base_appkeys:" + settings.appKey + "_cachekey";
this.isdebug = this.isdebug();
}
isdebug() {
return false;
}
desc() {
throw new Error("子类需要定义desc方法,返回缓存描述");
}
prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀");
}
async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) {
return null;
}
if (ex) {
await this.redisClient.setWithEx(cachekey, objvalstr, ex);
} else {
await this.redisClient.set(cachekey, objvalstr);
}
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
return JSON.parse(objvalstr);
} else {
return JSON.parse(cacheValue);
}
}
async invalidate(inputkey){
const cachekey=this.prefix+inputkey;
this.redisClient.delete(cachekey);
return 0;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串");
}
}
module.exports = CacheBase;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class CacheLocker extends CacheBase{
constructor(){
super();
this.prefix="locker_";
}
desc(){
}
prefix(){
}
async init(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
async enter(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpop(key);
}
async release(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
}
module.exports=CacheLocker;
// var x=new CacheLocker();
// x.init("hello").then(d=>{
// x.enter("hello").then(m=>{
// console.log(m);
// });
// });
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//开放平台缓存所有的应用的访问token
class ApiAccessKeyCache extends CacheBase {
constructor() {
super();
this.appDao = system.getObject("db.common.appDao");
}
desc() {
return "缓存访问Token";
}
prefix() {
return "gapps_accesskey:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (!items || items.length == 0) {
return null;
}
const configValue = await this.appDao.findOne(items[0], val);
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports = ApiAccessKeyCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
const uuidv4 = require('uuid/v4');
class ApiAccessKeyClientCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "平台作为一个应用,缓存访问token";
}
prefix() {
return "req_appkey_cachetoken:";
}
buildCacheVal(cachekey, inputkey, val, ex, ...items) {
return JSON.stringify({ accessKey: val });
}
}
module.exports = ApiAccessKeyClientCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiAccuCache extends CacheBase{
constructor(){
super();
this.apitradeDao=system.getObject("db.callcount.apitradeDao");
}
desc(){
return "API累计调用次数和累计余额";
}
prefix(){
return "api_accu:";
}
async addCallCount(apikey,n){
var key=this.prefix+apikey;
var result=await this.redisClient.hincrby(key,"callcount",n);
return result;
}
async addCallBalance(apikey,n){
var key=this.prefix+apikey;
var result=await this.redisClient.hincrby(key,"amount",n);
return result;
}
async getApiCallAccu(srckey){
var apikey=srckey.split("_")[0];
var key=this.prefix+srckey;
const cachedVal= await this.redisClient.hgetall(key);
if(!cachedVal || cachedVal=="undefined"){
var count= await this.apitradeDao.model.count({
where:{
srcappkey:apikey,
tradeType:"consume",
}
});
var amount=await this.apitradeDao.model.sum("amount",{
where:{
srcappkey:apikey,
}
});
var map={"callcount":count?count:0,"amount":amount?amount:0};
this.redisClient.hmset(key,map);
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
return map;
}else{
return cachedVal;
}
}
}
module.exports=ApiAccuCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiCallCountCache extends CacheBase{
constructor(){
super();
this.apitradeDao=system.getObject("db.common.apitradeDao");
}
desc(){
return "API调用次数";
}
prefix(){
return "api_call:";
}
async addCallCount(apikey,callpath,n){
var key=this.prefix+apikey+"_"+callpath;
var result=await this.redisClient.hincrby(key,"callcount",n);
return result;
}
async addCallBalance(apikey,callpath,n){
var key=this.prefix+apikey+"_"+callpath;
var result=await this.redisClient.hincrby(key,"amount",n);
return result;
}
async getApiCallCount(apikey,callpath){
var key=this.prefix+apikey+"_"+callpath;
const cachedVal= await this.redisClient.hgetall(key);
if(!cachedVal || cachedVal=="undefined"){
var count= await this.apitradeDao.model.count({
where:{
srcappkey:apikey,
op:callpath,
tradeType:"consume",
}
});
var amount=await this.apitradeDao.model.sum("amount",{
where:{
srcappkey:apikey,
op:callpath,
tradeType:"consume",
}
});
var map={"callcount":count?count:0,"amount":amount?amount:0};
this.redisClient.hmset(key,map);
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
return map;
}else{
return cachedVal;
}
}
}
module.exports=ApiCallCountCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class AppCache extends CacheBase{
constructor(){
super();
this.prefix="g_appkey:";
this.appDao=system.getObject("db.common.appDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存本地应用对象";
}
prefix(){
return "g_applocal_"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue=await this.appDao.findOne2(inputkey);
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports=AppCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class InitGiftCache extends CacheBase{
constructor(){
super();
this.pConfigDao=system.getObject("db.common.pconfigDao");
}
desc(){
return "初始赠送";
}
prefix(){
return "g_pconfig_initGift";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
const config=await this.pConfigDao.model.findOne({where:{configType:'initGift',appkey:inputkey},raw:true});
const num2=Number(config.configValue);
return num2;
}
}
module.exports=InitGiftCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
//缓存首次登录的赠送的宝币数量
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "应用UI配置缓存";
}
prefix() {
return "g_uiconfig:";
}
async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key);
}
async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value)
}
async keys(p) {
return this.redisClient.keys(p);
}
async get(k) {
return this.redisClient.get(k);
}
async del(k) {
return this.redisClient.delete(k);
}
async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............");
return this.redisClient.flushall();
}
}
module.exports = MagCache;
const CacheBase=require("../cache.base");
//缓存当前登录用户的opencode--指向公共平台的委托登录code
class OpenCodeCache extends CacheBase{
constructor(){
super();
}
desc(){
return "开放用户缓存";
}
prefix(){
return "pl_opencode_";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
return JSON.stringify(val);
}
}
module.exports=OpenCodeCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class PConfigCache extends CacheBase{
constructor(){
super();
this.pConfigDao=system.getObject("db.common.pconfigDao");
}
desc(){
return "平台配置参数";
}
prefix(){
return "g_pconfig";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
const configValue=await this.pConfigDao.model.findAll({where:{appkey:inputkey},attributes:["name","configType","configValue"],raw:true});
var s=JSON.stringify(configValue);
return s;
}
}
module.exports=PConfigCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class UIConfigCache extends CacheBase{
constructor(){
super();
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "应用UI配置缓存";
}
prefix(){
return "g_uiconfig:";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
var configValue =system.getUiConfig2(inputkey);
return JSON.stringify(configValue);
}
}
module.exports=UIConfigCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
// const authUtils = require("../../utils/businessManager/authUtils");
const uuidv4 = require('uuid/v4');
//缓存首次登录的赠送的宝币数量
class UIRemoteConfigCache extends CacheBase {
constructor() {
super();
}
desc() {
return "非平台应用UI配置缓存";
}
prefix() {
return "g_uiremoteconfig_";
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var url = items[0];
const cacheManager = await system.getObject("db.common.cacheManager");
var authUtils = system.getObject("util.businessManager.authUtils");
var appData = await authUtils.getTokenInfo(settings.appKey, settings.secret);
if (appData.status != 0) {
return null;
}
//按照访问token
var rtnKey=appData.data.accessKey;
const restS = await system.getObject("util.restClient");
var restResult = await restS.execPostWithAK({}, url, rtnKey);
if (restResult) {
if (restResult.status == 0) {
var resultRtn = restResult.data;
return JSON.stringify(resultRtn);
}
}
return null;
}
}
module.exports = UIRemoteConfigCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class VCodeCache extends CacheBase {
constructor() {
super();
this.smsUtil = system.getObject("util.smsClient");
}
// isdebug() {
// return settings.env == "dev";
// }
desc() {
return "缓存给手机发送的验证码60妙";
}
prefix() {
return "g_vcode_"
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
//inputkey采用appkey_mobile的形式
var mobile = inputkey.split("_")[1];
var tmplCode = val;
var signName = items ? items[0] : "";
var vcode = await this.smsUtil.getUidStr(6, 10);
// var content=tmpl.replace(/\|vcode\|/g,vcode);
//this.smsUtil.sendMsg(mobile,content);
if (!tmplCode && !signName) {
this.smsUtil.sendMsg(mobile, vcode);
} //tmplCode为发送短信编码,需在阿里开通,signName为短信头描述信息,二者没有传递则用默认的发送验证码
else {
this.smsUtil.aliSendMsg(mobile, tmplCode, signName, JSON.stringify({ code: vcode }));
}
return JSON.stringify({ vcode: vcode });
}
}
module.exports = VCodeCache;
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
var db = system.getObject("db.common.connection").getCon();
this.db = db;
console.log("........set dao model..........");
this.model = db.models[this.modelName];
console.log(this.modelName);
}
preCreate(u) {
return u;
}
async create(u, t) {
var u2 = this.preCreate(u);
if (t) {
return this.model.create(u2, { transaction: t }).then(u => {
return u;
});
} else {
return this.model.create(u2).then(u => {
return u;
});
}
}
static getModelName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery(qobj) {
var w =qobj.refwhere? qobj.refwhere:{};
if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
}
if (qobj.parentinfo) {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
}
//如果需要控制数据权限
if(qobj.datapriv){
w["id"]={ [this.db.Op.in]: qobj.datapriv};
}
if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
return this.model.findAll({ where: w, attributes: qobj.fields });
} else {
return this.model.findAll({ where: w, attributes: qobj.fields });
}
}
async bulkDelete(ids) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en;
}
async bulkDeleteByWhere(whereParam, t) {
var en = null;
if (t != null && t != 'undefined') {
whereParam.transaction = t;
return await this.model.destroy(whereParam);
} else {
return await this.model.destroy(whereParam);
}
}
async delete(qobj, t) {
var en = await this.model.findOne({ where: qobj });
if (t != null && t != 'undefined') {
if (en != null) {
return en.destroy({ transaction: t });
}
} else {
if (en != null) {
return en.destroy();
}
}
return null;
}
extraModelFilter(pobj) {
//return {"key":"include","value":{model:this.db.models.app}};
return null;
}
extraWhere(obj, where) {
return where;
}
orderBy() {
//return {"key":"include","value":{model:this.db.models.app}};
return [["created_at", "DESC"]];
}
buildQuery(qobj) {
var linkAttrs = [];
const pageNo = qobj.pageInfo.pageNo;
const pageSize = qobj.pageInfo.pageSize;
const search = qobj.search;
var qc = {};
//设置分页查询条件
qc.limit = pageSize;
qc.offset = (pageNo - 1) * pageSize;
//默认的查询排序
qc.order = this.orderBy();
//构造where条件
qc.where = {};
if (search) {
Object.keys(search).forEach(k => {
console.log(search[k], ":search[k]search[k]search[k]");
if (search[k] && search[k] != 'undefined' && search[k] != "") {
if ((k.indexOf("Date") >= 0 || k.indexOf("_at") >= 0)) {
if (search[k] != "" && search[k]) {
var stdate = new Date(search[k][0]);
var enddate = new Date(search[k][1]);
qc.where[k] = { [this.db.Op.between]: [stdate, enddate] };
}
}
else if (k.indexOf("id") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("channelCode") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("Type") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("Status") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("status") >= 0) {
qc.where[k] = search[k];
}
else {
if (k.indexOf("~") >= 0) {
linkAttrs.push(k);
} else {
qc.where[k] = { [this.db.Op.like]: "%" + search[k] + "%" };
}
}
}
});
}
this.extraWhere(qobj, qc.where, qc, linkAttrs);
var extraFilter = this.extraModelFilter(qobj);
if (extraFilter) {
qc[extraFilter.key] = extraFilter.value;
}
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
console.log(qc);
return qc;
}
buildaggs(qobj) {
var aggsinfos = [];
if (qobj.aggsinfo) {
qobj.aggsinfo.sum.forEach(aggitem => {
var t1 = [this.db.fn('SUM', this.db.col(aggitem.field)), aggitem.field + "_" + "sum"];
aggsinfos.push(t1);
});
qobj.aggsinfo.avg.forEach(aggitem => {
var t2 = [this.db.fn('AVG', this.db.col(aggitem.field)), aggitem.field + "_" + "avg"];
aggsinfos.push(t2);
});
}
return aggsinfos;
}
async findAggs(qobj, qcwhere) {
var aggArray = this.buildaggs(qobj);
if (aggArray.length != 0) {
qcwhere["attributes"] = {};
qcwhere["attributes"] = aggArray;
qcwhere["raw"] = true;
var aggResult = await this.model.findOne(qcwhere);
return aggResult;
} else {
return {};
}
}
async findAndCountAll(qobj, t) {
var qc = this.buildQuery(qobj);
var apps = await this.model.findAndCountAll(qc);
var aggresult = await this.findAggs(qobj, qc);
var rtn = {};
rtn.results = apps;
rtn.aggresult = aggresult;
return rtn;
}
preUpdate(obj) {
return obj;
}
async update(obj, tm) {
var obj2 = this.preUpdate(obj);
if (tm != null && tm != 'undefined') {
return this.model.update(obj2, { where: { id: obj2.id }, transaction: tm });
} else {
return this.model.update(obj2, { where: { id: obj2.id } });
}
}
async bulkCreate(ids, t) {
if (t != null && t != 'undefined') {
return await this.model.bulkCreate(ids, { transaction: t });
} else {
return await this.model.bulkCreate(ids);
}
}
async updateByWhere(setObj, whereObj, t) {
if (t && t != 'undefined') {
if (whereObj && whereObj != 'undefined') {
whereObj.transaction = t;
} else {
whereObj = { transaction: t };
}
}
return this.model.update(setObj, whereObj);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.db.query(sql, paras);
}
async customQuery(sql, paras, t) {
var tmpParas = null;//||paras=='undefined'?{type: this.db.QueryTypes.SELECT }:{ replacements: paras, type: this.db.QueryTypes.SELECT };
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' ? { type: this.db.QueryTypes.SELECT } : { replacements: paras, type: this.db.QueryTypes.SELECT };
}
return this.db.query(sql, tmpParas);
}
async findCount(whereObj = null) {
return this.model.count(whereObj, { logging: false }).then(c => {
return c;
});
}
async findSum(fieldName, whereObj = null) {
return this.model.sum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
var tmpWhere = {};
tmpWhere.limit = pageSize;
tmpWhere.offset = (pageIndex - 1) * pageSize;
if (whereObj != null) {
tmpWhere.where = whereObj;
}
if (orderObj != null && orderObj.length > 0) {
tmpWhere.order = orderObj;
}
if (attributesObj != null && attributesObj.length > 0) {
tmpWhere.attributes = attributesObj;
}
if (includeObj != null && includeObj.length > 0) {
tmpWhere.include = includeObj;
tmpWhere.distinct = true;
}else{
tmpWhere.raw = true;
}
return await this.model.findAndCountAll(tmpWhere);
}
async findOne(obj) {
return this.model.findOne({ "where": obj });
}
async findById(oid) {
return this.model.findById(oid);
}
}
module.exports = Dao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class AccountDao extends Dao{
constructor(){
super(Dao.getModelName(AccountDao));
}
async findOrCreate(ac,t){
var account= await this.model.findOne({where:{unionId:ac.unionId}},{transaction:t});
if(account){
return account;
}else{
account=await this.model.create(ac,{transaction:t});
return account;
}
}
async findOneByOnlyCode(onlycode){
return this.model.findOne({"where":{"onlyCode":onlycode}});
}
}
module.exports=AccountDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class AccountLogDao extends Dao{
constructor(){
super(Dao.getModelName(AccountLogDao));
}
}
module.exports=AccountLogDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class AuthDao extends Dao{
constructor(){
super(Dao.getModelName(AuthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=AuthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class DataauthDao extends Dao{
constructor(){
super(Dao.getModelName(DataauthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=DataauthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OrgDao extends Dao{
constructor(){
super(Dao.getModelName(OrgDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=OrgDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class PAccountDao extends Dao{
constructor(){
super(Dao.getModelName(PAccountDao));
}
async findPAccount(t){
return this.model.findOne({},{transaction:t});
}
}
module.exports=PAccountDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class RoleDao extends Dao{
constructor(){
super(Dao.getModelName(RoleDao));
}
async findOne(paramappid,t){
var app= await this.model.findOne({where:{appid:paramappid}},{transaction:t});
return app;
}
extraWhere(obj,w,qc,linkAttrs){
// if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj);
// // w["app_id"]=obj.appid;
// // }
// }
w["app_id"]=obj.appid;
w["company_id"]=obj.tanentid;
return w;
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.app,}]};
}
async preUpdate(u){
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
await this.model.update(obj2,{where:{id:obj2.id}});
var role=await this.model.findOne({where:{id:obj2.id}});
return role;
}
async preCreate(u){
return u;
}
async create(u,t){
var self=this;
var u2= await this.preCreate(u);
if(t){
var role= await this.model.create(u2,{transaction: t});
return role;
}else{
var role= await this.model.create(u2);
return role;
}
}
}
module.exports=RoleDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class UserDao extends Dao{
constructor(){
super(Dao.getModelName(UserDao));
this.appDao=system.getObject("db.common.appDao");
}
async getAuths(userid){
var self=this;
return this.model.findOne({
where:{id:userid},
include:[{model:self.db.models.account,attributes:["id","isSuper","referrerOnlyCode"]},
{model:self.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:self.db.models.product,as:"Products",attributes:["id","code"]}
]},
],
});
}
async getUserByUsername(username,appkey,t){
var app=await this.appDao.findOne(appkey);
var tUser=await this.model.findOne({
where:{userName:username,app_id:app.id},
include:[{model:this.db.models.app,raw:true},
// {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
// "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{model:this.db.models.account,attributes:["id","isSuper","referrerOnlyCode"],raw:true},
{model:this.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:this.db.models.product,as:"Products",attributes:["id","code"],raw:true}
]},
]},{transaction:t});
// if(tUser!=null){
// tUser=tUser.get({plain:true});
// tUser.partnerinfo=await this.partnerinfoDao.model.findOne({where:{onlyCode:tUser.onlyCode},raw:true});
// }
return tUser;
}
async getUserByOpenId(popenid,appkey,t){
var app=await this.appDao.findOne(appkey);
var tUser=await this.model.findOne({
where:{openId:popenid},
include:[{model:this.db.models.app,raw:true},
// {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
// "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{model:this.db.models.account,attributes:["id","isSuper","referrerOnlyCode"],raw:true},
{model:this.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:this.db.models.product,as:"Products",attributes:["id","code"],raw:true}
]},
]},{transaction:t});
if(tUser!=null){
tUser=tUser.get({plain:true});
tUser.partnerinfo=await this.partnerinfoDao.model.findOne({where:{onlyCode:tUser.onlyCode},raw:true});
}
// console.log("tUser.partnerinfo...................................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>999sy");
// console.log(tUser);
return tUser;
}
async setAccount(user,account,t){
var user=await user.setAccount(account,{transaction: t});
return user;
}
async setApp(user,app,t){
//按照APPId,获取app对象
var user=await user.setApp(app,{transaction: t});
return user;
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"]}]};
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.codepath && obj.codepath!=""){
if(obj.codepath.indexOf("appuser")>0 || obj.codepath.indexOf("organization")>0){//说明是应用管理员的查询
w["app_id"]=obj.appid;
w["owner_id"]=obj.tanentid;
}
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
async preUpdate(u){
if(u.roles && u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var user=await this.model.findOne({where:{id:obj2.id}});
user.setRoles(obj2.roles);
return user;
}
async findAndCountAll(qobj,t){
var users=await super.findAndCountAll(qobj,t);
return users;
}
async preCreate(u){
// var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(roles);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// u.roles=roles
return u;
}
async create(u,t){
var self=this;
var u2=await this.preCreate(u);
if(t){
return this.model.create(u2,{transaction: t}).then(user=>{
return user;
});
}else{
return this.model.create(u2).then(user=>{
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId,company_only_code,result){
var customerObj={companyOnlyCode:company_only_code};
var putSqlWhere={where:{id:userId}};
this.updateByWhere(customerObj,putSqlWhere);
return result;
}
}
module.exports=UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const Dao=require("../../dao.base");
class UsereaccountDao extends Dao{
constructor(){
super(Dao.getModelName(UsereaccountDao));
}
}
module.exports=UsereaccountDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ApiTradeDao extends Dao{
constructor(){
super(Dao.getModelName(ApiTradeDao));
}
// extraWhere(obj,w){
// if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("mytraderecord")>0){//说明是普通用户的交易查询
// w["user_id"]=obj.uid;
// }
// }
// return w;
// }
async create(tradeobj,t){
var trade=await super.create(tradeobj,t)
return trade;
}
}
module.exports=ApiTradeDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ArticleDao extends Dao{
constructor(){
super(Dao.getModelName(ArticleDao));
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.newschannel,attributes:["id","title"]},]};
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
}
module.exports=ArticleDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ChannelDao extends Dao{
constructor(){
super(Dao.getModelName(ChannelDao));
}
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.role,as:"Roles",attributes:["id","name"]}]};
}
async preUpdate(u){
if(u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var channel=await this.model.findOne({where:{id:obj2.id}});
channel.setRoles(obj2.roles);
return channel;
}
}
module.exports=ChannelDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class LoopplayDao extends Dao{
constructor(){
super(Dao.getModelName(LoopplayDao));
}
// channelCode: ""
// extraModelFilter(){
// return {"key":"include","value":[{model:this.db.models.newschannel,attributes:["id","title"]},]};
// }
extraWhere(obj, w){
let channelCode = obj.channelCode || '';
if(channelCode == "index") {
w["channelCode"] = '';
} else if(channelCode) {
w["channelCode"] = channelCode;
}
// if(pageType == 1) {
// w["status"] = {[this.db.Op.in]: ['1']};
// } else if (pageType == 2) {
// w["status"] = {[this.db.Op.in]: ['2']};
// } else if (pageType == 3) {
// w["status"] = {[this.db.Op.in]: ['4','8','16']};
// }
return w;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
}
module.exports=LoopplayDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class NewschannelDao extends Dao{
constructor(){
super(Dao.getModelName(NewschannelDao));
}
async findAgreenment(queryobj,qobj,req){
var result =await this.model.findAll({
where:{id:1},
include:{
model:this.db.models.article,
limit:1,
offset:0
},
});
console.log("---------------------------------------------------------------zhangjiao");
console.log(result);
return result;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
async findPrev5(queryobj,qobj){
console.log(qobj);
return this.model.findAll({
where:{isPubed:1},
include:{
model:this.db.models.article,
limit:5,
offset:0
},
limit:6,
offset:0,
});
}
}
module.exports=NewschannelDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class SloganpictureDao extends Dao{
constructor(){
super(Dao.getModelName(SloganpictureDao));
}
// extraModelFilter(){
// return {"key":"include","value":[{model:this.db.models.newschannel,attributes:["id","title"]},]};
// }
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
}
module.exports=SloganpictureDao;
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var glob = require("glob");
class APIDocManager{
constructor(){
this.doc={};
this.buildAPIDocMap();
}
async buildAPIDocMap(){
var self=this;
//订阅任务频道
var apiPath=settings.basepath+"/app/base/api/impl";
var rs = glob.sync(apiPath + "/**/*.js");
if(rs){
for(let r of rs){
// var ps=r.split("/");
// var nl=ps.length;
// var pkname=ps[nl-2];
// var fname=ps[nl-1].split(".")[0];
// var obj=system.getObject("api."+pkname+"."+fname);
var ClassObj=require(r);
var obj=new ClassObj();
var gk=obj.apiDoc.group+"|"+obj.apiDoc.groupDesc
if(!this.doc[gk]){
this.doc[gk]=[];
this.doc[gk].push(obj.apiDoc);
}else{
this.doc[gk].push(obj.apiDoc);
}
}
}
}
}
module.exports=APIDocManager;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ApiTradeDao extends Dao{
constructor(){
super(Dao.getModelName(ApiTradeDao));
}
// extraWhere(obj,w){
// if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("mytraderecord")>0){//说明是普通用户的交易查询
// w["user_id"]=obj.uid;
// }
// }
// return w;
// }
async create(tradeobj,t){
var trade=await super.create(tradeobj,t)
return trade;
}
}
module.exports=ApiTradeDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class AppDao extends Dao {
constructor() {
super(Dao.getModelName(AppDao));
}
async findOneById(id, t) {
var sqlWhere = {
where: { id: id },
attributes: ["id", "appkey", "secret", "domainName"], raw: true
};
if (t) {
sqlWhere.transaction = t;
}
var app = await this.model.findOne(sqlWhere);
return app;
}
async findOne(appKey, secret, t) {
var tmpAttributes = [`id`,
`appkey`,
`name`,
`domainName`,
`homePage`,
`docUrl`,
`authUrl`,
`logoUrl`,
`bkimageUrl`,
`showimgUrl`,
`detailimgUrl`,
`description`,
`isEnabled`,
`isPublish`,
`isCommon`,
`appType`,
`uiconfigUrl`,
`opCacheUrl`,
`notifyCacheCountUrl`];
if (t) {
var app = await this.model.findOne({ where: { appkey: appKey, secret: secret }, attributes: tmpAttributes, raw: true }, { transaction: t });
return app;
} else {
var app = await this.model.findOne({ where: { appkey: appKey, secret: secret }, attributes: tmpAttributes, raw: true });
return app;
}
}
async findOne2(appKey, t) {
var tmpAttributes = [`id`,
`appkey`,
`name`,
`domainName`,
`homePage`,
`docUrl`,
`authUrl`,
`logoUrl`,
`bkimageUrl`,
`showimgUrl`,
`detailimgUrl`,
`description`,
`isEnabled`,
`isPublish`,
`isCommon`,
`isSaas`,
`appType`,
`uiconfigUrl`,
`opCacheUrl`,
`notifyCacheCountUrl`];
if (t) {
var app = await this.model.findOne({ where: { appkey: appKey }, attributes: tmpAttributes, raw: true }, { transaction: t });
return app;
} else {
var app = await this.model.findOne({ where: { appkey: appKey }, attributes: tmpAttributes, raw: true });
return app;
}
}
extraWhere(obj, w, qc, linkAttrs) {
if (obj.codepath && obj.codepath != "") {
if (obj.codepath.indexOf("pmgmyapps") > 0) {//说明是应用管理员的查询
w["creator_id"] = obj.userid;
}
}
if (linkAttrs.length > 0) {
var search = obj.search;
var lnkKey = linkAttrs[0];
var strq = "$" + lnkKey.replace("~", ".") + "$";
w[strq] = { [this.db.Op.like]: "%" + search[lnkKey] + "%" };
}
return w;
}
}
module.exports = AppDao;
const fs=require("fs");
const settings=require("../../../../config/settings");
class CacheManager{
constructor(){
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap(){
var self=this;
self.doc={};
var cachePath=settings.basepath+"/app/base/db/cache/";
const files=fs.readdirSync(cachePath);
if(files){
files.forEach(function(r){
var classObj=require(cachePath+"/"+r);
self[classObj.name]=new classObj();
var refTmp=self[classObj.name];
if(refTmp.prefix){
self.doc[refTmp.prefix]=refTmp.desc;
}
else{
console.log("请在"+classObj.name+"缓存中定义prefix");
}
});
}
}
}
module.exports=CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const system = require("../../../system");
const Dao = require("../../dao.base");
class CompanyDao extends Dao {
constructor() {
super(Dao.getModelName(CompanyDao));
}
extraWhere(obj, w, qc, linkAttrs) {
return w;
}
// extraModelFilter(pobj){
// return {"key":"include",
// "value":[{
// model:this.db.models.user,
// as:"Users",
// through:{
// where:{id:pobj.uid}
// }
// },
// ]};
// }
}
module.exports = CompanyDao;
const Sequelize = require('sequelize');
const settings=require("../../../../config/settings")
const fs=require("fs")
const path=require("path");
var glob = require("glob");
class DbFactory{
constructor(){
const dbConfig=settings.database();
this.db=new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
dbConfig.config);
this.db.Sequelize=Sequelize;
this.db.Op=Sequelize.Op;
this.initModels();
this.initRelations();
}
async initModels(){
var self=this;
var modelpath=path.normalize(path.join(__dirname, '../..'))+"/models/";
console.log("modelpath=====================================================");
console.log(modelpath);
var models=glob.sync(modelpath+"/**/*.js");
console.log(models.length);
models.forEach(function(m){
console.log(m);
self.db.import(m);
});
console.log("init models....");
}
async initRelations(){
/**
一个账户对应多个登陆用户
一个账户对应一个commany
一个APP对应多个登陆用户
一个APP有多个角色
登陆用户和角色多对多
**/
/*建立账户和用户之间的关系*/
//account--不属于任何一个app,是统一用户
//用户登录时首先按照用户名和密码检查account是否存在,如果不存在则提示账号或密码不对,如果
//存在则按照按照accountid和应用key,查看user,后台实现对应user登录
//管理员添加用户,需要同时增加开放平台用户及其所属租户创建的公司
this.db.models.user.belongsTo(this.db.models.account,{constraints: false,});
this.db.models.account.hasMany(this.db.models.user,{constraints: false,});
this.db.models.user.belongsTo(this.db.models.company,{as:"owner",constraints: false,});//人员直属公司
this.db.models.user.belongsTo(this.db.models.user,{as:"tanentor",constraints: false,});//指定用户所属租户
this.db.models.app.belongsTo(this.db.models.user,{as:"creator",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.company,{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.dataauth.belongsTo(this.db.models.app,{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.role.belongsToMany(this.db.models.user, {as:"Users",through: 'p_userrole',constraints: false,});
this.db.models.pconfig.belongsTo(this.db.models.app,{constraints: false,});
this.db.models.pconfig.belongsTo(this.db.models.company,{constraints: false,});
/*建立应用和租户公司之间的关系*/
this.db.models.company.belongsToMany(this.db.models.app, {through: this.db.models.companyapp,constraints: false,});
this.db.models.app.belongsToMany(this.db.models.company, {through: this.db.models.companyapp,constraints: false,});
/*建立用户和租户之间的关系*/
this.db.models.user.belongsToMany(this.db.models.company, {through: this.db.models.usercompany,constraints: false,});
this.db.models.company.belongsToMany(this.db.models.user, {through: this.db.models.usercompany,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.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.org.belongsTo(this.db.models.app,{constraints: false,});
//组织机构和角色是多对多关系
this.db.models.org.belongsToMany(this.db.models.role,{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.user.belongsTo(this.db.models.org,{constraints: false,});
}
//async getCon(){,用于使用替换table模型内字段数据使用
getCon(){
var that=this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// throw err;
// });
//同步模型
if(settings.env=="dev"){
//console.log(pa);
// pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true}));
// });
// await this.db.models.user.create({nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
// .then(function(user){
// var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
// acc.save().then(a=>{
// user.setAccount(a);
// });
// });
}
return this.db;
}
getConhb(){
var that=this;
if(settings.env=="dev"){
}
return this.dbhb;
}
}
module.exports=DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class MetaDao{
constructor(){
//super(Dao.getModelName(AppDao));
}
}
module.exports=MetaDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OplogDao extends Dao{
constructor(){
super(Dao.getModelName(OplogDao));
}
}
module.exports=OplogDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class PConfigDao extends Dao{
constructor(){
super(Dao.getModelName(PConfigDao));
}
async findByConfigType(type,t){
return this.model.findOne({where:{configType:type}},{transaction:t});
}
extraWhere(obj,w,qc,linkAttrs){
// if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj);
// // w["app_id"]=obj.appid;
// // }
// }
w["app_id"]=obj.appid;
w["company_id"]=obj.tanentid;
return w;
}
}
module.exports=PConfigDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class TaskDao extends Dao{
constructor(){
super(Dao.getModelName(TaskDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
async delete(task,qobj,t){
return task.destroy({where:qobj,transaction:t});
}
}
module.exports=TaskDao;
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var cron = require('node-cron');
class TaskManager{
constructor(){
this.taskDic={};
this.redisClient=system.getObject("util.redisClient");
this.buildTaskMap();
}
async buildTaskMap(){
var self=this;
//订阅任务频道
await this.redisClient.subscribeTask("task",this);
var taskPath=settings.basepath+"/app/base/db/task/";
const files=fs.readdirSync(taskPath);
if(files){
files.forEach(function(r){
var classObj=require(taskPath+"/"+r);
self[classObj.name]=new classObj();
});
}
}
async addTask(taskClassName,exp){
(async (tn,ep)=>{
if(!this.taskDic[tn]){
this.taskDic[tn]=cron.schedule(ep,()=>{
this[tn].doTask();
});
}
})(taskClassName,exp);
}
async deleteTask(taskClassName){
if(this.taskDic[taskClassName]){
this.taskDic[taskClassName].destroy();
delete this.taskDic[taskClassName];
}
}
async clearlist(){
var x=await this.redisClient.clearlist("tasklist");
return x;
}
async publish(channel,msg){
var x=await this.redisClient.publish(channel,msg);
return x;
}
async newTask(taskstr){
return this.redisClient.rpush("tasklist",taskstr);
}
}
module.exports=TaskManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class UploadDao extends Dao{
constructor(){
super(Dao.getModelName(UploadDao));
}
}
module.exports=UploadDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MsgHistoryDao extends Dao{
constructor(){
super(Dao.getModelName(MsgHistoryDao));
}
extraWhere(obj,w){
if(obj.ukstr && obj.ukstr!=""){
// w={[this.db.Op.or]:[
// {[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
// {[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
// ]
// };
w[this.db.Op.or]=[
{[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
{[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
];
}
return w;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]];
}
}
module.exports=MsgHistoryDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MsgNoticeDao extends Dao{
constructor(){
super(Dao.getModelName(MsgNoticeDao));
}
async saveNotice(msg, t) {
var noticeFrom = await super.findOne({fromId : msg.senderId, toId : msg.targetId});
if(noticeFrom) {
var set = {lastMsgId:msg.id};
if(msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
await super.updateByWhere(set, {where:{id:noticeFrom.id}}, t);
} else {
noticeFrom = {
fromuser: msg.sender,
fromId:msg.senderId,
touser: msg.target,
toId:msg.targetId,
isAccepted:true,
lastMsgId:msg.id,
businessLicense_id : msg.businessLicense_id || 0
};
await super.create(noticeFrom, t);
}
var noticeTo = await super.findOne({fromId : msg.targetId, toId : msg.senderId});
if(noticeTo) {
var set = {lastMsgId:msg.id};
if(msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
await super.updateByWhere(set, {where:{id:noticeTo.id}}, t);
} else {
noticeTo = {
fromuser: msg.target,
fromId:msg.targetId,
touser: msg.sender,
toId:msg.senderId,
isAccepted:true,
lastMsgId:msg.id,
businessLicense_id : msg.businessLicense_id || 0
};
await super.create(noticeTo, t);
}
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]];
}
}
module.exports=MsgNoticeDao;
const system=require("../system");
const settings=require("../../config/settings.js");
const reclient=system.getObject("util.redisClient");
const md5 = require("MD5");
//获取平台配置兑换率
//初次登录的赠送数量
//创建一笔交易
//同时增加账户数量,增加系统平台账户
var dbf=system.getObject("db.common.connection");
var db=dbf.getCon();
db.sync({force:true}).then(async ()=>{
console.log("sync complete...");
//创建平台配置
const PConfig=db.models.pconfig;
var pconfigObjs=await PConfig.bulkCreate([
{configType:"price",configValue:"100",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"initGift",configValue:"10000",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"apiInitGift",configValue:"500",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"apiCallPrice",configValue:"10",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"logOpWrite",configValue:"-1",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},//操作日志步骤是否写入,0否,1是
]);
//创建平台账户
const PAccount=db.models.paccount;
const pa=await PAccount.create({});
//创建APP
const App=db.models.app;
const Account=db.models.account;
const Company=db.models.company;
const Auth=db.models.auth;
//创建role
const Role=db.models.role;
var hp=settings.homePage();
var authUrl=settings.authUrl();
//建立平台应用和上帝超级管理员
App.create({appkey:"wx76a324c5d201d1a4",
name:"蜂擎开放平台",
homePage:hp,
docUrl:settings.docUrl(),
authUrl:authUrl,isEnabled:true,isSaas:true,secret:"f99d413b767f09b5dff0b3610366cc46",logoUrl:"",
isCommon:true,
isPublic:false,
appType:"web",
}).then(app=>{
const User=db.models.user;
User.create({owner_id:settings.platformid,userName:"sm",password:md5("123"+ "_" + settings.salt),isSuper:true,isAdmin:true,isEnabled:true,nickName:"superman"}).then(function(u){
app.setCreator(u);
u.setApp(app);
Account.create({nickName:"superman",userName:"sm",password:md5("123")}).then(function(ac){
u.setAccount(ac);
});
//设置当前平台初始的租户,并默认设置当前租户所其用的APP
Company.create({name:"蜂擎云服科技有限公司"}).then(async function(cmp){
await u.addCompany(cmp,{through:{isCurrent:false}});
await cmp.addApp(app);
Role.bulkCreate([
{ name:"租户",code:"common",isSystem:1,app_id:app.id,company_id:cmp.id},
{ name:"路过",code:"pass",isSystem:1,app_id:app.id,company_id:cmp.id},
]);
});
//设置当前初始租户所开启的应用
//初始化平台的租户权限
Auth.create({
rolecode:"common",
bizcode:"companyinfo",
codepath:"paasroot/tanentCenter/appMag/companyinfo",
authstrs:"add,edit,delete",
app_id:1,
company_id:1
});
});
});
//创建role
// if(settings.env=="prod"){
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
// }
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
});
module.exports={
"bizName":"allapps",
"list":{
columnMetaData:[
{"width":"230","label":"应用KEY","prop":"appkey","isShowTip":true,"isTmpl":false},
{"width":"200","label":"应用类型","prop":"appType","isShowTip":true,"isTmpl":false},
{"width":"200","label":"是否公共服务","prop":"isCommon","isShowTip":true,"isTmpl":false},
{"width":"100","label":"应用名称","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"200","label":"应用密钥","prop":"secret","isShowTip":true,"isTmpl":false},
{"width":"200","label":"是否启用","prop":"isEnabled","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":"true"},
]
},
"form":[
{
"title":"应用控制",
"colnum":2,
"ctls":[
{"type":"switch","label":"是否启用","prop":"isEnabled","acText":"启用","inactText":"停用","placeHolder":"","style":""},
{"type":"switch","label":"是否公共服务","prop":"isCommon","acText":"是","inactText":"否","placeHolder":"","style":""},
{"type":"switch","label":"是否对外","prop":"isPublic","acText":"是","inactText":"否","placeHolder":"","style":""},
{ "type": "select", "label": "应用类型", "dicKey": "app_type", "prop": "appType", "labelField": "label", "valueField": "value", "placeHolder": "请选择支付类型", "style": "" },
// {"type":"switch","label":"启用多租户","prop":"isSaas","acText":"启用","inactText":"停用","placeHolder":"","style":""},
]
},
{
"title":"概要介绍",
"colnum":1,
"ctls":[
{ "type": "textarea", "label": "简介", "prop": "description", "placeHolder": "请输入产品简介", "style": "width:600px" }
]
},
{
"title":"基本信息",
"colnum":3,
"ctls":[
{"type":"input","label":"应用KEY","prop":"appkey","disabled":true,"placeHolder":"","style":""},
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
{"type":"input","label":"应用密钥","prop":"secret","disabled":true,"placeHolder":"","style":""},
{"type":"input","label":"域名","prop":"domainName","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"首页","prop":"homePage","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"认证URL","prop":"authUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"文档URL","prop":"docUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"配置URL","prop":"uiconfigUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"缓存操作URL","prop":"opCacheUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"接受API调用计数URL","prop":"notifyCacheCountUrl","disabled":false,"placeHolder":"","style":""},
]
},
{
"title":"个性化信息",
"colnum":2,
"ctls":[
{"type":"upload","label":"logo","prop":"logoUrl","disabled":false,"placeHolder":"","style":""},
{"type":"upload","label":"背景图","prop":"bkimageUrl","placeHolder":"应用名称","style":""},
{"type":"upload","label":"缩略图","prop":"showimgUrl","disabled":false,"placeHolder":"","style":"width:100px;height:100px"},
{"type":"upload","label":"细节图","prop":"detailimgUrl","disabled":false,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
// {"icon":"el-icon-edit","title":"管理员","type":"default","key":"adminModi","isInRow":true},
// {"icon":"el-icon-edit","title":"重置密码","type":"default","key":"resetpwd","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"list":{
columnMetaData:[
{"width":"100","label":"昵称","prop":"nickName","isShowTip":true,"isTmpl":false},
{"width":"100","label":"登录账号","prop":"userName","isShowTip":true,"isTmpl":false},
{"width":"100","label":"角色","prop":"Roles","isShowTip":true,"isTmpl":false},
{"width":"80","label":"状态","prop":"isEnabled","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":true},
]
},
"form":[
{
"title":"控制信息",
ctls:[
{"type":"switch","prop":"isAdmin","acText":"是管理员","inactText":"否","placeHolder":"请输入单次使用消耗的宝币数","style":""},
// {"type":"select","refModel":"pmproduct","isMulti":false,"label":"所属产品","prop":"pmproduct_id","labelField":"name","valueField":"id","style":""},
]
},
{
"title":"基本信息",
ctls:[
{"type":"input","label":"账号","prop":"userName","placeHolder":"登录账号","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"昵称","prop":"nickName","placeHolder":"昵称","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"电话","prop":"mobile","placeHolder":"请输入电话","style":"",rules:[ { "validator":"validatex","trigger": 'blur' },{ "required": true, "message": ' ', "trigger": 'blur' },]},
// {"type":"select","refModel":"auth.role","isMulti":true,"label":"角色","prop":"roles","labelField":"name","valueField":"id","style":""},
]
}
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"昵称","prop":"nickName","placeHolder":"请输入昵称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
{"icon":"el-icon-edit","title":"停用","type":"default","key":"stopUser","isInRow":true,"boolProp":"isEnabled","falseText":"启用"},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"bizName":"appconfig",
"list":{
columnMetaData:[
{"width":"100","label":"配置名称","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"200","label":"配置类型","prop":"configType","isShowTip":true,"isTmpl":false},
{"width":"200","label":"配置内容","prop":"configValue","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":"true"},
]
},
"form":[
{
"title":"配置信息",
"colnum":2,
"ctls":[
{"type":"select","label":"配置类型","dicKey":"configType","prop":"configType","labelField":"label","valueField":"value","placeHolder":"","style":""},
{"type":"input","label":"配置内容","prop":"configValue","disabled":false,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"select","label":"配置类型","dicKey":"configType","prop":"configType","labelField":"label","valueField":"value","placeHolder":"","style":""},
{"type":"input","label":"配置名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"list":{
columnMetaData:[
{"width":"100","label":"编码","prop":"code","isShowTip":true,"isTmpl":false},
{"width":"200","label":"名称","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"200","label":"是否系统角色","prop":"isSystem","isShowTip":true,"isTmpl":false},
{"width":"200","label":"描述","prop":"description","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":true},
]
},
"form":[
{
"title":"基本信息",
"column":1,
ctls:[
{"type":"input","label":"编码","prop":"code","placeHolder":"请输入一个编码","style":"",rules:[ { "required": true, "message": '请选择产品大类', "trigger": 'blur' },]},
{"type":"input","label":"名称","prop":"name","placeHolder":"请输入一个名称","style":"",rules:[ { "required": true, "message": '请选择产品大类', "trigger": 'blur' },]},
{"type":"input","label":"描述","prop":"description","placeHolder":"描述","style":"",rules:[ { "required": true, "message": '请选择产品大类', "trigger": 'blur' },]},
]
},
],
"search":[
{
"title":"高级查询",
ctls:[
{"type":"input","label":"名称","prop":"name","placeHolder":"请输入角色名称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-edit","title":"授权","type":"default","key":"auth","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"list":{
columnMetaData:[
{"width":"100","label":"昵称","prop":"nickName","isShowTip":true,"isTmpl":false},
{"width":"100","label":"登录账号","prop":"userName","isShowTip":true,"isTmpl":false},
{"width":"100","label":"角色","prop":"Roles","isShowTip":true,"isTmpl":false},
{"width":"50","label":"状态","prop":"isEnabled","isShowTip":true,"isTmpl":false},
{"width":"300","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":true},
]
},
"form":[
{
"title":"控制信息",
ctls:[
{"type":"switch","prop":"isAdmin","acText":"是管理员","inactText":"否","placeHolder":"请输入单次使用消耗的宝币数","style":""},
// {"type":"select","refModel":"auth.role","isMulti":true,"label":"角色","prop":"roles","labelField":"name","valueField":"id","style":""},
// {"type":"select","refModel":"pmproduct","isMulti":false,"label":"所属产品","prop":"pmproduct_id","labelField":"name","valueField":"id","style":""},
]
},
{
"title":"基本信息",
ctls:[
{"type":"input","label":"账号","prop":"userName","placeHolder":"登录账号","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"昵称","prop":"nickName","placeHolder":"昵称","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"电话","prop":"mobile","placeHolder":"请输入电话","style":"",rules:[ { "validator":"validatex","trigger": 'blur' },{ "required": true, "message": ' ', "trigger": 'blur' },]},
]
}
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"昵称","prop":"nickName","placeHolder":"请输入昵称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-edit","title":"岗位变更","type":"default","key":"positionChange","isInRow":true},
{"icon":"el-icon-edit","title":"数据授权","type":"default","key":"datapriv","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
{"icon":"el-icon-edit","title":"停用","type":"default","key":"stopUser","isInRow":true,"boolProp":"isEnabled","falseText":"启用"},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"bizName":"cachearches",
"list":{
columnMetaData:[
{"width":"300","label":"缓存键","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"300","label":"缓存说明","prop":"val","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":"true"},
]
},
"form":[
],
"search":[
{
"title":"键名称",
ctls:[
{"type":"input","label":"键名称","prop":"name","placeHolder":"键名称","style":""},
]
},
],
"auth":{
"add":[
],
"edit":[
{"icon":"el-icon-edit","title":"清空所有缓存","type":"default","key":"clearAll","isOnGrid":true},
{"icon":"el-icon-edit","title":"使失效","type":"default","key":"invalidate","isInRow":true},
],
"delete":[
],
"common":[
],
}
}
module.exports={
"bizName":"allapps",
"list":{
columnMetaData:[
{"width":"230","label":"名称","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"100","label":"是否当前公司","prop":"isCurrent","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":"true"},
]
},
"form":[
{
"title":"基本信息",
"colnum":2,
"ctls":[
{"type":"input","label":"公司名称","prop":"name","placeHolder":"请输入公司名称","style":"width:300px",rules:[{ "required": true, "message": " ", "trigger": 'blur' }]},
{"type":"input","label":"信用代码","prop":"creditCode","placeHolder":"应用名称","style":""},
{"type":"upload","label":"营业执照","prop":"licenseUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"备注","prop":"description","disabled":false,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"公司信息",
ctls:[
{"type":"input","label":"公司名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"设置为当前","type":"default","key":"setcurrent","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"list":{
columnMetaData:[
]
},
"form":[
{
"title":"基本信息",
"colnum":1,
ctls:[
{"type":"input","label":"编码","prop":"code","placeHolder":"输入组织编码","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"input","label":"名称","prop":"name","placeHolder":"输入组织名称","style":"",rules:[ { "required": true, "message": ' ', "trigger": 'blur' },]},
{"type":"switch","label":"是否岗位","targetprop":"Roles,isMain","prop":"isPosition","acText":"是","inactText":"否","placeHolder":"","style":""},
{"type":"select","refModel":"auth.role","defaultHide":true,"isMulti":true,"label":"角色","prop":"Roles","labelField":"name","valueField":"id","style":""},
{"type":"switch","label":"是否负责人岗","defaultHide":true,"prop":"isMain","acText":"是","inactText":"否","placeHolder":"","style":""},
{"type":"btn","label":"保存","prop":"btnLogin","placeHolder":"保存","style":{"width":"150px","margin-left":"100px","margin-top":"20px"},"face":"warning"},
]
}
],
"search":[
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-edit","title":"数据授权","type":"default","key":"datapriv","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
{"icon":"el-icon-edit","title":"停用","type":"default","key":"stopUser","isInRow":true,"boolProp":"isEnabled","falseText":"启用"},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports={
"bizName":"myapps",
"list":{
columnMetaData:[
{"width":"200","label":"应用KEY","prop":"appkey","isShowTip":true,"isTmpl":false},
{"width":"100","label":"应用名称","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"200","label":"应用密钥","prop":"secret","isShowTip":true,"isTmpl":false},
{"width":"200","label":"是否启用","prop":"isEnabled","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":"true"},
]
},
"form":[
{
"title":"应用控制",
"colnum":1,
"ctls":[
{"type":"switch","label":"是否启用","prop":"isEnabled","acText":"启用","inactText":"停用","placeHolder":"","style":""},
]
},
{
"title":"概要介绍",
"colnum":1,
"ctls":[
{ "type": "textarea", "label": "简介", "prop": "description", "placeHolder": "请输入产品简介", "style": "width:600px" }
]
},
{
"title":"基本信息",
"colnum":3,
"ctls":[
{"type":"input","label":"应用KEY","prop":"appkey","disabled":true,"placeHolder":"","style":""},
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
{"type":"input","label":"应用密钥","prop":"secret","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"域名","prop":"domainName","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"首页","prop":"homePage","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"认证URL","prop":"authUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"文档URL","prop":"docUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"配置URL","prop":"uiconfigUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"缓存操作URL","prop":"opCacheUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"接受API调用计数URL","prop":"notifyCacheCountUrl","disabled":false,"placeHolder":"","style":""},
]
},
{
"title":"个性化信息",
"colnum":2,
"ctls":[
{"type":"upload","label":"logo","prop":"logoUrl","disabled":false,"placeHolder":"","style":""},
{"type":"upload","label":"背景图","prop":"bkimageUrl","placeHolder":"应用名称","style":""},
{"type":"upload","label":"缩略图","prop":"showimgUrl","disabled":false,"placeHolder":"","style":"width:100px;height:100px"},
{"type":"upload","label":"细节图","prop":"domainName","disabled":false,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-plus","title":"新增","type":"default","key":"new","isOnGrid":true},
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-edit","title":"管理员","type":"default","key":"adminModi","isInRow":true},
{"icon":"el-icon-edit","title":"重置密码","type":"default","key":"resetpwd","isInRow":true},
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
const fs=require("fs");
const path=require("path");
const appsPath=path.normalize(__dirname+"/apps");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
}
function getBizFilePath(appJson,bizCode){
const filePath=bizsPath+"/"+appJson.appid+"/"+bizCode+".js";
return filePath;
}
//异常日志处理todo
function initAppBizs(appJson){
for(var bizCode in appJson.config.bizs)
{
const bizfilePath=getBizFilePath(appJson,bizCode);
try{
delete require.cache[bizfilePath];
const bizConfig=require(bizfilePath);
appJson.config.bizs[bizCode].config=bizConfig;
}catch(e){
console.log("bizconfig meta file not exist........");
}
}
return appJson;
}
//初始化资源树--objJson是rstree
function initRsTree(appjson,appidfolder,objJson,parentCodePath){
if(!parentCodePath){//说明当前是根结点
objJson.codePath=objJson.code;
}else{
objJson.codePath=parentCodePath+"/"+objJson.code;
}
if(objJson["bizCode"]){//表示叶子节点
objJson.auths=[];
if(appjson.config.bizs[objJson["bizCode"]]){
objJson.bizConfig=appjson.config.bizs[objJson["bizCode"]].config;
objJson.path=appjson.config.bizs[objJson["bizCode"]].path;
appjson.config.bizs[objJson["bizCode"]].codepath=objJson.codePath;
}
}else{
if(objJson.children){
objJson.children.forEach(obj=>{
initRsTree(appjson,appidfolder,obj,objJson.codePath);
});
}
}
}
fs.readdirSync(appsPath).forEach(f=>{
const ff=path.join(appsPath,f);
delete require.cache[ff];
var appJson=require(ff);
appJson= initAppBizs(appJson);
initRsTree(appJson,appJson.appid,appJson.config.rstree,null);
appJsons[appJson.appid]=appJson;
});
module.exports=appJsons;
module.exports={
"appid":"wx76a324c5d201d1a4",
"label":"企业服务工具箱",
"config":{
"rstree":{
"code":"toolroot",
"label":"工具箱",
"children":[
{
"code":"toggleHeader",
"icon":"el-icon-sort",
"isMenu":true,
"label":"折叠",
},
{
"code":"personCenter",
"label":"个人信息",
"src":"/imgs/logo.png",
"isSubmenu":true,
"children":[
{"code":"wallet","isGroup":true,"label":"账户","children":[
{"code":"mytraderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"path":""},
{"code":"smallmoney","label":"钱包","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"fillmoney","label":"充值","isMenu":true,},
]},
{"code":"tool","isGroup":true,"label":"工具","children":[
{"code":"entconfirm","label":"企业用户认证","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"fav","label":"收藏夹","isMenu":true,"bizCode":"fav","bizConfig":null,"path":""},
{"code":"filebox","label":"文件柜","isMenu":true,"bizCode":"filebox","bizConfig":null,"path":""},
]},
],
},
{
"code":"fillmoney",
"icon":"fa fa-money",
"isMenu":true,
"label":"充值",
},
{
"code":"platformop",
"label":"平台运营",
"icon":"fa fa-cubes",
"isSubmenu":true,
"children":[
{"code":"papp","isGroup":true,"label":"平台数据","children":[
{"code":"papparch","label":"应用档案","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"userarch","label":"用户档案","isMenu":true,"bizCode":"pusers","bizConfig":null,"path":""},
{"code":"traderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"qp":"my","path":""},
{"code":"pconfigs","label":"平台配置","isMenu":true,"bizCode":"pconfigs","bizConfig":null,"qp":"my","path":""},
]},
{"code":"pop","isGroup":true,"label":"平台运维","children":[
{"code":"cachearch","label":"缓存档案","isMenu":true,"bizCode":"cachearches","bizConfig":null,"path":""},
{"code":"oplogmag","label":"行为日志","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"machinearch","label":"机器档案","isMenu":true,"bizCode":"machines","bizConfig":null,"path":""},
{"code":"codezrch","label":"代码档案","isMenu":true,"bizCode":"codezrch","bizConfig":null,"path":""},
{"code":"imagearch","label":"镜像档案","isMenu":true},
{"code":"containerarch","label":"容器档案","isMenu":true},
]},
],
},
{
"code":"sysmag",
"label":"系统管理",
"icon":"fa fa-cube",
"isSubmenu":true,
"children":[
{"code":"usermag","isGroup":true,"label":"用户管理","children":[
{"code":"rolearch","label":"角色档案","isMenu":true,"bizCode":"roles","bizConfig":null},
{"code":"appuserarch","label":"用户档案","isMenu":true,"bizCode":"appusers","bizConfig":null},
]},
{"code":"productmag","isGroup":true,"label":"产品管理","children":[
{"code":"productarch","label":"产品档案","bizCode":"mgproducts","isMenu":true,"bizConfig":null},
{"code":"products","label":"首页产品档案","bizCode":"products","isMenu":false,"bizConfig":null},
]},
],
},
{
"code":"exit",
"icon":"fa fa-power-off",
"isMenu":true,
"label":"退出",
},
{
"code":"toolCenter",
"label":"工具集",
"src":"/imgs/logo.png",
"isSubmenu":false,
"isMenu":false,
"children":[
{"code":"tools","isGroup":true,"label":"查询工具","children":[
{"code":"xzquery","label":"续展查询","bizCode":"xzsearch","bizConfig":null,"path":""},
{"code":"xzgqquery","label":"续展过期查询","bizCode":"xzgqsearch","bizConfig":null,"path":""},
]},
],
},
],
},
"bizs":{
"cachearches":{"title":"首页产品档案","config":null,"path":"/platform/cachearches","comname":"cachearches"},
"products":{"title":"首页产品档案","config":null,"path":"/","comname":"products"},
"mgproducts":{"title":"产品档案","config":null,"path":"/platform/mgproducts","comname":"mgproducts"},
"codezrch":{"title":"代码档案","config":null,"path":"/platform/codezrch","comname":"codezrch"},
"machines":{"title":"机器档案","config":null,"path":"/platform/machines","comname":"machines"},
"pconfigs":{"title":"平台配置","config":null,"path":"/platform/pconfigs","comname":"pconfigs"},
"apps":{"title":"应用档案","config":null,"path":"/platform/apps","comname":"apps"},
"roles":{"title":"角色档案","config":null,"path":"/platform/roles","comname":"roles"},
"pusers":{"title":"平台用户档案","config":null,"path":"/platform/pusers","comname":"users"},
"appusers":{"title":"某应用用户档案","config":null,"path":"/platform/appusers","comname":"users"},
"oplogs":{"title":"行为日志","config":null,"path":"/platform/op/oplogs","comname":"oplogs"},
"trades":{"title":"交易记录","config":null,"path":"/platform/uc/trades","comname":"trades"},
"xzsearch":{"title":"续展查询","config":null,"isDynamicRoute":true,"path":"/products/xzsearch","comname":"xzsearch"},
"xzgqsearch":{"title":"续展过期查询","config":null,"isDynamicRoute":true,"path":"/products/xzgqsearch","comname":"xzgqsearch"},
},
"pauths":[
"add","edit","delete","export","show"
],
"pdict":{
"sex":{"male":"男","female":"女"},
"configType":{"price":"宝币兑换率","initGift":"初次赠送"},
"productCata":{"ip":"知产","ic":"工商","tax":"财税","hr":"人力","common":"常用"},
"logLevel":{"debug":0,"info":1,"warn":2,"error":3,"fatal":4},
"tradeType":{"fill":"充值","consume":"消费","gift":"赠送","giftMoney":"红包","refund":"退款"},
"tradeStatus":{"unSettle":"未结算","settled":"已结算"}
}
}
}
module.exports = (db, DataTypes) => {
return db.define("auth", {
rolecode: DataTypes.STRING,
bizcode: DataTypes.STRING,
codepath: DataTypes.STRING,
authstrs: DataTypes.STRING
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_auths',
validate: {
}
});
}
module.exports = (db, DataTypes) => {
return db.define("dataauth", {
modelname: DataTypes.STRING,
auths: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_dataauths',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("org", {
code: {
type:DataTypes.STRING(64),
allowNull: false,
},
name: {
type:DataTypes.STRING(64),
allowNull: false,
},
isLeaf:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
orgpath: {
type:DataTypes.STRING,
allowNull: false,
},
nodeType: {//默认为组织
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.node_type),
defaultValue:'org'
},
isPosition:{//是否是岗位
type:DataTypes.BOOLEAN,
defaultValue: false
},
isMain:{//是否是主岗
type:DataTypes.BOOLEAN,
defaultValue: false
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_org',
validate: {
}
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("orgrole", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_orgrole',
validate: {
},
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("role", {
name: DataTypes.STRING,
code: DataTypes.STRING,
description: DataTypes.STRING,
isSystem: {//是否系统数据,0否,1是
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_role',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("user", {
userName: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
nickName: {
type:DataTypes.STRING,
allowNull: true,
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
mobile:DataTypes.STRING,
mail: {
type:DataTypes.STRING,
allowNull: true,
},
headUrl: DataTypes.STRING,
isAdmin:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
isSuper:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
app_id:DataTypes.INTEGER,
account_id:DataTypes.INTEGER,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
opath:DataTypes.STRING,//作业务时,需要在业务表冗余当前处理人的opath
ppath:DataTypes.STRING,//权限路径,主岗下的人大于opath一级,查询时按照opath去查询
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_user',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("account", {
nickName: {
type:DataTypes.STRING(128),
allowNull: true,
},
userName:DataTypes.STRING,
password: {
type:DataTypes.STRING,
validate: {
// length(value){
// if(value.length<6){
// throw new Error("lenght。。。")
// }
// }
}
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
headUrl: DataTypes.STRING,
mobile: DataTypes.STRING,
baoBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
renBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_account',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("apitrade", {
tradeType: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.tradeType),
},
op:{//访问路径
type:DataTypes.STRING,
allowNull: true,
},
srcappkey:{//
type:DataTypes.STRING,
allowNull: true,
},
destappkey:{//
type:DataTypes.STRING,
allowNull: true,
},
params:{
type:DataTypes.STRING(1024),
allowNull: true,
},
clientIp:DataTypes.STRING,
agent:{
type:DataTypes.STRING,
allowNull: true,
},
isAllowed:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
amount: {//每条多少钱
type:DataTypes.INTEGER ,
allowNull: false,
defaultValue: 0
},
desc:DataTypes.STRING,//比如前500条免费
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt:false,
//freezeTableName: true,
// define the table's name
tableName: 'api_trade',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("app", {
appkey: DataTypes.STRING,//需要在后台补充
secret: DataTypes.STRING,//需要在后台补充
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
domainName: DataTypes.STRING,//域名
homePage: DataTypes.STRING,//首页
authUrl: DataTypes.STRING,//认证地址
docUrl: DataTypes.STRING,//接口文档地址
uiconfigUrl: DataTypes.STRING,//基础信息配置信息地址
logoUrl: DataTypes.STRING,//应用Logo
bkimageUrl: DataTypes.STRING,//应用背景图
showimgUrl: DataTypes.STRING,//应用显示图标
detailimgUrl: DataTypes.STRING,//应用详情介绍地址
opCacheUrl: DataTypes.STRING,//操作缓存地址
notifyCacheCountUrl: DataTypes.STRING,//接收API使用计数的通知URL
description: DataTypes.STRING,//应用描述
isSaas: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},//是否启用
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否启用
isPublish: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
isCommon: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否公共服务
appType: {
type: DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.app_type),
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_app',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("company", {
name: {
type:DataTypes.STRING,
allowNull: false,
},
creditCode: {
type:DataTypes.STRING,
allowNull: true,
},
licenseUrl: DataTypes.STRING,
description: DataTypes.STRING,
companykey:{
type:DataTypes.STRING,
allowNull: true,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_company',
validate: {
},
});
}
module.exports = (db, DataTypes) => {
return db.define("companyapp", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_companyapp',
validate: {
},
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("oplog", {
appkey: {
type:DataTypes.STRING,
allowNull: true,
},
appname:{
type:DataTypes.STRING,
allowNull: false,
},
userid: { type: DataTypes.INTEGER,allowNull: true},
username:{
type:DataTypes.STRING,
allowNull: true,
},
logLevel: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.logLevel),
defaultValue: "info",
},
op:{
type:DataTypes.STRING,
allowNull: true,
},
content:{
type:DataTypes.STRING(4000),
allowNull: true,
},
clientIp:DataTypes.STRING,
agent:{
type:DataTypes.STRING,
allowNull: true,
},
opTitle:DataTypes.STRING(500),
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt:false,
//freezeTableName: true,
// define the table's name
tableName: 'op_log',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("paccount", {
baoBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
renBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'pp_account',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
const enums={
price:"宝币兑换率",
initGift:"初次赠送",
apiCallPrice:"API调用价格",
apiInitGift:"API初次赠送次数",
logOpWrite:"操作日志步骤是否写入,0否,1是",
}
var PConfig=db.define("pconfig", {
name: {
type:DataTypes.STRING,
allowNull: false,
// get(){
// const ctype = this.getDataValue("configType");
// return enums[ctype];
// }
},
configType: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(enums),
set:function(val){
this.setDataValue("name",enums[val]);
this.setDataValue("configType",val);
}
},
configValue: {
type:DataTypes.STRING,
allowNull: false,
},
appkey: {
type:DataTypes.STRING,
allowNull: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_config',
validate: {
},
});
PConfig.enums=enums;
return PConfig;
}
module.exports = (db, DataTypes) => {
return db.define("task", {
app_id:DataTypes.STRING,//需要在后台补充
taskClassName: {
type:DataTypes.STRING(100),
allowNull: false,
unique: true
},//和user的from相同,在注册user时,去创建
taskexp: {
type:DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
desc:DataTypes.STRING,//需要在后台补充
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_task',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("usercompany", {
isCurrent: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_usercompany',
validate: {
},
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("msghistory", {
msgType:{
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.msgType),
},
sender:DataTypes.STRING,
senderId:DataTypes.INTEGER,
target:DataTypes.STRING,
targetId:DataTypes.INTEGER,
content: {
type: DataTypes.TEXT('long'),
allowNull: false,
},//需要在后台补充
isRead:{//分享时是否渠道店铺名称,0否,1是
type:DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msghistory',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("msgnotice", {
fromuser: DataTypes.STRING,//需要在后台补充
fromId:DataTypes.INTEGER,
touser: DataTypes.STRING,//需要在后台补充
toId:DataTypes.INTEGER,
businessLicense_id:DataTypes.INTEGER,
//"onlineset"+"¥"+data.appkey:[uk+"¥"+data.nickName+"¥"+data.imgUrl] uk=appid¥uid
isAccepted:DataTypes.BOOLEAN,
lastMsgId:DataTypes.INTEGER,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msgnotice',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment