Commit c1e56ddc by 宋毅

tj

parent 75d3f1a9
#!/bin/bash #!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang/node105:v2 FROM registry.cn-beijing.aliyuncs.com/hantang/node105:v2
MAINTAINER jy "jiangyong@gongsibao.com" MAINTAINER jy "jiangyong@gongsibao.com"
ADD bigdata /apps/bigdata/ ADD bigdata /apps/igirl-channel-app/
WORKDIR /apps/bigdata/ WORKDIR /apps/igirl-channel-app/
RUN cnpm install -S RUN cnpm install -S
CMD ["node","/apps/bigdata/main.js"] CMD ["node","/apps/igirl-channel-app/main.js"]
......
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
const system = require("../system");
const uuidv4 = require('uuid/v4');
const DocBase = require("./doc.base");
const settings = require("../../config/settings");
class APIBase extends DocBase {
constructor() {
super();
this.redisClient = system.getObject("util.redisClient");
this.cacheManager = system.getObject("db.common.cacheManager");
this.apitradeSvr = system.getObject("service.common.apitradeSve");
this.logCtl = system.getObject("web.common.oplogCtl");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
/**
* 白名单验证
* @param {*} gname 组名
* @param {*} methodname 方法名
*/
async isCheckWhiteList(gname, methodname) {
var fullname = gname + "." + methodname;
var lst = [
"auth.getAccessKey",
"meta.getBaseComp",
"meta.doc",
"meta.clearAllCache"
];
var x = lst.indexOf(fullname);
return x >= 0;
}
async checkAcck(gname, methodname, pobj, query, req) {
var apptocheck = null;
var isCheckWhite = await this.isCheckWhiteList(gname, methodname);
if (!isCheckWhite) {//在验证请单里面,那么就检查访问token
var ak = req.headers["accesskey"];
try {
apptocheck = await this.cacheManager["ApiAccessKeyCache"].cache(ak, null, null, null);
} catch (e) {
this.logCtl.error({
optitle: "获取访问token异常_error",
op: pobj.classname + "/" + methodname,
content: e.stack,
clientIp: pobj.clientIp
});
}
}
return { app: apptocheck, ispass: isCheckWhite || apptocheck };
}
async doexec(gname, methodname, pobj, query, req) {
var requestid = req.headers["request-id"] || this.getUUID();
try {
//检查访问token
var isPassResult = await this.checkAcck(gname, methodname, pobj, query, req);
if (!isPassResult.ispass) {
var tmpResult = system.getResultFail(system.tokenFail, "访问token失效,请重新获取");
tmpResult.requestId = "";
return tmpResult;
}
// //检查appkey
// let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(pobj.appKey);
// if(key==null){
// return system.getResultFail(system.appKeyError,"appKey授权有误");
// }
req.app = isPassResult.app;
var rtn = await this[methodname](pobj, query, req);
if (isPassResult.app) {
if (methodname && methodname.indexOf("apiAccessCount") < 0) {
this.apitradeSvr.create({
srcappkey: isPassResult.app.appkey,
tradeType: "consume",
op: req.classname + "/" + methodname,
params: JSON.stringify(pobj),
clientIp: req.clientIp,
agent: req.uagent + ";reqid=" + requestid,
destappkey: settings.appKey,
});
}
}
rtn.requestId = requestid;
return rtn;
} catch (e) {
console.log(e.stack, "api调用异常--error...................");
this.logCtl.error({
optitle: "api调用异常--error",
op: req.classname + "/" + methodname + ";reqid=" + requestid,
content: e.stack,
clientIp: req.clientIp
});
var rtnerror = system.getResultFail(-200, "出现异常,请联系管理员");
rtnerror.requestId = requestid;
return rtnerror;
}
}
}
module.exports = APIBase;
const system = require("../system");
const uuidv4 = require('uuid/v4');
class DocBase {
constructor() {
this.apiDoc = {
group: "逻辑分组",
groupDesc: "",
name: "",
desc: "请对当前类进行描述",
exam: "概要示例",
methods: []
};
this.initClassDoc();
}
initClassDoc() {
this.descClass();
this.descMethods();
}
descClass() {
var classDesc = this.classDesc();
this.apiDoc.group = classDesc.groupName;
this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc);
this.apiDoc.name = classDesc.name;
this.apiDoc.desc = this.examDescHtml(classDesc.desc);
this.apiDoc.exam = this.examHtml();
}
examDescHtml(desc) {
// var tmpDesc = desc.replace(/\\/g, "<br/>");
return desc;
}
examHtml() {
var exam = this.exam();
exam = exam.replace(/\\/g, "<br/>");
return exam;
}
exam() {
throw new Error("请在子类中定义类操作示例");
}
classDesc() {
throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构
{
groupName:"auth",
groupDesc:"认证相关的包"
desc:"关于认证的类",
exam:"",
}
`);
}
descMethods() {
var methoddescs = this.methodDescs();
for (var methoddesc of methoddescs) {
for (var paramdesc of methoddesc.paramdescs) {
this.descMethod(methoddesc.methodDesc, methoddesc.methodName
, paramdesc.paramDesc, paramdesc.paramName, paramdesc.paramType,
paramdesc.defaultValue, methoddesc.rtnTypeDesc, methoddesc.rtnType);
}
}
}
methodDescs() {
throw new Error(`
请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[
{
methodDesc:"生成访问token",
methodName:"getAccessKey",
paramdescs:[
{
paramDesc:"访问appkey",
paramName:"appkey",
paramType:"string",
defaultValue:"x",
},
{
paramDesc:"访问secret",
paramName:"secret",
paramType:"string",
defaultValue:null,
}
],
rtnTypeDesc:"xxxx",
rtnType:"xxx"
}
]
`);
}
descMethod(methodDesc, methodName, paramDesc, paramName, paramType, defaultValue, rtnTypeDesc, rtnType) {
var mobj = this.apiDoc.methods.filter((m) => {
if (m.name == methodName) {
return true;
} else {
return false;
}
})[0];
var param = {
pname: paramName,
ptype: paramType,
pdesc: paramDesc,
pdefaultValue: defaultValue,
};
if (mobj != null) {
mobj.params.push(param);
} else {
this.apiDoc.methods.push(
{
methodDesc: methodDesc ? methodDesc : "",
name: methodName,
params: [param],
rtnTypeDesc: rtnTypeDesc,
rtnType: rtnType
}
);
}
}
}
module.exports = DocBase;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class RoleAuthAPI extends APIBase {
constructor() {
super();
this.authS=system.getObject("service.auth.authSve");
}
async findAuthsByRole(p,q,req){
var tmpRoles=p.roles;
var appid=p.appid;
var comid=p.companyid;
var auths=await this.authS.findAuthsByRole(tmpRoles,appid,comid);
return system.getResult(auths);
}
exam(){
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "角色授权相关的API",
name: "RoleAuthAPI",
desc: "角色授权相关的API",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "按照角色获取权限,访问地址:/api/auth/roleAuth/findAuthsByRole",
methodName: "findAuthsByRole",
paramdescs: [
{
paramDesc: "应用的ID",
paramName: "appid",
paramType: "int",
defaultValue: "x",
},
{
paramDesc: "角色列表",
paramName: "roles",
paramType: "array",
defaultValue: null,
}
],
rtnTypeDesc: "逗号分隔的",
rtnType: "string"
}
];
}
}
module.exports = RoleAuthAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var glob = require("glob");
var settings = require("../../../../config/settings");
var cacheBaseComp = null;
class BaseCompAPI extends APIBase {
constructor() {
super();
this.cachsearchesSve = system.getObject("service.common.cachsearchesSve");
}
async clearAllCache(pobj, gobj, req) {
return await this.cachsearchesSve.clearAllCache(pobj);
}
async getBaseComp() {
if (cacheBaseComp) {
return cacheBaseComp;
}
var vuePath = settings.basepath + "/app/front/vues/base";
var baseComps = [];
var rs = glob.sync(vuePath + "/**/*.vue");
if (rs) {
rs.forEach(function (r) {
var comp = "";
if (settings.env == "dev") {
delete require.cache[r];
comp = require(r).replace(/\n/g, "");
} else {
comp = require(r).replace(/\n/g, "");
}
baseComps.push(comp);
});
}
// cacheBaseComp = escape(JSON.stringify(baseComps));
return system.getResult({ basecom: baseComps });
}
exam() {
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "meta",
groupDesc: "元数据相关的包",
name: "BaseCompAPI",
desc: "关于认证的类",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "baseComp",
methodName: "baseComp",
paramdescs: [
{
paramDesc: "访问appkey",
paramName: "appkey",
paramType: "string",
defaultValue: "x",
},
{
paramDesc: "访问secret",
paramName: "secret",
paramType: "string",
defaultValue: null,
}
],
rtnTypeDesc: "xxxx",
rtnType: "xxx"
}
];
}
}
module.exports = BaseCompAPI;
\ No newline at end of file
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class AuthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(AuthCtl));
}
async saveAuths(qobj,query,req){
var auths=qobj.aus;
var xrtn=await this.service.saveAuths(auths,req.appid,req.tocompanyid);
return system.getResult(xrtn);
}
async findAuthsByRole(qobj,query,req){
var rolecodestrs=qobj.rolecode;
var xrtn=await this.service.findAuthsByRole(rolecodestrs,req.appid,req.tocompanyid);
return system.getResult(xrtn);
}
}
module.exports=AuthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class DataauthCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(DataauthCtl));
}
async saveauth(qobj,querybij,req){
var arys=qobj.arys;
var uid=qobj.uid;
var refmodel=qobj.modelname;
var u=await this.service.saveauth({
user_id:uid,
modelname:refmodel,
auths:arys.join(","),
app_id:req.appid,
});
return system.getResult(u);
}
async fetchInitAuth(qobj,querybij,req){
var uid=qobj.uid;
var refmodel=qobj.modelname;
var authtmp=await this.service.findOne({user_id:uid,modelname:refmodel,app_id:req.appid});
if(authtmp){
var auths= authtmp.auths;
var arys=auths.split(",");
return system.getResult(arys);
}else{
return system.getResultSuccess([]);
}
}
}
module.exports=DataauthCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class OrgCtl extends CtlBase{
constructor(){
super("auth",CtlBase.getServiceName(OrgCtl));
this.compSvr=system.getObject("service.common.companySve");
}
//检查是否已经存在主要岗位
async checkMainPosition(p,q,req){
return this.service.checkMainPosition(p,q,req);
}
async changePos(p,q,req){
var toorgid=p.orgid;
var uid=p.uid;
var rtn= await this.service.changePos(toorgid,uid);
return system.getResult(rtn);
}
async create(p,q,req){
return super.create(p,q,req);
}
async delete(p,q,req){
return super.delete(p,q,req);
}
async update(p,q,req){
return super.update(p,q,req);
}
async initOrgs(p,q,req){
var tocompany=req.session.tocompany;
var cmkey=p.comkey;
if(cmkey){
tocompany =await this.compSvr.findOne({companykey:cmkey});
}
//按照公司名称查询,是否存在节点,不存在,就创建根节点
//如果存在就按照名称查询出当前和她的字节点
var rtn=await this.service.initOrgs(tocompany,req.appid);
return system.getResult(rtn);
}
async findOrgById(p,q,req){
var rtn=await this.service.findOrgById(p.id);
return system.getResult(rtn);
}
}
module.exports=OrgCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class RoleCtl extends CtlBase {
constructor() {
super("auth",CtlBase.getServiceName(RoleCtl));
//this.loginS=system.getObject("service.userSve");
this.roleS=system.getObject("service.auth.roleSve");
this.redisClient=system.getObject("util.redisClient");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
rtn.roles = [];
return system.getResultSuccess(rtn);
}
}
module.exports = RoleCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class AppCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async findAllApps(p,q,req) {
var rtns = await this.service.findAllApps(p.userid);
return system.getResult(rtns);
}
async update(pobj, queryobj, req){
return super.update(pobj, queryobj, req);
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
rtn.appkey = this.getUUID();
rtn.secret = this.getUUID();
return system.getResult(rtn);
}
async resetPass(pobj, queryobj, req) {
pobj.password = await super.encryptPasswd(settings.defaultpwd);
var rtn = this.service.resetPass(pobj);
return system.getResult(rtn);
}
async createAdminUser(pobj, queryobj, req) {
pobj.password = settings.defaultpwd;
var rtn = this.service.createAdminUser(pobj);
return system.getResult(rtn);
}
async create(pobj, queryobj, req) {
//设置创建者,需要同时创建app管理员、默认密码、电话
pobj.creator_id = req.session.user.id;
// pobj.password=super.encryptPasswd(settings.defaultpwd);
//构造默认的应用相关的URL
pobj.authUrl=settings.protocalPrefix+pobj.domainName+"/auth";
pobj.docUrl=settings.protocalPrefix+pobj.domainName+"/web/common/metaCtl/getApiDoc";
pobj.uiconfigUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/config/fetchAppConfig";
pobj.opCacheUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/opCache/opCacheData";
pobj.notifyCacheCountUrl=settings.protocalPrefix+pobj.domainName+"/api/meta/opCache/recvNotificationForCacheCount";
var app = await super.create(pobj,queryobj, req);
return system.getResult(app);
}
async fetchApiCallData(pobj, queryobj, req){
var curappkey=pobj.curappkey;
//检索出作为访问时的app呼出调用数据
var rtn= await this.service.fetchApiCallData(curappkey);
return system.getResultSuccess(rtn);
}
//接受缓存计数通知接口
async recvNotificationForCacheCount(p,q,req){
return this.service.recvNotificationForCacheCount(p);
}
}
module.exports = AppCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
class CachSearchesCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CachSearchesCtl));
}
async initNewInstance(queryobj, qobj) {
return system.getResultSuccess({});
}
async findAndCountAll(pobj, gobj, req) {
pobj.opCacheUrl = req.session.app.opCacheUrl;
pobj.appid = req.appid;
return await this.service.findAndCountAllCache(pobj);
}
async delCache(queryobj, qobj, req) {
var param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param);
}
async clearAllCache(queryobj, qobj, req) {
var param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param);
}
}
module.exports = CachSearchesCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
class CompanyCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CompanyCtl));
this.userS=system.getObject("service.auth.userSve");
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
return system.getResult(rtn);
}
//to do租户在创建公司的时候,需要同时维护平台下面,用户所属租户是当前租户的公司
//当删除公司时,需要同时删除公司关联的APP,还有用户关联的公司
async create(p,q,req){
var user=await this.userS.findOne({id:p.userid});
var uuidstr=this.getUUID();
p.companykey=uuidstr;
var company=await this.service.create(p,user);
req.session.tocompany=company;
return system.getResult(company);
}
async update(p,q,req){
//修改重新刷新页面,初始化页面的公司信息
var rtn=await super.update(p,q,req);
req.session.company=p;
return system.getResult(rtn);
}
async buyApp(p,q,req){
var cmpid=req.session.tocompany.id;
var user=req.session.user;
var cmpfind=await this.service.buyApp(p,cmpid,user);
req.session.tocompany=cmpfind;
return system.getResult(cmpfind.apps);
}
async giveupApp(p,q,req){
var comid=p.compid;
var appid=p.appid;
var rtn=await this.service.giveupApp(comid,appid);
return system.getResult(rtn);
}
//设置当前用户选择的公司为当前公司
async settocompany(p,q,req){
p.isCurrent=true;
req.session.tocompany=p;
var cmp= await this.service.settocompany(p);
return system.getResult(cmp);
}
async findAndCountAll(p,q,req){
var comps=await this.service.findAndCountAll(p,q,req);
var rtns=[];
for(var cmp of comps){
if(cmp.id!=settings.platformcompanyid){
var rtntmp={
id:cmp.id,
name:cmp.name,
companykey:cmp.companykey,
description:cmp.description,
logoUrl:cmp.logoUrl,
isCurrent:cmp.usercompany.isCurrent,
apps:cmp.apps?cmp.apps:[]
}
rtns.push(rtntmp);
}
}
var rtn = {};
rtn.results = {count:rtns.length,rows:rtns};
rtn.aggresult = {};
return system.getResult(rtn);
}
}
module.exports = CompanyCtl;
var system = require("../../../system")
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 system = require("../../../system");
const settings = require("../../../../config/settings");
function exp(db, DataTypes) {
var base = {
code: {
type: DataTypes.STRING(50),
unique: true
},
name: DataTypes.STRING(1000),
};
return base;
}
module.exports = exp;
const system = require("../../system");
const settings = require("../../../config/settings");
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", uiconfig.config.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", uiconfig.config.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const 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");
//缓存首次登录的赠送的宝币数量
class ApiAccuCache extends CacheBase{
constructor(){
super();
this.apitradeDao=system.getObject("db.callcount.apitradeDao");
}
desc(){
return "API累计调用次数和累计余额";
}
prefix(){
return "api_accu:";
}
async addCallCount(apikey,n){
var key=this.prefix+apikey;
var result=await this.redisClient.hincrby(key,"callcount",n);
return result;
}
async addCallBalance(apikey,n){
var key=this.prefix+apikey;
var result=await this.redisClient.hincrby(key,"amount",n);
return result;
}
async getApiCallAccu(srckey){
var apikey=srckey.split("_")[0];
var key=this.prefix+srckey;
const cachedVal= await this.redisClient.hgetall(key);
if(!cachedVal || cachedVal=="undefined"){
var count= await this.apitradeDao.model.count({
where:{
srcappkey:apikey,
tradeType:"consume",
}
});
var amount=await this.apitradeDao.model.sum("amount",{
where:{
srcappkey:apikey,
}
});
var map={"callcount":count?count:0,"amount":amount?amount:0};
this.redisClient.hmset(key,map);
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
return map;
}else{
return cachedVal;
}
}
}
module.exports=ApiAccuCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class ApiCallCountCache extends CacheBase{
constructor(){
super();
this.apitradeDao=system.getObject("db.common.apitradeDao");
}
desc(){
return "API调用次数";
}
prefix(){
return "api_call:";
}
async addCallCount(apikey,callpath,n){
var key=this.prefix+apikey+"_"+callpath;
var result=await this.redisClient.hincrby(key,"callcount",n);
return result;
}
async addCallBalance(apikey,callpath,n){
var key=this.prefix+apikey+"_"+callpath;
var result=await this.redisClient.hincrby(key,"amount",n);
return result;
}
async getApiCallCount(apikey,callpath){
var key=this.prefix+apikey+"_"+callpath;
const cachedVal= await this.redisClient.hgetall(key);
if(!cachedVal || cachedVal=="undefined"){
var count= await this.apitradeDao.model.count({
where:{
srcappkey:apikey,
op:callpath,
tradeType:"consume",
}
});
var amount=await this.apitradeDao.model.sum("amount",{
where:{
srcappkey:apikey,
op:callpath,
tradeType:"consume",
}
});
var map={"callcount":count?count:0,"amount":amount?amount:0};
this.redisClient.hmset(key,map);
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [key + "|" + this.desc]);
return map;
}else{
return cachedVal;
}
}
}
module.exports=ApiCallCountCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class AppCache extends CacheBase{
constructor(){
super();
this.prefix="g_appkey:";
this.appDao=system.getObject("db.common.appDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存本地应用对象";
}
prefix(){
return "g_applocal_"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue=await this.appDao.findOne2(inputkey);
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports=AppCache;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class InitGiftCache extends CacheBase{
constructor(){
super();
this.pConfigDao=system.getObject("db.common.pconfigDao");
}
desc(){
return "初始赠送";
}
prefix(){
return "g_pconfig_initGift";
}
async buildCacheVal(cachekey,inputkey,val,ex,...items){
const config=await this.pConfigDao.model.findOne({where:{configType:'initGift',appkey:inputkey},raw:true});
const num2=Number(config.configValue);
return num2;
}
}
module.exports=InitGiftCache;
const CacheBase=require("../cache.base");
//缓存当前登录用户的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.tocompanyid;
return w;
}
extraModelFilter(){
return {"key":"include","value":[{model:this.db.models.app,}]};
}
async preUpdate(u){
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
await this.model.update(obj2,{where:{id:obj2.id}});
var role=await this.model.findOne({where:{id:obj2.id}});
return role;
}
async preCreate(u){
return u;
}
async create(u,t){
var self=this;
var u2= await this.preCreate(u);
if(t){
var role= await this.model.create(u2,{transaction: t});
return role;
}else{
var role= await this.model.create(u2);
return role;
}
}
}
module.exports=RoleDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class 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;
}
}
async findAndCountAll(qobj, t) {
if(qobj.codepath.indexOf("comapps")>=0){
var rtn={};
var comp=await this.db.models.company.findOne({where:{companykey:qobj.search.companykey}});
var apps=await comp.getApps();
rtn.results={rows:apps,count:apps.length};
rtn.aggresult={};
return rtn;
}else{
return super.findAndCountAll(qobj, t);
}
}
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.tocompanyid;
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={
"bizName":"comapps",
"list":{
columnMetaData:[
{"width":"200","label":"应用KEY","prop":"appkey","isShowTip":true,"isTmpl":false},
{"width":"100","label":"应用名称","prop":"name","isShowTip":true,"isTmpl":false},
{"width":"200","label":"应用密钥","prop":"secret","isShowTip":true,"isTmpl":false},
{"width":"200","label":"是否启用","prop":"isEnabled","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":"true"},
]
},
"form":[
{
"title":"应用控制",
"colnum":1,
"ctls":[
{"type":"switch","label":"是否启用","prop":"isEnabled","acText":"启用","inactText":"停用","placeHolder":"","style":""},
{"type":"switch","label":"是否私有","prop":"isPublish","acText":"否","inactText":"是","placeHolder":"","style":""},
{ "type": "select", "label": "应用类型", "dicKey": "app_type", "prop": "appType", "labelField": "label", "valueField": "value", "placeHolder": "请选择支付类型", "style": "" },
]
},
{
"title":"概要介绍",
"colnum":1,
"ctls":[
{ "type": "textarea", "label": "简介", "prop": "description", "placeHolder": "请输入产品简介", "style": "width:600px" }
]
},
{
"title":"基本信息",
"colnum":3,
"ctls":[
{"type":"input","label":"应用KEY","prop":"appkey","disabled":true,"placeHolder":"","style":""},
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
{"type":"input","label":"应用密钥","prop":"secret","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"域名","prop":"domainName","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"首页","prop":"homePage","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"认证URL","prop":"authUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"文档URL","prop":"docUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"配置URL","prop":"uiconfigUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"缓存操作URL","prop":"opCacheUrl","disabled":false,"placeHolder":"","style":""},
{"type":"input","label":"接受API调用计数URL","prop":"notifyCacheCountUrl","disabled":false,"placeHolder":"","style":""},
]
},
{
"title":"个性化信息",
"colnum":2,
"ctls":[
{"type":"upload","label":"logo","prop":"logoUrl","disabled":false,"placeHolder":"","style":""},
{"type":"upload","label":"背景图","prop":"bkimageUrl","placeHolder":"应用名称","style":""},
{"type":"upload","label":"缩略图","prop":"showimgUrl","disabled":false,"placeHolder":"","style":"width:100px;height:100px"},
{"type":"upload","label":"细节图","prop":"domainName","disabled":false,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
],
"auth":{
"add":[
],
"edit":[
{"icon":"el-icon-edit","title":"弃租","type":"default","key":"giveup","isInRow":true},
],
"delete":[
],
"common":[
],
}
}
module.exports = (db, DataTypes) => {
return db.define("auth", {
rolecode: DataTypes.STRING,
bizcode: DataTypes.STRING,
codepath: DataTypes.STRING,
authstrs: DataTypes.STRING
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_auths',
validate: {
}
});
}
module.exports = (db, DataTypes) => {
return db.define("dataauth", {
modelname: DataTypes.STRING,
auths: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_dataauths',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("org", {
code: {
type:DataTypes.STRING(64),
allowNull: false,
},
name: {
type:DataTypes.STRING(64),
allowNull: false,
},
isLeaf:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
orgpath: {
type:DataTypes.STRING,
allowNull: false,
},
nodeType: {//默认为组织
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.node_type),
defaultValue:'org'
},
isPosition:{//是否是岗位
type:DataTypes.BOOLEAN,
defaultValue: false
},
isMain:{//是否是主岗
type:DataTypes.BOOLEAN,
defaultValue: false
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_org',
validate: {
}
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("orgrole", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_orgrole',
validate: {
},
});
}
\ No newline at end of file
module.exports = (db, DataTypes) => {
return db.define("role", {
name: DataTypes.STRING,
code: DataTypes.STRING,
description: DataTypes.STRING,
isSystem: {//是否系统数据,0否,1是
type: DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_role',
validate: {
}
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("user", {
userName: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
nickName: {
type:DataTypes.STRING,
allowNull: true,
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
mobile:DataTypes.STRING,
mail: {
type:DataTypes.STRING,
allowNull: true,
},
headUrl: DataTypes.STRING,
isAdmin:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
isSuper:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
wxopenid:DataTypes.STRING,
app_id:DataTypes.INTEGER,
account_id:DataTypes.INTEGER,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
opath:DataTypes.STRING,//作业务时,需要在业务表冗余当前处理人的opath
ppath:DataTypes.STRING,//权限路径,主岗下的人大于opath一级,查询时按照opath去查询
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_user',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("account", {
nickName: {
type:DataTypes.STRING(128),
allowNull: true,
},
userName:DataTypes.STRING,
password: {
type:DataTypes.STRING,
validate: {
// length(value){
// if(value.length<6){
// throw new Error("lenght。。。")
// }
// }
}
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
headUrl: DataTypes.STRING,
mobile: DataTypes.STRING,
baoBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
renBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_account',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("apitrade", {
tradeType: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.tradeType),
},
op:{//访问路径
type:DataTypes.STRING,
allowNull: true,
},
srcappkey:{//
type:DataTypes.STRING,
allowNull: true,
},
destappkey:{//
type:DataTypes.STRING,
allowNull: true,
},
params:{
type:DataTypes.STRING(1024),
allowNull: true,
},
clientIp:DataTypes.STRING,
agent:{
type:DataTypes.STRING,
allowNull: true,
},
isAllowed:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
amount: {//每条多少钱
type:DataTypes.INTEGER ,
allowNull: false,
defaultValue: 0
},
desc:DataTypes.STRING,//比如前500条免费
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt:false,
//freezeTableName: true,
// define the table's name
tableName: 'api_trade',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("app", {
appkey: DataTypes.STRING,//需要在后台补充
secret: DataTypes.STRING,//需要在后台补充
name: {
type: DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
domainName: DataTypes.STRING,//域名
homePage: DataTypes.STRING,//首页
authUrl: DataTypes.STRING,//认证地址
docUrl: DataTypes.STRING,//接口文档地址
uiconfigUrl: DataTypes.STRING,//基础信息配置信息地址
logoUrl: DataTypes.STRING,//应用Logo
bkimageUrl: DataTypes.STRING,//应用背景图
showimgUrl: DataTypes.STRING,//应用显示图标
detailimgUrl: DataTypes.STRING,//应用详情介绍地址
opCacheUrl: DataTypes.STRING,//操作缓存地址
notifyCacheCountUrl: DataTypes.STRING,//接收API使用计数的通知URL
description: DataTypes.STRING,//应用描述
isSaas: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: true
},//是否启用
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否启用
isPublish: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
isCommon: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否公共服务
appType: {
type: DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.app_type),
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_app',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("company", {
name: {
type:DataTypes.STRING,
allowNull: false,
},
creditCode: {
type:DataTypes.STRING,
allowNull: true,
},
licenseUrl: DataTypes.STRING,
description: DataTypes.STRING,
companykey:{
type:DataTypes.STRING,
allowNull: true,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_company',
validate: {
},
});
}
module.exports = (db, DataTypes) => {
return db.define("companyapp", {
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_companyapp',
validate: {
},
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("oplog", {
appkey: {
type:DataTypes.STRING,
allowNull: true,
},
appname:{
type:DataTypes.STRING,
allowNull: false,
},
userid: { type: DataTypes.INTEGER,allowNull: true},
username:{
type:DataTypes.STRING,
allowNull: true,
},
logLevel: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.logLevel),
defaultValue: "info",
},
op:{
type:DataTypes.STRING,
allowNull: true,
},
content:{
type:DataTypes.STRING(4000),
allowNull: true,
},
clientIp:DataTypes.STRING,
agent:{
type:DataTypes.STRING,
allowNull: true,
},
opTitle:DataTypes.STRING(500),
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt:false,
//freezeTableName: true,
// define the table's name
tableName: 'op_log',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("paccount", {
baoBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
renBalance:{
type:DataTypes.DECIMAL(12,2),
defaultValue:0.00,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'pp_account',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
const enums={
price:"宝币兑换率",
initGift:"初次赠送",
apiCallPrice:"API调用价格",
apiInitGift:"API初次赠送次数",
logOpWrite:"操作日志步骤是否写入,0否,1是",
}
var PConfig=db.define("pconfig", {
name: {
type:DataTypes.STRING,
allowNull: false,
// get(){
// const ctype = this.getDataValue("configType");
// return enums[ctype];
// }
},
configType: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(enums),
set:function(val){
this.setDataValue("name",enums[val]);
this.setDataValue("configType",val);
}
},
configValue: {
type:DataTypes.STRING,
allowNull: false,
},
appkey: {
type:DataTypes.STRING,
allowNull: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_config',
validate: {
},
});
PConfig.enums=enums;
return PConfig;
}
module.exports = (db, DataTypes) => {
return db.define("task", {
app_id:DataTypes.STRING,//需要在后台补充
taskClassName: {
type:DataTypes.STRING(100),
allowNull: false,
unique: true
},//和user的from相同,在注册user时,去创建
taskexp: {
type:DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
desc:DataTypes.STRING,//需要在后台补充
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_task',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("usercompany", {
isCurrent: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},//是否对外
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'p_usercompany',
validate: {
},
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("msghistory", {
msgType:{
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.msgType),
},
sender:DataTypes.STRING,
senderId:DataTypes.INTEGER,
target:DataTypes.STRING,
targetId:DataTypes.INTEGER,
content: {
type: DataTypes.TEXT('long'),
allowNull: false,
},//需要在后台补充
isRead:{//分享时是否渠道店铺名称,0否,1是
type:DataTypes.BOOLEAN,
defaultValue: false,
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msghistory',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("msgnotice", {
fromuser: DataTypes.STRING,//需要在后台补充
fromId:DataTypes.INTEGER,
touser: DataTypes.STRING,//需要在后台补充
toId:DataTypes.INTEGER,
businessLicense_id:DataTypes.INTEGER,
//"onlineset"+"¥"+data.appkey:[uk+"¥"+data.nickName+"¥"+data.imgUrl] uk=appid¥uid
isAccepted:DataTypes.BOOLEAN,
lastMsgId:DataTypes.INTEGER,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'msgnotice',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
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 TestTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(TestTask));
}
async subDoTask(){
console.log("TestTask1.....");
}
}
module.exports=TestTask;
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 TaskBase=require("../task.base");
class TestTask extends TaskBase{
constructor(){
super();
}
async doTask(){
console.log("TestTask.....");
}
}
module.exports=TestTask;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class AccountService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(AccountService));
//this.appDao=system.getObject("db.appDao");
}
}
module.exports=AccountService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class AuthService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(AuthService));
}
//字符串数组参数
async findAuthsByRole(rolecodestr,appid,comid){
//{where:{id:{[this.db.Op.in]:ids}}}
//var newattrs=rolecodestr.split(",");
var aths=await this.dao.model.findAll({
attributes:["bizcode","authstrs","codepath"],
where:{rolecode:{[this.db.Op.in]:rolecodestr},app_id:appid,company_id:comid}});
return aths;
}
async saveAuths(auths,appid,cmid){
//先按照code 和 bizcode查询
var self=this;
console.log("yyyyyyyyyvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
console.log(auths);
return self.db.transaction(async function (t){
for(var i=0;i<auths.length;i++){
var tmpAuth=auths[i];
tmpAuth.app_id=appid;
tmpAuth.company_id=cmid;
var objrtn=await self.dao.model.findOrCreate({
defaults:tmpAuth,
where:{rolecode:tmpAuth.rolecode,bizcode:tmpAuth.bizcode},//注意这里bizcode存储的是节点的code值
transaction:t,
});
console.log("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
console.log(objrtn);
if(!objrtn[1].created){
//就执行更新操作
await objrtn[0].update(tmpAuth,{where:{rolecode:tmpAuth.rolecode,bizcode:tmpAuth.bizcode,app_id:tmpAuth.app_id},transaction:t})
}
}
var aths=await self.dao.model.findAll({where:{rolecode:tmpAuth.rolecode,app_id:tmpAuth.app_id},transaction:t});
return aths;
});
}
}
module.exports=AuthService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base")
const settings=require("../../../../config/settings")
class DataauthService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(DataauthService));
}
async saveauth(obj){
//先按照uid,modelname,检查是否存在,不存在创建,存在更新
var oldauth= await this.dao.findOne({user_id:obj.user_id,modelname:obj.modelname,app_id:obj.add_id});
if(!oldauth){
return this.dao.create(obj);
}else{
obj.id=oldauth.id;
return this.dao.update(obj);
}
}
}
module.exports=DataauthService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class OrgService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(OrgService));
}
async delete(p,q,req){
var self=this;
var orgid=p.id;
var uone=await this.db.models.user.findOne({where:{org_id:orgid}});
if(!uone){
//先检查是否组织下有人员存在
return this.db.transaction(async function (t) {
var inst=await self.dao.model.findById(orgid);
var parentid=inst.org_id;
await inst.destroy({force:true,transaction:t});
//删除组织对应的角色
self.db.models.orgrole.destroy({where:{org_id:orgid},force:true,transaction:t});
//查询出父元素
var orgparent=await self.dao.model.findOne({
order:[["code","ASC"]],
where:{id:parentid},transaction:t,
include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]]}
]}
]});
return orgparent.orgs;
});
}else{
return null;
}
}
async update(p,q,req){
var self=this;
var cmkey=p.comkey;//如果是来自租户界面的修改
return this.db.transaction(async function (t) {
p.isLeaf=p.isPosition;
var orgupdate=await self.dao.model.findOne({where:{id:p.id},transaction:t});
await self.dao.model.update(p,{where:{id:p.id},transaction:t});
var usersupdate=await self.db.models.user.findAll({where:{org_id:orgupdate.id}});
//如果节点名称或岗位性质发生变化
//if(p.name!=orgupdate.name || p.isMain!=orgupdate.isMain){
for(var ud of usersupdate){
ud.opath=p.orgpath;
var n=p.orgpath.lastIndexOf("/");
ud.ppath=p.isMain?p.orgpath.substring(0,n):p.orgpath;
await ud.save({transaction:t});
}
//}
if(p.Roles && !cmkey){//如果不是来自租户界面的修改
var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
await orgupdate.setRoles(roles,{transaction:t});
//同时要给这个岗位下的user,更新角色 todo
for(var ud of usersupdate){
await ud.setRoles(roles,{transaction:t});
}
}
var orgparent=await self.dao.model.findOne({
order:[["code","ASC"]],
where:{id:orgupdate.org_id},transaction:t,
include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]});
return orgparent.orgs;
});
}
async checkMainPosition(p,q,req){
var orgmain=await this.dao.model.findOne({where:{org_id:p.org_id,isMain:true}});
if(orgmain){
return {"isHave":true};
}else{
return null;
}
}
async changePos(toorgid,uid){
//查询出当前用户,设置当前用户的orgid为修改目标
var self=this;
return this.db.transaction(async function (t) {
var ufind=await self.db.models.user.findById(uid);
var org=await self.dao.model.findOne({
where:{id:toorgid},
include:[
{model:self.db.models.role,as:"roles"},
]});
ufind.org_id=toorgid;
ufind.opath=org.orgpath;
if(org.isMain){//如果是主岗
var n=org.orgpath.lastIndexOf("/");
ufind.ppath=org.orgpath.substring(0,n);
}else{
ufind.ppath= org.orgpath;
}
await ufind.save({transaction:t});
await ufind.setRoles(org.roles,{transaction:t});
return ufind;
});
//查询出目标org,关联查询出角色
//设置当前用户的角色
}
async create(p,q,req){
var self=this;
var cmkey=p.comkey;
return this.db.transaction(async function (t) {
if(cmkey){
var tmpcompany =await self.db.models.company.findOne({where:{companykey:cmkey},transaction:t});
p.company_id=tmpcompany.id;
}
var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
p.isLeaf=p.isPosition;
p.app_id=null;
var orgnew=await self.dao.model.create(p,{transaction:t});
if(roles && roles.length>0){
await orgnew.setRoles(roles,{transaction:t});
}
var orgparent=await self.dao.model.findOne({
order:[["code","ASC"]],
where:{id:orgnew.org_id},transaction:t,
include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]});
return orgparent.orgs;
});
}
async findOrgById(id){
var org=await this.dao.model.findOne({
order:[["code","ASC"]],
where:{id:id},
include:[
{model:this.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:this.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:this.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:this.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:this.db.models.role,as:"roles",attributes:['id','code','name']},
]});
return org.orgs;
}
async initOrgs(company,appid){
var self=this;
return this.db.transaction(async function (t) {
var org=await self.dao.model.findOne({
order:[["code","ASC"]],
//where:{name:company.name,company_id:company.id,app_id:appid},transaction:t,
where:{name:company.name,company_id:company.id},transaction:t,
include:[
{model:self.db.models.org,as:"orgs", order:[["code","ASC"]],include:[
{model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]},
{model:self.db.models.role,as:"roles",attributes:['id','code','name']},
]});
if(org!=null){
return org;
}else{
var root= await self.dao.model.create({
code:"root"+company.id,
name:company.name,
isLeaf:false,
isPostion:false,
isMain:false,
orgpath:"/",
company_id:company.id,
app_id:null,
},{transaction:t});
return root;
}
});
}
}
module.exports=OrgService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class RoleService extends ServiceBase{
constructor(){
super("auth",ServiceBase.getDaoName(RoleService));
//this.appDao=system.getObject("db.appDao");
}
async findOneByCode(code){
return this.dao.model.findOne({where:{code:code}});
}
}
module.exports=RoleService;
const system=require("../../../system");
const 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(uid) {
var apps=null;
var dicRtn = {};
var wheresql= {};
if(uid){
wheresql[this.db.Op.and]={
[this.db.Op.or]:
[
{isPublish:false, creator_id: uid},
{isEnabled: true,isPublish:true}
],
};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
}else{
wheresql= {isEnabled: true,isPublish:true};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl','homePage'] });
}
for (var app of apps) {
var tmk = uiconfig.config.pdict.app_type[app.appType];
if (!dicRtn[tmk]) {
dicRtn[tmk] = [];
dicRtn[tmk].push(app);
} else {
dicRtn[tmk].push(app);
}
}
return dicRtn;
}
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 giveupApp(comid,appid){
var self=this;
return this.db.transaction(async function (t){
//检查当前company_id下面是否有用户存在,如果已经存在就不要删除了
var c=await self.db.models.user.count({where:{owner_id:comid}});
if(c>1){
return null;
}else{
if(c==1){
await self.db.models.user.destroy({where:{owner_id:comid},force: true});
}
await self.db.models.companyapp.destroy({where:{company_id:comid,app_id:appid}});
return {};
}
});
}
async buyApp(p,cmid,user){
var self=this;
var appid=p.id;
var cmid=cmid;
return this.db.transaction(async function (t){
//先按照用户id,取消所有当前
// var cmp=await self.db.models.company.findOne({where:{
// id:cmid,
// }});
// cmp.addApp(p,{transaction:t});
var seladd=await self.db.models.companyapp.create({
company_id:cmid,
app_id:appid
},{transaction:t});
//创建当前购买应用的管理员账号,设置所属公司,不需要建立公司关系在在中间表
var appadminuser=await self.userS.createAdminUser({
userName:user.userName,
password:user.password,
mobile:user.mobile,
app_id:appid,
owner_id:cmid,
tanentor_id:user.id,//租户的id
},{transaction:t});
//查询当前公司,关联出apps
var cmpfind=await self.db.models.company.findOne({where:{
id:cmid,
},
include:[
{model:self.db.models.app}
],
transaction:t
});
return cmpfind;
});
}
async settocompany(p){
var self=this;
var uid=p.userid;
var cid=p.id;
return this.db.transaction(async function (t){
//先按照用户id,取消所有当前
var up1=await self.db.models.usercompany.update({isCurrent:false},{where:{user_id:uid},transaction:t});
//按照用户id和公司id,设置当前
var up2=await self.db.models.usercompany.update({isCurrent:true},{where:{user_id:uid,company_id:cid},transaction:t});
return p;
});
}
async findAndCountAll(p,q,req){
var u= await this.userS.dao.model.findOne({where:{id:p.userid},
include: [
{
model: this.db.models.company,through:{attributes:['isCurrent']},include:[
{model:this.db.models.app}
]
},
]
});
var cmps=await u.companies;
return cmps;
}
}
module.exports = CompanyService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const settings=require("../../../../config/settings");
class MetaService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(MetaService));
this.restS=system.getObject("util.restClient");
}
async getApiDoc(appid){
var p=settings.basepath+"/app/base/db/impl/common/apiDocManager.js";
var ClassObj= require(p) ;
var obj=new ClassObj();
return obj.doc;
}
async getApiDocRemote(appid,docUrl){
var rtn=await this.restS.execPost({}, docUrl);
if(rtn.stdout){
var dod=JSON.parse(rtn.stdout);
if(dod.data){
return dod.data;
}
}
return null;
}
async getUiConfig(appid){
const cfg=await this.cacheManager["UIConfigCache"].cache(appid,null,60);
return cfg;
}
async getRemoteUiConfig(appkey,uiconfigUrl){
const cfg=await this.cacheManager["UIRemoteConfigCache"].cache(appkey,null,120,uiconfigUrl);
return cfg;
}
}
module.exports=MetaService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class OplogService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(OplogService));
//this.appDao=system.getObject("db.appDao");
this.opLogUrl = settings.apiconfig.opLogUrl();
this.opLogEsIsAdd = settings.apiconfig.opLogEsIsAdd();
}
async create(qobj) {
if (!qobj || !qobj.op || qobj.op.indexOf("metaCtl/getUiConfig") >= 0 ||
qobj.op.indexOf("userCtl/checkLogin") >= 0 ||
qobj.op.indexOf("oplogCtl") >= 0 ||
qobj.op.indexOf("getDicConfig") >= 0 ||
qobj.op.indexOf("getRouteConfig") >= 0 ||
qobj.op.indexOf("getRsConfig") >= 0) {
return null;
}
var rc = system.getObject("util.execClient");
var rtn = null;
try {
// var myDate = new Date();
// var tmpTitle=myDate.toLocaleString()+":"+qobj.optitle;
qobj.optitle = (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":" + qobj.optitle;
if (this.opLogEsIsAdd == 1) {
qobj.content = qobj.content.replace("field list", "字段列表")
qobj.created_at = (new Date()).getTime();
//往Es中写入日志
var addEsData = JSON.stringify(qobj);
rc.execPost(qobj, this.opLogUrl);
} else {
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
} catch (e) {
console.log("addLog------>>>>>>error-----------------------*****************");
console.log(e);
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
}
}
module.exports = OplogService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class PConfigService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(PConfigService));
//this.appDao=system.getObject("db.appDao");
}
async findOrSetPrice(num,appkey){
return this.cacheManager["PriceConfigCache"].cacheGlobalVal(num,appkey);
}
async create(pobj){
await this.cacheManager["PConfigCache"].invalidate(pobj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(pobj.appkey);
return this.dao.create(pobj);
}
async update(pobj,tm=null){
await this.cacheManager["PConfigCache"].invalidate(pobj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(pobj.appkey);
return this.dao.update(pobj,tm);
}
async updateByWhere(setObj,whereObj,t){
await this.cacheManager["PConfigCache"].invalidate(setObj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(setObj.appkey);
return this.dao.updateByWhere(setObj,whereObj,t);
}
//获取配置的发票税率
async getInvoiceTaxRate(){
var tmpInvoiceTaxRate=7;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "invoiceTaxRate";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
tmpInvoiceTaxRate=Number(pconfigResult.configValue);
}
return tmpInvoiceTaxRate;
}
//获取配置的信息
async getConfigValue(configName){
var configValue=0;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === configName;
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
configValue=Number(pconfigResult.configValue);
}
return configValue;
}
//获取配置的推荐人分润比例
async getReferrerProfitRatio(){
var tmpInvoiceTaxRate=10;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "referrerProfitRatio";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
tmpInvoiceTaxRate=Number(pconfigResult.configValue);
}
return tmpInvoiceTaxRate;
}
//商机分配渠道配置,格式:wssyh5,yzc等
async getBussinessAllotChannelConfig(){
var bussinessAllotChannel="wssyh5";
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "bussinessAllotChannelConfig";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
bussinessAllotChannel=pconfigResult.configValue;
}
return bussinessAllotChannel;
}
}
module.exports=PConfigService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TaskService));
//this.appDao=system.getObject("db.appDao");
this.taskManager=system.getObject("db.taskManager");
this.emailClient=system.getObject("util.mailClient");
this.personTaxDao=system.getObject("db.individualincometaxDao");
this.ossClient=system.getObject("util.ossClient");
}
//写文件并上传到阿里云,返回上传的路径
async writexls(wb,sharecode){
var that=this;
var uuid=uuidv4();
var u=uuid.replace(/\-/g,"");
var fname="zc_"+u+".xlsx";
var filepath="/tmp/"+fname;
var promise=new Promise((resv,rej)=>{
wb.xlsx.writeFile(filepath).then(async function(d) {
var rtn=await that.ossClient.upfile(fname,filepath);
fs.unlink(filepath,function(err){});
return resv(rtn);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
//读取模板文件
async readxls(){
var promise=new Promise((resv,rej)=>{
var workbook = new excel.Workbook();
workbook.properties.date1904 = true;
var bpth=path.normalize(path.join(__dirname, '../'));
workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
.then(function() {
return resv(workbook);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
async buildworkbook(taxCalcList){
var workbook = await this.readxls();
var sheet = workbook.getWorksheet(1);
sheet.columns = [
{ header: '年度', key: 'statisticalYear', width: 10 },
{ header: '月份', key: 'statisticalMonth', width: 10 },
{ header: '员工姓名', key: 'employeeName', width: 10 },
{ header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
{ header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
// { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '子女教育', key: 'childrenEducation', width: 10 },
{ header: '继续教育', key: 'continuingEducation', width: 10 },
{ header: '房贷利息', key: 'interestExpense', width: 10 },
{ header: '住房租金', key: 'housingRent', width: 10 },
{ header: '赡养老人', key: 'supportElderly', width: 10 },
{ header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
{ header: '专项扣除合计', key: 'specialDeduction', width: 10 },
{ header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
{ header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
{ header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
{ header: '适用税率', key: 'taxRate', width: 10 },
{ header: '速算扣除', key: 'deductionNumber', width: 10 },
{ header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
{ header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
// (累计税前薪资-累计五险一金-累计免征额-累计已扣专项)*税率-速算扣除-累计已纳个税=本月应纳个税
];
taxCalcList.forEach(r=>{
sheet.addRow(r);
});
return workbook;
}
async makerpt(qobj){
var self=this;
return this.db.transaction(async t=>{
const sharecode=qobj.sharecode;
const email=qobj.email;
//按照sharecode获取单位某次个税计算
var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
var sheetNameSufix="个税汇总表";
if(taxCalcList && taxCalcList.length>0){
var year=taxCalcList[0].statisticalYear;
var month=taxCalcList[0].statisticalMonth;
sheetNameSufix=year+month+sheetNameSufix;
}
var wb=await this.buildworkbook(taxCalcList);
//生成excel
var result=await this.writexls(wb,sharecode);
//异步不等待发送邮件给
var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
//发送手机短信
//写到按咋回哦sharecode,修改下载的url
return result.url;
});
}
async create(qobj){
var self=this;
return this.db.transaction(async t=>{
var task=await this.dao.create(qobj,t);
//发布任务事件
var action="new";
var taskClassName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
await self.taskManager.newTask(msg);
await self.taskManager.publish("task","newtask");
return task;
});
}
async restartTasks2(qobj){
return this.restartTasks(qobj);
}
async restartTasks(qobj){
var self=this;
var rtn={};
var tasks=await this.dao.model.findAll({raw:true});
//清空任务列表
await this.taskManager.clearlist();
for(var i=0;i<tasks.length;i++){
var tmpTask2=tasks[i];
try {
(async (tmpTask,that)=>{
var action="new";
var taskClassName=tmpTask.taskClassName;
var exp=tmpTask.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
// await that.taskManager.newTask(msg);
// await that.taskManager.publish("task","newtask");
await that.taskManager.addTask(taskClassName,exp);
})(tmpTask2,self);
} catch (e) {
rtn=null;
}
}
return rtn;
}
async delete(qobj){
var self=this;
return this.db.transaction(async t=>{
var task= await this.dao.model.findOne({where:qobj});
await this.dao.delete(task,qobj,t);
//发布任务事件
var action="delete";
var taskName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskName;
//发布任务,消息是action_taskClassName
await this.taskManager.publish("task",msg,null);
return task;
});
}
}
module.exports=TaskService;
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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