Commit 7b46dfb2 by 蒋勇

d

parent 5ced773c
node_modules/
\ No newline at end of file
#!/bin/bash #!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang2/node105:v2 FROM kong:2.0
MAINTAINER jy "jiangyong@gongsibao.com" MAINTAINER jy "jiangyong@gongsibao.com"
ADD center-manage /apps/center-manage/ RUN rm -rf /usr/local/share/lua/5.1/kong/plugins/jwt
WORKDIR /apps/center-manage/ ADD kong/kong/plugins/jwt /usr/local/share/lua/5.1/kong/plugins/jwt/
RUN cnpm install -S
CMD ["node","/apps/center-manage/main.js"]
......
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
const system = require("../system");
const uuidv4 = require('uuid/v4');
const settings = require("../../config/settings");
class APIBase{
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
}
async doexec(gname, methodname, pobj, query, req) {
try {
console.log("**********************************************")
console.log(req.headers)
let custtags=req.headers["x-consumetag"].split("|");
req.xctx={
appkey:req.headers["x-appkey"],
companyid:custtags[0].split("_")[1],
password:custtags[1].split("_")[1],
username:req.headers["x-consumer-username"],
credid:req.headers["x-credential-identifier"]
}
var rtn = await this[methodname](pobj, query, req);
return rtn;
} catch (e) {
console.log(e.stack, "api调用异常--error...................");
var rtnerror = system.getResultFail(-200, "出现异常,请联系管理员");
return rtnerror;
}
}
}
module.exports = APIBase;
const system = require("../system");
const uuidv4 = require('uuid/v4');
class DocBase {
constructor() {
this.apiDoc = {
group: "逻辑分组",
groupDesc: "",
name: "",
desc: "请对当前类进行描述",
exam: "概要示例",
methods: []
};
this.initClassDoc();
}
initClassDoc() {
this.descClass();
this.descMethods();
}
descClass() {
var classDesc = this.classDesc();
this.apiDoc.group = classDesc.groupName;
this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc);
this.apiDoc.name = classDesc.name;
this.apiDoc.desc = this.examDescHtml(classDesc.desc);
this.apiDoc.exam = this.examHtml();
}
examDescHtml(desc) {
// var tmpDesc = desc.replace(/\\/g, "<br/>");
return desc;
}
examHtml() {
var exam = this.exam();
exam = exam.replace(/\\/g, "<br/>");
return exam;
}
exam() {
throw new Error("请在子类中定义类操作示例");
}
classDesc() {
throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构
{
groupName:"auth",
groupDesc:"认证相关的包"
desc:"关于认证的类",
exam:"",
}
`);
}
descMethods() {
var methoddescs = this.methodDescs();
for (var methoddesc of methoddescs) {
for (var paramdesc of methoddesc.paramdescs) {
this.descMethod(methoddesc.methodDesc, methoddesc.methodName
, paramdesc.paramDesc, paramdesc.paramName, paramdesc.paramType,
paramdesc.defaultValue, methoddesc.rtnTypeDesc, methoddesc.rtnType);
}
}
}
methodDescs() {
throw new Error(`
请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[
{
methodDesc:"生成访问token",
methodName:"getAccessKey",
paramdescs:[
{
paramDesc:"访问appkey",
paramName:"appkey",
paramType:"string",
defaultValue:"x",
},
{
paramDesc:"访问secret",
paramName:"secret",
paramType:"string",
defaultValue:null,
}
],
rtnTypeDesc:"xxxx",
rtnType:"xxx"
}
]
`);
}
descMethod(methodDesc, methodName, paramDesc, paramName, paramType, defaultValue, rtnTypeDesc, rtnType) {
var mobj = this.apiDoc.methods.filter((m) => {
if (m.name == methodName) {
return true;
} else {
return false;
}
})[0];
var param = {
pname: paramName,
ptype: paramType,
pdesc: paramDesc,
pdefaultValue: defaultValue,
};
if (mobj != null) {
mobj.params.push(param);
} else {
this.apiDoc.methods.push(
{
methodDesc: methodDesc ? methodDesc : "",
name: methodName,
params: [param],
rtnTypeDesc: rtnTypeDesc,
rtnType: rtnType
}
);
}
}
}
module.exports = DocBase;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class AccessAuthAPI extends APIBase {
constructor() {
super();
this.appS = system.getObject("service.common.appSve");
this.apitradeSvr = system.getObject("service.common.apitradeSve");
this.authUtils = system.getObject("util.businessManager.authUtils");
this.userSve = system.getObject("service.auth.userSve");
}
//不从平台应用列表入口登录时
//先要调用平台登录接口
//返回token,利用这个token再去登录某个具体APP
//会话存储具体APP的用户信息
//每个前端应用打开时,先检查是否存在token
//如果存在,就去访问获取用户信息,---调用本接口--即刻
//进入或登录某个具体应用
//前提是已经具备了统一管理的账号,并且已经在统一管理账号登录,客户端具备了token
//进入某个具体应用时,需要指定 x-appkey请求头
//
async loginToApp(p,q,req){
let appkey=req.xctx.appkey;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
{
methodDesc: "生成访问token,访问地址:http://......../api/auth/accessAuth/getAccessKey,访问token需要放置到后续API方法调用的请求头中",
methodName: "getAccessKey",
paramdescs: [
{
paramDesc: "访问appkey",
paramName: "appkey",
paramType: "string",
defaultValue: "",
},
{
paramDesc: "访问secret",
paramName: "secret",
paramType: "string",
defaultValue: "",
}
],
rtnTypeDesc: "返回JSON对象字符串",
rtnType: "json object {accessKey: xxxxxx, app: {xxx:xxx}},注意app,是当前app信息,详细见后面示例"
},
];
}
exam() {
return ``
}
}
module.exports = AccessAuthAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class RoleAuthAPI extends APIBase {
constructor() {
super();
this.authS=system.getObject("service.auth.authSve");
}
async findAuthsByRole(p,q,req){
var tmpRoles=p.roles;
var appid=p.appid;
var comid=p.companyid;
var auths=await this.authS.findAuthsByRole(tmpRoles,appid,comid);
return system.getResult(auths);
}
exam(){
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "角色授权相关的API",
name: "RoleAuthAPI",
desc: "角色授权相关的API",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "按照角色获取权限,访问地址:/api/auth/roleAuth/findAuthsByRole",
methodName: "findAuthsByRole",
paramdescs: [
{
paramDesc: "应用的ID",
paramName: "appid",
paramType: "int",
defaultValue: "x",
},
{
paramDesc: "角色列表",
paramName: "roles",
paramType: "array",
defaultValue: null,
}
],
rtnTypeDesc: "逗号分隔的",
rtnType: "string"
}
];
}
}
module.exports = RoleAuthAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class AppAPI extends APIBase {
constructor() {
super();
this.appS = system.getObject("service.common.appSve");
}
async create(pobj,q,req){
// console.log("oooooooooooooooooooooooooooooooooooooooooooooooo")
// console.log(req.xctx)
let rtn=this.appS.create(pobj,q,req);
return system.getResult(rtn);
}
async del(pobj,q,req){
let rtn=this.appS.delete(pobj,q,req);
return system.getResult(rtn);
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
];
}
exam() {
return ``
}
}
module.exports = AppAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var 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 upline(pobj, gobj, req){
console.log("......................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...");
console.log(JSON.stringify(pobj));
console.log("......................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...");
return system.getResult(pobj);
}
async clearAllCache(pobj, gobj, req) {
return await this.cachsearchesSve.clearAllCache(pobj);
}
async getBaseComp() {
if (cacheBaseComp) {
return system.getResult(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 = { basecom: baseComps };
return system.getResult(cacheBaseComp);
}
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");
}
static getServiceName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async setContextParams(pobj, qobj, req) {
req.xctx={
appkey:req.headers["x-appkey"],
}
}
async doexec(methodname, pobj, query, req) {
try {
await this.setContextParams(pobj, query, req);
//从请求头里面取appkey_consumename
// var consumeName=req.headers[""]
// var appkey=
// if( this.session["appkey_consumename"]) {
// }else{
// //从头里取,从redis中取出缓存对象赋值到控制基类的session属性
// //appkey_consumename
// this.session={};
// }
//req.session=redis缓存的上下文对象
var rtn = await this[methodname](pobj, query, req);
return rtn;
} catch (e) {
console.log(e.stack, "出现异常,请联系管理员.......");
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.tocompanyid);
return system.getResult(xrtn);
}
async findAuthsByRole(qobj,query,req){
var rolecodestrs=qobj.rolecode;
var xrtn=await this.service.findAuthsByRole(rolecodestrs,req.appid,req.tocompanyid);
return system.getResult(xrtn);
}
}
module.exports=AuthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class DataauthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(DataauthCtl));
}
async saveauth(qobj,querybij,req){
var arys=qobj.arys;
var uid=qobj.uid;
var refmodel=qobj.modelname;
var u=await this.service.saveauth({
user_id:uid,
modelname:refmodel,
auths:arys.join(","),
app_id:req.appid,
});
return system.getResult(u);
}
async fetchInitAuth(qobj,querybij,req){
var uid=qobj.uid;
var refmodel=qobj.modelname;
var authtmp=await this.service.findOne({user_id:uid,modelname:refmodel,app_id:req.appid});
if(authtmp){
var auths= authtmp.auths;
var arys=auths.split(",");
return system.getResult(arys);
}else{
return system.getResultSuccess([]);
}
}
}
module.exports=DataauthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class OrgCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(OrgCtl));
this.compSvr=system.getObject("service.common.companySve");
}
//检查是否已经存在主要岗位
async checkMainPosition(p,q,req){
return this.service.checkMainPosition(p,q,req);
}
async changePos(p,q,req){
var toorgid=p.orgid;
var uid=p.uid;
var rtn= await this.service.changePos(toorgid,uid);
return system.getResult(rtn);
}
async create(p,q,req){
return super.create(p,q,req);
}
async delete(p,q,req){
return super.delete(p,q,req);
}
async update(p,q,req){
return super.update(p,q,req);
}
async initOrgs(p,q,req){
var tocompany=req.session.tocompany;
var cmkey=p.comkey;
if(cmkey){
tocompany =await this.compSvr.findOne({companykey:cmkey});
}
//按照公司名称查询,是否存在节点,不存在,就创建根节点
//如果存在就按照名称查询出当前和她的字节点
var rtn=await this.service.initOrgs(tocompany,req.appid);
return system.getResult(rtn);
}
async findOrgById(p,q,req){
var rtn=await this.service.findOrgById(p.id);
return system.getResult(rtn);
}
}
module.exports=OrgCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class RoleCtl extends CtlBase {
constructor() {
super("auth",CtlBase.getServiceName(RoleCtl));
//this.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");
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
}
async initNewInstance(queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
//获取验证码,发送给指定手机
async sendVCode(pobj, qobj, req) {
var mobile = pobj.mobile;
let v=await this.smsS.sendVCode(mobile);
return system.getResult({ vcodestr: v });
}
async exit(pobj, qobj, req) {
}
async pmregister(pobj, qobj, req) {
//平台注册设置平台的应用ID
pobj.app_id=settings.pmappid;
var rtn=await this.service.pmregister(pobj);
return system.getResult(rtn);
}
async create(pobj, queryobj, req) {
var rtn=await this.service.register(pobj);
return system.getResult(rtn);
}
async pmlogin(pobj, qobj, req) {
//平台注册设置平台的应用ID
let rtn=await this.service.pmlogin(pobj, qobj,req);
return system.getResult(rtn);
}
async pmloginByVCode(pobj, qobj, req){
let rtn=this.service.pmloginByVCode(pobj, qobj);
return system.getResult(rtn);
}
async sendVCode(pobj, qobj,req){
let rtn=await this.service.sendVCode(pobj, qobj);
return system.getResult(rtn);
}
}
module.exports = UserCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class AppCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async findAllApps(p,q,req) {
var rtns = await this.service.findAllApps(p.userid);
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 giveupApp(p,q,req){
var comid=p.compid;
var appid=p.appid;
var rtn=await this.service.giveupApp(comid,appid);
return system.getResult(rtn);
}
//设置当前用户选择的公司为当前公司
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,
companykey:cmp.companykey,
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 appconfig = system.getSysConfig();
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(appconfig.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", appconfig.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", appconfig.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
constructor() {
this.redisClient = system.getObject("util.redisClient");
this.desc = this.desc();
this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "sadd_base:cachekey";
this.isdebug = this.isdebug();
}
isdebug() {
return false;
}
desc() {
throw new Error("子类需要定义desc方法,返回缓存描述");
}
prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀");
}
async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) {
return null;
}
if (ex) {
await this.redisClient.setWithEx(cachekey, objvalstr, ex);
} else {
await this.redisClient.set(cachekey, objvalstr);
}
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
return JSON.parse(objvalstr);
} else {
// this.redisClient.setWithEx(cachekey, cacheValue, ex);
return JSON.parse(cacheValue);
}
}
async getCache(inputkey, ex) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null") {
return null;
} else {
if (ex) {
this.redisClient.set(cachekey, cacheValue, ex);
}
return JSON.parse(cacheValue);
}
}
async invalidate(inputkey) {
const cachekey = this.prefix + inputkey;
this.redisClient.delete(cachekey);
return 0;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串");
}
}
module.exports = CacheBase;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class CacheLocker extends CacheBase{
constructor(){
super();
this.prefix="locker_";
}
desc(){
}
prefix(){
}
async init(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
async enter(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpop(key);
}
async release(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
}
module.exports=CacheLocker;
const CacheBase = require("../cache.base");
const system = require("../../system");
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "管理当前缓存的key";
}
prefix() {
return "g_magcache:";
}
async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key);
}
async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value)
}
async keys(p) {
return this.redisClient.keys(p);
}
async get(k) {
return this.redisClient.get(k);
}
async del(k) {
return this.redisClient.delete(k);
}
async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............");
return this.redisClient.flushall();
}
}
module.exports = MagCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class 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;
var tmplCode = val;
var signName = items ? items[0] : "";
var vcode = await this.smsUtil.getUidStr(6, 10);
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) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log( this.model);
return this.model.create(u2, { transaction: t }).then(u => {
return u;
});
} else {
return this.model.create(u2).then(u => {
return u;
});
}
}
static getModelName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery(qobj) {
var w =qobj.refwhere? qobj.refwhere:{};
if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
}
if (qobj.parentinfo) {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
}
//如果需要控制数据权限
if(qobj.datapriv){
w["id"]={ [this.db.Op.in]: qobj.datapriv};
}
if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
return this.model.findAll({ where: w, attributes: qobj.fields });
} else {
return this.model.findAll({ where: w, attributes: qobj.fields });
}
}
async bulkDelete(ids) {
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 AuthDao extends Dao{
constructor(){
super(Dao.getModelName(AuthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=AuthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class DataauthDao extends Dao{
constructor(){
super(Dao.getModelName(DataauthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=DataauthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OrgDao extends Dao{
constructor(){
super(Dao.getModelName(OrgDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=OrgDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class RoleDao extends Dao{
constructor(){
super(Dao.getModelName(RoleDao));
}
async findOne(paramappid,t){
var app= await this.model.findOne({where:{appid:paramappid}},{transaction:t});
return app;
}
extraWhere(obj,w,qc,linkAttrs){
// if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj);
// // w["app_id"]=obj.appid;
// // }
// }
w["app_id"]=obj.appid;
w["company_id"]=obj.tocompanyid;
return w;
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.app,}]};
}
async preUpdate(u){
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
await this.model.update(obj2,{where:{id:obj2.id}});
var role=await this.model.findOne({where:{id:obj2.id}});
return role;
}
async preCreate(u){
return u;
}
async create(u,t){
var self=this;
var u2= await this.preCreate(u);
if(t){
var role= await this.model.create(u2,{transaction: t});
return role;
}else{
var role= await this.model.create(u2);
return role;
}
}
}
module.exports=RoleDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class UserDao extends Dao{
constructor(){
super(Dao.getModelName(UserDao));
}
async getAuths(userid){
var self=this;
return this.model.findOne({
where:{id:userid},
include:[{model:self.db.models.account,attributes:["id","isSuper","referrerOnlyCode"]},
{model:self.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:self.db.models.product,as:"Products",attributes:["id","code"]}
]},
],
});
}
async getUserByUsername(username,appkey,t){
var app=await this.appDao.findOne(appkey);
var tUser=await this.model.findOne({
where:{userName:username,app_id:app.id},
include:[{model:this.db.models.app,raw:true},
// {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
// "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{model:this.db.models.account,attributes:["id","isSuper","referrerOnlyCode"],raw:true},
{model:this.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:this.db.models.product,as:"Products",attributes:["id","code"],raw:true}
]},
]},{transaction:t});
// if(tUser!=null){
// tUser=tUser.get({plain:true});
// tUser.partnerinfo=await this.partnerinfoDao.model.findOne({where:{onlyCode:tUser.onlyCode},raw:true});
// }
return tUser;
}
async getUserByOpenId(popenid,appkey,t){
var app=await this.appDao.findOne(appkey);
var tUser=await this.model.findOne({
where:{openId:popenid},
include:[{model:this.db.models.app,raw:true},
// {model:this.db.models.partnerinfo,attributes:["id","user_id","app_id","userName","applyType","applyName","workPic","tagInfo","mobile","tel","applyProvince","applyCity",
// "applyArea","applyAddr","identityCardPic","identityCard","businessLicensePic","businessLicenseNum","entName","cardNo","realName"]},
{model:this.db.models.account,attributes:["id","isSuper","referrerOnlyCode"],raw:true},
{model:this.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:this.db.models.product,as:"Products",attributes:["id","code"],raw:true}
]},
]},{transaction:t});
if(tUser!=null){
tUser=tUser.get({plain:true});
tUser.partnerinfo=await this.partnerinfoDao.model.findOne({where:{onlyCode:tUser.onlyCode},raw:true});
}
// console.log("tUser.partnerinfo...................................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>999sy");
// console.log(tUser);
return tUser;
}
async setAccount(user,account,t){
var user=await user.setAccount(account,{transaction: t});
return user;
}
async setApp(user,app,t){
//按照APPId,获取app对象
var user=await user.setApp(app,{transaction: t});
return user;
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.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.tocompanyid;
}
}
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){
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
console.log(u2);
return this.model.create(u2,{transaction: t}).then(user=>{
return user;
});
}else{
return this.model.create(u2).then(user=>{
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId,company_only_code,result){
var customerObj={companyOnlyCode:company_only_code};
var putSqlWhere={where:{id:userId}};
this.updateByWhere(customerObj,putSqlWhere);
return result;
}
}
module.exports=UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const fs=require("fs");
const settings=require("../../../../config/settings");
class CacheManager{
constructor(){
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap(){
var self=this;
self.doc={};
var cachePath=settings.basepath+"/app/base/db/cache/";
const files=fs.readdirSync(cachePath);
if(files){
files.forEach(function(r){
var classObj=require(cachePath+"/"+r);
self[classObj.name]=new classObj();
var refTmp=self[classObj.name];
if(refTmp.prefix){
self.doc[refTmp.prefix]=refTmp.desc;
}
else{
console.log("请在"+classObj.name+"缓存中定义prefix");
}
});
}
}
}
module.exports=CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const Sequelize = require('sequelize');
const settings=require("../../../../config/settings")
const fs=require("fs")
const path=require("path");
var glob = require("glob");
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/";
var models=glob.sync(modelpath+"/**/*.js");
console.log(models.length);
models.forEach(function(m){
console.log(m);
self.db.import(m);
});
console.log("init models....");
}
async initRelations(){
this.db.models.dataauth.belongsTo(this.db.models.user,{constraints: false,});
/*建立用户和角色之间的关系*/
this.db.models.user.belongsToMany(this.db.models.role, {as:"Roles",through: 'p_userrole',constraints: false,});
this.db.models.role.belongsToMany(this.db.models.user, {as:"Users",through: 'p_userrole',constraints: false,});
/*组织机构*/
this.db.models.org.belongsTo(this.db.models.org,{constraints: false,});
this.db.models.org.hasMany(this.db.models.org,{constraints: false,});
//组织机构和角色是多对多关系
this.db.models.org.belongsTo(this.db.models.role,{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,});
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.org.belongsTo(this.db.models.app,{constraints: false,});
this.db.models.auth.belongsTo(this.db.models.app,{constraints: false,});
this.db.models.user.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.role.belongsTo(this.db.models.company, {constraints: false,});
this.db.models.org.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.auth.belongsTo(this.db.models.company,{constraints: false,});
this.db.models.route.belongsTo(this.db.models.app,{constraints: false,});
this.db.models.plugin.belongsTo(this.db.models.app,{constraints: false,});
}
//async getCon(){,用于使用替换table模型内字段数据使用
getCon(){
var that=this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// throw err;
// });
//同步模型
if(settings.env=="dev"){
//console.log(pa);
// pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true}));
// });
// await this.db.models.user.create({nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
// .then(function(user){
// var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
// acc.save().then(a=>{
// user.setAccount(a);
// });
// });
}
return this.db;
}
}
module.exports=DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system=require("../system");
const settings=require("../../config/settings.js");
const reclient=system.getObject("util.redisClient");
const md5 = require("MD5");
//获取平台配置兑换率
//初次登录的赠送数量
//创建一笔交易
//同时增加账户数量,增加系统平台账户
var dbf=system.getObject("db.common.connection");
var db=dbf.getCon();
db.sync({force:true}).then(async ()=>{
const apps=await system.getObject("service.common.appSve");
let appnew=await apps.create( {
"name":"center-app",
"domainName":"t9.com",
"backend":"cm.com"
});
let Role=db.models["role"];
await Role.create({code:"ta",name:"租户",app_id:appnew.id,company_id:settings.pmcompanyid})
const us=await system.getObject("service.auth.userSve");
let usuper=await us.pmregister({userName:"sm",password:"951753",isSuper:true,isAdmin:true,isEnabled:true,nickName:"superman",app_id:appnew.id,company_id:settings.id})
//创建role
// if(settings.env=="prod"){
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
// }
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
});
module.exports = {
"config": {
"pdict": {
"app_type": { "api": "API服务","web": "PCWEB","app":"移动APP","xcx":"小程序","access":"接入"},
"data_priv": { "auth.role": "角色", "auth.user": "用户" },
"noticeType": {"sms": "短信", "email": "邮件","wechat":"微信"},
"authType": {"add": "新增", "edit": "编辑","delete":"删除","export":"导出","show":"查看"},
"mediaType": {"vd": "视频", "ad": "音频","qt":"其它"},
"usageType": {"kt": "课堂","taxkt":"财税课堂", "qt": "其它"},
"opstatus": {"0": "失败", "1": "成功"},
"sex": {"male": "男", "female": "女"},
"configType": {"price": "宝币兑换率", "initGift": "初次赠送","apiInitGift":"API初次赠送","apiCallPrice":"api调用价格"},
"logLevel": {"debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4},
"msgType": { "sys": "系统", "single": "单点", "multi": "群发", "mryzSingle": "每日易照单点", "mryzLicense": "群发", },
"tradeType": {
"fill": "充值宝币", "consume": "消费宝币", "gift": "赠送宝币", "giftMoney": "红包", "refund": "退款", "payment": "付款",
},
"node_type":{"org":"组织","arc":"文档"}
}
}
}
const fs=require("fs");
const path=require("path");
const appPath=path.normalize(__dirname+"/app");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
config:require(appPath+"/"+"platform.js").config
}
module.exports=appJsons;
module.exports = (db, DataTypes) => {
return db.define("auth", {
rolecode: DataTypes.STRING,
bizcode: DataTypes.STRING,
codepath: DataTypes.STRING,
authstrs: DataTypes.STRING
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_auths',
validate: {
}
});
}
module.exports = (db, DataTypes) => {
return db.define("dataauth", {
modelname: DataTypes.STRING,
auths: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_dataauths',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("org", {
code: {
type:DataTypes.STRING(64),
allowNull: false,
},
name: {
type:DataTypes.STRING(64),
allowNull: false,
},
isLeaf:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
orgpath: {
type:DataTypes.STRING,
allowNull: false,
},
nodeType: {//默认为组织
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(appconfig.pdict.node_type),
defaultValue:'org'
},
isPosition:{//是否是岗位
type:DataTypes.BOOLEAN,
defaultValue: false
},
isMain:{//是否是主岗
type:DataTypes.BOOLEAN,
defaultValue: false
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_org',
validate: {
}
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("orgrole", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_orgrole',
validate: {
},
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("role", {
name: DataTypes.STRING,
code: DataTypes.STRING,
description: DataTypes.STRING,
isSystem: {//是否系统数据,0否,1是
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_role',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("user", {
userName: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
nickName: {
type:DataTypes.STRING,
allowNull: true,
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(appconfig.pdict.sex),
},
mobile:DataTypes.STRING,
mail: {
type:DataTypes.STRING,
allowNull: true,
},
headUrl: DataTypes.STRING,
isAdmin:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
isSuper:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
center_id:DataTypes.STRING,
jwtkey:DataTypes.STRING,
jwtsecret:DataTypes.STRING,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
opath:DataTypes.STRING,//作业务时,需要在业务表冗余当前处理人的opath
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 appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("app", {
appkey:{
type: DataTypes.STRING,
allowNull: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
domainName: DataTypes.STRING,//域名
backend:DataTypes.STRING,//域名
homePage: DataTypes.STRING,//首页
authUrl: DataTypes.STRING,//认证地址
docUrl: DataTypes.STRING,//接口文档地址
configUrl: DataTypes.STRING,//基础信息配置信息地址
logoUrl: DataTypes.STRING,//应用Logo
bkimageUrl: DataTypes.STRING,//应用背景图
showimgUrl: DataTypes.STRING,//应用显示图标
detailimgUrl: DataTypes.STRING,//应用详情介绍地址
opCacheUrl: DataTypes.STRING,//操作缓存地址
description: DataTypes.STRING,//应用描述
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(appconfig.pdict.app_type),
},
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_app',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("company", {
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_company',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("plugin", {
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_plugin',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig=system.getSysConfig();
module.exports = (db, DataTypes) => {
return db.define("route", {
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
center_id: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_route',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class AccountService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(AccountService));
//this.appDao=system.getObject("db.appDao");
}
}
module.exports=AccountService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class AuthService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(AuthService));
}
//字符串数组参数
async findAuthsByRole(rolecodestr,appid,comid){
//{where:{id:{[this.db.Op.in]:ids}}}
//var newattrs=rolecodestr.split(",");
var aths=await this.dao.model.findAll({
attributes:["bizcode","authstrs","codepath"],
where:{rolecode:{[this.db.Op.in]:rolecodestr},app_id:appid,company_id:comid}});
return aths;
}
async saveAuths(auths,appid,cmid){
//先按照code 和 bizcode查询
var self=this;
console.log("yyyyyyyyyvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
console.log(auths);
return self.db.transaction(async function (t){
for(var i=0;i<auths.length;i++){
var tmpAuth=auths[i];
tmpAuth.app_id=appid;
tmpAuth.company_id=cmid;
var objrtn=await self.dao.model.findOrCreate({
defaults:tmpAuth,
where:{rolecode:tmpAuth.rolecode,bizcode:tmpAuth.bizcode},//注意这里bizcode存储的是节点的code值
transaction:t,
});
console.log("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
console.log(objrtn);
if(!objrtn[1].created){
//就执行更新操作
await objrtn[0].update(tmpAuth,{where:{rolecode:tmpAuth.rolecode,bizcode:tmpAuth.bizcode,app_id:tmpAuth.app_id},transaction:t})
}
}
var aths=await self.dao.model.findAll({where:{rolecode:tmpAuth.rolecode,app_id:tmpAuth.app_id},transaction:t});
return aths;
});
}
}
module.exports=AuthService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base")
const settings=require("../../../../config/settings")
class DataauthService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(DataauthService));
}
async saveauth(obj){
//先按照uid,modelname,检查是否存在,不存在创建,存在更新
var oldauth= await this.dao.findOne({user_id:obj.user_id,modelname:obj.modelname,app_id:obj.add_id});
if(!oldauth){
return this.dao.create(obj);
}else{
obj.id=oldauth.id;
return this.dao.update(obj);
}
}
}
module.exports=DataauthService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class OrgService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(OrgService));
}
async delete(p,q,req){
var self=this;
var orgid=p.id;
var uone=await this.db.models.user.findOne({where:{org_id:orgid}});
if(!uone){
//先检查是否组织下有人员存在
return this.db.transaction(async function (t) {
var inst=await self.dao.model.findById(orgid);
var parentid=inst.org_id;
await inst.destroy({force:true,transaction:t});
//删除组织对应的角色
self.db.models.orgrole.destroy({where:{org_id:orgid},force:true,transaction:t});
//查询出父元素
var orgparent=await self.dao.model.findOne({
order:[["code","ASC"]],
where:{id:parentid},transaction:t,
include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]]}
]}
]});
return orgparent.orgs;
});
}else{
return null;
}
}
async update(p,q,req){
var self=this;
var cmkey=p.comkey;//如果是来自租户界面的修改
return this.db.transaction(async function (t) {
p.isLeaf=p.isPosition;
var orgupdate=await self.dao.model.findOne({where:{id:p.id},transaction:t});
await self.dao.model.update(p,{where:{id:p.id},transaction:t});
var usersupdate=await self.db.models.user.findAll({where:{org_id:orgupdate.id}});
//如果节点名称或岗位性质发生变化
//if(p.name!=orgupdate.name || p.isMain!=orgupdate.isMain){
for(var ud of usersupdate){
ud.opath=p.orgpath;
var n=p.orgpath.lastIndexOf("/");
ud.ppath=p.isMain?p.orgpath.substring(0,n):p.orgpath;
await ud.save({transaction:t});
}
//}
if(p.Roles && !cmkey){//如果不是来自租户界面的修改
var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
await orgupdate.setRoles(roles,{transaction:t});
//同时要给这个岗位下的user,更新角色 todo
for(var ud of usersupdate){
await ud.setRoles(roles,{transaction:t});
}
}
var orgparent=await self.dao.model.findOne({
order:[["code","ASC"]],
where:{id:orgupdate.org_id},transaction:t,
include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]});
return orgparent.orgs;
});
}
async checkMainPosition(p,q,req){
var orgmain=await this.dao.model.findOne({where:{org_id:p.org_id,isMain:true}});
if(orgmain){
return {"isHave":true};
}else{
return null;
}
}
async changePos(toorgid,uid){
//查询出当前用户,设置当前用户的orgid为修改目标
var self=this;
return this.db.transaction(async function (t) {
var ufind=await self.db.models.user.findById(uid);
var org=await self.dao.model.findOne({
where:{id:toorgid},
include:[
{model:self.db.models.role,as:"roles"},
]});
ufind.org_id=toorgid;
ufind.opath=org.orgpath;
if(org.isMain){//如果是主岗
var n=org.orgpath.lastIndexOf("/");
ufind.ppath=org.orgpath.substring(0,n);
}else{
ufind.ppath= org.orgpath;
}
await ufind.save({transaction:t});
await ufind.setRoles(org.roles,{transaction:t});
return ufind;
});
//查询出目标org,关联查询出角色
//设置当前用户的角色
}
async create(p,q,req){
var self=this;
var cmkey=p.comkey;
return this.db.transaction(async function (t) {
if(cmkey){
var tmpcompany =await self.db.models.company.findOne({where:{companykey:cmkey},transaction:t});
p.company_id=tmpcompany.id;
}
var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
p.isLeaf=p.isPosition;
p.app_id=null;
var orgnew=await self.dao.model.create(p,{transaction:t});
if(roles && roles.length>0){
await orgnew.setRoles(roles,{transaction:t});
}
var orgparent=await self.dao.model.findOne({
order:[["code","ASC"]],
where:{id:orgnew.org_id},transaction:t,
include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]});
return orgparent.orgs;
});
}
async findOrgById(id){
var org=await this.dao.model.findOne({
order:[["code","ASC"]],
where:{id:id},
include:[
{model:this.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:this.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:this.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:this.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:this.db.models.role,as:"roles",attributes:['id','code','name']},
]});
return org.orgs;
}
async initOrgs(company,appid){
var self=this;
return this.db.transaction(async function (t) {
var org=await self.dao.model.findOne({
order:[["code","ASC"]],
//where:{name:company.name,company_id:company.id,app_id:appid},transaction:t,
where:{name:company.name,company_id:company.id},transaction:t,
include:[
{model:self.db.models.org,as:"orgs", order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]});
if(org!=null){
return org;
}else{
var root= await self.dao.model.create({
code:"root"+company.id,
name:company.name,
isLeaf:false,
isPostion:false,
isMain:false,
orgpath:"/",
company_id:company.id,
app_id:null,
},{transaction:t});
return root;
}
});
}
}
module.exports=OrgService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class RoleService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(RoleService));
//this.appDao=system.getObject("db.appDao");
}
async findOneByCode(code){
return this.dao.model.findOne({where:{code:code}});
}
}
module.exports=RoleService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
const jwt = require('jsonwebtoken');
class UserService extends ServiceBase {
constructor() {
super("auth", ServiceBase.getDaoName(UserService));
this.companyDao=system.getObject("db.common.companyDao");
this.roleDao=system.getObject("db.common.roleDao");
}
//平台注册,默认角色,不具备平台级别的管理或运营功能
//注册接口
//封装kongurl
async pmregister(p,q){
var self=this;
let tmppwd=p.password;
if(!tmppwd){
tmppwd=settings.defaultpwd;
}
p.password=this.getEncryptStr(tmppwd);
return this.db.transaction(async function (t) {
//创建一个默认公司,公司名称xxxx的公司
let cmp=await self.companyDao.create({name:p.userName+"的公司"},t);
p.company_id=cmp.id;
let u=await self.dao.create(p,t)
//设置默认角色,租户
//设置默认普通角色,由于有了租户概念,所以注册时,需要知道当前租户和应用的id 才可以设置默认角色 todo
var role = await self.roleDao.model.findOne({ where: { code: "ta" }, transaction: t });
await u.setRoles([role], { transaction: t });
//创建统一账号
let cred=await self.cregister(u.userName,cmp.id,p.password)
console.log("......................................");
console.log(cred.consumer.id);
if(cred){
u.center_id=cred.consumer.id;
u.jwtkey=cred.key;
u.jwtsecret=cred.secret;
try{
await u.save({transaction:t});
}catch(e){
console.log(e);
await self.cunregister(p.userName);
throw new Error("保存用户失败");
}
return u;
}else{
throw new Error("创建统一账号失败");
}
});
}
//平台登录
//登录接口封装kong-url
//登录路由放行
//p里面含有appkey,company_id,userName,password
async pmlogin(p,q,req){
var self=this;
//先要按照用户名,在统一账户中查找存在性
//如果不存在
let consumer=await this.cget(UserService.consumerUrl(p.userName));
if(!consumer.data){
return null;
}else{
let password=consumer.data.tags[1].split("_")[1];
let inpassword=this.getEncryptStr(p.password);
if(password!=inpassword){
return null;
}
}
var rtn={}
return this.db.transaction(async function (t) {
let userfind=await self.dao.findOne({userName:p.userName,app_id:settings.pmappid,company_id:settings.pmcompanyid});
if(userfind){
let token= await self.cmakejwt(userfind.jwtkey,userfind.jwtsecret,null);
rtn.token=token;
rtn.user=userfind;
return rtn;
}else{
return null;
}
})
}
//平台注册与登录
//用户验证码登录
//
async pmloginByVCode(p,q,req){
var rtn={}
//检查传递过来的手机验证码是否与缓存的一致
let mobile=p.mobile;
let vcode=p.vcode;
let cachevcode=await this.cacheManager ["VCodeCache"].getCache(mobile,60)
if(vcode!=cachevcode.vcode){
return null;
}else{
//检查是否在库里存在
//appkey--company_id---需要控制器基类里设置到p对象里
let user=await this.findOne({userName:mobile,app_id:settings.pmappid,company_id:settings.pmcompanyid})
if(user){
//生成token
let token= await this.cmakejwt(user.jwtkey,user.jwtsecret,null);
rtn.token=token;
rtn.user=user;
return rtn;
}else{
//先按照用户名查续身份信息,获取key,secret,
let u=await this.pmregister({userName:mobile,nickName:mobile});
let token= await this.cmakejwt(u.jwtkey,u.jwtsecret,null);
rtn.token=token;
rtn.user=u;
return rtn;
}
}
//不一致那么就
}
//发送手机验证码并缓存
async sendVCode(p,q,req){
let mobile=p.mobile;
let vcodeobj=await this.cacheManager ["VCodeCache"].cache(mobile,null,60);
return vcodeobj.vcode;
}
async reSendVCode(p,q,req){
let mobile=p.mobile;
await this.cacheManager ["VCodeCache"].invalidate(mobile);
let vcodeobj=await this.cacheManager ["VCodeCache"].cache(mobile,null,60);
return vcodeobj.vcode;
}
//创建统一账号及jwt身份
async cregister(uname,cmpid,pass){
try{
var rtn2=null;
let rtn=await system.postJsonTypeReq(UserService.newConsumerUrl(),{username:uname,tags:["cmp_"+cmpid,"pass_"+pass]})
console.log(rtn)
if(rtn.statusCode==409){
throw new Error("已经存在相同的统一账号名称!");
}else{
//创建身份
rtn2=await system.post3wFormTypeReq(UserService.newJwtCredUrl(uname))
}
if(rtn.statusCode==201 && rtn2.statusCode==201){
return rtn2.data;
}
return null;
}catch(e){
console.log(e);
return null;
}
}
async jwtsign(plkey,secretstr,opts){
let promise=new Promise(function(resv,rej){
jwt.sign({ iss: plkey },secretstr,opts,function(err,rtn){
if(err){
rej(err);
}else{
resv(rtn);
}
});
});
return promise;
}
//只要登录 生成新的访问jwttoken
async cmakejwt(key,secret,opts){
var token =await this.jwtsign(key, secret,opts);
return token;
}
//删除统一账号
async cunregister(uname){
try{
let rtn=await system.delReq(UserService.consumerUrl(uname))
if(rtn.statusCode==204){
return {};
}
return null;
}catch(e){
return null;
}
}
//登录统一账号
async clogin(uname){
//检查是否存在重名
}
//按用户名查询统一用户
async findCUser(uname){
}
}
module.exports = UserService;
// // (async ()=>{
// let u=new UserService();
// // // let x=await u.cregister("jiangong")
// // // console.log(x)
// // // let x=await u.cunregister("jiangong")
// // // console.log(x)
// // // let t=await u.cmakejwt()
// // // console.log(t)
// let ux=u.register({userName:"jiangyong3",password:"123"})
// console.log(ux);
// // })()
\ No newline at end of file
const system=require("../../../system");
const settings=require("../../../../config/settings");
const ServiceBase=require("../../sve.base")
var WXPay = require('wx-pay');
const uuidv4 = require('uuid/v4');
class ApiTradeService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(ApiTradeService));
}
async create(tradeObj){
var self=this;
return this.db.transaction(async function (t){
//获取缓存二个值,一个是赠送次数,一个是调用价格
var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
var apiInitGift = pconfig.find(item => {
return item.configType === "apiInitGift";
});
var apiCallPrice = pconfig.find(item => {
return item.configType === "apiCallPrice";
});
var app=await self.cacheManager["AppCache"].cacheApp(tradeObj.appkey,null,1);
tradeObj.app_id=app.id;
var callCache=await self.cacheManager["ApiCallCountCache"].getApiCallCount(tradeObj.appkey,tradeObj.op);
var callAccuCache=await self.cacheManager["ApiAccuCache"].getApiCallAccu(tradeObj.appkey);
var calledCount=Number(callCache.callcount);
var balance=Number(callCache.amount);
if(calledCount>Number(apiInitGift.configValue)){//调用次数大于免费次数
tradeObj.amount=Number(apiCallPrice.configValue);
}else{
tradeObj.amount=0;
}
//解决日志大于4000写入的问题
if(tradeObj.params.length>3980){
tradeObj.params=tradeObj.params.substring(0,3980);
}
var apitrade=await self.dao.model.create(tradeObj,{transaction:t});
//按照调用方法缓存
await self.cacheManager["ApiCallCountCache"].addCallCount(tradeObj.appkey,tradeObj.op,1);
await self.cacheManager["ApiCallCountCache"].addCallBalance(tradeObj.appkey,tradeObj.op,tradeObj.amount);
//累计缓存调用次数和金额
await self.cacheManager["ApiAccuCache"].addCallCount(tradeObj.appkey,1);
await self.cacheManager["ApiAccuCache"].addCallBalance(tradeObj.appkey,tradeObj.amount);
// await self.cacheManager["ApiCircuitBreakers"].addCallCount(-1);
return apitrade;
});
}
async beforesel(tradeObj){
var self=this;
var callCaches=await self.cacheManager["ApiCircuitBreakers"].getApiCall();
var calledCounts=Number(callCaches.callcount);
if( calledCounts>100 ){
// return {status:-1,msg:"服务器繁忙,请稍候再试",data:null};
}
else {
// await self.cacheManager["ApiCircuitBreakers"].addCallCount(1);
}
var callCache=await self.cacheManager["ApiCircuitBreakerCache"].getApiCall(tradeObj.appkey);
var calledCount=Number(callCache.callcount);
if( calledCount>1000 ){
return {status:-1,msg:"调用次数太多,请稍候再试",data:null};
}
else {
var result=await self.cacheManager["ApiCircuitBreakerCache"].addCallCount(tradeObj.appkey,1);
}
return {status:1,msg:"OK"};
}
}
module.exports=ApiTradeService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class AppdetailService{
constructor(){
this.cacheManager=system.getObject("db.cacheManager");
}
//app调用次数
async findAndCountAlldetail(obj){
var details=[];
var apicallAccu= await this.cacheManager["ApiAccuCache"].getApiCallAccu(obj);
var result={rows:[],count:0};
var keys=await this.cacheManager["MagCache"].keys("api_call_" + obj + "*");
var detail=null;
for(let j=0;j<keys.length;j++){
var d=keys[j];
var pathdetail=d.substr(d.lastIndexOf("_")+1,d.length);
var apicalldetailAccu= await this.cacheManager["ApiCallCountCache"].getApiCallCount(obj,pathdetail);
var detail={"detailPath":d,"detailCount":apicalldetailAccu.callcount,"detailAmount":apicalldetailAccu.amount};
details.push(detail);
}
result.rows=details;
result.count=details.length;
return result;
}
async delCache(obj){
return this.cacheManager["MagCache"].del(obj.key);
}
async clearAllCache(obj){
return this.cacheManager["MagCache"].clearAll();
}
}
module.exports=AppdetailService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class ArticleService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(ArticleService));
this.newschannelDao=system.getObject("db.newschannelDao");
}
//获取频道列表
async findChannel(obj){
// const apps=await super.findAndCountAll(obj);
var usageType = obj.usageType;
if(usageType==null||usageType==""||usageType=="undefined"){
return {code:-101,msg:"参数有误",data:null};
}
try {
var sqlwhere = {
where: {usageType:usageType},
attributes: ["id", "code", "title", "bgimg", "isPubed", "usageType", "app_id"],
order: [["orderNo", 'ASC']],
raw: true
};
var list = await this.newschannelDao.model.findAll(sqlwhere);
if (list == null || list.length == 0) {
return {code:0,msg:"没有信息",data:null};
}else {
return {code:1,msg:"操作成功",data:list};
}
}catch (e) {
return {code:-1,msg:"操作失败",data:null};
}
}
//获取该频道所有列表
async findAndCountAll2(obj){
// const apps=await super.findAndCountAll(obj);
var newschannel = obj.newschannel_id;
var pageSize=obj.page_size;
var currentPage=obj.current_page;
if(newschannel==null||newschannel==""||newschannel=="undefined"){
return {code:-101,msg:"参数有误",data:null};
}
if(pageSize==null||pageSize==""||pageSize=="undefined"){
pageSize="";
}
if(currentPage==null||currentPage==""||currentPage=="undefined"){
currentPage="";
}
try {
var sqlwhere = {
where: {newschannel_id:newschannel},
attributes: ["id","code", "title", "listimg", "videourl", "desc", "mediaType", "usageType",
"test","newschannel_id", "app_id"],
order: [["orderNo", 'ASC']],
raw: true
};
if(pageSize!=""&&currentPage!=""){
var tPageSize=Number(pageSize);
var tCurrentPage=Number(currentPage);
if(tCurrentPage<1){
tCurrentPage=1;
}
if(tPageSize>50){
tPageSize=50;
}
if(tPageSize<1){
tPageSize=1;
}
sqlwhere.limit=tPageSize;
sqlwhere.offset= (tCurrentPage - 1) * tPageSize;
}
var list = await this.dao.model.findAll(sqlwhere);
if (list == null || list.length == 0) {
return {code:0,msg:"没有信息",data:null};
}else {
return {code:1,msg:"操作成功",data:list};
}
}catch (e) {
return {code:-1,msg:"操作失败",data:null};
}
// apps.forEach(a=>{
// if(a.content && a.content!=""){
// a.content=decodeURIComponent(a.content);
// }
// });
// console.log("xxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxx");
// for(var arch of apps.rows){
// var c=arch.content.toString("utf-8") ;
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(c);
// if(c && c!=""){
// arch.content=c;
// }
// }
// return apps;
}
//获取详细信息
async findArticle(obj){
// const apps=await super.findAndCountAll(obj);
var id = obj.id;
if(id==null||id==""||id=="undefined"){
return {code:-101,msg:"参数有误",data:null};
}
try {
var sqlwhere = {
where: {id:id},
attributes: ["id","code", "title", "listimg", "videourl", "desc", "content", "mediaType", "usageType",
"test", "app_id"],
order: [["created_at", 'desc']],
raw: true
};
var list = await this.dao.model.findOne(sqlwhere);
if (list == null || list.length == 0) {
return {code:0,msg:"没有信息",data:null};
}else {
return {code:1,msg:"操作成功",data:list};
}
}catch (e) {
return {code:-1,msg:"操作失败",data:null};
}
}
}
module.exports=ArticleService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class NewschannelService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(NewschannelService));
//this.appDao=system.getObject("db.appDao");
}
async findAgreenment(queryobj,qobj,req){
return this.dao.findAgreenment();
}
async findPrev5(queryobj,qobj){
return this.dao.findPrev5();
}
}
module.exports=NewschannelService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class SloganpictureService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(SloganpictureService));
//this.appDao=system.getObject("db.appDao");
}
async findAndCountAll(obj){
const apps=await super.findAndCountAll(obj);
// apps.forEach(a=>{
// if(a.content && a.content!=""){
// a.content=decodeURIComponent(a.content);
// }
// });
// console.log("xxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxx");
// for(var arch of apps.rows){
// var c=arch.content.toString("utf-8") ;
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(c);
// if(c && c!=""){
// arch.content=c;
// }
// }
return apps;
}
}
module.exports=SloganpictureService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class AppService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(AppService));
this.userS = system.getObject("service.auth.userSve");
this.routeDao=system.getObject("db.common.routeDao");
}
async getApp(appkey) {
return this.cacheManager["AppCache"].cache(appkey, null);
}
async findAllApps(uid) {
var apps=null;
var dicRtn = {};
var wheresql= {};
if(uid){
wheresql[this.db.Op.and]={
[this.db.Op.or]:
[
{isPublish:false, creator_id: uid},
{isEnabled: true,isPublish:true}
],
};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
}else{
wheresql= {isEnabled: true,isPublish:true};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
}
for (var app of apps) {
var tmk = uiconfig.config.pdict.app_type[app.appType];
if (!dicRtn[tmk]) {
dicRtn[tmk] = [];
dicRtn[tmk].push(app);
} else {
dicRtn[tmk].push(app);
}
}
return dicRtn;
}
//创建应用
//每个应用建立两个路由,一个api路由
//对api路由启用jwt插件
async create(pobj, qobj, req) {
var self = this;
return this.db.transaction(async function (t) {
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
var app = await self.dao.create(pobj, t);
//创建后台应用服务
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
let svobj=await self.cjsonregister(AppService.newServiceUrl(),{name:app.name,url:"http://"+app.backend})
//添加路由
let routeobj=await self.cjsonregister(AppService.newRouteUrl(app.name),{name:app.name,hosts:[app.domainName]})
let routeapi=await self.cjsonregister(AppService.newRouteUrl(app.name),{name:app.name+"_api",hosts:[app.domainName],paths:["/api"],strip_path:false})
let r1=await self.routeDao.create({name:app.name,center_id:routeobj.id},t);
let r2=await self.routeDao.create({name:app.name+"_api",center_id:routeapi.id},t);
//给api路由启动插件
await self.cjsonregister(AppService.bindPluginUrl(app.name+"_api"),{name:"jwt"})
if(svobj && routeobj && r1 && r2){
try{
app.appkey=svobj.id;
await app.save({transaction:t});
}catch(e){
await self.cdel(AppService.routeUrl(app.name))
await self.cdel(AppService.routeUrl(app.name+"_api"))
await self.cdel(AppService.serviceUrl(app.name))
}
}else{
throw new Error("创建应用服务失败");
}
return app;
});
}
//删除应用
async delete(pobj, qobj){
var self=this;
return this.db.transaction(async function (t) {
await self.dao.delete(pobj,t)
//删除路由
await self.cdel(AppService.routeUrl(pobj.name));
//删除api路由
await self.cdel(AppService.routeUrl(pobj.name+"_api"));
//删除服务
await self.cdel(AppService.serviceUrl(pobj.name));
return {}
})
}
async findAndCountAll(obj) {
var self = this;
const apps = await super.findAndCountAll(obj);
return apps;
}
}
module.exports = AppService;
// (async ()=>{
// let u=new AppService();
// // let x=await u.cregister("jiangong")
// // console.log(x)
// // let x=await u.cunregister("jiangong")
// // console.log(x)
// // let t=await u.cmakejwt()
// // console.log(t)
// //let ux=await u.cjsonregister(AppService.newRouteUrl("test-service2"),{name:"test-service2",hosts:["ttest1.com"]})
// //let ux=await u.cjsonregister(AppService.newServiceUrl(),{name:"test-service3",url:"http://zhichan.gongsibao.com"})
// //let ux=await u.cdel(AppService.routeUrl("test-service2"))
// //let ux=await u.cdel(AppService.serviceUrl("test-service2"))
// // let ux=await u.create({name:"test4-service",backend:"zhichan-service",domainName:"domain.com"})
// // console.log(ux);
// // let delrtn=await u.delete({id:2,name:"test4-service"})
// // console.log(delrtn);
// })()
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const uuidv4 = require('uuid/v4');
class CachSearchesSve {
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
this.appDao = system.getObject("db.common.appDao");
this.authUtils = system.getObject("util.businessManager.authUtils");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async buildCacheRtn(pageValues) {
var ps = pageValues.map(k => {
var tmpList = k.split("|");
if (tmpList.length == 2) {
return { name: tmpList[0], val: tmpList[1], key: k };
}
});
return ps;
}
async findAndCountAllCache(obj) {
const pageNo = obj.pageInfo.pageNo;
const pageSize = obj.pageInfo.pageSize;
const limit = pageSize;
const offset = (pageNo - 1) * pageSize;
var search_name = obj.search && obj.search.name ? obj.search.name : "";
var cacheCacheKeyPrefix = "sadd_base_appkeys:" + settings.appKey + "_cachekey";
if (obj.appid == settings.platformid) {
var cacheList = await this.cacheManager["MagCache"].getCacheSmembersByKey(cacheCacheKeyPrefix);
if (search_name) {
cacheList = cacheList.filter(f => f.indexOf(search_name) >= 0);
}
var pageValues = cacheList.slice(offset, offset + limit);
var kobjs = await this.buildCacheRtn(pageValues);
var tmpList = { results: { rows: kobjs, count: cacheList.length } };
return system.getResult(tmpList);
} else {
var body = {
pageInfo: obj.pageInfo,
search: obj.search
};
var tmpList = await this.opOtherAppCache("findAndCountAll", body, obj.opCacheUrl);
return tmpList;
}
}
async delCache(obj) {
if (obj.appid == settings.platformid) {
var keyList = obj.key.split("|");
if (keyList.length == 2) {
var cacheCacheKeyPrefix = "sadd_base_appkeys:" + settings.appKey + "_cachekey";
await this.cacheManager["MagCache"].delCacheBySrem(cacheCacheKeyPrefix, obj.key);
await this.cacheManager["MagCache"].del(keyList[0]);
return { status: 0 };
}
} else {
var body = {
del_cachekey: obj.key
};
return await this.opOtherAppCache("delCache", body, obj.opCacheUrl);
}
}
async clearAllCache(obj) {
if (obj.appid == settings.platformid) {
await this.cacheManager["MagCache"].clearAll();
return { status: 0 };
}
return await this.opOtherAppCache("clearAllCache", {}, obj.opCacheUrl);
}
//app调用次数
async findAndCountAlldetail(obj) {
var apicallAccu = await this.cacheManager["ApiAccuCache"].getApiCallAccu(obj);
var result = { rows: [], count: 0 };
var keys = await this.cacheManager["MagCache"].keys("api_call_" + appkey + "*");
var detail = null;
for (let j = 0; j < keys.length; j++) {
var d = keys[j];
var pathdetail = d.substr(d.lastIndexOf("_") + 1, d.length);
var apicalldetailAccu = await this.cacheManager["ApiCallCountCache"].getApiCallCount(appkey, pathdetail);
var detail = { "detailPath": d, "detailCount": apicalldetailAccu.callcount };
}
result.rows = detail;
}
//操作别的应用的缓存
async opOtherAppCache(action_type, body = null, opCacheUrl) {
var appData = await this.authUtils.getTokenInfo(settings.appKey, settings.secret);
if (appData.status != 0) {
return appData;
}
//按照访问token
const restS = await system.getObject("util.restClient");
var restResult = await restS.execPostWithAK(
{
action_type: action_type,
body: body
},
opCacheUrl, appData.data.accessKey);
if (restResult && restResult.status == 0) {
return restResult;
}
return system.getResultFail();
}
}
module.exports = CachSearchesSve;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
class CompanyService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(CompanyService));
this.userS=system.getObject("service.auth.userSve");
}
async create(p,user){
var self=this;
return this.db.transaction(async function (t){
var company=await self.dao.model.create(p,{transaction:t});
await user.addCompany(company,{transaction:t});
//先按照用户id,取消所有当前
var up1=await self.db.models.usercompany.update({isCurrent:false},{where:{user_id:user.id},transaction:t});
//按照用户id和公司id,设置当前
var up2=await self.db.models.usercompany.update({isCurrent:true},{where:{user_id:user.id,company_id:company.id},transaction:t});
return company;
});
}
async delete(pobj){
var self=this;
return this.db.transaction(async function (t){
//查询出要删除的租户
var usercomp=await self.db.models.usercompany.findOne({where:{user_id:pobj.userid,company_id:pobj.id}});
await usercomp.destroy({where:{user_id:pobj.userid,company_id:pobj.id},transaction:t});
//to 删除公司选择的应用
await self.db.models.companyapp.destroy({where:{
company_id:pobj.id
},transaction:t});
var rtn=await self.dao.delete({id:pobj.id},t);
//按照公司ID,查询当前user表里是否有记录,如果已经有,就不要删除记录todo
return rtn;
});
}
async giveupApp(comid,appid){
var self=this;
return this.db.transaction(async function (t){
//检查当前company_id下面是否有用户存在,如果已经存在就不要删除了
var c=await self.db.models.user.count({where:{owner_id:comid}});
if(c>1){
return null;
}else{
if(c==1){
await self.db.models.user.destroy({where:{owner_id:comid},force: true});
}
await self.db.models.companyapp.destroy({where:{company_id:comid,app_id:appid}});
return {};
}
});
}
async buyApp(p,cmid,user){
var self=this;
var appid=p.id;
var cmid=cmid;
return this.db.transaction(async function (t){
//先按照用户id,取消所有当前
// var cmp=await self.db.models.company.findOne({where:{
// id:cmid,
// }});
// cmp.addApp(p,{transaction:t});
var seladd=await self.db.models.companyapp.create({
company_id:cmid,
app_id:appid
},{transaction:t});
//创建当前购买应用的管理员账号,设置所属公司,不需要建立公司关系在在中间表
var appadminuser=await self.userS.createAdminUser({
userName:user.userName,
password:user.password,
mobile:user.mobile,
app_id:appid,
owner_id:cmid,
tanentor_id:user.id,//租户的id
},{transaction:t});
//查询当前公司,关联出apps
var cmpfind=await self.db.models.company.findOne({where:{
id:cmid,
},
include:[
{model:self.db.models.app}
],
transaction:t
});
return cmpfind;
});
}
async settocompany(p){
var self=this;
var uid=p.userid;
var cid=p.id;
return this.db.transaction(async function (t){
//先按照用户id,取消所有当前
var up1=await self.db.models.usercompany.update({isCurrent:false},{where:{user_id:uid},transaction:t});
//按照用户id和公司id,设置当前
var up2=await self.db.models.usercompany.update({isCurrent:true},{where:{user_id:uid,company_id:cid},transaction:t});
return p;
});
}
async findAndCountAll(p,q,req){
var u= await this.userS.dao.model.findOne({where:{id:p.userid},
include: [
{
model: this.db.models.company,through:{attributes:['isCurrent']},include:[
{model:this.db.models.app}
]
},
]
});
var cmps=await u.companies;
return cmps;
}
}
module.exports = CompanyService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const settings=require("../../../../config/settings");
class MetaService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(MetaService));
this.restS=system.getObject("util.restClient");
}
async getApiDoc(appid){
var p=settings.basepath+"/app/base/db/impl/common/apiDocManager.js";
var ClassObj= require(p) ;
var obj=new ClassObj();
return obj.doc;
}
async getApiDocRemote(appid,docUrl){
var rtn=await this.restS.execPost({}, docUrl);
if(rtn.stdout){
var dod=JSON.parse(rtn.stdout);
if(dod.data){
return dod.data;
}
}
return null;
}
async getUiConfig(appid){
const cfg=await this.cacheManager["UIConfigCache"].cache(appid,null,60);
return cfg;
}
async getRemoteUiConfig(appkey,uiconfigUrl){
const cfg=await this.cacheManager["UIRemoteConfigCache"].cache(appkey,null,120,uiconfigUrl);
return cfg;
}
}
module.exports=MetaService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class OplogService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(OplogService));
//this.appDao=system.getObject("db.appDao");
this.opLogUrl = settings.apiconfig.opLogUrl();
this.opLogEsIsAdd = settings.apiconfig.opLogEsIsAdd();
}
async create(qobj) {
if (!qobj || !qobj.op || qobj.op.indexOf("metaCtl/getUiConfig") >= 0 ||
qobj.op.indexOf("userCtl/checkLogin") >= 0 ||
qobj.op.indexOf("oplogCtl") >= 0 ||
qobj.op.indexOf("getDicConfig") >= 0 ||
qobj.op.indexOf("getRouteConfig") >= 0 ||
qobj.op.indexOf("getRsConfig") >= 0) {
return null;
}
var rc = system.getObject("util.execClient");
var rtn = null;
try {
// var myDate = new Date();
// var tmpTitle=myDate.toLocaleString()+":"+qobj.optitle;
qobj.optitle = (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":" + qobj.optitle;
if (this.opLogEsIsAdd == 1) {
qobj.content = qobj.content.replace("field list", "字段列表")
qobj.created_at = (new Date()).getTime();
//往Es中写入日志
var addEsData = JSON.stringify(qobj);
rc.execPost(qobj, this.opLogUrl);
} else {
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
} catch (e) {
console.log("addLog------>>>>>>error-----------------------*****************");
console.log(e);
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
}
}
module.exports = OplogService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class PConfigService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(PConfigService));
//this.appDao=system.getObject("db.appDao");
}
async findOrSetPrice(num,appkey){
return this.cacheManager["PriceConfigCache"].cacheGlobalVal(num,appkey);
}
async create(pobj){
await this.cacheManager["PConfigCache"].invalidate(pobj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(pobj.appkey);
return this.dao.create(pobj);
}
async update(pobj,tm=null){
await this.cacheManager["PConfigCache"].invalidate(pobj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(pobj.appkey);
return this.dao.update(pobj,tm);
}
async updateByWhere(setObj,whereObj,t){
await this.cacheManager["PConfigCache"].invalidate(setObj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(setObj.appkey);
return this.dao.updateByWhere(setObj,whereObj,t);
}
//获取配置的发票税率
async getInvoiceTaxRate(){
var tmpInvoiceTaxRate=7;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "invoiceTaxRate";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
tmpInvoiceTaxRate=Number(pconfigResult.configValue);
}
return tmpInvoiceTaxRate;
}
//获取配置的信息
async getConfigValue(configName){
var configValue=0;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === configName;
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
configValue=Number(pconfigResult.configValue);
}
return configValue;
}
//获取配置的推荐人分润比例
async getReferrerProfitRatio(){
var tmpInvoiceTaxRate=10;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "referrerProfitRatio";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
tmpInvoiceTaxRate=Number(pconfigResult.configValue);
}
return tmpInvoiceTaxRate;
}
//商机分配渠道配置,格式:wssyh5,yzc等
async getBussinessAllotChannelConfig(){
var bussinessAllotChannel="wssyh5";
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "bussinessAllotChannelConfig";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
bussinessAllotChannel=pconfigResult.configValue;
}
return bussinessAllotChannel;
}
}
module.exports=PConfigService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class AppService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(AppService));
this.userS = system.getObject("service.auth.userSve");
}
async getApp(appkey) {
return this.cacheManager["AppCache"].cache(appkey, null);
}
async findAllApps(uid) {
var apps=null;
var dicRtn = {};
var wheresql= {};
if(uid){
wheresql[this.db.Op.and]={
[this.db.Op.or]:
[
{isPublish:false, creator_id: uid},
{isEnabled: true,isPublish:true}
],
};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
}else{
wheresql= {isEnabled: true,isPublish:true};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
}
for (var app of apps) {
var tmk = uiconfig.config.pdict.app_type[app.appType];
if (!dicRtn[tmk]) {
dicRtn[tmk] = [];
dicRtn[tmk].push(app);
} else {
dicRtn[tmk].push(app);
}
}
return dicRtn;
}
//创建应用
//每个应用建立两个路由,一个api路由
//对api路由启用jwt插件
async create(pobj, qobj, req) {
var self = this;
return this.db.transaction(async function (t) {
var app = await self.dao.create(pobj, t);
//创建后台应用服务
let svobj=await self.cjsonregister(AppService.newServiceUrl(),{name:app.name,url:"http://"+app.backend})
//添加路由
let routeobj=await self.cjsonregister(AppService.newRouteUrl(app.name),{name:app.name,hosts:[app.domainName]})
let routeapi=await self.cjsonregister(AppService.newRouteUrl(app.name),{name:app.name+"_api",hosts:[app.domainName],paths:["/api"],strip_path:false})
//给api路由启动插件
if(svobj && routeobj){
try{
app.appkey=svobj.id;
await app.save({transaction:t});
}catch(e){
await self.cdel(AppService.routeUrl(app.name))
await self.cdel(AppService.routeUrl(app.name+"_api"))
await self.cdel(AppService.serviceUrl(app.name))
}
}else{
throw new Error("创建应用服务失败");
}
return app;
});
}
//删除应用
async delete(pobj, qobj){
var self=this;
return this.db.transaction(async function (t) {
await self.dao.delete(pobj,t)
//删除路由
await self.cdel(AppService.routeUrl(pobj.name));
//删除api路由
await self.cdel(AppService.routeUrl(pobj.name+"_api"));
//删除服务
await self.cdel(AppService.serviceUrl(pobj.name));
return {}
})
}
async findAndCountAll(obj) {
var self = this;
const apps = await super.findAndCountAll(obj);
return apps;
}
}
module.exports = AppService;
// (async ()=>{
// let u=new AppService();
// // let x=await u.cregister("jiangong")
// // console.log(x)
// // let x=await u.cunregister("jiangong")
// // console.log(x)
// // let t=await u.cmakejwt()
// // console.log(t)
// //let ux=await u.cjsonregister(AppService.newRouteUrl("test-service2"),{name:"test-service2",hosts:["ttest1.com"]})
// //let ux=await u.cjsonregister(AppService.newServiceUrl(),{name:"test-service3",url:"http://zhichan.gongsibao.com"})
// //let ux=await u.cdel(AppService.routeUrl("test-service2"))
// //let ux=await u.cdel(AppService.serviceUrl("test-service2"))
// // let ux=await u.create({name:"test4-service",backend:"zhichan-service",domainName:"domain.com"})
// // console.log(ux);
// // let delrtn=await u.delete({id:2,name:"test4-service"})
// // console.log(delrtn);
// })()
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class RouteService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(AppService));
}
//创建应用
//每个应用建立两个路由,一个api路由
//对api路由启用jwt插件
async create(serviceName, routedata, req) {
var self = this;
return this.db.transaction(async function (t) {
var rtn=null;
try {
//添加路由
let routeobj = await self.cjsonregister(AppService.newRouteUrl(serviceName), { name: routedata.name, hosts: routedata.hosts, paths: routedata.paths, strip_path: routedata.isstrip })
routedata.center_id = routeobj.id;
rtn = await self.dao.create(routedata, t);
} catch (e) {
await self.cdel(AppService.routeUrl(routedata.name));
}
return rtn;
});
}
async findAndCountAll(obj) {
var self = this;
const apps = await super.findAndCountAll(obj);
return apps;
}
}
module.exports = RouteService;
// (async ()=>{
// let u=new AppService();
// // let x=await u.cregister("jiangong")
// // console.log(x)
// // let x=await u.cunregister("jiangong")
// // console.log(x)
// // let t=await u.cmakejwt()
// // console.log(t)
// //let ux=await u.cjsonregister(AppService.newRouteUrl("test-service2"),{name:"test-service2",hosts:["ttest1.com"]})
// //let ux=await u.cjsonregister(AppService.newServiceUrl(),{name:"test-service3",url:"http://zhichan.gongsibao.com"})
// //let ux=await u.cdel(AppService.routeUrl("test-service2"))
// //let ux=await u.cdel(AppService.serviceUrl("test-service2"))
// // let ux=await u.create({name:"test4-service",backend:"zhichan-service",domainName:"domain.com"})
// // console.log(ux);
// // let delrtn=await u.delete({id:2,name:"test4-service"})
// // console.log(delrtn);
// })()
\ No newline at end of file
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TaskService));
//this.appDao=system.getObject("db.appDao");
this.taskManager=system.getObject("db.taskManager");
this.emailClient=system.getObject("util.mailClient");
this.personTaxDao=system.getObject("db.individualincometaxDao");
this.ossClient=system.getObject("util.ossClient");
}
//写文件并上传到阿里云,返回上传的路径
async writexls(wb,sharecode){
var that=this;
var uuid=uuidv4();
var u=uuid.replace(/\-/g,"");
var fname="zc_"+u+".xlsx";
var filepath="/tmp/"+fname;
var promise=new Promise((resv,rej)=>{
wb.xlsx.writeFile(filepath).then(async function(d) {
var rtn=await that.ossClient.upfile(fname,filepath);
fs.unlink(filepath,function(err){});
return resv(rtn);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
//读取模板文件
async readxls(){
var promise=new Promise((resv,rej)=>{
var workbook = new excel.Workbook();
workbook.properties.date1904 = true;
var bpth=path.normalize(path.join(__dirname, '../'));
workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
.then(function() {
return resv(workbook);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
async buildworkbook(taxCalcList){
var workbook = await this.readxls();
var sheet = workbook.getWorksheet(1);
sheet.columns = [
{ header: '年度', key: 'statisticalYear', width: 10 },
{ header: '月份', key: 'statisticalMonth', width: 10 },
{ header: '员工姓名', key: 'employeeName', width: 10 },
{ header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
{ header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
// { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '子女教育', key: 'childrenEducation', width: 10 },
{ header: '继续教育', key: 'continuingEducation', width: 10 },
{ header: '房贷利息', key: 'interestExpense', width: 10 },
{ header: '住房租金', key: 'housingRent', width: 10 },
{ header: '赡养老人', key: 'supportElderly', width: 10 },
{ header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
{ header: '专项扣除合计', key: 'specialDeduction', width: 10 },
{ header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
{ header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
{ header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
{ header: '适用税率', key: 'taxRate', width: 10 },
{ header: '速算扣除', key: 'deductionNumber', width: 10 },
{ header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
{ header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
// (累计税前薪资-累计五险一金-累计免征额-累计已扣专项)*税率-速算扣除-累计已纳个税=本月应纳个税
];
taxCalcList.forEach(r=>{
sheet.addRow(r);
});
return workbook;
}
async makerpt(qobj){
var self=this;
return this.db.transaction(async t=>{
const sharecode=qobj.sharecode;
const email=qobj.email;
//按照sharecode获取单位某次个税计算
var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
var sheetNameSufix="个税汇总表";
if(taxCalcList && taxCalcList.length>0){
var year=taxCalcList[0].statisticalYear;
var month=taxCalcList[0].statisticalMonth;
sheetNameSufix=year+month+sheetNameSufix;
}
var wb=await this.buildworkbook(taxCalcList);
//生成excel
var result=await this.writexls(wb,sharecode);
//异步不等待发送邮件给
var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
//发送手机短信
//写到按咋回哦sharecode,修改下载的url
return result.url;
});
}
async create(qobj){
var self=this;
return this.db.transaction(async t=>{
var task=await this.dao.create(qobj,t);
//发布任务事件
var action="new";
var taskClassName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
await self.taskManager.newTask(msg);
await self.taskManager.publish("task","newtask");
return task;
});
}
async restartTasks2(qobj){
return this.restartTasks(qobj);
}
async restartTasks(qobj){
var self=this;
var rtn={};
var tasks=await this.dao.model.findAll({raw:true});
//清空任务列表
await this.taskManager.clearlist();
for(var i=0;i<tasks.length;i++){
var tmpTask2=tasks[i];
try {
(async (tmpTask,that)=>{
var action="new";
var taskClassName=tmpTask.taskClassName;
var exp=tmpTask.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
// await that.taskManager.newTask(msg);
// await that.taskManager.publish("task","newtask");
await that.taskManager.addTask(taskClassName,exp);
})(tmpTask2,self);
} catch (e) {
rtn=null;
}
}
return rtn;
}
async delete(qobj){
var self=this;
return this.db.transaction(async t=>{
var task= await this.dao.model.findOne({where:qobj});
await this.dao.delete(task,qobj,t);
//发布任务事件
var action="delete";
var taskName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskName;
//发布任务,消息是action_taskClassName
await this.taskManager.publish("task",msg,null);
return task;
});
}
}
module.exports=TaskService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class UploadService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(UploadService));
//this.appDao=system.getObject("db.appDao");
}
}
module.exports=UploadService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class MsgHistoryService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(MsgHistoryService));
this.msgnoticeDao = system.getObject("db.msgnoticeDao");
this.userDao = system.getObject("db.userDao");
this.redisClient = system.getObject("util.redisClient");
this.businesslicenseDao = system.getObject("db.businesslicenseDao");
}
getApp(appkey){
return this.cacheManager["AppCache"].cacheApp(appkey);
}
async saveMsg(msg) {
var self = this;
console.log("save msg ", msg);
// 事务
await this.db.transaction(async function (t){
// 1.保存聊天信息
msg = await self.dao.create(msg, t);
// 2.保存好友信息
await self.msgnoticeDao.saveNotice(msg, t);
});
return msg;
}
async pushBusinessLicenseMsg(senderId, targetId, businessLicense_id) {
if(!businessLicense_id) {
return 0;
}
var notice = await this.msgnoticeDao.findOne({fromId : senderId, toId : targetId});
if(notice && notice.businessLicense_id == businessLicense_id) {
return 0;
}
var senderUser = await this.userDao.findById(senderId);
var targetUser = await this.userDao.findById(targetId);
var senderChannel = senderUser.app_id + "¥" + senderUser.id;
var targetChannel = targetUser.app_id + "¥" + targetUser.id;
var sender = senderUser.app_id + "¥" + senderUser.id + "¥" + senderUser.headUrl;
var target = targetUser.app_id + "¥" + targetUser.id + "¥" + targetUser.headUrl;
var msg = {
msgType: "mryzLicense",
sender:sender,
senderId:senderId,
target:target,
targetId:targetId,
content:businessLicense_id,
isRead:false,
businessLicense_id:businessLicense_id
}
var obj = await this.saveMsg(msg);
var bl = await this.businesslicenseDao.findById(businessLicense_id);
msg.businessLicense = bl;
msg.id = obj.id;
msg.created_at = obj.created_at;
this.redisClient.publish(senderChannel, JSON.stringify(msg));
this.redisClient.publish(targetChannel, JSON.stringify(msg));
return 1;
}
async getChatList(senderId, targetId, maxId, pageSize) {
let sql = "SELECT * FROM `msghistory` WHERE id < :maxId AND ((senderId = :senderId AND targetId = :targetId) OR (targetId = :senderId AND senderId = :targetId)) ORDER BY id DESC LIMIT :pageSize "
let params = {senderId:senderId, targetId: targetId, maxId: maxId, pageSize: pageSize};
var list = await this.dao.customQuery(sql, params);
if(!list || list.length == 0) {
return [];
}
var licenseIds = [];
var msgIds = [];
list.forEach(item => {
if(item.msgType == 'mryzLicense') {
licenseIds.push(Number(item.businessLicense_id));
}
msgIds.push(item.id);
});
if(licenseIds.length > 0) {
let licenseSql = "SELECT * FROM yz_business_license WHERE id IN (" + licenseIds.join(",") + ") ";
var licenseList = await this.businesslicenseDao.customQuery(licenseSql);
var licenseMap = [];
licenseList.forEach(item => {
licenseMap["id" + item.id] = item;
});
list.forEach(item => {
if(item.msgType == 'mryzLicense') {
item.businessLicense = licenseMap['id' + item.businessLicense_id];
}
});
}
var self = this;
setTimeout(function(){
self.setRead(senderId, targetId, list);
}, 1000);
return list;
}
async setRead(senderId, targetId, list) {
if(!list || list.length == 0) {
return;
}
var target = await this.userDao.findById(targetId);
if(!target) {
return;
}
var pushIds = [];
for(var item of list) {
if(item.isRead || senderId != item.targetId) {
continue;
}
pushIds.push(item.id);
}
if(pushIds.length == 0) {
return;
}
this.dao.updateByWhere({isRead: true}, {where:{id:{[this.db.Op.in]:pushIds}}});
var channel = target.app_id + "¥" + target.id;
var rs = await this.redisClient.publish(channel, JSON.stringify({type:"readmsg", data : pushIds}));
console.log(rs, "------------------------------------------ publish result ");
}
async readMsg(userId, id) {
var msg = await this.dao.findById(id);
if(!msg || userId != msg.targetId) {
return 0;
}
msg.isRead = true;
await msg.save();
var user = await this.userDao.findById(msg.senderId);
if(!user) {
return 0;
}
var channel = user.app_id + "¥" + user.id;
return await this.redisClient.publish(channel, JSON.stringify({type:"readmsg", data : [msg.id]}));
}
}
module.exports=MsgHistoryService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class MsgNoticeService extends ServiceBase {
constructor() {
super(ServiceBase.getDaoName(MsgNoticeService));
//this.appDao=system.getObject("db.appDao");
this.userDao = system.getObject("db.userDao");
this.businesslicenseDao = system.getObject("db.businesslicenseDao");
this.msghistoryDao = system.getObject("db.msghistoryDao");
}
getApp(appkey) {
return this.cacheManager["AppCache"].cacheApp(appkey);
}
async getUserList(userId) {
var list = await this.dao.model.findAll({
where: {
fromId: userId
},
order: [
["updated_at", "DESC"]
],
raw: true
});
if (!list || list.length == 0) {
return [];
}
var msgIds = [];
var businessLicenseIds = [];
var userIds = [];
for (var item of list) {
msgIds.push(item.lastMsgId);
businessLicenseIds.push(item.businessLicense_id);
userIds.push(item.toId);
}
var msgMap = [];
var businessLicenseMap = [];
var userMap = [];
var unreadMap = [];
// 最后一条聊天记录
if (msgIds.length > 0) {
var msgList = await this.msghistoryDao.customQuery("SELECT * FROM msghistory WHERE id IN (" + msgIds.join(",") + ") ");
msgList.forEach(item => {
msgMap["id" + item.id] = item;
});
}
// 最后一次聊天关联执照
if (businessLicenseIds.length > 0) {
var licenseList = await this.businesslicenseDao.customQuery("SELECT * FROM yz_business_license WHERE id IN (" + businessLicenseIds.join(",") + ") ");
var serviceTypeIds = [];
for (var item of licenseList) {
serviceTypeIds.push(item.serviceTypeOneId);
serviceTypeIds.push(item.serviceTypeTwoId);
}
if (serviceTypeIds.length > 0) {
var sql = "SELECT id, name FROM `p_service_type` WHERE id IN (" + serviceTypeIds.join(",") + ") ";
var typeList = await this.dao.customQuery(sql);
var typeMap = [];
if (typeList && typeList.length > 0) {
for (var t of typeList) {
typeMap["type_id_" + t.id] = t.name;
if (t.id == item.serviceTypeOneId) {
item.serviceTypeOneName = t.name;
} else if (t.id == item.serviceTypeTwoId) {
item.serviceTypeTwoName = t.name;
} else {}
}
}
}
for (var item of licenseList) {
item.serviceTypeOneName = typeMap["type_id_" + item.serviceTypeOneId];
item.serviceTypeTwoName = typeMap["type_id_" + item.serviceTypeTwoId];
}
licenseList.forEach(item => {
businessLicenseMap["id" + item.id] = item;
});
}
// 聊天好友用户信息
if (userIds.length > 0) {
var userList = await this.userDao.customQuery("SELECT * FROM p_user WHERE id IN (" + userIds.join(",") + ") ");
userList.forEach(item => {
userMap["id" + item.id] = item;
});
}
// 未读消息数量
var unreadList = await this.userDao.customQuery("SELECT senderId, COUNT(1) AS num FROM `msghistory` WHERE isRead = 0 AND targetId = " + userId + " GROUP BY senderId ");
unreadList.forEach(item => {
unreadMap["id" + item.senderId] = item.num;
});
var rs = [];
for (var i in list) {
var item = list[i];
item.lastMsg = msgMap["id" + item.lastMsgId];
item.businessLicense = businessLicenseMap["id" + item.businessLicense_id];
item.friend = userMap["id" + item.toId];
item.unreadCount = unreadMap["id" + item.toId] || 0;
rs.push(item);
}
return rs;
}
async countUnread(userId) {
debugger;
var unreadList = await this.userDao.customQuery("SELECT COUNT(1) AS num FROM `msghistory` WHERE isRead = 0 AND targetId = " + userId);
var count = 0;
if (unreadList && unreadList.length > 0) {
count = unreadList[0].num || 0;
}
return count;
}
}
module.exports = MsgNoticeService;
\ No newline at end of file
const system = require("../system");
var moment = require('moment');
const settings = require("../../config/settings");
class ServiceBase {
constructor(gname, daoName) {
//this.dbf=system.getObject("db.connection");
this.db = system.getObject("db.common.connection").getCon();
this.cacheManager = system.getObject("db.common.cacheManager");
this.daoName = daoName;
this.dao = system.getObject("db." + gname + "." + daoName);
this.restS = system.getObject("util.restClient");
this.md5 = require("MD5");
}
getEncryptStr(str) {
if (!str) {
throw new Error("字符串不能为空");
}
var md5 = this.md5(str + "_" + settings.salt);
return md5.toString().toLowerCase();
}
static getDaoName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")).toLowerCase() + "Dao";
}
async findAndCountAll(obj) {
const apps = await this.dao.findAndCountAll(obj);
return apps;
}
async refQuery(qobj) {
return this.dao.refQuery(qobj);
}
async bulkDelete(ids) {
var en = await this.dao.bulkDelete(ids);
return en;
}
async delete(qobj) {
return this.dao.delete(qobj);
}
async create(qobj) {
return this.dao.create(qobj);
}
async update(qobj, tm = null) {
return this.dao.update(qobj, tm);
}
async updateByWhere(setObj, whereObj, t) {
return this.dao.updateByWhere(setObj, whereObj, t);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.dao.customExecAddOrPutSql(sql, paras);
}
async customQuery(sql, paras, t) {
return this.dao.customQuery(sql, paras, t);
}
async findCount(whereObj = null) {
return this.dao.findCount(whereObj);
}
async findSum(fieldName, whereObj = null) {
return this.dao.findSum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
return this.dao.getPageList(pageIndex, pageSize, whereObj, orderObj, attributesObj, includeObj);
}
async findOne(obj) {
return this.dao.findOne(obj);
}
async findById(oid) {
return this.dao.findById(oid);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid(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(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo(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('');
}
//kong统一处理
//统一注册组件
async cformregister(opurl,opts){
try{
let rtn=await system.post3wFormTypeReq(opurl,opts)
console.log(rtn);
if(rtn.statusCode==409){
//return new Error("已经存在相同的统一账号名称!");
return null;
}
if(rtn.statusCode==201){
return rtn.data;
}else{
throw new Error(rtn.data);
}
}catch(e){
console.log(e);
return null;
}
}
async cget(opurl){
let rtn=await system.getReq(opurl)
return rtn;
}
async cjsonregister(opurl,opts){
try{
let rtn=await system.postJsonTypeReq(opurl,opts)
console.log(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,",rtn);
if(rtn.statusCode==409){
//return new Error("已经存在相同的统一账号名称!");
return null;
}
if(rtn.statusCode==201){
return rtn.data;
}else{
throw new Error(rtn.data);
}
return null;
}catch(e){
console.log(e);
return null;
}
}
async cdel(opurl){
try{
let rtn=await system.delReq(opurl)
if(rtn.statusCode==204){
return {};
}else{
throw new Error(rtn.data);
}
}catch(e){
console.log(e);
return null;
}
}
static bindPluginUrl(rname){
return settings.kongurl+"routes/"+rname+"/plugins";
}
static newRouteUrl(sname){
return settings.kongurl+"services/"+sname+"/routes";
}
static newServiceUrl(){
return settings.kongurl+"services";
}
static newConsumerUrl(){
return settings.kongurl+"consumers";
}
static newJwtCredUrl(consumername){
return settings.kongurl+"consumers/"+consumername+"/jwt";
}
static serviceUrl(sname){
return settings.kongurl+"services/"+sname;
}
static routeUrl(rname){
return settings.kongurl+"routes/"+rname;
}
static consumerUrl(consumerName){
return settings.kongurl+"consumers/"+consumerName;
}
}
module.exports = ServiceBase;
var fs = require("fs");
var objsettings = require("../config/objsettings");
var settings = require("../config/settings");
const request = require('request');
class System {
static declare(ns) {
var ar = ns.split('.');
var root = System;
for (var i = 0, len = ar.length; i < len; ++i) {
var n = ar[i];
if (!root[n]) {
root[n] = {};
root = root[n];
} else {
root = root[n];
}
}
}
static async delReq(url,qdata){
let rtn={}
let promise=new Promise(function(resv,rej){
request.del({
url: url,
qs: qdata
}, function(error, response, body) {
rtn.statusCode=response.statusCode
if (!error) {
if(body){
let data=JSON.parse(body)
rtn.data=data
}else{
rtn.data=null
}
resv(rtn);
}else{
rej(error)
}
});
})
return promise;
}
static async getReq(url,qdata){
let rtn={}
let promise=new Promise(function(resv,rej){
request.get({
url: url,
json: true,
qs: qdata
}, function(error, response, body) {
rtn.statusCode=response.statusCode;
if (!error) {
if(body){
rtn.data=body
}else{
rtn.data=null
}
resv(rtn);
}else{
rej(error);
}
});
})
return promise;
}
static async postJsonTypeReq(url,data){
let rtn={}
let promise=new Promise(function(resv,rej){
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: data
}, function(error, response, body) {
rtn.statusCode=response.statusCode
if (!error) {
if(body){
rtn.data=body
}else{
rtn.data=null
}
resv(rtn);
}else{
rej(error)
}
});
})
return promise;
}
static async post3wFormTypeReq(url,data){
let rtn={}
let promise=new Promise(function(resv,rej){
request.post({
url: url,
form: data
}, function(error, response, body) {
rtn.statusCode=response.statusCode
if (!error) {
let data=JSON.parse(body)
rtn.data=data
resv(rtn);
}else{
rej(error)
}
});
})
return promise;
}
static async postMpFormTypeReq(url,formdata){
let promise=new Promise(function(resv,rej){
request.post({
url: url,
formData: formdata
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
resv(body);
}else{
rej(error)
}
});
})
return promise;
}
/**
* 请求返回成功
* @param {*} data 操作成功返回的数据,有值为成功,无值为失败
* @param {*} okmsg 操作成功的描述
* @param {*} req 请求头信息
*/
static getResult(data, opmsg = "操作成功", req) {
return {
status: !data ? -1 : 0,
msg: opmsg,
data: data,
bizmsg: req && req.session && req.session.bizmsg ? req.session.bizmsg : "empty"
};
}
/**
* 请求返回成功
* @param {*} data 操作成功返回的数据
* @param {*} okmsg 操作成功的描述
*/
static getResultSuccess(data, okmsg = "success") {
return {
status: 0,
msg: okmsg,
data: data,
};
}
/**
* 请求返回失败
* @param {*} status 操作失败状态,默认为-1
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
static getResultFail(status = -1, errmsg = "fail", data = null) {
return {
status: status,
msg: errmsg,
data: data,
};
}
/**
* 请求处理异常
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
static getResultError(errmsg = "fail", data = null) {
return {
status: -200,
msg: errmsg,
data: data,
};
}
static register(key, ClassObj,groupName,filename) {
if (System.objTable[key] != null) {
throw new Error("相同key的对象已经存在");
} else {
let obj = new ClassObj(groupName,filename);
System.objTable[key] = obj;
}
return System.objTable[key];
}
static getObject(objpath) {
var pathArray = objpath.split(".");
var packageName = pathArray[0];
var groupName = pathArray[1];
var filename = pathArray[2];
var classpath = "";
if (filename) {
classpath = objsettings[packageName] + "/" + groupName;
} else {
classpath = objsettings[packageName];
filename = groupName;
}
var objabspath = classpath + "/" + filename + ".js";
//判断文件的存在性
//如果不存在,需要查看packageName
//如果packageName=web.service,dao
if (System.objTable[objabspath] != null) {
return System.objTable[objabspath];
} else {
var ClassObj =null;
try{
ClassObj = require(objabspath);
}catch(e){
let fname=objsettings[packageName+"base"];
ClassObj = require(fname);
}
if(ClassObj.name=="Dao"){
let modelname=filename.substring(0,filename.lastIndexOf("Dao"))
return System.register(objabspath, ClassObj,modelname);
}
if(ClassObj.name.indexOf("Ctl")>=0){
console.log(ClassObj.name);
}
return System.register(objabspath, ClassObj,groupName,filename);
}
}
static getSysConfig() {
var configPath = settings.basepath + "/app/base/db/metadata/index.js";
// if(settings.env=="dev"){
// console.log("delete "+configPath+"cache config");
// delete require.cache[configPath];
// }
delete require.cache[configPath];
var configValue = require(configPath);
return configValue.config;
}
static get_client_ip(req) {
var ip = req.headers['x-forwarded-for'] ||
req.ip ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket && req.connection.socket.remoteAddress) || '';
var x = ip.match(/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/);
if (x) {
return x[0];
} else {
return "localhost";
}
};
}
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
/*
编码说明,
1000----1999 为请求参数验证和app权限验证
2000----2100 为请求用户信息操作验证,如:注册,登录,获取验证码,修改用户信息,修改用户密码
*/
System.objTable = {};
//访问token失效,请重新获取
System.tokenFail = 1000;
//appKey授权有误
System.appKeyError = 1100;
//应用处于待审核等待启用状态
System.waitAuditApp = 1110;
//获取访问token失败
System.getAppInfoFail = 1130;
//已经存在此用户,注册失败
System.existUserRegFail = 2000;
//用户名或密码错误
System.userLoginFail = 2010;
//用户名错误
System.userNameLoginFail = 2020;
//验证验证码错误
System.verifyVCodeFail = 2030;
//opencode存储的值已经失效
System.verifyOpencodeFail = 2040;
//重复操作
System.redoFail = 2050;
module.exports = System;
// (async ()=>{
// try{
// let d=await System.getReq("http://127.0.0.1:8001x/services")
// console.log(d)
// }catch(e){
// console.log(e);
// }
// })()
\ No newline at end of file
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 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.
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 diff is collapsed. Click to expand it.
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.
This diff is collapsed. Click to expand it.
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.
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.
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