Commit 33af1194 by 宋毅

tj

parent 5ef39829
#!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang/node105:v2
MAINTAINER jy "jiangyong@gongsibao.com"
ADD bigdata /apps/bigdata/
WORKDIR /apps/bigdata/
ADD igirl-zcapi-web /apps/igirl-zcapi-web/
WORKDIR /apps/igirl-zcapi-web/
RUN cnpm install -S
CMD ["node","/apps/bigdata/main.js"]
CMD ["node","/apps/igirl-zcapi-web/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
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 system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class AuthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(AuthCtl));
}
async saveAuths(qobj,query,req){
var auths=qobj.aus;
var xrtn=await this.service.saveAuths(auths,req.appid,req.tanentid);
return system.getResult(xrtn);
}
async findAuthsByRole(qobj,query,req){
var rolecodestrs=qobj.rolecode;
var xrtn=await this.service.findAuthsByRole(rolecodestrs,req.appid,req.tanentid);
return system.getResult(xrtn);
}
}
module.exports=AuthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class DataauthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(DataauthCtl));
}
async saveauth(qobj,querybij,req){
var arys=qobj.arys;
var uid=qobj.uid;
var refmodel=qobj.modelname;
var u=await this.service.saveauth({
user_id:uid,
modelname:refmodel,
auths:arys.join(","),
app_id:req.appid,
});
return system.getResult(u);
}
async fetchInitAuth(qobj,querybij,req){
var uid=qobj.uid;
var refmodel=qobj.modelname;
var authtmp=await this.service.findOne({user_id:uid,modelname:refmodel,app_id:req.appid});
if(authtmp){
var auths= authtmp.auths;
var arys=auths.split(",");
return system.getResult(arys);
}else{
return system.getResultSuccess([]);
}
}
}
module.exports=DataauthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class OrgCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(OrgCtl));
}
//检查是否已经存在主要岗位
async checkMainPosition(p,q,req){
return this.service.checkMainPosition(p,q,req);
}
async changePos(p,q,req){
var toorgid=p.orgid;
var uid=p.uid;
var rtn= await this.service.changePos(toorgid,uid);
return system.getResult(rtn);
}
async create(p,q,req){
return super.create(p,q,req);
}
async delete(p,q,req){
return super.delete(p,q,req);
}
async update(p,q,req){
return super.update(p,q,req);
}
async initOrgs(p,q,req){
var tocompany=req.session.tocompany;
//按照公司名称查询,是否存在节点,不存在,就创建根节点
//如果存在就按照名称查询出当前和她的字节点
var rtn=await this.service.initOrgs(tocompany,req.appid);
return system.getResult(rtn);
}
async findOrgById(p,q,req){
var rtn=await this.service.findOrgById(p.id);
return system.getResult(rtn);
}
}
module.exports=OrgCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class RoleCtl extends CtlBase {
constructor() {
super("auth",CtlBase.getServiceName(RoleCtl));
//this.loginS=system.getObject("service.userSve");
this.roleS=system.getObject("service.auth.roleSve");
this.redisClient=system.getObject("util.redisClient");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
}
module.exports = RoleCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
//this.loginS=system.getObject("service.userSve");
this.acS = system.getObject("service.auth.accountSve");
this.companyS = system.getObject("service.common.companySve");
}
async initNewInstance(queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
//获取验证码,发送给指定手机
async fetchVcode(pobj, qobj, req) {
var mobile = pobj.u;
//生成一个验证码,发送
// var vcode = await this.service.getUidStr(6, 10);
// await this.smsS.sendMsg(mobile, vcode);
return system.getResult({ vcodestr: "123" });
}
async checkLogin(gobj, qobj, req) {
//当前如果缓存中存在user,还是要检查当前user所在的域名,如果不和来访一致,则退出重新登录
if (req.session.user) {
var x = null;
if (req.session.user.Roles) {
x = req.session.user.Roles.map(r => { return r.code });
}
var tmp = {
id: req.session.user.id,
userName: req.session.user.userName,
nickName: req.session.user.nickName,
mobile: req.session.user.mobile,
isAdmin: req.session.user.isAdmin,
isSuper:req.session.user.isSuper,
created_at: req.session.user.created_at,
email: req.session.user.email,
headUrl: req.session.user.headUrl,
roles: x ? x.join(",") : "",
owner:req.session.user?req.session.user.owner:null,
tanentor_id:req.session.user?req.session.user.tanentor_id:null,
}
return system.getResult(tmp, "操作成功", req);
} else {
req.session.user = null;
//req.session.destroy();
return system.getResult(null, "操作失败", req);
}
}
async exit(pobj, qobj, req) {
if(req.session.app.id==settings.platformid){
req.session.user = null;
req.session.tocompany=null;
req.session.destroy();
return system.getResultSuccess({ "env": settings.env });
}else{
req.session.user=req.session.originalUID;
req.session.app=req.session.originalAPP;
return system.getResultSuccess({ "env": settings.env });
}
}
/**
*
* //用户重名检查--account
*
* 先按照username和password检查,是否存在account,
* 如果不存在account(第一次注册),检查查询字符串中是否存在appkey,
* 如果不存在说明是平台用户注册,就从会话中取出app_id
*
* 如果存在(已经注册过)
* 检查查询字符串appkey,如果存在,那么就按照appkey和userName和password去查看是否存在用户
* 如果存在,提示已经有同名用户存在;
* 如果不存在,那么就创建app下的用户
* 如果不存在,就按照会话中app_id去查看是否存在用户
*
*/
//重名检查,检查是否有
async checkSameName(pobj, qobj, req) {
var uname = pobj.uname;
//按照appid查询出app
var rtn = await this.service.checkSameName(uname, req.appid);
return system.getResult(rtn);
}
/**
* 查询某一个应用管理员信息
* @param {*} pobj
* @param {*} qobj
* @param {*} req
*/
async findAppAdmin(pobj, qobj, req) {
var appid = pobj.appid;
var user = await this.service.findOne({ isAdmin: true, app_id: appid });
return system.getResult(user);
}
async register(pobj, qobj, req) {
var appid = req.session.app.id;
var jumpUrl = req.session.app.authUrl;
var fmuser = pobj.u;
fmuser.app_id = req.appid;
if (!fmuser.userName) {
return system.getResult(null, "用户名不能为空");
}
if (!fmuser.mobile) {
return system.getResult(null, "手机号不能为空");
}
if (!fmuser.password) {
return system.getResult(null, "密码不能为空");
}
if (appid == settings.platformid){//如果是开放平台应用注册,设置所属公司
fmuser.owner_id=settings.platformid;
}else{//否则 todo
if(!fmuser.owner_id && req.session.tocompany){
fmuser.owner_id=req.tanentid;
}
}
var ruser = await this.service.register(fmuser);
if (ruser) {
if (appid != settings.platformid) {//说明是委托注册或登录
// this.redisClient.setWithEx(req.session.id,ruser,3600);
await this.cacheManager["OpenCodeCache"].cache(req.session.id, ruser, 30);
jumpUrl = jumpUrl + "?code=" + req.session.id;
} else {
//登录
req.session.user = ruser;
//设置系统默认公司
var pcompany=await this.companyS.findById(settings.platformcompanyid);
req.session.company=pcompany;
}
return system.getResultSuccess({ user: ruser, jumpUrl: jumpUrl });
} else {
return system.getResult(null, "用户已存在, 请修改并重试");
}
}
//管理员新增用户,设置默认密码
async create(pobj, queryobj, req) {
pobj.appid = req.appid;
pobj.owner_id=req.tanentid;
//新增用户时,获取当前用户的租户id
pobj.tanentor_id=req.session.user.tanentor_id;
var rtn=await this.service.createUser(pobj);
return system.getResult(rtn);
}
/**
* inuser 当前的req.session.app不是平台时,退出按钮关闭的是
* req.session.inuser
* @param {*} req
*/
async authByCode(req) {
var opencode = req.query.code;
var user = await this.service.authByCode(opencode);
if (user) {
req.session.originalUID=req.session.user;
req.session.originalAPP=req.session.app;
req.session.user = user;//防止覆盖租户的session
req.session.tocompany=user.owner;//从应用中导航到平台管理,平台完成登录
} else {
req.session.user = null;
}
return user;
}
// async bindCompany(p,q,req){
// var cmpinfo=p.u;
// var cmp=await this.service.bindCompany(cmpinfo,req.session.user.id);
// req.session.company=cmp;
// return system.getResult(cmp);
// }
//非开放平台登录方法
async goLoginForApp(p,q,req){
var app=p;
var appid=app.id;
var jumpUrl = app.authUrl;
var usercurrent=req.session.user;
var pobj={};
pobj.u={
userName:usercurrent.userName,
password:usercurrent.password,
mobile:usercurrent.mobile,
app_id:appid,
isNavto:true,
owner_id:req.session.tocompany?req.session.tocompany.id:null
}
var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
if (existedUser != null) {
await this.cacheManager["OpenCodeCache"].cache(req.session.id, existedUser, 60);
jumpUrl = jumpUrl + "?code=" + req.session.id;
return system.getResult({ user: existedUser, jumpUrl: jumpUrl });
}else {
return system.getResultFail(-1, "账号或密码有误.");
}
}
async login(pobj, qobj, req) {
var appid = req.session.app.id;
var jumpUrl = req.session.app.authUrl;
if (req.session.toapp) {
jumpUrl = req.session.toapp.authUrl;
pobj.u.isNavto=true;
//state为p_app表中appkey
} else{
pobj.u.isNavto=false;
}
pobj.u.app_id = appid;
if(!pobj.u.owner_id){//说明不是从平台界面,利用go进入,所以是自主登录
pobj.u.owner_id=pobj.tanentid;
}
var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
if (existedUser != null) {
if (appid != settings.platformid) {//非平台应用
await this.cacheManager["OpenCodeCache"].cache(req.session.id, existedUser, 60);
jumpUrl = jumpUrl + "?code=" + req.session.id;
if (req.session.toapp) {
jumpUrl = jumpUrl + "&srcKey=" + req.session.app.appkey;
}
} else {
req.session.user = existedUser;
//查询出companys信息,缓存当前的compnay,todo 放到service
var pcompany=await this.companyS.findById(settings.platformcompanyid);
req.session.company=pcompany;
//设置平台登录后默认要去往的租户公司
//查看用户身上是否有tanentor_id值,如果没有,说明是平台租户
var maproleids= existedUser.Roles.map((r)=>r.id);
var istanentorpassrole=maproleids.indexOf(settings.passroleid)>=0 || maproleids.indexOf(settings.commonroleid)>=0;
if(istanentorpassrole && !existedUser.isAdmin && !existedUser.isSuper){
var coms=existedUser.companies;
if(coms && coms.length>1){//因为平台默认公司的存在
var comfinds=coms.find((item)=>{
return item.usercompany.isCurrent==true;
});
if(comfinds){
req.session.tocompany=comfinds;
}
}
}else{
req.session.tocompany=existedUser.owner;
}
}
if (!existedUser.isEnabled) {
return system.getResultFail(system.waitAuditApp, "您的账户处于待审核等待启用状态.");
}
return system.getResult({ user: existedUser, jumpUrl: jumpUrl });
} else {
return system.getResultFail(-1, "账号或密码有误.");
}
}
}
module.exports = UserCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class AppCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async findAllApps() {
var rtns = await this.service.findAllApps();
return system.getResult(rtns);
}
async update(pobj, queryobj, req){
return super.update(pobj, queryobj, req);
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
rtn.appkey = this.getUUID();
rtn.secret = this.getUUID();
return system.getResult(rtn);
}
async resetPass(pobj, queryobj, req) {
pobj.password = await super.encryptPasswd(settings.defaultpwd);
var rtn = this.service.resetPass(pobj);
return system.getResult(rtn);
}
async createAdminUser(pobj, queryobj, req) {
pobj.password = settings.defaultpwd;
var rtn = this.service.createAdminUser(pobj);
return system.getResult(rtn);
}
async create(pobj, queryobj, req) {
//设置创建者,需要同时创建app管理员、默认密码、电话
pobj.creator_id = req.session.user.id;
// pobj.password=super.encryptPasswd(settings.defaultpwd);
//构造默认的应用相关的URL
pobj.authUrl=settings.protocalPrefix+pobj.domainName+"/auth";
pobj.docUrl=settings.protocalPrefix+pobj.domainName+"/web/common/metaCtl/getApiDoc";
pobj.uiconfigUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/config/fetchAppConfig";
pobj.opCacheUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/opCache/opCacheData";
pobj.notifyCacheCountUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/opCache/recvNotificationForCacheCount";
var app = await super.create(pobj,queryobj, req);
return system.getResult(app);
}
async fetchApiCallData(pobj, queryobj, req){
var curappkey=pobj.curappkey;
//检索出作为访问时的app呼出调用数据
var rtn= await this.service.fetchApiCallData(curappkey);
return system.getResultSuccess(rtn);
}
//接受缓存计数通知接口
async recvNotificationForCacheCount(p,q,req){
return this.service.recvNotificationForCacheCount(p);
}
}
module.exports = AppCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
class CachSearchesCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CachSearchesCtl));
}
async initNewInstance(queryobj, qobj) {
return system.getResultSuccess({});
}
async findAndCountAll(pobj, gobj, req) {
pobj.opCacheUrl = req.session.app.opCacheUrl;
pobj.appid = req.appid;
return await this.service.findAndCountAllCache(pobj);
}
async delCache(queryobj, qobj, req) {
var param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param);
}
async clearAllCache(queryobj, qobj, req) {
var param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param);
}
}
module.exports = CachSearchesCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class CompanyCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CompanyCtl));
this.userS=system.getObject("service.auth.userSve");
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
return system.getResult(rtn);
}
//to do租户在创建公司的时候,需要同时维护平台下面,用户所属租户是当前租户的公司
//当删除公司时,需要同时删除公司关联的APP,还有用户关联的公司
async create(p,q,req){
var user=await this.userS.findOne({id:p.userid});
var uuidstr=this.getUUID();
p.companykey=uuidstr;
var company=await this.service.create(p,user);
req.session.tocompany=company;
return system.getResult(company);
}
async update(p,q,req){
//修改重新刷新页面,初始化页面的公司信息
var rtn=await super.update(p,q,req);
req.session.company=p;
return system.getResult(rtn);
}
async buyApp(p,q,req){
var cmpid=req.session.tocompany.id;
var user=req.session.user;
var cmpfind=await this.service.buyApp(p,cmpid,user);
req.session.tocompany=cmpfind;
return system.getResult(cmpfind.apps);
}
//设置当前用户选择的公司为当前公司
async settocompany(p,q,req){
p.isCurrent=true;
req.session.tocompany=p;
var cmp= await this.service.settocompany(p);
return system.getResult(cmp);
}
async findAndCountAll(p,q,req){
var comps=await this.service.findAndCountAll(p,q,req);
var rtns=[];
for(var cmp of comps){
if(cmp.id!=settings.platformcompanyid){
var rtntmp={
id:cmp.id,
name:cmp.name,
description:cmp.description,
logoUrl:cmp.logoUrl,
isCurrent:cmp.usercompany.isCurrent,
apps:cmp.apps?cmp.apps:[]
}
rtns.push(rtntmp);
}
}
var rtn = {};
rtn.results = {count:rtns.length,rows:rtns};
rtn.aggresult = {};
return system.getResult(rtn);
}
}
module.exports = CompanyCtl;
var system = require("../../../system")
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;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class CacheLocker extends CacheBase{
constructor(){
super();
this.prefix="locker_";
}
desc(){
}
prefix(){
}
async init(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
async enter(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpop(key);
}
async release(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
}
module.exports=CacheLocker;
// var x=new CacheLocker();
// x.init("hello").then(d=>{
// x.enter("hello").then(m=>{
// console.log(m);
// });
// });
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//开放平台缓存所有的应用的访问token
class ApiAccessKeyCache extends CacheBase {
constructor() {
super();
this.appDao = system.getObject("db.common.appDao");
}
desc() {
return "缓存访问Token";
}
prefix() {
return "gapps_accesskey:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
if (!items || items.length == 0) {
return null;
}
const configValue = await this.appDao.findOne(items[0], val);
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports = ApiAccessKeyCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiAccuCache extends CacheBase{
constructor(){
super();
this.apitradeDao=system.getObject("db.callcount.apitradeDao");
}
desc(){
return "API累计调用次数和累计余额";
}
prefix(){
return "api_accu:";
}
async addCallCount(apikey,n){
var key=this.prefix+apikey;
var result=await this.redisClient.hincrby(key,"callcount",n);
return result;
}
async addCallBalance(apikey,n){
var key=this.prefix+apikey;
var result=await this.redisClient.hincrby(key,"amount",n);
return result;
}
async getApiCallAccu(srckey){
var apikey=srckey.split("_")[0];
var key=this.prefix+srckey;
const cachedVal= await this.redisClient.hgetall(key);
if(!cachedVal || cachedVal=="undefined"){
var count= await this.apitradeDao.model.count({
where:{
srcappkey:apikey,
tradeType:"consume",
}
});
var amount=await this.apitradeDao.model.sum("amount",{
where:{
srcappkey:apikey,
}
});
var map={"callcount":count?count:0,"amount":amount?amount:0};
this.redisClient.hmset(key,map);
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
return map;
}else{
return cachedVal;
}
}
}
module.exports=ApiAccuCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiCallCountCache extends CacheBase{
constructor(){
super();
this.apitradeDao=system.getObject("db.common.apitradeDao");
}
desc(){
return "API调用次数";
}
prefix(){
return "api_call:";
}
async addCallCount(apikey,callpath,n){
var key=this.prefix+apikey+"_"+callpath;
var result=await this.redisClient.hincrby(key,"callcount",n);
return result;
}
async addCallBalance(apikey,callpath,n){
var key=this.prefix+apikey+"_"+callpath;
var result=await this.redisClient.hincrby(key,"amount",n);
return result;
}
async getApiCallCount(apikey,callpath){
var key=this.prefix+apikey+"_"+callpath;
const cachedVal= await this.redisClient.hgetall(key);
if(!cachedVal || cachedVal=="undefined"){
var count= await this.apitradeDao.model.count({
where:{
srcappkey:apikey,
op:callpath,
tradeType:"consume",
}
});
var amount=await this.apitradeDao.model.sum("amount",{
where:{
srcappkey:apikey,
op:callpath,
tradeType:"consume",
}
});
var map={"callcount":count?count:0,"amount":amount?amount:0};
this.redisClient.hmset(key,map);
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
return map;
}else{
return cachedVal;
}
}
}
module.exports=ApiCallCountCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class InitGiftCache extends CacheBase{
constructor(){
super();
this.pConfigDao=system.getObject("db.common.pconfigDao");
}
desc(){
return "初始赠送";
}
prefix(){
return "g_pconfig_initGift";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
const config=await this.pConfigDao.model.findOne({where:{configType:'initGift',appkey:inputkey},raw:true});
const num2=Number(config.configValue);
return num2;
}
}
module.exports=InitGiftCache;
const CacheBase=require("../cache.base");
//缓存当前登录用户的opencode--指向公共平台的委托登录code
class OpenCodeCache extends CacheBase{
constructor(){
super();
}
desc(){
return "开放用户缓存";
}
prefix(){
return "pl_opencode_";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
return JSON.stringify(val);
}
}
module.exports=OpenCodeCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class PConfigCache extends CacheBase{
constructor(){
super();
this.pConfigDao=system.getObject("db.common.pconfigDao");
}
desc(){
return "平台配置参数";
}
prefix(){
return "g_pconfig";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
const configValue=await this.pConfigDao.model.findAll({where:{appkey:inputkey},attributes:["name","configType","configValue"],raw:true});
var s=JSON.stringify(configValue);
return s;
}
}
module.exports=PConfigCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
// const authUtils = require("../../utils/businessManager/authUtils");
const uuidv4 = require('uuid/v4');
//缓存首次登录的赠送的宝币数量
class UIRemoteConfigCache extends CacheBase {
constructor() {
super();
}
desc() {
return "非平台应用UI配置缓存";
}
prefix() {
return "g_uiremoteconfig_";
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var url = items[0];
const cacheManager = await system.getObject("db.common.cacheManager");
var authUtils = system.getObject("util.businessManager.authUtils");
var appData = await authUtils.getTokenInfo(settings.appKey, settings.secret);
if (appData.status != 0) {
return null;
}
//按照访问token
var rtnKey=appData.data.accessKey;
const restS = await system.getObject("util.restClient");
var restResult = await restS.execPostWithAK({}, url, rtnKey);
if (restResult) {
if (restResult.status == 0) {
var resultRtn = restResult.data;
return JSON.stringify(resultRtn);
}
}
return null;
}
}
module.exports = UIRemoteConfigCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class VCodeCache extends CacheBase {
constructor() {
super();
this.smsUtil = system.getObject("util.smsClient");
}
// isdebug() {
// return settings.env == "dev";
// }
desc() {
return "缓存给手机发送的验证码60妙";
}
prefix() {
return "g_vcode_"
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
//inputkey采用appkey_mobile的形式
var mobile = inputkey.split("_")[1];
var tmplCode = val;
var signName = items ? items[0] : "";
var vcode = await this.smsUtil.getUidStr(6, 10);
// var content=tmpl.replace(/\|vcode\|/g,vcode);
//this.smsUtil.sendMsg(mobile,content);
if (!tmplCode && !signName) {
this.smsUtil.sendMsg(mobile, vcode);
} //tmplCode为发送短信编码,需在阿里开通,signName为短信头描述信息,二者没有传递则用默认的发送验证码
else {
this.smsUtil.aliSendMsg(mobile, tmplCode, signName, JSON.stringify({ code: vcode }));
}
return JSON.stringify({ vcode: vcode });
}
}
module.exports = VCodeCache;
const system=require("../../../system");
const Dao=require("../../dao.base");
class AccountDao extends Dao{
constructor(){
super(Dao.getModelName(AccountDao));
}
async findOrCreate(ac,t){
var account= await this.model.findOne({where:{unionId:ac.unionId}},{transaction:t});
if(account){
return account;
}else{
account=await this.model.create(ac,{transaction:t});
return account;
}
}
async findOneByOnlyCode(onlycode){
return this.model.findOne({"where":{"onlyCode":onlycode}});
}
}
module.exports=AccountDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class AuthDao extends Dao{
constructor(){
super(Dao.getModelName(AuthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=AuthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class DataauthDao extends Dao{
constructor(){
super(Dao.getModelName(DataauthDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=DataauthDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OrgDao extends Dao{
constructor(){
super(Dao.getModelName(OrgDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
}
module.exports=OrgDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class PAccountDao extends Dao{
constructor(){
super(Dao.getModelName(PAccountDao));
}
async findPAccount(t){
return this.model.findOne({},{transaction:t});
}
}
module.exports=PAccountDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class RoleDao extends Dao{
constructor(){
super(Dao.getModelName(RoleDao));
}
async findOne(paramappid,t){
var app= await this.model.findOne({where:{appid:paramappid}},{transaction:t});
return app;
}
extraWhere(obj,w,qc,linkAttrs){
// if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj);
// // w["app_id"]=obj.appid;
// // }
// }
w["app_id"]=obj.appid;
w["company_id"]=obj.tanentid;
return w;
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.app,}]};
}
async preUpdate(u){
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
await this.model.update(obj2,{where:{id:obj2.id}});
var role=await this.model.findOne({where:{id:obj2.id}});
return role;
}
async preCreate(u){
return u;
}
async create(u,t){
var self=this;
var u2= await this.preCreate(u);
if(t){
var role= await this.model.create(u2,{transaction: t});
return role;
}else{
var role= await this.model.create(u2);
return role;
}
}
}
module.exports=RoleDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class UsereaccountDao extends Dao{
constructor(){
super(Dao.getModelName(UsereaccountDao));
}
}
module.exports=UsereaccountDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ApiTradeDao extends Dao{
constructor(){
super(Dao.getModelName(ApiTradeDao));
}
// extraWhere(obj,w){
// if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("mytraderecord")>0){//说明是普通用户的交易查询
// w["user_id"]=obj.uid;
// }
// }
// return w;
// }
async create(tradeobj,t){
var trade=await super.create(tradeobj,t)
return trade;
}
}
module.exports=ApiTradeDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ArticleDao extends Dao{
constructor(){
super(Dao.getModelName(ArticleDao));
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.newschannel,attributes:["id","title"]},]};
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
}
module.exports=ArticleDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ChannelDao extends Dao{
constructor(){
super(Dao.getModelName(ChannelDao));
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.role,as:"Roles",attributes:["id","name"]}]};
}
async preUpdate(u){
if(u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var channel=await this.model.findOne({where:{id:obj2.id}});
channel.setRoles(obj2.roles);
return channel;
}
}
module.exports=ChannelDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class LoopplayDao extends Dao{
constructor(){
super(Dao.getModelName(LoopplayDao));
}
// channelCode: ""
// extraModelFilter(){
// return {"key":"include","value":[{model:this.db.models.newschannel,attributes:["id","title"]},]};
// }
extraWhere(obj, w){
let channelCode = obj.channelCode || '';
if(channelCode == "index") {
w["channelCode"] = '';
} else if(channelCode) {
w["channelCode"] = channelCode;
}
// if(pageType == 1) {
// w["status"] = {[this.db.Op.in]: ['1']};
// } else if (pageType == 2) {
// w["status"] = {[this.db.Op.in]: ['2']};
// } else if (pageType == 3) {
// w["status"] = {[this.db.Op.in]: ['4','8','16']};
// }
return w;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
}
module.exports=LoopplayDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class NewschannelDao extends Dao{
constructor(){
super(Dao.getModelName(NewschannelDao));
}
async findAgreenment(queryobj,qobj,req){
var result =await this.model.findAll({
where:{id:1},
include:{
model:this.db.models.article,
limit:1,
offset:0
},
});
console.log("---------------------------------------------------------------zhangjiao");
console.log(result);
return result;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
async findPrev5(queryobj,qobj){
console.log(qobj);
return this.model.findAll({
where:{isPubed:1},
include:{
model:this.db.models.article,
limit:5,
offset:0
},
limit:6,
offset:0,
});
}
}
module.exports=NewschannelDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class SloganpictureDao extends Dao{
constructor(){
super(Dao.getModelName(SloganpictureDao));
}
// extraModelFilter(){
// return {"key":"include","value":[{model:this.db.models.newschannel,attributes:["id","title"]},]};
// }
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["orderNo","ASC"]];
}
}
module.exports=SloganpictureDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ApiTradeDao extends Dao{
constructor(){
super(Dao.getModelName(ApiTradeDao));
}
// extraWhere(obj,w){
// if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("mytraderecord")>0){//说明是普通用户的交易查询
// w["user_id"]=obj.uid;
// }
// }
// return w;
// }
async create(tradeobj,t){
var trade=await super.create(tradeobj,t)
return trade;
}
}
module.exports=ApiTradeDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class AppDao extends Dao {
constructor() {
super(Dao.getModelName(AppDao));
}
async findOneById(id, t) {
var sqlWhere = {
where: { id: id },
attributes: ["id", "appkey", "secret", "domainName"], raw: true
};
if (t) {
sqlWhere.transaction = t;
}
var app = await this.model.findOne(sqlWhere);
return app;
}
async findOne(appKey, secret, t) {
var tmpAttributes = [`id`,
`appkey`,
`name`,
`domainName`,
`homePage`,
`docUrl`,
`authUrl`,
`logoUrl`,
`bkimageUrl`,
`showimgUrl`,
`detailimgUrl`,
`description`,
`isEnabled`,
`isPublish`,
`isCommon`,
`appType`,
`uiconfigUrl`,
`opCacheUrl`,
`notifyCacheCountUrl`];
if (t) {
var app = await this.model.findOne({ where: { appkey: appKey, secret: secret }, attributes: tmpAttributes, raw: true }, { transaction: t });
return app;
} else {
var app = await this.model.findOne({ where: { appkey: appKey, secret: secret }, attributes: tmpAttributes, raw: true });
return app;
}
}
async findOne2(appKey, t) {
var tmpAttributes = [`id`,
`appkey`,
`name`,
`domainName`,
`homePage`,
`docUrl`,
`authUrl`,
`logoUrl`,
`bkimageUrl`,
`showimgUrl`,
`detailimgUrl`,
`description`,
`isEnabled`,
`isPublish`,
`isCommon`,
`isSaas`,
`appType`,
`uiconfigUrl`,
`opCacheUrl`,
`notifyCacheCountUrl`];
if (t) {
var app = await this.model.findOne({ where: { appkey: appKey }, attributes: tmpAttributes, raw: true }, { transaction: t });
return app;
} else {
var app = await this.model.findOne({ where: { appkey: appKey }, attributes: tmpAttributes, raw: true });
return app;
}
}
extraWhere(obj, w, qc, linkAttrs) {
if (obj.codepath && obj.codepath != "") {
if (obj.codepath.indexOf("pmgmyapps") > 0) {//说明是应用管理员的查询
w["creator_id"] = obj.userid;
}
}
if (linkAttrs.length > 0) {
var search = obj.search;
var lnkKey = linkAttrs[0];
var strq = "$" + lnkKey.replace("~", ".") + "$";
w[strq] = { [this.db.Op.like]: "%" + search[lnkKey] + "%" };
}
return w;
}
}
module.exports = AppDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class CompanyDao extends Dao {
constructor() {
super(Dao.getModelName(CompanyDao));
}
extraWhere(obj, w, qc, linkAttrs) {
return w;
}
// extraModelFilter(pobj){
// return {"key":"include",
// "value":[{
// model:this.db.models.user,
// as:"Users",
// through:{
// where:{id:pobj.uid}
// }
// },
// ]};
// }
}
module.exports = CompanyDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class PConfigDao extends Dao{
constructor(){
super(Dao.getModelName(PConfigDao));
}
async findByConfigType(type,t){
return this.model.findOne({where:{configType:type}},{transaction:t});
}
extraWhere(obj,w,qc,linkAttrs){
// if(obj.codepath && obj.codepath!=""){
// // if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// // console.log(obj);
// // w["app_id"]=obj.appid;
// // }
// }
w["app_id"]=obj.appid;
w["company_id"]=obj.tanentid;
return w;
}
}
module.exports=PConfigDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MsgHistoryDao extends Dao{
constructor(){
super(Dao.getModelName(MsgHistoryDao));
}
extraWhere(obj,w){
if(obj.ukstr && obj.ukstr!=""){
// w={[this.db.Op.or]:[
// {[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
// {[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
// ]
// };
w[this.db.Op.or]=[
{[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]},
{[this.db.Op.and]:[{sender:obj.extra},{target:obj.ukstr}]},
];
}
return w;
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]];
}
}
module.exports=MsgHistoryDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MsgNoticeDao extends Dao{
constructor(){
super(Dao.getModelName(MsgNoticeDao));
}
async saveNotice(msg, t) {
var noticeFrom = await super.findOne({fromId : msg.senderId, toId : msg.targetId});
if(noticeFrom) {
var set = {lastMsgId:msg.id};
if(msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
await super.updateByWhere(set, {where:{id:noticeFrom.id}}, t);
} else {
noticeFrom = {
fromuser: msg.sender,
fromId:msg.senderId,
touser: msg.target,
toId:msg.targetId,
isAccepted:true,
lastMsgId:msg.id,
businessLicense_id : msg.businessLicense_id || 0
};
await super.create(noticeFrom, t);
}
var noticeTo = await super.findOne({fromId : msg.targetId, toId : msg.senderId});
if(noticeTo) {
var set = {lastMsgId:msg.id};
if(msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
await super.updateByWhere(set, {where:{id:noticeTo.id}}, t);
} else {
noticeTo = {
fromuser: msg.target,
fromId:msg.targetId,
touser: msg.sender,
toId:msg.senderId,
isAccepted:true,
lastMsgId:msg.id,
businessLicense_id : msg.businessLicense_id || 0
};
await super.create(noticeTo, t);
}
}
orderBy(){
//return {"key":"include","value":{model:this.db.models.app}};
return [["id","DESC"]];
}
}
module.exports=MsgNoticeDao;
const system=require("../system");
const settings=require("../../config/settings.js");
const reclient=system.getObject("util.redisClient");
const md5 = require("MD5");
//获取平台配置兑换率
//初次登录的赠送数量
//创建一笔交易
//同时增加账户数量,增加系统平台账户
var dbf=system.getObject("db.common.connection");
var db=dbf.getCon();
db.sync({force:true}).then(async ()=>{
console.log("sync complete...");
//创建平台配置
const PConfig=db.models.pconfig;
var pconfigObjs=await PConfig.bulkCreate([
{configType:"price",configValue:"100",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"initGift",configValue:"10000",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"apiInitGift",configValue:"500",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"apiCallPrice",configValue:"10",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},
{configType:"logOpWrite",configValue:"-1",app_id:settings.platformid,company_id:settings.platformcompanyid,appkey:settings.appKey},//操作日志步骤是否写入,0否,1是
]);
//创建平台账户
const PAccount=db.models.paccount;
const pa=await PAccount.create({});
//创建APP
const App=db.models.app;
const Account=db.models.account;
const Company=db.models.company;
const Auth=db.models.auth;
//创建role
const Role=db.models.role;
var hp=settings.homePage();
var authUrl=settings.authUrl();
//建立平台应用和上帝超级管理员
App.create({appkey:"wx76a324c5d201d1a4",
name:"蜂擎开放平台",
homePage:hp,
docUrl:settings.docUrl(),
authUrl:authUrl,isEnabled:true,isSaas:true,secret:"f99d413b767f09b5dff0b3610366cc46",logoUrl:"",
isCommon:true,
isPublic:false,
appType:"web",
}).then(app=>{
const User=db.models.user;
User.create({owner_id:settings.platformid,userName:"sm",password:md5("123"+ "_" + settings.salt),isSuper:true,isAdmin:true,isEnabled:true,nickName:"superman"}).then(function(u){
app.setCreator(u);
u.setApp(app);
Account.create({nickName:"superman",userName:"sm",password:md5("123")}).then(function(ac){
u.setAccount(ac);
});
//设置当前平台初始的租户,并默认设置当前租户所其用的APP
Company.create({name:"蜂擎云服科技有限公司"}).then(async function(cmp){
await u.addCompany(cmp,{through:{isCurrent:false}});
await cmp.addApp(app);
Role.bulkCreate([
{ name:"租户",code:"common",isSystem:1,app_id:app.id,company_id:cmp.id},
{ name:"路过",code:"pass",isSystem:1,app_id:app.id,company_id:cmp.id},
]);
});
//设置当前初始租户所开启的应用
//初始化平台的租户权限
Auth.create({
rolecode:"common",
bizcode:"companyinfo",
codepath:"paasroot/tanentCenter/appMag/companyinfo",
authstrs:"add,edit,delete",
app_id:1,
company_id:1
});
});
});
//创建role
// if(settings.env=="prod"){
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
// }
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
});
module.exports = (db, DataTypes) => {
return db.define("auth", {
rolecode: DataTypes.STRING,
bizcode: DataTypes.STRING,
codepath: DataTypes.STRING,
authstrs: DataTypes.STRING
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_auths',
validate: {
}
});
}
module.exports = (db, DataTypes) => {
return db.define("dataauth", {
modelname: DataTypes.STRING,
auths: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_dataauths',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("org", {
code: {
type:DataTypes.STRING(64),
allowNull: false,
},
name: {
type:DataTypes.STRING(64),
allowNull: false,
},
isLeaf:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
orgpath: {
type:DataTypes.STRING,
allowNull: false,
},
nodeType: {//默认为组织
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.node_type),
defaultValue:'org'
},
isPosition:{//是否是岗位
type:DataTypes.BOOLEAN,
defaultValue: false
},
isMain:{//是否是主岗
type:DataTypes.BOOLEAN,
defaultValue: false
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_org',
validate: {
}
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("orgrole", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_orgrole',
validate: {
},
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("role", {
name: DataTypes.STRING,
code: DataTypes.STRING,
description: DataTypes.STRING,
isSystem: {//是否系统数据,0否,1是
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_role',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("account", {
nickName: {
type:DataTypes.STRING(128),
allowNull: true,
},
userName:DataTypes.STRING,
password: {
type:DataTypes.STRING,
validate: {
// length(value){
// if(value.length<6){
// throw new Error("lenght。。。")
// }
// }
}
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
headUrl: DataTypes.STRING,
mobile: DataTypes.STRING,
baoBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
renBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_account',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("apitrade", {
tradeType: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.tradeType),
},
op:{//访问路径
type:DataTypes.STRING,
allowNull: true,
},
srcappkey:{//
type:DataTypes.STRING,
allowNull: true,
},
destappkey:{//
type:DataTypes.STRING,
allowNull: true,
},
params:{
type:DataTypes.STRING(1024),
allowNull: true,
},
clientIp:DataTypes.STRING,
agent:{
type:DataTypes.STRING,
allowNull: true,
},
isAllowed:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
amount: {//每条多少钱
type:DataTypes.INTEGER ,
allowNull: false,
defaultValue: 0
},
desc:DataTypes.STRING,//比如前500条免费
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt:false,
//freezeTableName: true,
// define the table's name
tableName: 'api_trade',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("app", {
appkey: DataTypes.STRING,//需要在后台补充
secret: DataTypes.STRING,//需要在后台补充
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
domainName: DataTypes.STRING,//域名
homePage: DataTypes.STRING,//首页
authUrl: DataTypes.STRING,//认证地址
docUrl: DataTypes.STRING,//接口文档地址
uiconfigUrl: DataTypes.STRING,//基础信息配置信息地址
logoUrl: DataTypes.STRING,//应用Logo
bkimageUrl: DataTypes.STRING,//应用背景图
showimgUrl: DataTypes.STRING,//应用显示图标
detailimgUrl: DataTypes.STRING,//应用详情介绍地址
opCacheUrl: DataTypes.STRING,//操作缓存地址
notifyCacheCountUrl: DataTypes.STRING,//接收API使用计数的通知URL
description: DataTypes.STRING,//应用描述
isSaas: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},//是否启用
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否启用
isPublish: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
isCommon: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否公共服务
appType: {
type: DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.app_type),
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_app',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("company", {
name: {
type:DataTypes.STRING,
allowNull: false,
},
creditCode: {
type:DataTypes.STRING,
allowNull: true,
},
licenseUrl: DataTypes.STRING,
description: DataTypes.STRING,
companykey:{
type:DataTypes.STRING,
allowNull: true,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_company',
validate: {
},
});
}
module.exports = (db, DataTypes) => {
return db.define("companyapp", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_companyapp',
validate: {
},
});
}
module.exports = (db, DataTypes) => {
return db.define("paccount", {
baoBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
renBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'pp_account',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
const enums={
price:"宝币兑换率",
initGift:"初次赠送",
apiCallPrice:"API调用价格",
apiInitGift:"API初次赠送次数",
logOpWrite:"操作日志步骤是否写入,0否,1是",
}
var PConfig=db.define("pconfig", {
name: {
type:DataTypes.STRING,
allowNull: false,
// get(){
// const ctype = this.getDataValue("configType");
// return enums[ctype];
// }
},
configType: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(enums),
set:function(val){
this.setDataValue("name",enums[val]);
this.setDataValue("configType",val);
}
},
configValue: {
type:DataTypes.STRING,
allowNull: false,
},
appkey: {
type:DataTypes.STRING,
allowNull: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_config',
validate: {
},
});
PConfig.enums=enums;
return PConfig;
}
module.exports = (db, DataTypes) => {
return db.define("usercompany", {
isCurrent: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_usercompany',
validate: {
},
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("msghistory", {
msgType:{
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.msgType),
},
sender:DataTypes.STRING,
senderId:DataTypes.INTEGER,
target:DataTypes.STRING,
targetId:DataTypes.INTEGER,
content: {
type: DataTypes.TEXT('long'),
allowNull: false,
},//需要在后台补充
isRead:{//分享时是否渠道店铺名称,0否,1是
type:DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msghistory',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("msgnotice", {
fromuser: DataTypes.STRING,//需要在后台补充
fromId:DataTypes.INTEGER,
touser: DataTypes.STRING,//需要在后台补充
toId:DataTypes.INTEGER,
businessLicense_id:DataTypes.INTEGER,
//"onlineset"+"¥"+data.appkey:[uk+"¥"+data.nickName+"¥"+data.imgUrl] uk=appid¥uid
isAccepted:DataTypes.BOOLEAN,
lastMsgId:DataTypes.INTEGER,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msgnotice',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const TaskBase=require("../task.base");
var system=require("../../system")
const logCtl=system.getObject("web.oplogCtl");
class BehivetoBossCustomerTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(BehivetoBossCustomerTask));
this.wxapi=system.getObject("applet.bossShopApplet");
}
async subDoTask(){
await this.execCustomer();
await this.execOrder();
await this.exectm();
}
async execCustomer(){
console.log("导入老客户数据*******************************任务*************************************99");
var tmp=await this.wxapi.customersbysalemanlist();
//日志记录
logCtl.info({
optitle:"导入老客户数据",
op:"base/db/task/BehivetoBossCustomerTask.js",
content:"执行结果:"+JSON.stringify(tmp),
clientIp:""
});
}
async execOrder(){
console.log("导入老客户订单数据*******************************任务*************************************99");
var tmp=await this.wxapi.customersbysalemanlist();
//日志记录
logCtl.info({
optitle:"导入老客户订单数据",
op:"base/db/task/BehivetoBossCustomerTask.js",
content:"执行结果:"+JSON.stringify(tmp),
clientIp:""
});
}
async exectm(){
console.log("导入商标数据*******************************任务*************************************99");
var tmp=await this.wxapi.findbhtm();
//日志记录
logCtl.info({
optitle:"导入商标数据",
op:"base/db/task/BehivetoBossCustomerTask.js",
content:"执行结果:"+JSON.stringify(tmp),
clientIp:""
});
}
}
module.exports=BehivetoBossCustomerTask;
//
// var task=new PlatformBalanceTask();
// task.checkPlatformBalance().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const TaskBase=require("../task.base");
var system=require("../../system")
const logCtl=system.getObject("web.oplogCtl");
class BusinessOneAllotTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(BusinessOneAllotTask));
this.channelmanageallotSve=system.getObject("service.channelmanageallotSve");
}
async subDoTask(){
await this.execTj();
}
async execTj(){
console.log("商机分配平台待服务执行结果*******************************任务*************************************99");
var tmp=await this.channelmanageallotSve.businessOneAllot("https://boss.gongsibao.com/distributeneed#/businesschance/waitdeal?from=mobile");
//日志记录
logCtl.info({
optitle:"商机分配平台待服务执行结果",
op:"base/db/task/BusinessOneAllotTask.js",
content:"执行结果:"+JSON.stringify(tmp),
clientIp:""
});
}
}
module.exports=BusinessOneAllotTask;
//
// var task=new PlatformBalanceTask();
// task.checkPlatformBalance().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const TaskBase=require("../task.base");
var system=require("../../system")
const logCtl=system.getObject("web.oplogCtl");
class BusinessTwoAllotTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(BusinessTwoAllotTask));
this.channelmanageallotSve=system.getObject("service.channelmanageallotSve");
}
async subDoTask(){
await this.execTj();
}
async execTj(){
console.log("商机分配平台跟进中执行结果*******************************任务*************************************88");
var tmp=await this.channelmanageallotSve.businessOneAllot("https://boss.gongsibao.com/distributeneed#/businesschance/waitdeal?from=mobile");
//日志记录
logCtl.info({
optitle:"商机分配平台跟进中执行结果",
op:"base/db/task/BusinessTwoAllotTask.js",
content:"执行结果:"+JSON.stringify(tmp),
clientIp:""
});
}
}
module.exports=BusinessTwoAllotTask;
//
// var task=new PlatformBalanceTask();
// task.checkPlatformBalance().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const TaskBase=require("../task.base");
const system=require("../../system")
class CheckDownloadTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(CheckDownloadTask));
this.rs=system.getObject("util.restClient");
}
async subDoTask(){
//循环检查downloadtasks队列中的记录
console.log("CheckDownloadTask.........outer");
var xt=await this.redisClient.rpop("downloadtaxtasks");
console.log("CheckDownloadTask........."+xt);
while(xt && xt.indexOf("_")>=0){
console.log("CheckDownloadTask inner.........");
var ccid=xt.split("_")[0];
var cemail=xt.split("_")[1];
//await this.rs.execPost({cid:ccid,email:cemail},"http://127.0.0.1:3000/web/taskCtl/makerpt");
this.rs.execPost({sharecode:ccid,email:cemail},"https://boss.gongsibao.com/web/taskCtl/makerpt");
xt=await this.redisClient.rpop("downloadtaxtasks");
}
}
}
module.exports=CheckDownloadTask;
const TaskBase=require("../task.base");
var system=require("../../system")
const http=require("http")
const querystring = require('querystring');
var settings=require("../../../config/settings");
class PlatformBalanceTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(PlatformBalanceTask));
this.tradeSve=system.getObject("service.tradeSve");
this.pAccountDao=system.getObject("db.pAccountDao");
this.accountlogSve=system.getObject("service.accountlogSve");
}
async subDoTask(){
await this.checkPlatformBalance();
}
async checkPlatformBalance(){
var accounts = await this.pAccountDao.model.findAll({attributes:["id","baoBalance","renBalance"],raw:true});
var that = this;
var sumBao=0;
var sumRen=0;
if(accounts.length>0){
var account = accounts[0];
var trades = await this.tradeSve.dao.model.findAll({attributes:["id","baoAmount","renAmount","tradeType","status"],raw:true});
trades.forEach(trade=>{
// "fill": "充值", "consume": "消费", "gift": "赠送", "giftMoney": "红包", "refund": "退款","payment":"付款",
// "orderTrade": "订单交易", "orderRefund": "订单退款", "orderPersonFee": "订单个人分润",
// "orderPlatformFee": "订单平台分润","recommendFee": "推荐分润", "tmSubDeductCoin": "商标提报宝币扣除",
// "cashWithdrawal": "现金提现","platUseFee":"平台使用费","publicExpense":"官费","invoiceTaxes":"税费"
//宝币:
// user: "fill": "充值", "consume": "消费", "gift": "赠送","tmSubDeductCoin": "商标提报宝币扣除",
// platform:
//人民币:
// user: "fill": "充值","orderPersonFee": "订单个人分润","recommendFee": "推荐分润","cashWithdrawal": "现金提现",
// platform: "orderTrade": "订单交易","orderRefund": "订单退款","orderPlatformFee": "订单平台分润","platUseFee":"平台使用费","publicExpense":"官费","invoiceTaxes":"税费"
sumBao=sumBao - Number(trade.baoAmount);
if(trade.tradeType!="orderTrade" ){
if(trade.tradeType=="fill" || trade.tradeType=="orderPersonFee" || trade.tradeType=="recommendFee" ){
sumRen=(sumRen*10000-Number(trade.renAmount)*10000)/10000;
}else if(trade.tradeType=="platformPayment" || trade.tradeType=="subPublicExpense"){
sumRen=(sumRen*10000+Number(trade.renAmount)*10000)/10000;
}
}else{
sumRen=(sumRen*10000+Number(trade.renAmount)*10000)/10000;
}
});
if(sumBao==Number(account.baoBalance) && sumRen==Number(account.renBalance)){
console.log(account.id+"---------------------------------success");
}else{
console.log(account.id+"+++++++++++"+sumBao+"++++++++++++++"+sumRen+"++++++++++++"+account.baoBalance+"++++++"+account.renBalance+"--");
// var obj={id:account.id,baoBalance:sumBao,renBalance:sumRen};
// var logObj={
// accountId:account.id,beforeBaoBalance:account.baoBalance,beforeRenBalance:account.renBalance,
// afterBaoBalance:sumBao,afterRenBalance:sumRen,logType:"platform"
// };
// var a = await that.tradeSve.db.transaction(async function (t){
// var accountUpdate = await that.pAccountDao.update(obj,t);
// var log = await that.accountlogSve.create(logObj,t);
// });
}
}
}
}
module.exports=PlatformBalanceTask;
// var task=new PlatformBalanceTask();
// task.checkPlatformBalance().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const TaskBase=require("../task.base");
var system=require("../../system")
// const http=require("http")
// const querystring = require('querystring');
// var settings=require("../../../config/settings");
class StatisticalRateTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(StatisticalRateTask));
this.statisticalrateSve=system.getObject("service.statisticalrateSve");
}
async subDoTask(){
await this.execTj();
}
async execTj(){
await this.statisticalrateSve.syncStatisticsData();
}
}
module.exports=StatisticalRateTask;
//
// var task=new PlatformBalanceTask();
// task.checkPlatformBalance().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const TaskBase=require("../task.base");
class TestTask0 extends TaskBase{
constructor(){
super(TaskBase.getServiceName(TestTask0));
}
async subDoTask(){
console.log("TestTask0.....");
}
}
module.exports=TestTask0;
const TaskBase = require("../task.base");
var system = require("../../system")
const logCtl = system.getObject("web.oplogCtl");
class TmDynamicsAllotTask extends TaskBase {
constructor() {
super(TaskBase.getServiceName(BusinessOneAllotTask));
this.bytmdynamicsSve = system.getObject("service.bytmdynamicsSve");
}
async subDoTask() {
await this.execSend();
}
async execSend() {
var tmp = await this.bytmdynamicsSve.notifyWxTmDynamics();
//日志记录
logCtl.info({
optitle: "商标监控动态数量增加微信通知执行结果",
op: "base/db/task/TmDynamicsAllotTask.js",
content: "执行结果:" + tmp,
clientIp: ""
});
}
}
module.exports = TmDynamicsAllotTask;
const TaskBase=require("../task.base");
var system=require("../../system")
const http=require("http")
const querystring = require('querystring');
var settings=require("../../../config/settings");
class UserBalanceTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(UserBalanceTask));
this.tradeSve=system.getObject("service.tradeSve");
this.accountSve=system.getObject("service.accountSve");
this.accountlogSve=system.getObject("service.accountlogSve");
}
async subDoTask(){
await this.checkUserBalance();
}
async checkUserBalance(){
// console.log("checkUserBalance------------------------------------------------------------");
var accounts = await this.accountSve.dao.model.findAll({attributes:["id","unionId","baoBalance","renBalance"],raw:true});
// console.log(accounts);
// console.log("遍历--------------------------------------------------");
var that = this;
for(var i=0;i<accounts.length;i++){
var sumBao=0;
var sumRen=0;
var account = accounts[i];
var trades = await this.tradeSve.dao.model.findAll({where:{account_id:account.id},raw:true});
trades.forEach(trade=>{
if(trade.tradeType=="orderPersonFee" || trade.tradeType=="recommendFee" || trade.tradeType=="cashWithdrawal"
|| trade.tradeType=="gift"
|| trade.tradeType=="consume" || trade.tradeType=="fill" || trade.tradeType=="tmSubDeductCoin"){
sumBao=(Number(trade.baoAmount)*10000+sumBao*10000)/10000;
if(trade.tradeType!="fill"){
sumRen=(Number(trade.renAmount)*10000+sumRen*10000)/10000;
}
// console.log(sumBao+"++++++++++++++++"+sumRen);
// else{
// sumRen=Number(trade.renAmount)-sumRen;
// }
}
// "fill": "充值", "consume": "消费", "gift": "赠送", "giftMoney": "红包", "refund": "退款","payment":"付款",
// "orderTrade": "订单交易", "orderRefund": "订单退款", "orderPersonFee": "订单个人分润",
// "orderPlatformFee": "订单平台分润","recommendFee": "推荐分润", "tmSubDeductCoin": "商标提报宝币扣除",
// "cashWithdrawal": "现金提现","platUseFee":"平台使用费","publicExpense":"官费","invoiceTaxes":"税费"
//宝币:
// user: "fill": "充值", "consume": "消费", "gift": "赠送","tmSubDeductCoin": "商标提报宝币扣除",
// platform:
//人民币:
// user: "fill": "充值","orderPersonFee": "订单个人分润","recommendFee": "推荐分润","cashWithdrawal": "现金提现",
// platform: "orderTrade": "订单交易","orderRefund": "订单退款","orderPlatformFee": "订单平台分润","platUseFee":"平台使用费","publicExpense":"官费","invoiceTaxes":"税费"
});
if(sumBao==Number(account.baoBalance) && sumRen==Number(account.renBalance)){
// console.log(account.id+"---------------------------------success");
}else{
console.log(account.id+"+++++"+sumBao+"+++++"+sumRen+"+++++"+account.baoBalance+"+++++"+account.renBalance+"--");
// var obj={id:account.id,baoBalance:sumBao,renBalance:sumRen};
// var logObj={
// accountId:account.id,accountUnionId:account.unionId,beforeBaoBalance:account.baoBalance,beforeRenBalance:account.renBalance,
// afterBaoBalance:sumBao,afterRenBalance:sumRen,logType:"user"
// };
// var a = await that.accountSve.db.transaction(async function (t){
// var accountUpdate = await that.accountSve.update(obj,t);
// var log = await that.accountlogSve.create(logObj,t);
// });
}
}
}
}
module.exports=UserBalanceTask;
// var task=new UserBalanceTask();
// task.checkUserBalance().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
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;
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){
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;
return this.db.transaction(async function (t) {
var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
p.isLeaf=p.isPosition;
p.app_id=req.appid;
var orgnew=await self.dao.model.create(p,{transaction:t});
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,
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:appid
},{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 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 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("common",ServiceBase.getDaoName(ApiTradeService));
this.appS=system.getObject("service.common.appSve");
}
async create(tradeObj){
var self=this;
return this.db.transaction(async function (t){
//获取缓存二个值,一个是赠送次数,一个是调用价格,取目标应用的appkey
var pconfig=await self.cacheManager["PConfigCache"].cache(tradeObj.destappkey,null,null);
var apiInitGift = pconfig.find(item => {
return item.configType === "apiInitGift";
});
var apiCallPrice = pconfig.find(item => {
return item.configType === "apiCallPrice";
});
var callCache=await self.cacheManager["ApiCallCountCache"].getApiCallCount(tradeObj.srcappkey,tradeObj.op);
var callAccuCache=await self.cacheManager["ApiAccuCache"].getApiCallAccu(tradeObj.srcappkey+"_"+tradeObj.destappkey);
//需要每次增加计数之前,通知目标app,目前的计数值,由目标APP来决定是否准许访问
var appdest=await self.cacheManager["AppCache"].cache(tradeObj.destappkey);
if(appdest.id!=settings.platformid){
var recvCountNotityUrl=appdest.notifyCacheCountUrl;
self.apiCallWithAk(recvCountNotityUrl,callAccuCache);
}else{
self.appS.recvNotificationForCacheCount(callAccuCache);
}
var calledCount=Number(callCache.callcount);
var balance=Number(callCache.amount);
if(calledCount>Number(apiInitGift?apiInitGift.configValue:0)){//调用次数大于免费次数
tradeObj.amount=Number(apiCallPrice?apiCallPrice.configValue:0);
}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.srcappkey,tradeObj.op,1);
await self.cacheManager["ApiCallCountCache"].addCallBalance(tradeObj.srcappkey,tradeObj.op,tradeObj.amount);
//累计缓存调用次数和金额
await self.cacheManager["ApiAccuCache"].addCallCount(tradeObj.srcappkey+"_"+tradeObj.destappkey,1);
await self.cacheManager["ApiAccuCache"].addCallBalance(tradeObj.srcappkey+"_"+tradeObj.destappkey,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");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
class AppService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(AppService));
//this.appDao=system.getObject("db.appDao");
this.userS = system.getObject("service.auth.userSve");
this.tradeD = system.getObject("db.common.apitradeDao");
}
async getApp(appkey) {
return this.cacheManager["AppCache"].cache(appkey, null);
}
async findAllApps() {
var dicRtn = {};
var apps = await this.dao.model.findAll({ where: { isEnabled: true }, 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;
}
async resetPass(pobj) {
var appid = pobj.appid;
var uobj = { password: pobj.password }
return await this.userS.dao.model.update(uobj, { where: { userName: pobj.userName, app_id: pobj.appid } });
}
async createAdminUser(pobj) {
var u = { userName: pobj.userName, password: pobj.password, app_id: pobj.appid, isAdmin: true, mobile: pobj.mobile };
var rtn = await this.userS.register(u);
return rtn;
}
async create(pobj, qobj, req) {
var self = this;
return this.db.transaction(async function (t) {
var app = await self.dao.create(pobj, t);
//创建role
const Role = self.db.models.role;
//to do 由于有了租户的概念,所以目前不能创建属于特定租户的角色,进入后台后应该可以获取当前租户信息
// await Role.create(
// { name: "普通", code: "common", isSystem: 1, app_id: app.id }, { transaction: t }
// );
return app;
});
}
async findAndCountAll(obj) {
var self = this;
const apps = await super.findAndCountAll(obj);
for (let i = 0; i < apps.results.rows.length; i++) {
var a = apps.results.rows[i];
var appkey = a.appkey;
var apicallAccu = await this.cacheManager["ApiAccuCache"].getApiCallAccu(appkey);
a.apiCallCount = apicallAccu.callcount;
a.amount = apicallAccu.amount;
}
return apps;
}
async recvNotificationForCacheCount(pobj) {
console.log(pobj);
return;
}
async fetchApiCallData(curappkey) {
//当前APP,呼出发生的调用次数和累积应付
//var apicallAccu= await this.cacheManager["ApiAccuCache"].getApiCallAccu(curappkey);
//当前APP,呼出发生的调用次数和累积应付
var apicallAccuCount = await this.tradeD.model.count({
where: {
srcappkey: curappkey,
tradeType: "consume",
}
});
var apicallAccuAmount = await this.tradeD.model.sum("amount", {
where: {
srcappkey: curappkey,
tradeType: "consume",
}
});
//当前APP对外提供服务,累积发生的调用次数及累积应收
var count = await this.tradeD.model.count({
where: {
destappkey: curappkey,
tradeType: "consume",
}
});
var amount = await this.tradeD.model.sum("amount", {
where: {
destappkey: curappkey,
}
});
var rtn = {
apioutcallcount: apicallAccuCount,
apioutcallamount: apicallAccuAmount,
apiincallcount: count,
apiincallamount: amount,
}
return rtn;
}
}
module.exports = AppService;
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 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");
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 uuidv4 = require('uuid/v4');
class AuthUtils {
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
/**
* 获取访问token信息
* @param {*} appkey 应用key
* @param {*} secret 应用密钥
*/
async getTokenInfo(appkey, secret) {
var rtnKey = this.getUUID();
var cacheAccessKey = await this.cacheManager["ApiAccessKeyClientCache"].cache(appkey, rtnKey, 3600);
if (cacheAccessKey) {
rtnKey = cacheAccessKey.accessKey;
}//获取之前的token值
var appData = await this.cacheManager["ApiAccessKeyCache"].cache(rtnKey, secret, 3600, appkey);
if (!appData) {
return system.getResultFail(system.getAppInfoFail, "key或secret错误.");
}
if (!appData.isEnabled) {
return system.getResultFail(system.waitAuditApp, "应用处于待审核等待启用状态.");
}
appData.accessKey = rtnKey;
return system.getResultSuccess(appData);
}
}
module.exports = AuthUtils;
const system=require("../system");
const Core = require('@alicloud/pop-core');
class SmsClient{
constructor(){
this.smsTeml="http://123.57.156.109:4103/api/Send";
this.restClient=system.getObject("util.restClient");
this.aliclient=new Core({
accessKeyId: 'LTAI4FtNp3wcqFzaADvo1WtZ',
accessKeySecret: 'VBKn1Anx4UmMF0LKNz7PVaCFG1phcg',
endpoint: 'https://dysmsapi.aliyuncs.com',
apiVersion: '2017-05-25'
});
}
async aliSendMsg(to,tmplcode,signName,jsonContent){
var params = {
"RegionId": "default",
"PhoneNumbers": to,
"SignName": signName,
"TemplateCode": tmplcode,
"TemplateParam": jsonContent
}
var requestOption = {
method: 'POST'
};
this.aliclient.request('SendSms', params, requestOption).then((result) => {
console.log(JSON.stringify(result));
}, (ex) => {
console.log(ex);
})
}
async sendMsg(to,content){
var txtObj ={
"appId":8,
"mobilePhone":to,
"content":content
}
return this.restClient.execPost(txtObj,this.smsTeml);
}
async getUidStr(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
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=SmsClient;
// var sms=new SmsClient();
// sms.aliSendMsg("13381139519","SMS_173946419","iboss",JSON.stringify({code:"hello"}));
var settings = {
redis: {
host: "43.247.184.32",
port: 8967,
password: "Gongsibao2018",
db: 9,
},
database: {
dbname: "paas",
user: "write",
password: "write",
config: {
host: '43.247.184.35',
port: 8899,
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 90000000,
idle: 1000000
},
debug: false,
dialectOptions: {
requestTimeout: 999999,
// instanceName:'DEV'
} //设置MSSQL超时时间
}
},
// redis: {
// host: "192.168.4.222",
// port: 6379,
// password: "123456",
// db: 9,
// },
// database:{
// dbname : "paas",
// user: "root",
// password: "123456",
// config: {
// host: '192.168.4.119',
// port: 3306,
// dialect: 'mysql',
// operatorsAliases: false,
// pool: {
// max: 5,
// min: 0,
// acquire: 90000000,
// idle: 1000000
// },
// debug:false,
// dialectOptions:{
// requestTimeout: 999999,
// // instanceName:'DEV'
// } //设置MSSQL超时时间
// }
// },
reqEsDevUrl: "http://192.168.4.249:9200/",
reqHomePageDevUrl: "http://p.apps.com:4001/",
reqAuthUrl: "http://p.apps.com:4001/auth",
docUrl:"http://p.apps.com:4001/web/common/metaCtl/getApiDoc"
};
module.exports = settings;
var path = require('path');
var ENVINPUT={
DB_HOST:process.env.DB_HOST,
DB_PORT:process.env.DB_PORT,
DB_USER:process.env.DB_USER,
DB_PWD:process.env.DB_PWD,
DB_NAME:process.env.PAAS_DB_NAME,
REDIS_HOST:process.env.REDIS_HOST,
REDIS_PORT:process.env.REDIS_PORT,
REDIS_PWD:process.env.REDIS_PWD,
REDIS_DB:process.env.PAAS_REDIS_DB,
APP_ENV:process.env.APP_ENV?process.env.APP_ENV:"dev"
};
var settings = {
env:ENVINPUT.APP_ENV,
platformid:1,
platformcompanyid:1,
commonroleid:1,
passroleid:2,
tanentroleid:1,
protocalPrefix:"http://",
appKey:"wx76a324c5d201d1a4",
secret:"f99d413b767f09b5dff0b3610366cc46",
salt: "%iatpD1gcxz7iF#B",
defaultpwd:"987456",
basepath : path.normalize(path.join(__dirname, '../..')),
port : process.env.NODE_PORT || 4001,
reqEsAddr:function(){
if(this.env=="dev"){
var localsettings=require("./localsettings");
return "http://43.247.184.94:7200/";//localsettings.reqEsDevUrl;
}else {
return "http://43.247.184.94:7200/";
}
},
apiconfig:{
opLogUrl:function(){
return settings.reqEsAddr()+"bigdata_zc_op_log/_doc?pretty";
},
opLogEsIsAdd:function(){
return 1;
},
},
homePage:function(){
if(this.env=="dev"){
var localsettings=require("./localsettings");
return localsettings.reqHomePageDevUrl;
}else {
return "http://open.gongsibao.com/";
}
},
authUrl:function(){
if(this.env=="dev"){
var localsettings=require("./localsettings");
return localsettings.reqAuthUrl;
}else {
return "http://open.gongsibao.com/auth";
}
},
docUrl:function(){
if(this.env=="dev"){
var localsettings=require("./localsettings");
return localsettings.docUrl;
}else {
return "http://open.gongsibao.com/web/common/metaCtl/getApiDoc";
}
},
redis:function(){
if(this.env=="dev"){
var localsettings=require("./localsettings");
return localsettings.redis;
}else {
return {
host:ENVINPUT.REDIS_HOST,
port:ENVINPUT.REDIS_PORT,
password:ENVINPUT.REDIS_PWD,
db:ENVINPUT.REDIS_DB,
};
}
},
database:function(){
if(this.env=="dev"){
var localsettings=require("./localsettings");
return localsettings.database;
}else{
return {
dbname : ENVINPUT.DB_NAME,
user : ENVINPUT.DB_USER,
password : ENVINPUT.DB_PWD,
config : {
host: ENVINPUT.DB_HOST,
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 90000000,
idle: 1000000
},
debug:false,
dialectOptions:{
requestTimeout: 999999,
// instanceName:'DEV'
} //设置MSSQL超时时间
},
};
}
}
};
settings.ENVINPUT=ENVINPUT;
module.exports = settings;
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="keywords" content="PAAS 开放平台">
<meta name="viewport" content="width=device-width, initial-scale=0.8, maximum-scale=0.8, user-scalable=1">
<title id="idtitle"><%=app.name%></title>
<link rel="stylesheet" href="/css/ele/index_2.5.4.css">
<link rel="stylesheet" href="/css/pagecom.css">
<link rel="stylesheet" href="/css/fontawesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/fontawesome/css/toolicon-style.css">
<link rel="stylesheet" href="/css/fontface-timely.css">
<script src="/js/vue/vue.min_2.6.10.js"></script>
<script src="/js/vue/vue-router.min.js"></script>
<script src="/js/vue/vuex.min.js"></script>
<script src="/js/ele/index_2.5.4.js"></script>
<script src="/js/vue/axios.min.js"></script>
<script>
//缓存当前域名对应的公司信息,公司、页脚、银行账号---全局变量
var appinfo = JSON.parse(unescape('<%=appinfo%>'));
//缓存当前的基础组件列表
var companyinfo= JSON.parse(unescape('<%=company%>'));
if(companyinfo.status && companyinfo.status==-1){
companyinfo=null;
}
var tocompanyinfo= JSON.parse(unescape('<%=tocompany%>'));
if(tocompanyinfo.status && tocompanyinfo.status==-1){
tocompanyinfo=null;
}
</script>
<style>
body{
margin: 0px;
padding: 0px;
font-size: 14px;
}
.app-main{
width:100%;
height:100%;
background:url("<%=app.bkimageUrl?app.bkimageUrl:'/imgs/pt3.jpg'%>") no-repeat;background-size: cover;
box-sizing: border-box;
}
.app-header{
display: flex;
justify-content:space-between;
color: white;
padding: 15px;
box-sizing: border-box;
}
.app-stage{
display: flex;
width: 100%;
padding: 5px;
box-sizing: border-box;
}
.app-stage .rightcontent{
flex-grow:1;
box-sizing: border-box;
}
.app-stage .rightcontent .el-card__body {
height: 100%;
}
.app-stage .rightcontent >.el-card{
border-radius: 0px;
height: 100%;
box-shadow:unset;
box-sizing: border-box;
}
#appName{
font-size: 30px;
font-family:MicrosoftYaHei;
cursor: pointer;
}
.el-button--text{
color: white
}
.activeColor{
color:deepskyblue;
}
</style>
</head>
<body>
<div id="app" v-loading="loading" class="app-main" style="visibility:hidden">
<div id="app-header" class="app-header">
<div id="appName" >
<span @click=appclick><%=app.name%> </span>
<span style="font-size:16px;" v-if="currentCompany">
<span style="font-size:20px" class="fa fa-home"></span>
<span v-if="currentUser && currentUser.owner && currentUser.owner.id!=1">{{currentUser.owner.name}}</span>
<!-- <span v-else>{{currentCompany.name}}</span> -->
</span>
</div>
<div id="login">
<gsb-button-group v-if="!currentUser" @select="onselect" ikey="login" :btns="logins"></gsb-button-group>
<span v-if="currentUser">欢迎您,{{currentUser.nickName}}<el-button @click="exitclick" type="text" icon="el-icon-setting">退出</el-button></span>
<span style="cursor:pointer" @click="settingclick" v-if="currentUser && currentUser.isSuper"><i class="el-icon-setting"></i>后台管理</span>
</div>
</div>
<div id="app-stage" class="app-stage">
<div class="rightcontent">
<transition name="slide-fade">
<router-view>
</router-view>
</transition>
</div>
</div>
</div>
<script src="/js/vue/jquery.min.js"></script>
<script src="/js/common.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
\ No newline at end of file
@font-face {
font-family: 'toolicon';
src: url('../fonts/toolicon.eot?247j9t');
src: url('../fonts/toolicon.eot?247j9t#iefix') format('embedded-opentype'),
url('../fonts/toolicon.ttf?247j9t') format('truetype'),
url('../fonts/toolicon.woff?247j9t') format('woff'),
url('../fonts/toolicon.svg?247j9t#toolicon') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="tool-"], [class*=" tool-"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: 'toolicon' !important;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.tool-reset:before {
content: "\e911";
}
.tool-look1:before {
content: "\e912";
}
.tool-upload:before {
content: "\e913";
}
.tool-Order1:before {
content: "\e90d";
}
.tool-add:before {
content: "\e90e";
}
.tool-copy1:before {
content: "\e90f";
}
.tool-order1:before {
content: "\e910";
}
.tool-ID-card:before {
content: "\e906";
}
.tool-scanning:before {
content: "\e907";
}
.tool-scanning1:before {
content: "\e908";
}
.tool-bg_icon_Transformation:before {
content: "\e909";
}
.tool-search:before {
content: "\e90a";
}
.tool-query:before {
content: "\e90b";
}
.tool-summary:before {
content: "\e90c";
}
.tool-cash:before {
content: "\e900";
}
.tool-invoice:before {
content: "\e901";
}
.tool-trademark-1:before {
content: "\e902";
}
.tool-eglass-data:before {
content: "\e903";
}
.tool-order:before {
content: "\e904";
}
.tool-paper-report:before {
content: "\e905";
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment