Commit 2e679cf1 by 孙亚楠

d

parent 5afee49d
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
"type": "node", "type": "node",
"request": "launch", "request": "launch",
"name": "Launch Program", "name": "Launch Program",
"program": "${workspaceFolder}/xggsve-trade/main.js" "program": "${workspaceFolder}/xggsve-chance/main.js"
} }
] ]
} }
\ No newline at end of file
node_modules/
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings");
const DocBase = require("./doc.base");
const uuidv4 = require('uuid/v4');
const md5 = require("MD5");
class APIBase extends DocBase {
constructor() {
super();
this.cacheManager = system.getObject("db.common.cacheManager");
this.logCtl = system.getObject("web.common.oplogCtl");
this.oplogSve = system.getObject("service.common.oplogSve");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
/**
* 验证签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async verifySign(params, app_key) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!params.sign) {
return system.getResult(null, "请求参数sign为空");
}
if (!params.times_tamp) {
return system.getResult(null, "请求参数times_tamp为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey]) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResult(null, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
if (params.sign != resultTmpSign) {
return system.getResult(null, "签名验证失败");
}
return system.getResultSuccess();
}
/**
* 白名单验证
* @param {*} gname 组名
* @param {*} methodname 方法名
*/
async isCheckWhiteList(gname, methodname) {
var fullname = gname + "." + methodname;
var lst = [
"test.testApi"
];
var x = lst.indexOf(fullname);
return x >= 0;
}
async checkAcck(gname, methodname, pobj, query, req) {
var appInfo = null;
var result = system.getResultSuccess();
var ispass = await this.isCheckWhiteList(gname, methodname);
var appkey = req.headers["accesskey"];
var app_id = req.headers["app_id"];
if (ispass) {
return result;
}//在白名单里面
if (app_id) {
// var signResult = await this.verifySign(pobj.action_body, appInfo.appSecret);
// if (signResult.status != 0) {
// result.status = system.signFail;
// result.msg = signResult.msg;
// }
}//验签
else if (appkey) {
appInfo = await this.cacheManager["ApiAccessKeyCheckCache"].cache(appkey, { status: true }, 3000);
if (!appInfo || !appInfo.app) {
result.status = system.tokenFail;
result.msg = "请求头accesskey失效,请重新获取";
}
}//验证accesskey
else {
result.status = -1;
result.msg = "请求头没有相关访问参数,请验证后在进行请求";
}
return result;
}
async doexec(gname, methodname, pobj, query, req) {
var requestid = this.getUUID();
try {
var rtn = await this[methodname](pobj, query, req);
rtn.requestid = requestid;
this.oplogSve.createDb({
appid: req.headers["app_id"] || "",
appkey: "",
requestId: requestid,
op: req.classname + "/" + methodname,
content: JSON.stringify(pobj),
resultInfo: JSON.stringify(rtn),
clientIp: req.clientIp,
agent: req.uagent,
opTitle: "api服务提供方appKey:" + settings.appKey,
});
return rtn;
} catch (e) {
console.log(e.stack, "api调用出现异常,请联系管理员..........")
this.logCtl.error({
appid: "" + pobj.action_process,
appkey: "",
requestId: requestid,
op: pobj.classname + "/" + methodname,
content: e.stack,
clientIp: pobj.clientIp,
agent: req.uagent,
optitle: "api调用出现异常,请联系管理员",
});
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=classDesc.groupDesc;
this.apiDoc.name=classDesc.name;
this.apiDoc.desc=classDesc.desc;
this.apiDoc.exam=this.examHtml();
}
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;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class ConfigAPI extends APIBase {
constructor() {
super();
this.metaS = system.getObject("service.common.metaSve");
}
//返回
async fetchAppConfig(pobj, qobj, req) {
var cfg = await this.metaS.getUiConfig(settings.appKey, null, 100);
if (cfg) {
return system.getResultSuccess(cfg);
}
return system.getResultFail();
}
exam(){
return "xxx";
}
classDesc() {
return {
groupName: "",
groupDesc: "",
name: "",
desc: "",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "",
methodName: "",
paramdescs: [
{
paramDesc: "",
paramName: "",
paramType: "",
defaultValue: "",
}
],
rtnTypeDesc: "",
rtnType: ""
}
];
}
}
module.exports = ConfigAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class OpCacheAPI extends APIBase {
constructor() {
super();
this.cacheSve = system.getObject("service.common.cacheSve");
}
//返回
async opCacheData(pobj, qobj, req) {
if (pobj.action_type == "findAndCountAll") {
return await this.cacheSve.findAndCountAll(pobj.body);
} else if (pobj.action_type == "delCache") {
return await this.cacheSve.delCache(pobj.body);
} else if (pobj.action_type == "clearAllCache") {
return await this.cacheSve.clearAllCache(pobj.body);
} else {
return system.getResultFail();
}
}
exam() {
return "xxx";
}
classDesc() {
return {
groupName: "",
groupDesc: "",
name: "",
desc: "",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "",
methodName: "",
paramdescs: [
{
paramDesc: "",
paramName: "",
paramType: "",
defaultValue: null,
}
],
rtnTypeDesc: "",
rtnType: ""
}
];
}
// exam() {
// return "";
// }
// classDesc() {
// return {
// groupName: "",
// groupDesc: "",
// name: "",
// desc: "",
// exam: "",
// };
// }
// methodDescs() {
// return [
// {
// methodDesc: "",
// methodName: "",
// paramdescs: [
// {
// paramDesc: "",
// paramName: "",
// paramType: "",
// defaultValue: "",
// }
// ],
// rtnTypeDesc: "",
// rtnType: ""
// }
// ];
// }
}
module.exports = OpCacheAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class ActionAPI extends APIBase {
constructor() {
super();
this.storderSve = system.getObject("service.trade.storderSve");
this.storderitemSve = system.getObject("service.trade.storderitemSve");
this.stpaySve = system.getObject("service.trade.stpaySve");
}
/**
* 接口跳转
* action_process 执行的流程
* action_type 执行的类型
* action_body 执行的参数
*/
async springboard(pobj, qobj, req) {
var result;
if (!pobj.action_process) {
return system.getResult(null, "action_process参数不能为空");
}
if (!pobj.action_type) {
return system.getResult(null, "action_type参数不能为空");
}
try {
result = await this.handleRequest(pobj.action_process, pobj.action_type, pobj.action_body);
} catch (error) {
console.log(error);
}
return result;
}
async handleRequest(action_process, action_type, action_body) {
var opResult = null;
switch (action_type) {
// 图片验证码
case "test":
opResult = await this.storderSve.test(action_body);
break;
case "orderPage":
opResult = await this.storderSve.pageByCondition(action_body);
break;
case "orderAdd":
opResult = await this.storderSve.saveOrder(action_body);
break;
case "orderInfo":
opResult = await this.storderSve.info(action_body);
break;
case "orderPay":
opResult = await this.storderSve.pay(action_body);
break;
case "orderAudit1":
opResult = await this.storderSve.audit1(action_body);
break;
case "orderAudit2":
opResult = await this.storderSve.audit2(action_body);
break;
case "orderTrade":
opResult = await this.storderSve.trade(action_body);
break;
break;
case "itemPage":
opResult = await this.storderitemSve.pageByCondition(action_body);
break;
case "itemTradeOfflineCB":
opResult = await this.storderitemSve.tradeOfflineCB(action_body);
break;
case "itemByIds":
opResult = await this.storderitemSve.byIds(action_body);
break;
case "itemByInvoiceId":
opResult = await this.storderitemSve.bySaasInvoiceId(action_body);
break;
case "updateItemInvoice":
opResult = await this.storderitemSve.updateInvoice(action_body);
break;
case "cancelItemInvoice":
opResult = await this.storderitemSve.cancelInvoice(action_body);
break;
case "cancelInvoiceByDataIds":
opResult = await this.storderitemSve.cancelInvoiceByDataIds(action_body);
break;
case "invoiceTrade":
opResult = await this.storderitemSve.invoiceTrade(action_body);
break;
case "saveStPay":
opResult = await this.stpaySve.saveStPay(action_body);
break;
case "mapByBusiIds":
opResult = await this.stpaySve.mapByBusiIds(action_body);
break;
case "updateStatus":
opResult = await this.stpaySve.updateStatus(action_body);
break;
case "tradeItemBycreditCode":
opResult = await this.storderitemSve.tradeItemBycreditCode(action_body);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
exam() {
return `<pre><pre/>`;
}
classDesc() {
return {
groupName: "op",
groupDesc: "元数据服务包",
name: "ActionAPI",
desc: "此类是对外提供接口服务",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: `<pre><pre/>`,
methodName: "springboard",
paramdescs: [
{
paramDesc: "请求的行为,传递如:sjb",
paramName: "action_process",
paramType: "string",
defaultValue: null,
},
{
paramDesc: "业务操作类型,详情见方法中的描述",
paramName: "action_type",
paramType: "string",
defaultValue: null,
},
{
paramDesc: "业务操作类型的参数,action_body必须传递的参数有,times_tamp(时间戳,类型int)、sign(签名,类型string),其余的为业务需要的参数",
paramName: "action_body",
paramType: "json",
defaultValue: null,
}
],
rtnTypeDesc: `<pre><pre/>`,
rtnType: `<pre><pre/>`
}
];
}
}
module.exports = ActionAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
class TestAPI extends APIBase {
constructor() {
super();
this.orderSve = system.getObject("service.order.orderSve");
this.platformUtils = system.getObject("util.businessManager.opPlatformUtils");
}
async test(pobj, query, req) {
// var tmp = await this.orderSve.createLicense(pobj.action_body);
//获取验证码
// await this.platformUtils.fetchVCode(pobj.action_body.mobile);
//创建用户
// var result = await this.platformUtils.createUserInfo("13075556691", "13075556693", "9366");
//创建用户
var result = await this.platformUtils.login("13075556691", "9366");
return result;
}
exam() {
return "";
}
classDesc() {
return {
groupName: "",
groupDesc: "",
name: "",
desc: "",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "",
methodName: "",
paramdescs: [
{
paramDesc: "",
paramName: "",
paramType: "",
defaultValue: "",
}
],
rtnTypeDesc: "",
rtnType: ""
}
];
}
}
module.exports = TestAPI;
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings");
class CtlBase {
constructor(gname, sname) {
this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname);
this.cacheManager = system.getObject("db.common.cacheManager");
this.md5 = require("MD5");
}
encryptPasswd(passwd) {
if (!passwd) {
throw new Error("请输入密码");
}
var md5 = this.md5(passwd + "_" + settings.salt);
return md5.toString().toLowerCase();
}
notify(req, msg) {
if (req.session) {
req.session.bizmsg = msg;
}
}
async findOne(queryobj, qobj) {
var rd = await this.service.findOne(qobj);
return system.getResult(rd, null);
}
async findAndCountAll(queryobj, obj, req) {
obj.codepath = req.codepath;
if (req.session.user) {
obj.uid = req.session.user.id;
obj.appid = req.session.user.app_id;
obj.onlyCode = req.session.user.unionId;
obj.account_id = req.session.user.account_id;
obj.ukstr = req.session.user.app_id + "¥" + req.session.user.id + "¥" + req.session.user.nickName + "¥" + req.session.user.headUrl;
}
var apps = await this.service.findAndCountAll(obj);
return system.getResult(apps, null);
}
async refQuery(queryobj, qobj) {
var rd = await this.service.refQuery(qobj);
return system.getResult(rd, null);
}
async bulkDelete(queryobj, ids) {
var rd = await this.service.bulkDelete(ids);
return system.getResult(rd, null);
}
async delete(queryobj, qobj) {
var rd = await this.service.delete(qobj);
return system.getResult(rd, null);
}
async create(queryobj, qobj, req) {
if (req && req.session && req.session.app) {
qobj.app_id = req.session.app.id;
qobj.onlyCode = req.session.user.unionId;
if (req.codepath) {
qobj.codepath = req.codepath;
}
}
var rd = await this.service.create(qobj);
return system.getResult(rd, null);
}
async update(queryobj, qobj, req) {
if (req && req.session && req.session.user) {
qobj.onlyCode = req.session.user.unionId;
}
if (req.codepath) {
qobj.codepath = req.codepath;
}
var rd = await this.service.update(qobj);
return system.getResult(rd, null);
}
static getServiceName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async initNewInstance(queryobj, req) {
return system.getResult({}, null);
}
async findById(oid) {
var rd = await this.service.findById(oid);
return system.getResult(rd, null);
}
async timestampConvertDate(time) {
if (time == null) {
return "";
}
var date = new Date(Number(time * 1000));
var y = 1900 + date.getYear();
var m = "0" + (date.getMonth() + 1);
var d = "0" + date.getDate();
return y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
}
async universalTimeConvertLongDate(time) {
if (time == null) {
return "";
}
var d = new Date(time);
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}
async universalTimeConvertShortDate(time) {
if (time == null) {
return "";
}
var d = new Date(time);
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
}
async doexec(methodname, pobj, query, req) {
try {
var rtn = await this[methodname](pobj, query, req);
return rtn;
} catch (e) {
console.log(e.stack);
// this.logCtl.error({
// optitle: "Ctl调用出错",
// op: pobj.classname + "/" + methodname,
// content: e.stack,
// clientIp: pobj.clientIp
// });
return system.getResultFail(-200, "Ctl出现异常,请联系管理员");
}
}
trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
doTimeCondition(params, fields) {
if (!params || !fields || fields.length == 0) {
return;
}
for (var f of fields) {
if (params[f]) {
var suffix = this.endWith(f, 'Begin') ? " 00:00:00" : " 23:59:59";
params[f] = params[f] + suffix;
}
}
}
endWith(source, str){
if(!str || !source || source.length == 0 || str.length > source.length) {
return false;
}
return source.substring(source.length - str.length) == str;
}
}
module.exports = CtlBase;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const uuidv4 = require('uuid/v4');
var svgCaptcha = require('svg-captcha');
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
this.captchaPrev = "xgg_captcha_";
this.redisClient = system.getObject("util.redisClient");
}
async captcha(qobj, pobj, req) {
var uuid = uuidv4();
var key = uuid.replace(/\-/g, "");
var options = {
size: 4,
noise: 1,
ignoreChars: '0o1i'
};
options.width = this.trim(qobj.width) || 120;
options.height = this.trim(qobj.height) || 32;
options.background = this.trim(qobj.background) || "#E8E8E8";
try {
var redisKey = this.captchaPrev + key;
var cap = svgCaptcha.create(options);
console.log(cap);
await this.redisClient.setWithEx(redisKey, cap.text, 3 * 60);
return system.getResultSuccess({
key: key,
captcha: cap.data,
});
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async smsCode(qobj, pobj, req) {
var mobile = this.trim(qobj.mobile);
// var captchaKey = this.trim(qobj.captchaKey);
// var captchaCode = this.trim(qobj.captchaCode);
try {
if (!/^1[23456789]\d{9}$/.test(mobile)) {
return system.getResult(null, "手机号码格式不正确");
}
// var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";
// if (!code) {
// return system.getResult(null, "图片验证码过期,请刷新重试");
// }
// if (code.toLowerCase() != captchaCode.toLowerCase()) {
// await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
// return system.getResult(null, "图片验证码不一致,请刷新重试");
// }
// TODO 发送短信验证码
return system.getResultSuccess("发送成功");
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async login(qobj, pobj, req, res) {
var loginName = this.trim(pobj.loginName);
var password = this.trim(pobj.password);
var captchaKey = this.trim(qobj.captchaKey);
var captchaCode = this.trim(qobj.captchaCode);
try {
// var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";
// if (!code) {
// return system.getResult(null, "图片验证码过期,请点击重试");
// }
// if (code.toLowerCase() != captchaCode.toLowerCase()) {
// await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
// return system.getResult(null, "图片验证码不一致,请点击重试");
// }
var adminUser = await this.service.findById(1);
adminUser.lastLoginTime = new Date();
await adminUser.save();
var xggadminsid = uuidv4();
xggadminsid = "3cb49932-fa02-44f0-90db-9f06fe02e5c7";
await this.redisClient.setWithEx(xggadminsid, JSON.stringify(adminUser), 60 * 60 * 2);
// 处理登录逻辑
var result = {
xggadminsid: xggadminsid,
}
return system.getResultSuccess(result);
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async forgetPassword(qobj, pobj, req, res) {
var mobile = this.trim(pobj.mobile);
var vcode = this.trim(pobj.vcode);
var password = this.trim(qobj.password);
try {
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async currentUser(qobj, pobj, req) {
return system.getResultSuccess(req.loginUser);
}
async getMenu(qobj, pobj, req) {
var menu = [
{"name": "首页", "path": "/", "submenu": [] },
{
"name": "商户中心",
"path": "/merchants",
"submenu": [{"name": "客户管理", "team": [{"name": "商户信息", "path": "/merchants/businessInformation"}, {"name": "签约信息", "path": "/merchants/contractInformation"} ] } ]
}, {
"name": "交易中心",
"path": "/trading",
"submenu": [{"name": "资金管理", "team": [{"name": "资金账户", "path": "/trading/capitalAccount"}, {"name": "充值申请", "path": "/trading/topUpApplication"}, {"name": "资金交易", "path": "/trading/cashTransactions"}, {"name": "资金流水", "path": "/trading/capitalFlows"} ] }, {"name": "订单管理", "team": [{"name": "订单信息", "path": "/trading/orderInformation"} ] }, {"name": "用户管理", "team": [{"name": "用户信息", "path": "/trading/userInformation"}, {"name": "用户签约", "path": "/trading/usersSignUp"} ] } ]
}, {
"name": "财务中心",
"path": "/financial",
"submenu": [{"name": "发票管理", "team": [{"name": "发票申请", "path": "/financial/invoiceApplyFor"}, {"name": "发票管理", "path": "/financial/invoiceManagement"} ] } ]
}, {
"name": "数据中心",
"path": "/information",
"submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] } ]
}, {
"name": "系统中心",
"path": "/system",
"submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] }
]
}
]
return system.getResultSuccess(menu);
}
/**
* 开放平台回调处理
* @param {*} req
*/
async authByCode(req) {
var opencode = req.query.code;
var user = await this.service.authByCode(opencode);
if (user) {
req.session.user = user;
} else {
req.session.user = null;
}
//缓存opencode,方便本应用跳转到其它应用
// /auth?code=xxxxx,缓存没有意义,如果需要跳转到其它应用,需要调用
//平台开放的登录方法,返回 <待跳转的目标地址>/auth?code=xxxxx
//this.cacheManager["OpenCodeCache"].cacheOpenCode(user.id,opencode);
return user;
}
async navSysSetting(pobj, qobj, req) {
//开始远程登录,返回code
var jumpobj = await this.service.navSysSetting(req.session.user);
if (jumpobj) {
return system.getResultSuccess(jumpobj);
}
return system.getResultFail();
}
async loginUser(qobj, pobj, req) {
return super.findById(req.session.user.id);
}
async initNewInstance(queryobj, req) {
var rtn = {};
rtn.roles = [];
if (rtn) {
return system.getResultSuccess(rtn);
}
return system.getResultFail();
}
async checkLogin(gobj, qobj, req) {
//当前如果缓存中存在user,还是要检查当前user所在的域名,如果不和来访一致,则退出重新登录
if (req.session.user) {
var x = null;
if (req.session.user.Roles) {
x = req.session.user.Roles.map(r => {
return r.code
});
}
var tmp = {
id: req.session.user.id,
userName: req.session.user.userName,
nickName: req.session.user.nickName,
mobile: req.session.user.mobile,
isAdmin: req.session.user.isAdmin,
created_at: req.session.user.created_at,
email: req.session.user.email,
headUrl: req.session.user.headUrl,
roles: x ? x.join(",") : ""
}
return system.getResult(tmp, "用户登录", req);
} else {
req.session.user = null;
//req.session.destroy();
return system.getResult(null, "用户未登录", req);
}
}
async exit(pobj, qobj, req) {
req.session.user = null;
req.session.destroy();
return system.getResultSuccess({
"env": settings.env
});
}
}
module.exports = UserCtl;
\ No newline at end of file
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
var svgCaptcha = require('svg-captcha');
class CaptchaCtl {
constructor() {
//this.appS=system.getObject("service.appSve");
}
async randomkey() {
return uuidv4();
}
}
module.exports = CaptchaCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
class OplogCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve");
}
async initNewInstance(qobj) {
var u = uuidv4();
var aid = u.replace(/\-/g, "");
var rd = { name: "", appid: aid }
return system.getResultSuccess(rd, null);
}
async debug(obj) {
obj.logLevel = "debug";
return this.create(obj);
}
async info(obj) {
obj.logLevel = "info";
return this.create(obj);
}
async warn(obj) {
obj.logLevel = "warn";
return this.create(obj);
}
async error(obj) {
obj.logLevel = "error";
return this.create(obj);
}
async fatal(obj) {
obj.logLevel = "fatal";
return this.create(obj);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
}
module.exports = OplogCtl;
const system = require("../../../system");
const settings = require("../../../../config/settings");
function exp(db, DataTypes) {
var base = {
code: {
type: DataTypes.STRING(50),
unique: true
},
name: DataTypes.STRING(1000),
};
return base;
}
module.exports = exp;
const system = require("../../system");
const settings = require("../../../config/settings");
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", uiconfig.config.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", uiconfig.config.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
constructor() {
this.redisClient = system.getObject("util.redisClient");
this.desc = this.desc();
this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "s_sadd_appkeys:" + settings.appKey + "_cachekey";
this.isdebug = this.isdebug();
}
isdebug() {
return false;
}
desc() {
throw new Error("子类需要定义desc方法,返回缓存描述");
}
prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀");
}
async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) {
return null;
}
if (ex) {
await this.redisClient.setWithEx(cachekey, objvalstr, ex);
} else {
await this.redisClient.set(cachekey, objvalstr);
}
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
return JSON.parse(objvalstr);
} else {
return JSON.parse(cacheValue);
}
}
async invalidate(inputkey) {
const cachekey = this.prefix + inputkey;
this.redisClient.delete(cachekey);
return 0;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串");
}
}
module.exports = CacheBase;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class ApiAccessKeyCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "应用中缓存访问token";
}
prefix() {
return settings.cacheprefix + "_accesskey:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var acckapp = await this.restS.execPost({ appkey: settings.appKey, secret: settings.secret }, settings.paasUrl() + "api/auth/accessAuth/getAccessKey");
var s = acckapp.stdout;
if (s) {
var tmp = JSON.parse(s);
if (tmp.status == 0) {
return JSON.stringify(tmp.data);
}
}
return null;
}
}
module.exports = ApiAccessKeyCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class ApiAccessKeyCheckCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "应用中来访访问token缓存";
}
prefix() {
return settings.cacheprefix + "_verify_reqaccesskey:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var cacheManager = system.getObject("db.common.cacheManager");
//当来访key缓存不存在时,需要去开放平台检查是否存在来访key缓存
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
if (checkresult.status == 0) {
var s = checkresult.data;
return JSON.stringify(s);
} else {
await cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
var s = checkresult.data;
return JSON.stringify(s);
}
}
}
module.exports = ApiAccessKeyCheckCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class ApiAppIdCheckCache extends CacheBase {
constructor() {
super();
}
desc() {
return "应用中来访访问appid缓存";
}
prefix() {
return settings.cacheprefix + "_verify_appid:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
}
}
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class ApiUserCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "应用中来访访问token缓存";
}
prefix() {
return settings.cacheprefix + "_userdata:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var cacheManager = system.getObject("db.common.cacheManager");
//当来访key缓存不存在时,需要去开放平台检查是否存在来访key缓存
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
if (checkresult.status == 0) {
var s = checkresult.data;
return JSON.stringify(s);
} else {
await cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
var s = checkresult.data;
return JSON.stringify(s);
}
}
}
module.exports = ApiUserCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "应用UI配置缓存";
}
//暂时没有用到,只是使用其帮助的方法
prefix() {
return settings.cacheprefix + "_uiconfig:";
}
async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key);
}
async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value)
}
async keys(p) {
return this.redisClient.keys(p);
}
async get(k) {
return this.redisClient.get(k);
}
async del(k) {
return this.redisClient.delete(k);
}
async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............");
return this.redisClient.flushall();
}
}
module.exports = MagCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class UIConfigCache extends CacheBase {
constructor() {
super();
}
isdebug() {
return settings.env == "dev";
}
desc() {
return "应用UI配置缓存";
}
prefix() {
return settings.cacheprefix + "_appself_uiconfig:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var configValue = system.getUiConfig2(inputkey);
return JSON.stringify(configValue);
}
}
module.exports = UIConfigCache;
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
this.redisClient = system.getObject("util.redisClient");
var db = system.getObject("db.common.connection").getCon();
this.db = db;
console.log("........set dao model..........");
this.model = db.models[this.modelName];
}
async preCreate(u) {
if (!u.id && !u.autoIncrement) {
u.id = await this.redisClient.genrateId(this.modelName);
}
return u;
}
async create(u, t) {
var u2 = await this.preCreate(u);
if (t) {
return this.model.create(u2, {
transaction: t
}).then(u => {
return u;
});
} else {
return this.model.create(u2, {
transaction: t
}).then(u => {
return u;
});
}
}
async bulkCreate(objs, t) {
if (!objs || objs.length == 0) {
return;
}
for (var obj of objs) {
if (!obj.id && !obj.autoIncrement) {
obj.id = await this.redisClient.genrateId(this.modelName);
}
}
if (t) {
return await this.model.bulkCreate(objs, { transaction: t });
} else {
return await this.model.bulkCreate(objs);
}
}
static getModelName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery(qobj) {
var w = {};
if (qobj.likestr) {
w[qobj.fields[0]] = {
[this.db.Op.like]: "%" + qobj.likestr + "%"
};
return this.model.findAll({
where: w,
attributes: qobj.fields
});
} else {
return this.model.findAll({
attributes: qobj.fields
});
}
}
async bulkDelete(ids) {
var en = await this.model.destroy({
where: {
id: {
[this.db.Op.in]: ids
}
}
});
return en;
}
async delete(qobj) {
var en = await this.model.findOne({
where: qobj
});
if (en != null) {
return en.destroy();
}
return null;
}
extraModelFilter() {
//return {"key":"include","value":{model:this.db.models.app}};
return null;
}
extraWhere(obj, where) {
return where;
}
orderBy() {
//return {"key":"include","value":{model:this.db.models.app}};
return [
["created_at", "DESC"]
];
}
buildQuery(qobj) {
var linkAttrs = [];
const pageNo = qobj.pageInfo.pageNo;
const pageSize = qobj.pageInfo.pageSize;
const search = qobj.search;
const orderInfo = qobj.orderInfo; //格式:[["created_at", 'desc']]
var qc = {};
//设置分页查询条件
qc.limit = pageSize;
qc.offset = (pageNo - 1) * pageSize;
//默认的查询排序
if (orderInfo) {
qc.order = orderInfo;
} else {
qc.order = this.orderBy();
}
//构造where条件
qc.where = {};
if (search) {
Object.keys(search).forEach(k => {
console.log(search[k], ":search[k]search[k]search[k]");
if (search[k] && search[k] != 'undefined' && search[k] != "") {
if ((k.indexOf("Date") >= 0 || k.indexOf("_at") >= 0)) {
if (search[k] != "" && search[k]) {
var stdate = new Date(search[k][0]);
var enddate = new Date(search[k][1]);
qc.where[k] = {
[this.db.Op.between]: [stdate, enddate]
};
}
} else if (k.indexOf("id") >= 0) {
qc.where[k] = search[k];
} else if (k.indexOf("channelCode") >= 0) {
qc.where[k] = search[k];
} else if (k.indexOf("Type") >= 0) {
qc.where[k] = search[k];
} else if (k.indexOf("Status") >= 0) {
qc.where[k] = search[k];
} else if (k.indexOf("status") >= 0) {
qc.where[k] = search[k];
} else {
if (k.indexOf("~") >= 0) {
linkAttrs.push(k);
} else {
qc.where[k] = {
[this.db.Op.like]: "%" + search[k] + "%"
};
}
}
}
});
}
this.extraWhere(qobj, qc.where, qc, linkAttrs);
var extraFilter = this.extraModelFilter();
if (extraFilter) {
qc[extraFilter.key] = extraFilter.value;
}
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
console.log(qc);
return qc;
}
async findAndCountAll(qobj, t) {
var qc = this.buildQuery(qobj);
var apps = await this.model.findAndCountAll(qc);
return apps;
}
preUpdate(obj) {
return obj;
}
async update(obj, tm) {
var obj2 = this.preUpdate(obj);
if (tm != null && tm != 'undefined') {
return this.model.update(obj2, {
where: {
id: obj2.id
},
transaction: tm
});
} else {
return this.model.update(obj2, {
where: {
id: obj2.id
}
});
}
}
async updateByWhere(setObj, whereObj, t) {
if (t && t != 'undefined') {
if (whereObj && whereObj != 'undefined') {
whereObj.transaction = t;
} else {
whereObj = {
transaction: t
};
}
}
return this.model.update(setObj, whereObj);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.db.query(sql, paras);
}
async customQuery(sql, paras, t) {
var tmpParas = null; //||paras=='undefined'?{type: this.db.QueryTypes.SELECT }:{ replacements: paras, type: this.db.QueryTypes.SELECT };
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = {
type: this.db.QueryTypes.SELECT
};
tmpParas.transaction = t;
} else {
tmpParas = {
replacements: paras,
type: this.db.QueryTypes.SELECT
};
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' ? {
type: this.db.QueryTypes.SELECT
} : {
replacements: paras,
type: this.db.QueryTypes.SELECT
};
}
return this.db.query(sql, tmpParas);
}
async customUpdate(sql, paras, t) {
var tmpParas = null;
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = {
type: this.db.QueryTypes.UPDATE
};
tmpParas.transaction = t;
} else {
tmpParas = {
replacements: paras,
type: this.db.QueryTypes.UPDATE
};
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' ? {
type: this.db.QueryTypes.UPDATE
} : {
replacements: paras,
type: this.db.QueryTypes.UPDATE
};
}
return this.db.query(sql, tmpParas);
}
async findCount(whereObj = null) {
return this.model.count(whereObj, {
logging: false
}).then(c => {
return c;
});
}
async findSum(fieldName, whereObj = null) {
return this.model.sum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
var tmpWhere = {};
tmpWhere.limit = pageSize;
tmpWhere.offset = (pageIndex - 1) * pageSize;
if (whereObj != null) {
tmpWhere.where = whereObj;
}
if (orderObj != null && orderObj.length > 0) {
tmpWhere.order = orderObj;
}
if (attributesObj != null && attributesObj.length > 0) {
tmpWhere.attributes = attributesObj;
}
if (includeObj != null && includeObj.length > 0) {
tmpWhere.include = includeObj;
tmpWhere.distinct = true;
}
tmpWhere.raw = true;
return await this.model.findAndCountAll(tmpWhere);
}
async findOne(obj, t) {
var params = {
"where": obj
};
if (t) {
params.transaction = t;
}
return this.model.findOne(params);
}
async findById(oid) {
return this.model.findById(oid);
}
async setListCodeName(list, field) {
if (!list) {
return;
}
for (item of list) {
await this.setRowCodeName(item, field);
}
}
async setRowCodeName(item, field) {
if (!item || !field) {
return;
}
var map = this[field + "Map"] || {};
if (!item) {
return;
}
item[field + "Name"] = map[item[field] || ""] || "";
}
async getById(id, attrs) {
if (!id) {
return null;
}
attrs = attrs || "*";
var sql = "SELECT " + attrs + " FROM " + this.model.tableName + " where id = :id ";
var list = await this.customQuery(sql, {
id: id
});
return list && list.length > 0 ? list[0] : null;
}
async getListByIds(ids, attrs) {
if (!ids || ids.length == 0) {
return [];
}
attrs = attrs || "*";
var sql = "SELECT " + attrs + " FROM " + this.model.tableName + " where id IN (:ids) ";
return await this.customQuery(sql, {
ids: ids
}) || [];
}
}
module.exports = Dao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class UserDao extends Dao{
constructor(){
super(Dao.getModelName(UserDao));
}
async getAuths(userid){
var self=this;
return this.model.findOne({
where:{id:userid},
include:[{model:self.db.models.account,attributes:["id","isSuper","referrerOnlyCode"]},
{model:self.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:self.db.models.product,as:"Products",attributes:["id","code"]}
]},
],
});
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"]}]};
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// console.log(obj);
// w["app_id"]=obj.appid;
// }
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
async preUpdate(u){
if(u.roles && u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var user=await this.model.findOne({where:{id:obj2.id}});
user.setRoles(obj2.roles);
return user;
}
async findAndCountAll(qobj,t){
var users=await super.findAndCountAll(qobj,t);
return users;
}
async preCreate(u){
// var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(roles);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// u.roles=roles
return u;
}
async create(u,t){
var self=this;
var u2=await this.preCreate(u);
if(t){
return this.model.create(u2,{transaction: t}).then(user=>{
return user;
});
}else{
return this.model.create(u2).then(user=>{
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId,company_only_code,result){
var customerObj={companyOnlyCode:company_only_code};
var putSqlWhere={where:{id:userId}};
this.updateByWhere(customerObj,putSqlWhere);
return result;
}
}
module.exports=UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var glob = require("glob");
class APIDocManager{
constructor(){
this.doc={};
this.buildAPIDocMap();
}
async buildAPIDocMap(){
var self=this;
//订阅任务频道
var apiPath=settings.basepath+"/app/base/api/impl";
var rs = glob.sync(apiPath + "/**/*.js");
if(rs){
for(let r of rs){
// var ps=r.split("/");
// var nl=ps.length;
// var pkname=ps[nl-2];
// var fname=ps[nl-1].split(".")[0];
// var obj=system.getObject("api."+pkname+"."+fname);
var ClassObj=require(r);
var obj=new ClassObj();
var gk=obj.apiDoc.group+"|"+obj.apiDoc.groupDesc
if(!this.doc[gk]){
this.doc[gk]=[];
this.doc[gk].push(obj.apiDoc);
}else{
this.doc[gk].push(obj.apiDoc);
}
}
}
}
}
module.exports=APIDocManager;
const fs = require("fs");
const settings = require("../../../../config/settings");
class CacheManager {
constructor() {
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap() {
var self = this;
self.doc = {};
var cachePath = settings.basepath + "/app/base/db/cache/";
const files = fs.readdirSync(cachePath);
if (files) {
files.forEach(function (r) {
var classObj = require(cachePath + "/" + r);
if (classObj.name) {
self[classObj.name] = new classObj();
var refTmp = self[classObj.name];
if (refTmp.prefix) {
self.doc[refTmp.prefix] = refTmp.desc;
} else {
console.log("请在" + classObj.name + "缓存中定义prefix");
}
}
});
}
}
}
module.exports = CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
\ No newline at end of file
const Sequelize = require('sequelize');
const settings = require("../../../../config/settings")
const fs = require("fs")
const path = require("path");
var glob = require("glob");
class DbFactory {
constructor() {
const dbConfig = settings.database();
this.db = new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
dbConfig.config);
this.db.Sequelize = Sequelize;
this.db.Op = Sequelize.Op;
this.initModels();
this.initRelations();
}
async initModels() {
var self = this;
var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
console.log("modelpath=====================================================");
console.log(modelpath);
var models = glob.sync(modelpath + "/**/*.js");
console.log(models.length);
models.forEach(function (m) {
console.log(m);
self.db.import(m);
});
console.log("init models....");
}
async initRelations() {
/**
一个账户对应多个登陆用户
一个账户对应一个commany
一个APP对应多个登陆用户
一个APP有多个角色
登陆用户和角色多对多
**/
/*建立账户和用户之间的关系*/
//account--不属于任何一个app,是统一用户
//用户登录时首先按照用户名和密码检查account是否存在,如果不存在则提示账号或密码不对,如果
//存在则按照按照accountid和应用key,查看user,后台实现对应user登录
}
//async getCon(){,用于使用替换table模型内字段数据使用
getCon() {
var that = this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// throw err;
// });
//同步模型
if (settings.env == "dev") {
//console.log(pa);
// pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true}));
// });
// await this.db.models.user.create({nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
// .then(function(user){
// var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
// acc.save().then(a=>{
// user.setAccount(a);
// });
// });
}
return this.db;
}
getConhb() {
var that = this;
if (settings.env == "dev") {
}
return this.dbhb;
}
}
module.exports = DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class MetaDao{
constructor(){
//super(Dao.getModelName(AppDao));
}
}
module.exports=MetaDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OplogDao extends Dao{
constructor(){
super(Dao.getModelName(OplogDao));
}
}
module.exports=OplogDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class TaskDao extends Dao{
constructor(){
super(Dao.getModelName(TaskDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
async delete(task,qobj,t){
return task.destroy({where:qobj,transaction:t});
}
}
module.exports=TaskDao;
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var cron = require('node-cron');
class TaskManager{
constructor(){
this.taskDic={};
this.redisClient=system.getObject("util.redisClient");
this.buildTaskMap();
}
async buildTaskMap(){
var self=this;
//订阅任务频道
await this.redisClient.subscribeTask("task",this);
var taskPath=settings.basepath+"/app/base/db/task/";
const files=fs.readdirSync(taskPath);
if(files){
files.forEach(function(r){
var classObj=require(taskPath+"/"+r);
self[classObj.name]=new classObj();
});
}
}
async addTask(taskClassName,exp){
(async (tn,ep)=>{
if(!this.taskDic[tn]){
this.taskDic[tn]=cron.schedule(ep,()=>{
this[tn].doTask();
});
}
})(taskClassName,exp);
}
async deleteTask(taskClassName){
if(this.taskDic[taskClassName]){
this.taskDic[taskClassName].destroy();
delete this.taskDic[taskClassName];
}
}
async clearlist(){
var x=await this.redisClient.clearlist("tasklist");
return x;
}
async publish(channel,msg){
var x=await this.redisClient.publish(channel,msg);
return x;
}
async newTask(taskstr){
return this.redisClient.rpush("tasklist",taskstr);
}
}
module.exports=TaskManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const system = require("../../../system");
const Dao = require("../../dao.base");
class StOrderDao extends Dao {
constructor() {
super(Dao.getModelName(StOrderDao));
}
async listByIds(ids, attrs) {
if (!ids || ids.length == 0) {
return [];
}
var sql = [];
sql.push("SELECT");
sql.push(attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE id IN (:ids)");
return await this.customQuery(sql.join(" "), {
ids: ids
}) || [];
}
async mapByIds(ids, attrs) {
var result = {};
if (!ids || ids.length == 0) {
return result;
}
var list = await this.findListByIds(ids, attrs);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
async countByCondition(params) {
var sql = [];
sql.push("SELECT");
sql.push("count(1) as num");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE deleted_at IS NULL");
this.setCondition(sql, params);
var list = await this.customQuery(sql.join(" "), params);
if (!list || list.length == 0) {
return 0;
}
return list[0].num;
}
async listByCondition(params) {
params.startRow = Number(params.startRow || 0);
params.pageSize = Number(params.pageSize || 10);
var sql = [];
sql.push("SELECT");
sql.push(params.attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE deleted_at IS NULL");
this.setCondition(sql, params);
sql.push("ORDER BY created_at DESC");
sql.push("LIMIT :startRow, :pageSize");
return await this.customQuery(sql.join(" "), params);
}
setCondition(sql, params) {
if (!params || !sql) {
return;
}
if (params.saas_id) {
sql.push("AND saas_id = :saas_id");
}
if (params.saas_merchant_id) {
sql.push("AND saas_merchant_id = :saas_merchant_id");
}
if (params.saas_merchant_ids) {
sql.push("AND saas_merchant_id IN (:saas_merchant_ids)");
}
if (params.out_trade_no) {
sql.push("AND out_trade_no = :out_trade_no");
}
if (params.trade_status) {
sql.push("AND trade_status = :trade_status");
}
if (params.check_status) {
sql.push("AND check_status = :check_status");
}
if (params.acc_type) {
sql.push("AND acc_type = :acc_type");
}
if (params.createBegin) {
sql.push("AND created_at >= :createBegin");
}
if (params.createEnd) {
sql.push("AND created_at <= :createEnd");
}
}
}
module.exports = StOrderDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class StOrderItemDao extends Dao {
constructor() {
super(Dao.getModelName(StOrderItemDao));
}
async byIds(params) {
let attrs = params.attrs || "*";
let ids = params.ids;
if (!ids || ids.length == 0) {
return [];
}
let sql = [];
sql.push("SELECT");
sql.push(attrs);
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE id IN (:ids) ");
if (params.trade_statuses && params.trade_statuses.length > 0) {
sql.push("AND trade_status IN (:trade_statuses)");
}
if (params.saas_merchant_id) {
sql.push("AND saas_merchant_id IN (:saas_merchant_id)");
}
if (params.unInvoice) {
sql.push("AND saas_invoice_id = ''");
}
if (params.order_type) {
sql.push("AND order_type = :order_type");
}
return await this.customQuery(sql.join(" "), params);
}
async bySaasInvoiceId(params) {
let attrs = params.attrs || "*";
let sql = [];
sql.push("SELECT");
sql.push(attrs);
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE saas_invoice_id = :saas_invoice_id ");
return await this.customQuery(sql.join(" "), params);
}
async updateTrade(params, t) {
let sql = "UPDATE st_order_item SET trade_time = :trade_time, trade_status = '00', trade_desc = :trade_desc WHERE id IN (:ids) AND trade_status = '01' ";
await this.customUpdate(sql, params, t);
}
async updateTradeByOrderId(orderId, tradeStatus, t) {
let sql = "UPDATE st_order_item SET trade_status = :tradeStatus WHERE order_id = :orderId";
await this.customUpdate(sql, {orderId: orderId, tradeStatus: tradeStatus}, t);
}
async updateInvoice(params, t) {
let sql = "UPDATE st_order_item SET saas_invoice_id = :saas_invoice_id WHERE id IN (:ids) ";
await this.customUpdate(sql, params, t);
}
async cancelInvoice(params, t) {
let sql = "UPDATE st_order_item SET saas_invoice_id = '' WHERE saas_invoice_id = :saas_invoice_id ";
await this.customUpdate(sql, params, t);
}
async cancelInvoiceByDataIds(params, t) {
let sql = "UPDATE st_order_item SET saas_invoice_id = '' WHERE id in (:data_ids) ";
await this.customUpdate(sql, params, t);
}
async countItems(params, t) {
let sql = "SELECT count(1) AS num FROM st_order_item WHERE order_id = :order_id AND trade_status = :trade_status";
let list = await this.customQuery(sql, params, t);
if (!list || list.length == 0) {
return 0;
}
return list[0].num || 0;
}
async listByIds(ids, attrs) {
if (!ids || ids.length == 0) {
return [];
}
let sql = [];
sql.push("SELECT");
sql.push(attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE id IN (:ids)");
return await this.customQuery(sql.join(" "), {
ids: ids
}) || [];
}
async mapByIds(ids, attrs) {
let result = {};
if (!ids || ids.length == 0) {
return result;
}
let list = await this.findListByIds(ids, attrs);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
async genTradeNo(orderId, t) {
let sql = `UPDATE ${this.model.tableName} SET trade_no = CONCAT('T', id, SUBSTR(order_id, LENGTH(order_id) - 2, 4), SUBSTRING(REPLACE(RAND(),'.',''),3,4)) WHERE order_id = :orderId`;
return await this.customUpdate(sql, {orderId: orderId}, t);
}
async countByCondition(params) {
var sql = [];
sql.push("SELECT");
sql.push("count(1) as num");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE deleted_at IS NULL");
this.setCondition(sql, params);
let list = await this.customQuery(sql.join(" "), params);
if (!list || list.length == 0) {
return 0;
}
return list[0].num;
}
async listByCondition(params) {
params.startRow = Number(params.startRow || 0);
params.pageSize = Number(params.pageSize || 10);
let sql = [];
sql.push("SELECT");
sql.push(params.attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE deleted_at IS NULL");
this.setCondition(sql, params);
sql.push("ORDER BY created_at DESC");
sql.push("LIMIT :startRow, :pageSize");
return await this.customQuery(sql.join(" "), params);
}
setCondition(sql, params) {
if (!params || !sql) {
return;
}
if (params.saas_id) {
sql.push("AND saas_id = :saas_id");
}
if (params.saas_merchant_id) {
sql.push("AND saas_merchant_id = :saas_merchant_id");
}
if (params.order_id) {
sql.push("AND order_id = :order_id");
}
if (params.order_type) {
sql.push("AND order_type = :order_type");
}
if (params.saas_merchant_ids) {
sql.push("AND saas_merchant_id IN (:saas_merchant_ids)");
}
if (params.out_trade_no) {
sql.push("AND out_trade_no = :out_trade_no");
}
if (params.trade_status) {
sql.push("AND trade_status = :trade_status");
}
if (params.trade_status_array) {
sql.push("AND trade_status in (:trade_status_array)");
}
if (params.acc_name) {
params.acc_name_like = `%${params.acc_name}%`;
sql.push("AND acc_name LIKE :acc_name_like");
}
if (params.acc_no) {
sql.push("AND acc_no = :acc_no");
}
if (params.credit_code) {
sql.push("AND credit_code = :credit_code");
}
if(params.credit_code_array){
sql.push("AND credit_code in (:credit_code_array)");
}
if (params.createBegin) {
sql.push("AND created_at >= :createBegin");
}
if (params.createEnd) {
sql.push("AND created_at <= :createEnd");
}
if (params.unInvoice) {
sql.push("AND saas_invoice_id = ''");
}
if (params.saas_invoice_id) {
sql.push("AND saas_invoice_id = :saas_invoice_id");
}
if(params.data_ids && params.data_ids.length>0){
sql.push("AND id in (:data_ids)");
}
}
async invoiceTrade(params){
let sql = [];
sql.push(`select * from st_order_item `);
sql.push("WHERE deleted_at IS NULL and 1=1 ");
this.setCondition(sql, params);
sql.push("ORDER BY created_at DESC");
sql.push("LIMIT :startRow, :pageSize");
return await this.customQuery(sql.join(" "), params);
}
}
module.exports = StOrderItemDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class StPayDao extends Dao {
constructor() {
super(Dao.getModelName(StPayDao));
}
}
module.exports = StPayDao;
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...");
//创建role
// if(settings.env=="prod"){
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
// }
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
});
module.exports = {
"appid": "40d64e586551405c9bcafab87266bb04",
"label": "研发开放平台",
"config": {
"rstree": {
"code": "paasroot",
"label": "paas",
"children": [
// {
// "code": "register",
// "icon": "fa fa-power-off",
// "path": "register",
// "isMenu": false,
// "label": "注册",
// "isctl": "no"
// },
],
},
"bizs": {
},
"pdict": {
"logLevel": { "debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4 },
"sex": {"male": "男", "female": "女"},
}
}
}
\ No newline at end of file
module.exports={
"bizName":"oplogs",
"list":{
columnMetaData:[
{"width":"200","label":"应用","prop":"appname","isShowTip":true,"isTmpl":false},
{"width":"200","label":"时间","prop":"created_at","isShowTip":true,"isTmpl":false},
{"width":"100","label":"用户名","prop":"username","isShowTip":true,"isTmpl":false},
{"width":"100","label":"性别","prop":"sex","isShowTip":true,"isTmpl":false},
{"width":"200","label":"行为","prop":"op","isShowTip":true,"isTmpl":false},
{"width":"200","label":"内容","prop":"content","isShowTip":true,"isTmpl":false},
{"width":"200","label":"客户端IP","prop":"clientIp","isShowTip":true,"isTmpl":false},
{"width":"200","label":"客户端环境","prop":"agent","isShowTip":true,"isTmpl":false},
]
},
"form":[
{
"title":"应用名称",
"validProp":"name",
"rule": [
{ "required": true, "message": '请输入应用名称', "trigger": 'blur' },
],
ctls:[
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
{
"title":"应用ID",
"ctls":[
{"type":"input","label":"应用ID","prop":"appid","disabled":true,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"应用名称",
ctls:[
{"type":"input","label":"操作用户","prop":"username","placeHolder":"请模糊输入应用名称","style":""},
]
},
{
"title":"客户环境",
ctls:[
{"type":"input","label":"客户环境","prop":"agent","placeHolder":"请模糊输入客户环境","style":""},
]
},
// {
// "title":"",
// "min":1,
// "max":1,
// ctls:[
// {"type":"check","dicKey":"sex","label":"客户环境","prop":"sex","style":""},
// ]
// },
// <gsb-select v-model="formModel[item.prop]"
// :dicKey="item.dicKey"
// :autoComplete="item.autoComplete"
// :isMulti="item.isMulti"
// :modelName="item.modelName"
// :isFilter="item.isFilter"
// :labelField="item.labelField"
// :valueField="item.valueField"></gsb-select>
{
"title":"性别",
ctls:[
{"type":"select","dicKey":"sex","label":"性别","prop":"sex","labelField":"label","valueField":"value","style":""},
]
},
],
"auth":{
"add":[
],
"edit":[
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isOnGrid":true},
],
"common":[
],
}
}
const fs=require("fs");
const path=require("path");
const appsPath=path.normalize(__dirname+"/apps");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
}
function getBizFilePath(appJson,bizCode){
const filePath=bizsPath+"/"+"bizjs"+"/"+bizCode+".js";
return filePath;
}
//异常日志处理todo
function initAppBizs(appJson){
for(var bizCode in appJson.config.bizs)
{
const bizfilePath=getBizFilePath(appJson,bizCode);
try{
delete require.cache[bizfilePath];
const bizConfig=require(bizfilePath);
appJson.config.bizs[bizCode].config=bizConfig;
}catch(e){
console.log("bizconfig meta file not exist........");
}
}
return appJson;
}
//初始化资源树--objJson是rstree
function initRsTree(appjson,appidfolder,objJson,parentCodePath){
if(!parentCodePath){//说明当前是根结点
objJson.codePath=objJson.code;
}else{
objJson.codePath=parentCodePath+"/"+objJson.code;
}
if(objJson["bizCode"]){//表示叶子节点
objJson.auths=[];
if(appjson.config.bizs[objJson["bizCode"]]){
objJson.bizConfig=appjson.config.bizs[objJson["bizCode"]].config;
objJson.path=appjson.config.bizs[objJson["bizCode"]].path;
appjson.config.bizs[objJson["bizCode"]].codepath=objJson.codePath;
}
}else{
if(objJson.children){
objJson.children.forEach(obj=>{
initRsTree(appjson,appidfolder,obj,objJson.codePath);
});
}
}
}
fs.readdirSync(appsPath).forEach(f=>{
const ff=path.join(appsPath,f);
delete require.cache[ff];
var appJson=require(ff);
appJson= initAppBizs(appJson);
initRsTree(appJson,appJson.appid,appJson.config.rstree,null);
appJsons[appJson.appid]=appJson;
});
module.exports=appJsons;
module.exports={
"appid":"wx76a324c5d201d1a4",
"label":"企业服务工具箱",
"config":{
"rstree":{
"code":"toolroot",
"label":"工具箱",
"children":[
{
"code":"toggleHeader",
"icon":"el-icon-sort",
"isMenu":true,
"label":"折叠",
},
{
"code":"personCenter",
"label":"个人信息",
"src":"/imgs/logo.png",
"isSubmenu":true,
"children":[
{"code":"wallet","isGroup":true,"label":"账户","children":[
{"code":"mytraderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"path":""},
{"code":"smallmoney","label":"钱包","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"fillmoney","label":"充值","isMenu":true,},
]},
{"code":"tool","isGroup":true,"label":"工具","children":[
{"code":"entconfirm","label":"企业用户认证","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"fav","label":"收藏夹","isMenu":true,"bizCode":"fav","bizConfig":null,"path":""},
{"code":"filebox","label":"文件柜","isMenu":true,"bizCode":"filebox","bizConfig":null,"path":""},
]},
],
},
{
"code":"fillmoney",
"icon":"fa fa-money",
"isMenu":true,
"label":"充值",
},
{
"code":"platformop",
"label":"平台运营",
"icon":"fa fa-cubes",
"isSubmenu":true,
"children":[
{"code":"papp","isGroup":true,"label":"平台数据","children":[
{"code":"papparch","label":"应用档案","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"userarch","label":"用户档案","isMenu":true,"bizCode":"pusers","bizConfig":null,"path":""},
{"code":"traderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"qp":"my","path":""},
{"code":"pconfigs","label":"平台配置","isMenu":true,"bizCode":"pconfigs","bizConfig":null,"qp":"my","path":""},
]},
{"code":"pop","isGroup":true,"label":"平台运维","children":[
{"code":"cachearch","label":"缓存档案","isMenu":true,"bizCode":"cachearches","bizConfig":null,"path":""},
{"code":"oplogmag","label":"行为日志","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"machinearch","label":"机器档案","isMenu":true,"bizCode":"machines","bizConfig":null,"path":""},
{"code":"codezrch","label":"代码档案","isMenu":true,"bizCode":"codezrch","bizConfig":null,"path":""},
{"code":"imagearch","label":"镜像档案","isMenu":true},
{"code":"containerarch","label":"容器档案","isMenu":true},
]},
],
},
{
"code":"sysmag",
"label":"系统管理",
"icon":"fa fa-cube",
"isSubmenu":true,
"children":[
{"code":"usermag","isGroup":true,"label":"用户管理","children":[
{"code":"rolearch","label":"角色档案","isMenu":true,"bizCode":"roles","bizConfig":null},
{"code":"appuserarch","label":"用户档案","isMenu":true,"bizCode":"appusers","bizConfig":null},
]},
{"code":"productmag","isGroup":true,"label":"产品管理","children":[
{"code":"productarch","label":"产品档案","bizCode":"mgproducts","isMenu":true,"bizConfig":null},
{"code":"products","label":"首页产品档案","bizCode":"products","isMenu":false,"bizConfig":null},
]},
],
},
{
"code":"exit",
"icon":"fa fa-power-off",
"isMenu":true,
"label":"退出",
},
{
"code":"toolCenter",
"label":"工具集",
"src":"/imgs/logo.png",
"isSubmenu":false,
"isMenu":false,
"children":[
{"code":"tools","isGroup":true,"label":"查询工具","children":[
{"code":"xzquery","label":"续展查询","bizCode":"xzsearch","bizConfig":null,"path":""},
{"code":"xzgqquery","label":"续展过期查询","bizCode":"xzgqsearch","bizConfig":null,"path":""},
]},
],
},
],
},
"bizs":{
"cachearches":{"title":"首页产品档案","config":null,"path":"/platform/cachearches","comname":"cachearches"},
"products":{"title":"首页产品档案","config":null,"path":"/","comname":"products"},
"mgproducts":{"title":"产品档案","config":null,"path":"/platform/mgproducts","comname":"mgproducts"},
"codezrch":{"title":"代码档案","config":null,"path":"/platform/codezrch","comname":"codezrch"},
"machines":{"title":"机器档案","config":null,"path":"/platform/machines","comname":"machines"},
"pconfigs":{"title":"平台配置","config":null,"path":"/platform/pconfigs","comname":"pconfigs"},
"apps":{"title":"应用档案","config":null,"path":"/platform/apps","comname":"apps"},
"roles":{"title":"角色档案","config":null,"path":"/platform/roles","comname":"roles"},
"pusers":{"title":"平台用户档案","config":null,"path":"/platform/pusers","comname":"users"},
"appusers":{"title":"某应用用户档案","config":null,"path":"/platform/appusers","comname":"users"},
"oplogs":{"title":"行为日志","config":null,"path":"/platform/op/oplogs","comname":"oplogs"},
"trades":{"title":"交易记录","config":null,"path":"/platform/uc/trades","comname":"trades"},
"xzsearch":{"title":"续展查询","config":null,"isDynamicRoute":true,"path":"/products/xzsearch","comname":"xzsearch"},
"xzgqsearch":{"title":"续展过期查询","config":null,"isDynamicRoute":true,"path":"/products/xzgqsearch","comname":"xzgqsearch"},
},
"pauths":[
"add","edit","delete","export","show"
],
"pdict":{
"sex":{"male":"男","female":"女"},
"configType":{"price":"宝币兑换率","initGift":"初次赠送"},
"productCata":{"ip":"知产","ic":"工商","tax":"财税","hr":"人力","common":"常用"},
"logLevel":{"debug":0,"info":1,"warn":2,"error":3,"fatal":4},
"tradeType":{"fill":"充值","consume":"消费","gift":"赠送","giftMoney":"红包","refund":"退款"},
"tradeStatus":{"unSettle":"未结算","settled":"已结算"}
}
}
}
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
},
openId:DataTypes.STRING,
app_id:DataTypes.INTEGER,
account_id:DataTypes.INTEGER,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
},{
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("oplog", {
appid: DataTypes.STRING,
appkey: DataTypes.STRING,
requestId: DataTypes.STRING,
logLevel: {
type: DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.logLevel),
defaultValue: "info",
},
op: DataTypes.STRING,
content: DataTypes.STRING(5000),
resultInfo: DataTypes.TEXT,
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: [
]
});
}
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}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("storder", {
saas_merchant_id: DataTypes.STRING, // saas商户id
out_trade_no: DataTypes.STRING, // 商户订单号
service_rate: DataTypes.INTEGER, // 商户订单号
amt: DataTypes.BIGINT, // 请求打款金额
actual_amt: DataTypes.BIGINT, // 实发金额
deduct_amt: DataTypes.BIGINT, // 扣款金额
service_tax: DataTypes.BIGINT, // 服务费
project_name: DataTypes.STRING, // 项目名称
item_count: DataTypes.INTEGER, // 打款笔数
order_type: DataTypes.STRING, // 订单类型 00未设置 10平台交易 20商户交易
acc_type: DataTypes.STRING, // 打款通道 00 银行 01 支付宝 02 微信
trade_mode: DataTypes.STRING, // 打款模式 00 未选择 01 系统打款 02 手工打款
trade_status: DataTypes.STRING, // 交易状态 00 成功 01 待处理 02 失败 03 部分成功
check_status: DataTypes.STRING, // 审核状态 00 一审 01 一审失败 02 二审 03 二审失败 04 二审通过
check1_remark: DataTypes.STRING, // 一审备注
check2_remark: DataTypes.STRING, // 二审备注
pay_voucher: DataTypes.STRING, // 付款凭证 暂用此字段,以后创建交易付款
pay_bank_account: DataTypes.STRING, // 订单付款账户名称
pay_bank_name: DataTypes.STRING, // 订单付款开户银行名称
pay_bank_no: DataTypes.STRING, // 订单付款银行账户
order_file: DataTypes.STRING, // 打款文件地址
saas_id: DataTypes.STRING, // saas_id
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'st_order',
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}]
// }
],
});
}
\ No newline at end of file
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("storderitem", {
trade_no: DataTypes.STRING, // 打款编号
saas_merchant_id: DataTypes.STRING, // saas商户id
order_id: DataTypes.STRING, // 订单id
order_type: DataTypes.STRING, // 订单类型 00未设置 10平台交易 20商户交易
out_trade_no: DataTypes.STRING, // 商户订单号
acc_name: DataTypes.STRING, // 收款户名
acc_no: DataTypes.STRING, // 收款账号
credit_code: DataTypes.STRING, // 统一社会信用代码
open_bank: DataTypes.STRING, // 开户银行全称
amt: DataTypes.BIGINT, // 请求打款金额
actual_amt: DataTypes.BIGINT, // 实发金额
deduct_amt: DataTypes.BIGINT, // 扣款金额
service_tax: DataTypes.BIGINT, // 服务费
trade_status: DataTypes.STRING, // 交易状态 00 成功 01 待处理 02 失败
trade_time: DataTypes.DATE, // 交易时间
trade_desc: DataTypes.STRING, // 交易描述
trade_receipt: DataTypes.STRING, // 回执
remark: DataTypes.STRING, // 上传备注
saas_id: DataTypes.STRING, // saas id
saas_invoice_id: DataTypes.STRING, // 发票id
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'st_order_item',
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}]
// }
]
});
}
\ No newline at end of file
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("stpay", {
saas_id: { type: DataTypes.STRING(32), allowNull: true, defaultValue: "", COMMENT: '订单id' },
saas_merchant_id: { type: DataTypes.STRING(32), allowNull: true, defaultValue: "", COMMENT: '商户id, 可为空' },
busi_name: { type: DataTypes.STRING(32), allowNull: true, defaultValue: "", COMMENT: '业务名称' },
busi_id: { type: DataTypes.STRING(32), allowNull: true, defaultValue: "", COMMENT: '业务id' },
pay_type: { type: DataTypes.INTEGER, allowNull: true, defaultValue: "1", COMMENT: '支付类型 1线下支付 2...' },
amount: { type: DataTypes.BIGINT, allowNull: true, defaultValue: "0", COMMENT: '支付金额' },
pay_status: { type: DataTypes.STRING(4), allowNull: true, defaultValue: "", COMMENT: '支付状态 10待支付 20已支付' },
pay_voucher_img: { type: DataTypes.STRING(300), allowNull: true, defaultValue: "", COMMENT: '支付凭证' },
trade_no: { type: DataTypes.STRING(64), allowNull: true, defaultValue: "", COMMENT: '交易流水号' },
account_info: { type: DataTypes.STRING, allowNull: true, defaultValue: "", COMMENT: '收款账户快照' }
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'st_pay',
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}]
// }
],
});
}
\ No newline at end of file
const system=require("../system")
const logCtl=system.getObject("web.common.oplogCtl");
class TaskBase{
constructor(className){
this.redisClient=system.getObject("util.redisClient");
this.serviceName=className;
}
async doTask(){
try {
await this.subDoTask();
//日志记录
logCtl.info({
optitle:this.serviceName+",任务成功执行完成",
op:"base/db/task.base.js",
content:"",
clientIp:""
});
} catch (e) {
//日志记录
logCtl.error({
optitle:this.serviceName+"任务执行异常",
op:"base/db/task.base.js",
content:e.stack,
clientIp:""
});
}
}
async subDoTask(){
console.log("请在子类中重写此方法进行操作业务逻辑............................!");
}
static getServiceName(ClassObj){
return ClassObj["name"];
}
}
module.exports=TaskBase;
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 TestTask extends TaskBase{
constructor(){
super();
}
async doTask(){
console.log("TestTask.....");
}
}
module.exports=TestTask;
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
constructor() {
super("auth", ServiceBase.getDaoName(UserService));
}
async authByCode(opencode) {
var existedUser = null;
var rawUser = null;
var openuser = await this.apiCallWithAk(settings.paasUrl() + "api/auth/accessAuth/authByCode", { opencode: opencode });
if (openuser) {
//先查看自己系统中是否已经存在当前用户
existedUser = await this.dao.model.findOne({ where: { ucname: openuser.userName, ucid: openuser.id }, raw: true });
if (!existedUser) {
existedUser = await this.register(openuser);
}
rawUser = existedUser.get({ raw: true });
rawUser.Roles = openuser.Roles;
}
return rawUser;
}
async getUserLoginInfo(token) {
var acckapp = await this.cacheManager["ApiUserCache"].cache(token, null, settings.usertimeout);
}
async register(openuser) {
var param = {
ucname: openuser.userName, ucid: openuser.id,
last_login_time: new Date()
}
var cruser = await this.dao.create(param);
return cruser;
}
//在平台进行登录,返回目标认证地址
async navSysSetting(user) {
var sysLoginUrl = settings.paasUrl() + "web/auth/userCtl/login?appKey=" + settings.appKey + "\&toKey=" + settings.paasKey;
var x = { userName: user.userName, password: user.password, mobile: user.mobile };
var restResult = await this.restS.execPost({ u: x }, sysLoginUrl);
if (restResult) {
var rtnres = JSON.parse(restResult.stdout);
if (rtnres.status == 0) {
return rtnres.data;
}
}
return null;
}
async getUserByUserNamePwd(u) {
var user = await this.dao.model.findOne({
where: { userName: u.userName, password: u.password, app_id: u.app_id },
include: [
{ model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
]
});
return user;
}
async checkSameName(uname, appid) {
var ac = await this.dao.model.findOne({ where: { userName: uname, app_id: appid } });
var rtn = { isExist: false };
if (ac) {
rtn.isExist = true;
}
return rtn;
}
}
module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class CacheService {
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
}
async buildCacheRtn(pageValues) {
var ps = pageValues.map(k => {
var tmpList = k.split("|");
if (tmpList.length == 2) {
return { name: tmpList[0], val: tmpList[1], key: k };
}
});
return ps;
}
async findAndCountAll(obj) {
const pageNo = obj.pageInfo.pageNo;
const pageSize = obj.pageInfo.pageSize;
const limit = pageSize;
const offset = (pageNo - 1) * pageSize;
var search_name = obj.search && obj.search.name ? obj.search.name : "";
var cacheCacheKeyPrefix = "sadd_children_appkeys:" + settings.appKey + "_cachekey";
var cacheList = await this.cacheManager["MagCache"].getCacheSmembersByKey(cacheCacheKeyPrefix);
if (search_name) {
cacheList = cacheList.filter(f => f.indexOf(search_name) >= 0);
}
var pageValues = cacheList.slice(offset, offset + limit);
var kobjs = await this.buildCacheRtn(pageValues);
var tmpList = { results: { rows: kobjs, count: cacheList.length } };
return system.getResultSuccess(tmpList);
}
async delCache(obj) {
var keyList = obj.del_cachekey.split("|");
if (keyList.length == 2) {
var cacheCacheKeyPrefix = "sadd_children_appkeys:" + settings.appKey + "_cachekey";
await this.cacheManager["MagCache"].delCacheBySrem(cacheCacheKeyPrefix, obj.del_cachekey);
await this.cacheManager["MagCache"].del(keyList[0]);
return { status: 0 };
}
}
async clearAllCache(obj) {
await this.cacheManager["MagCache"].clearAll();
return { status: 0 };
}
}
module.exports = CacheService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
var settings=require("../../../../config/settings");
class MetaService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(MetaService));
}
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 getUiConfig(appid){
const cfg=await this.cacheManager["UIConfigCache"].cache(appid,null,60);
return cfg;
}
async getBaseComp(){
var basecomp=await this.apiCallWithAk(settings.paasUrl()+"api/meta/baseComp/getBaseComp",{});
return basecomp.basecom;
}
async findAuthsByRole(rolesarray, appid){
var result =await this.apiCallWithAk(settings.paasUrl()+"api/auth/roleAuth/findAuthsByRole",{
roles:rolesarray,
appid:appid
});
return result;
}
}
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 > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
}
} catch (e) {
console.log(e.stack, "addLog------error-----------------------*****************");
qobj.content = e.stack;
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
}
}
async createDb(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;
}
try {
qobj.optitle = (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":" + qobj.optitle;
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
} catch (e) {
console.log(e.stack, "addLog------error-----------------------*****************");
qobj.content = e.stack;
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
}
}
}
module.exports = OplogService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TaskService));
//this.appDao=system.getObject("db.appDao");
this.taskManager=system.getObject("db.taskManager");
this.emailClient=system.getObject("util.mailClient");
this.personTaxDao=system.getObject("db.individualincometaxDao");
this.ossClient=system.getObject("util.ossClient");
}
//写文件并上传到阿里云,返回上传的路径
async writexls(wb,sharecode){
var that=this;
var uuid=uuidv4();
var u=uuid.replace(/\-/g,"");
var fname="zc_"+u+".xlsx";
var filepath="/tmp/"+fname;
var promise=new Promise((resv,rej)=>{
wb.xlsx.writeFile(filepath).then(async function(d) {
var rtn=await that.ossClient.upfile(fname,filepath);
fs.unlink(filepath,function(err){});
return resv(rtn);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
//读取模板文件
async readxls(){
var promise=new Promise((resv,rej)=>{
var workbook = new excel.Workbook();
workbook.properties.date1904 = true;
var bpth=path.normalize(path.join(__dirname, '../'));
workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
.then(function() {
return resv(workbook);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
async buildworkbook(taxCalcList){
var workbook = await this.readxls();
var sheet = workbook.getWorksheet(1);
sheet.columns = [
{ header: '年度', key: 'statisticalYear', width: 10 },
{ header: '月份', key: 'statisticalMonth', width: 10 },
{ header: '员工姓名', key: 'employeeName', width: 10 },
{ header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
{ header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
// { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '子女教育', key: 'childrenEducation', width: 10 },
{ header: '继续教育', key: 'continuingEducation', width: 10 },
{ header: '房贷利息', key: 'interestExpense', width: 10 },
{ header: '住房租金', key: 'housingRent', width: 10 },
{ header: '赡养老人', key: 'supportElderly', width: 10 },
{ header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
{ header: '专项扣除合计', key: 'specialDeduction', width: 10 },
{ header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
{ header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
{ header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
{ header: '适用税率', key: 'taxRate', width: 10 },
{ header: '速算扣除', key: 'deductionNumber', width: 10 },
{ header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
{ header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
// (累计税前薪资-累计五险一金-累计免征额-累计已扣专项)*税率-速算扣除-累计已纳个税=本月应纳个税
];
taxCalcList.forEach(r=>{
sheet.addRow(r);
});
return workbook;
}
async makerpt(qobj){
var self=this;
return this.db.transaction(async t=>{
const sharecode=qobj.sharecode;
const email=qobj.email;
//按照sharecode获取单位某次个税计算
var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
var sheetNameSufix="个税汇总表";
if(taxCalcList && taxCalcList.length>0){
var year=taxCalcList[0].statisticalYear;
var month=taxCalcList[0].statisticalMonth;
sheetNameSufix=year+month+sheetNameSufix;
}
var wb=await this.buildworkbook(taxCalcList);
//生成excel
var result=await this.writexls(wb,sharecode);
//异步不等待发送邮件给
var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
//发送手机短信
//写到按咋回哦sharecode,修改下载的url
return result.url;
});
}
async create(qobj){
var self=this;
return this.db.transaction(async t=>{
var task=await this.dao.create(qobj,t);
//发布任务事件
var action="new";
var taskClassName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
await self.taskManager.newTask(msg);
await self.taskManager.publish("task","newtask");
return task;
});
}
async restartTasks2(qobj){
return this.restartTasks(qobj);
}
async restartTasks(qobj){
var self=this;
var rtn={};
var tasks=await this.dao.model.findAll({raw:true});
//清空任务列表
await this.taskManager.clearlist();
for(var i=0;i<tasks.length;i++){
var tmpTask2=tasks[i];
try {
(async (tmpTask,that)=>{
var action="new";
var taskClassName=tmpTask.taskClassName;
var exp=tmpTask.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
// await that.taskManager.newTask(msg);
// await that.taskManager.publish("task","newtask");
await that.taskManager.addTask(taskClassName,exp);
})(tmpTask2,self);
} catch (e) {
rtn=null;
}
}
return rtn;
}
async delete(qobj){
var self=this;
return this.db.transaction(async t=>{
var task= await this.dao.model.findOne({where:qobj});
await this.dao.delete(task,qobj,t);
//发布任务事件
var action="delete";
var taskName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskName;
//发布任务,消息是action_taskClassName
await this.taskManager.publish("task",msg,null);
return task;
});
}
}
module.exports=TaskService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
class StOrderService extends ServiceBase {
constructor() {
super("trade", ServiceBase.getDaoName(StOrderService));
this.storderitemDao = system.getObject("db.trade.storderitemDao");
this.dictionary = system.getObject("util.dictionary");
}
async test(params) {
return system.getResultSuccess("test");
}
// 打款列表页
async pageByCondition(params) {
let page = {
count: 0,
rows: []
}
params.currentPage = Number(params.currentPage || 1);
params.pageSize = Number(params.pageSize || 10);
params.startRow = (params.currentPage - 1) * params.pageSize;
page.count = await this.dao.countByCondition(params);
if (page.count == 0) {
return system.getResultSuccess(page);
}
page.rows = await this.dao.listByCondition(params);
if (page.rows) {
for (var row of page.rows) {
this.handleDate(row, ["created_at"], null);
if(row.acc_type == "00"){
row.acc_type_name = "银行";
}else if(row.acc_type == "01"){
row.acc_type_name = "支付宝";
}else if(row.acc_type ="02"){
row.acc_type_name ="微信"
}else{
row.acc_type_name = "其他";
}
}
this.dictionary.setRowsName("ORDER", page.rows, ["order_type", "acc_type", "trade_mode", "trade_status", "check_status"]);
}
return system.getResultSuccess(page);
}
async info(params) {
let order = await this.dao.getById(params.id);
if (!order) {
return system.getResult(null, "批次不存在");
}
this.handleDate(order, ["created_at"], null);
this.dictionary.setRowName("ORDER", order, ["order_type", "acc_type", "trade_mode", "trade_status", "check_status"]);
return system.getResultSuccess(order);
}
// 保存打款信息
async saveOrder(order) {
if (!order) {
return system.getResult(null, "批次不存在");
}
let itemList = order.itemList || [];
if (itemList.length == 0) {
return system.getResult(null, "批次明细不存在");
}
let self = this;
order = await this.db.transaction(async t => {
order = await self.dao.create(order, t);
for (let item of itemList) {
item.autoIncrement = true;
item.order_id = order.id;
item.order_type = order.order_type;
item.saas_merchant_id = order.saas_merchant_id;
item.out_trade_no = order.out_trade_no;
item.saas_id = order.saas_id;
}
await self.storderitemDao.bulkCreate(itemList, t);
await self.storderitemDao.genTradeNo(order.id, t);
return order;
});
return system.getResultSuccess(order);
}
async pay(params) {
let type = this.trim(params.type);
let rs;
if (type === "offline") {
rs = await this.offlinePay(params);
} else {
return system.getResult(null, "暂不支持在线付款");
}
return rs;
}
async offlinePay(params) {
let id = this.trim(params.id);
let order = await this.dao.findById(id);
if (!order) {
return system.getResult(null, "批次不存在");
}
if (order.pay_voucher) {
// 防止重复更新
return system.getResultSuccess();
}
if (!params.pay_voucher) {
return system.getResult(null, "请上传凭证");
}
order.pay_voucher = this.trim(params.pay_voucher);
let pay_bank_account = this.trim(params.pay_bank_account);
if (pay_bank_account) {
order.pay_bank_account = pay_bank_account;
}
let pay_bank_name = this.trim(params.pay_bank_name);
if (pay_bank_name) {
order.pay_bank_name = pay_bank_name;
}
let pay_bank_no = this.trim(params.pay_bank_no);
if (pay_bank_no) {
order.pay_bank_no = pay_bank_no;
}
// 一审
order.check_status = "01";
await order.save();
return system.getResultSuccess();
}
// 一审
async audit1(params) {
let _params = {
id: this.trim(params.id),
pre: "01",
status: Number(params.status || 0) == 1 ? "03" : "02",
remark: params.remark,
auditType: 1
}
return await this.doAudit(_params, async (order) => {
if (_params.status != "02") {
return;
}
order.trade_status = "02";
await order.save();
// 更新order_item状态
let rs = await this.storderitemDao.updateTradeByOrderId(order.id, order.trade_status);
console.log(rs);
});
}
// 二审
async audit2(params) {
let _params = {
id: this.trim(params.id),
pre: "03",
status: Number(params.status || 0) == 1 ? "05" : "04",
remark: params.remark,
auditType: 2
}
let rs = await this.doAudit(_params, async (order) => {
if (_params.status == "05") {
order.trade_status = "00";
} else if (_params.status == "04") {
order.trade_status = "02";
}
await order.save();
// 更新order_item状态
let rs = await this.storderitemDao.updateTradeByOrderId(order.id, order.trade_status);
console.log(rs);
});
return rs;
}
async doAudit(params, cb) {
let id = this.trim(params.id);
let pre = this.trim(params.pre);
let status = params.status;
let remark = this.trim(params.remark);
let auditType = params.auditType;
let auditName = auditType === 1 ? "一审" : "二审";
remark = this.trim(remark);
if (!remark) {
return system.getResult(null, `请填写${auditName}备注`);
}
let order = await this.dao.findById(id);
this.dictionary.setRowName("ORDER", order, ["check_status"]);
if (!order) {
return system.getResult(null, "批次不存在");
}
if (order.check_status !== pre) {
return system.getResult(null, `${auditName}失败,当前状态为[${order.check_status_name}]`);
}
order[`check${auditType}_remark`] = remark;
order.check_status = status;
await order.save();
if (cb) {
cb(order);
}
return system.getResultSuccess(order);
}
// 打款
async trade(params) {
// 打款模式 01系统打款 02手工打款
let trade_mode = this.trim(params.trade_mode);
if (!trade_mode || ["01", "02"].indexOf(trade_mode) == -1) {
return system.getResult(null, "打款模式错误");
}
if (trade_mode == "01") {
return system.getResult(null, "系统打款正在开发中,暂时只支持手工打款");
}
let order = await this.dao.findById(params.id);
if (!order) {
return system.getResult(null, "批次不存在");
}
if (order.check_status != "05") {
return system.getResult(null, "批次未审核通过,请等待审核操作");
}
if (order.trade_mode != "00") {
return system.getResult(null, "批次已经操作过打款,不要重复操作");
}
order.trade_mode = trade_mode;
order.trade_status = "01";
await order.save();
return system.getResultSuccess(order);
}
}
module.exports = StOrderService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
class StOrderItemService extends ServiceBase {
constructor() {
super("trade", ServiceBase.getDaoName(StOrderItemService));
this.storderDao = system.getObject("db.trade.storderDao");
this.dictionary = system.getObject("util.dictionary");
}
async pageByCondition(params) {
let page = {
count: 0,
rows: []
};
params.currentPage = Number(params.currentPage || 1);
params.pageSize = Number(params.pageSize || 10);
params.startRow = (params.currentPage - 1) * params.pageSize;
page.count = await this.dao.countByCondition(params);
if (page.count == 0) {
return system.getResultSuccess(page);
}
page.rows = await this.dao.listByCondition(params);
if (page.rows) {
for (var row of page.rows) {
this.handleDate(row, ["created_at"], null);
}
this.dictionary.setRowsName("ORDER_ITEM", page.rows, ["trade_status"]);
}
return system.getResultSuccess(page);
}
async tradeOfflineCB(params) {
let item_ids = params.item_ids || [];
if (item_ids.length == 0) {
return system.getResultSuccess();
}
let trade_time = params.trade_time;
if (!trade_time) {
return system.getResult(null, "请填写交易时间");
}
let order = await this.storderDao.findById(params.order_id);
if (order.check_status != "05") {
return system.getResult(null, "批次未审核");
}
if (order.trade_mode == "00") {
return system.getResult(null, "批次未触发打款");
}
let itemParams = {
ids: item_ids,
trade_status: params.trade_status,
trade_desc: params.trade_desc,
trade_time: params.trade_time
};
let countParams = {
order_id: order.id,
trade_status: "00"
};
let orderParams = {
id: order.id
};
let self = this;
await this.db.transaction(async t => {
await self.dao.updateTrade(itemParams, t);
let count = await self.dao.countItems(countParams, t);
if (count == order.item_count) {}
orderParams.trade_status = count == order.item_count ? "00" : "03";
await self.storderDao.update(orderParams, t);
return order;
});
return system.getResultSuccess();
}
async tradeOnlineCB(params) {}
async updateInvoice(params) {
let rs = await this.dao.updateInvoice(params);
return system.getResult(rs);
}
async cancelInvoice(params) {
let rs = await this.dao.cancelInvoice(params);
return system.getResult(rs);
}
async byIds(params) {
let list = await this.dao.byIds(params);
return system.getResultSuccess(list);
}
async bySaasInvoiceId(params) {
let rs = await this.dao.bySaasInvoiceId(params);
return system.getResultSuccess(rs);
}
/**
* 根据 invoice_id 和 order_type 查询交易流水
* @param {*} params
*/
async invoiceTrade(params){
if(!params.id){
return system.getResult(null, `参数错误 ID不能为空`);
}
if(!params.order_type){
return system.getResult(null,`订单类型不能为空`);
}
try {
let tparam = {order_type:this.trim(params.order_type)};
if (params.data_ids && params.data_ids.length > 0) {
tparam.data_ids = params.data_ids;
} else if (params.id) {
tparam.saas_invoice_id = params.id;
} else {
return system.getResult([]);
}
let res = await this.dao.invoiceTrade(tparam) || [];
for(let item of res){
this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
}
return system.getResult(res);
} catch (error) {
console.log(error);
return system.getResult(null,`系统错误`);
}
}
/**
* 根据统一社会信用代码获取所有的订单流水
* @param params
* @returns {Promise<void>}
*/
async tradeItemBycreditCode(params){
if(!(params.credit_code_array instanceof Array) && params.credit_code_array.length <0){
return system.getResult(null, `参数格式错误`);
}
try{
let page = {
count: 0,
rows: []
};
params.currentPage = Number(params.currentPage || 1);
params.pageSize = Number(params.pageSize || 10);
params.startRow = (params.currentPage - 1) * params.pageSize;
page.count = await this.dao.countByCondition(params);
if (page.count == 0) {
return system.getResultSuccess(page);
}
page.rows = await this.dao.invoiceTrade(params);
if(page.rows){
for (let item of page.rows) {
this.handleDate(item, ["created_at","trade_time"], null);
item.amt = system.f2y(item.amt);
item.actual_amt = system.f2y(item.actual_amt);
item.deduct_amt = system.f2y(item.deduct_amt);
item.service_tax = system.f2y(item.service_tax);
if(item.order_type == "10"){//00未设置 10平台交易 20商户交易
item.order_type_name = "平台交易";
}else if(item.order_type=="20"){
item.order_type_name = "商户交易";
}else{
item.order_type_name = "未设置";
}
if(item.trade_status=="00"){//交易状态 00 成功 01 待处理 02 失败
item.trade_status_name = "成功";
}else if(item.trade_status=="01"){
item.trade_status_name = "待处理";
}else if(item.trade_status=="02"){
item.trade_status_name = "失败";
}else{
item.trade_status_name = "";
}
}
}
return system.getResult(page);
}catch (e) {
console.log(e);
return system.getResult(null, `系统错误`);
}
}
/***
* fn:根据ID取消发票关联
* @param params
* @returns {Promise<void>}
*/
async cancelInvoiceByDataIds(params){
if(!params.data_ids || params.data_ids.length==0) {
return system.getResult(null, `参数错误 DATA_IDS 不能为空`);
}
try{
let res = await this.dao.cancelInvoiceByDataIds(params);
return res;
}catch (e) {
console.log(e);
return system.getResult(null, `系统错误`);
}
}
}
module.exports = StOrderItemService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
class StPayService extends ServiceBase {
constructor() {
super("trade", ServiceBase.getDaoName(StPayService));
this.PAY_TYUPE = ["1", '2']; //支付类型 1线下支付 2...
this.PAY_STATUS = ["10", "20"]; //支付状态 10待支付 20已支付
}
/**
* 创建交易流水
* @param params
* @returns {Promise<void>}
*/
async saveStPay(params) {
if (!params.busi_name) {
return system.getResult(`业务名称不能为空`);
}
if (!params.busi_id) {
return system.getResult(`业务ID不能为空`);
}
if (!this.PAY_TYUPE.includes(params.pay_type)) {
return system.getResult("支付类型错误")
}
if (!this.PAY_STATUS.includes(params.pay_status)) {
return system.getResult("支付状态错误")
}
let stpay = {
busi_id: this.trim(params.busi_id),
busi_name: this.trim(params.busi_name),
saas_id: this.trim(params.saas_id),
saas_merchant_id: this.trim(params.saas_merchant_id),
pay_type: this.trim(params.pay_type),
amount: this.trim(params.amount),
pay_status: this.trim(params.pay_status),
pay_voucher_img: this.trim(params.pay_voucher_img),
trade_no: this.trim(params.trade_no),
account_info: this.trim(params.account_info),
};
try {
let res = await this.dao.create(stpay);
return system.getResult(res);
} catch (e) {
console.log(e);
return system.getResult(`系统错误`)
}
}
/**
* 更新支付记录
* @param pay_status
* @param pay_voucher_img
* @param trade_no
* @returns {Promise<void>}
*/
async updateStatus (params) {
let _bean = await this.dao.model.findOne({
where: {
id: this.trim(params.id),
}
});
if (!_bean) {
return system.getResult(null, `业务${_bean.id}不存在`);
}
if(params.pay_status){
if (!this.PAY_STATUS.includes(params.pay_status)) {
return system.getResult("支付状态错误")
}
_bean.pay_status = this.trim(params.pay_status);
}
if (params.pay_voucher_img){
_bean.pay_voucher_img = this.trim(params.pay_voucher_img);
}
if (params.trade_no){
_bean.trade_no = this.trim(params.trade_no);
}
try{
let res = await _bean.save();
return system.getResult(res);
}catch (e) {
console.log(e);
return system.getResult(null, `系统错误`)
}
}
/**
* 获取业务支付记录
* @param busi_name
* @param busiIds
* @returns {Promise<void>}
*/
async mapByBusiIds(params) {
if (!params.busi_name) {
return system.getResult(`业务名称不能为空`);
}
try {
let list = await this.dao.model.findAll({
where: {
busi_name: this.trim(params.busi_name),
busi_id: {
[this.db.Op.in]: params.busiIds,
}
}
});
let map = {};
for (let element of list) {
if(element.pay_type=="1"){
element.pay_type_name = "线下支付";
}else{
element.pay_type_name = "其他支付";
}
if(element.pay_status=="10"){
element.pay_status_name = "待支付 ";
}else if(element.pay_status=="20"){
element.pay_status_name = "20已支付";
}else{
element.pay_status_name = "";
}
let temp = map[element.busi_id] || [];
temp.push(element);
map[element.busi_id]=temp;
}
return system.getResult(map);
}catch (e) {
console.log(e);
return system.getResult(`系统错误`);
}
}
}
module.exports = StPayService;
\ No newline at end of file
const system = require("../system");
const moment = require('moment')
const settings = require("../../config/settings");
const md5 = require("MD5");
class ServiceBase {
constructor(gname, daoName) {
//this.dbf=system.getObject("db.connection");
this.db = system.getObject("db.common.connection").getCon();
this.cacheManager = system.getObject("db.common.cacheManager");
this.daoName = daoName;
this.dao = system.getObject("db." + gname + "." + daoName);
this.restS = system.getObject("util.restClient");
}
/**
* 验证签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async verifySign(params, app_key) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!params.sign) {
return system.getResult(null, "请求参数sign为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResult(null, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
if (params.sign != resultTmpSign) {
return system.getResult(null, "返回值签名验证失败");
}
return system.getResultSuccess();
}
/**
* 创建签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async createSign(params, app_key) {
if (!params) {
return system.getResultFail(-310, "请求参数为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResultFail(-330, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResultFail(-350, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
return system.getResultSuccess(resultTmpSign);
}
/**
* 验证参数信息不能为空
* @param {*} params 验证的参数
* @param {*} verifyParamsCount 需要验证参数的数量,如至少验证3个,则传入3
* @param {*} columnList 需要过滤掉的验证参数列表,格式:[]
*/
async verifyParams(params, verifyParamsCount, columnList) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!columnList) {
columnList = [];
}
var keys = Object.keys(params);
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
if (keys.length < verifyParamsCount) {
return system.getResult(null, "请求参数不完整");
}
var tResult = system.getResultSuccess();
for (let k = 0; k < keys.length; k++) {
const tKeyValue = keys[k];
if (columnList.length == 0 || columnList.indexOf(tKeyValue) < 0) {
if (!tKeyValue) {
tResult = system.getResult(null, k + "参数不能为空");
break;
}
}//白名单为空或不在白名单中,则需要验证不能为空
}
return tResult;
}
async apiCallWithAk(url, params) {
var acckapp = await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey);
var acck = acckapp.accessKey;
//按照访问token
var restResult = await this.restS.execPostWithAK(params, url, acck);
if (restResult) {
if (restResult.status == 0) {
var resultRtn = restResult.data;
return resultRtn;
} else {
await this.cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
return null;
}
}
return null;
}
// async apiCallWithAkNoWait(url,params){
// var acckapp=await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey);
// var acck=acckapp.accessKey;
// //按照访问token
// var restResult=await this.restS.execPostWithAK(params,url,acck);
// if(restResult){
// if(restResult.status==0){
// var resultRtn=restResult.data;
// return resultRtn;
// }else{
// await this.cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
// return null;
// }
// }
// return null;
// }
static getDaoName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")).toLowerCase() + "Dao";
}
async findAndCountAll(obj) {
const apps = await this.dao.findAndCountAll(obj);
return apps;
}
async refQuery(qobj) {
return this.dao.refQuery(qobj);
}
async bulkDelete(ids) {
var en = await this.dao.bulkDelete(ids);
return en;
}
async delete(qobj) {
return this.dao.delete(qobj);
}
async create(qobj) {
return this.dao.create(qobj);
}
async update(qobj, tm = null) {
return this.dao.update(qobj, tm);
}
async updateByWhere(setObj, whereObj, t) {
return this.dao.updateByWhere(setObj, whereObj, t);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.dao.customExecAddOrPutSql(sql, paras);
}
async customQuery(sql, paras, t) {
return this.dao.customQuery(sql, paras, t);
}
async findCount(whereObj = null) {
return this.dao.findCount(whereObj);
}
async findSum(fieldName, whereObj = null) {
return this.dao.findSum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
return this.dao.getPageList(pageIndex, pageSize, whereObj, orderObj, attributesObj, includeObj);
}
async findOne(obj) {
return this.dao.findOne(obj);
}
async findById(oid) {
return this.dao.findById(oid);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
handleDate(row, fields, pattern, addHours) {
pattern = pattern || "YYYY-MM-DD HH:mm:ss";
if (!row) {
return;
}
for (var field of fields) {
if (row[field]) {
if(addHours) {
row[field] = moment(row[field]).add(addHours,"hours").format(pattern);
} else {
row[field] = moment(row[field]).format(pattern);
}
}
}
}
addWhereTime(where, field, begin, end) {
if(!begin && !end) {
return;
}
if (begin && end) {
where[field] = {
[this.db.Op.between]: [begin, end]
};
} else if (begin && !end) {
where[field] = {
[this.db.Op.gte]: begin
};
} else if (!begin && end) {
where[field] = {
[this.db.Op.lte]: end
};
}
}
trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
async getEncryptStr(str) {
str = this.trim(str);
if (!str) {
throw new Error("字符串不能为空");
}
var pwd = md5(str + "_" + settings.salt);
return pwd.toString().toLowerCase();
}
}
module.exports = ServiceBase;
var sha1 = require('sha1'),
events = require('events'),
emitter = new events.EventEmitter(),
xml2js = require('xml2js');
// 微信类
var Weixin = function(path) {
this.data = '';
this.msgType = 'text';
this.fromUserName = '';
this.toUserName = '';
this.funcFlag = 0;
this.path=path;
}
// 验证
Weixin.prototype.checkSignature = function(req) {
// 获取校验参数
this.signature = req.query.signature,
this.timestamp = req.query.timestamp,
this.nonce = req.query.nonce,
this.echostr = req.query.echostr;
// 按照字典排序
var array = [this.token, this.timestamp, this.nonce];
array.sort();
// 连接
var str = sha1(array.join(""));
// 对比签名
if(str == this.signature) {
return true;
} else {
return false;
}
}
// ------------------ 监听 ------------------------
// 监听文本消息
Weixin.prototype.textMsg = function(callback) {
emitter.on("weixinTextMsg", callback);
return this;
}
// 监听图片消息
Weixin.prototype.imageMsg = function(callback) {
emitter.on("weixinImageMsg", callback);
return this;
}
// 监听地理位置消息
Weixin.prototype.locationMsg = function(callback) {
emitter.on("weixinLocationMsg", callback);
return this;
}
// 监听链接消息
Weixin.prototype.urlMsg = function(callback) {
emitter.on("weixinUrlMsg", callback);
return this;
}
// 监听事件
Weixin.prototype.eventMsg = function(callback) {
emitter.on("weixinEventMsg", callback);
return this;
}
// ----------------- 消息处理 -----------------------
/*
* 文本消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType text
* Content 文本消息内容
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseTextMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"content" : this.data.Content[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinTextMsg", msg);
return this;
}
/*
* 图片消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType image
* Content 图片链接
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseImageMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"picUrl" : this.data.PicUrl[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinImageMsg", msg);
return this;
}
/*
* 地理位置消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType location
* Location_X x
* Location_Y y
* Scale 地图缩放大小
* Label 位置信息
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseLocationMsg = function(data) {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"locationX" : this.data.Location_X[0],
"locationY" : this.data.Location_Y[0],
"scale" : this.data.Scale[0],
"label" : this.data.Label[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinLocationMsg", msg);
return this;
}
/*
* 链接消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType link
* Title 消息标题
* Description 消息描述
* Url 消息链接
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseLinkMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"title" : this.data.Title[0],
"description" : this.data.Description[0],
"url" : this.data.Url[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinUrlMsg", msg);
return this;
}
/*
* 事件消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType event
* Event 事件类型,subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
* EventKey 事件KEY值,与自定义菜单接口中KEY值对应
*/
Weixin.prototype.parseEventMsg = function() {
var eventKey = '';
if (this.data.EventKey) {
eventKey = this.data.EventKey[0];
}
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"event" : this.data.Event[0],
"eventKey" : eventKey,
"appk":this.path,
}
emitter.emit("weixinEventMsg", msg);
return this;
}
// --------------------- 消息返回 -------------------------
// 返回文字信息
Weixin.prototype.sendTextMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<Content><![CDATA[" + msg.content + "]]></Content>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// 返回音乐信息
Weixin.prototype.sendMusicMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<Music>" +
"<Title><![CDATA[" + msg.title + "]]></Title>" +
"<Description><![CDATA[" + msg.description + "DESCRIPTION]]></Description>" +
"<MusicUrl><![CDATA[" + msg.musicUrl + "]]></MusicUrl>" +
"<HQMusicUrl><![CDATA[" + msg.HQMusicUrl + "]]></HQMusicUrl>" +
"</Music>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// 返回图文信息
Weixin.prototype.sendNewsMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
//
var articlesStr = "";
for (var i = 0; i < msg.articles.length; i++)
{
articlesStr += "<item>" +
"<Title><![CDATA[" + msg.articles[i].title + "]]></Title>" +
"<Description><![CDATA[" + msg.articles[i].description + "]]></Description>" +
"<PicUrl><![CDATA[" + msg.articles[i].picUrl + "]]></PicUrl>" +
"<Url><![CDATA[" + msg.articles[i].url + "]]></Url>" +
"</item>";
}
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<ArticleCount>" + msg.articles.length + "</ArticleCount>" +
"<Articles>" + articlesStr + "</Articles>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// ------------ 主逻辑 -----------------
// 解析
Weixin.prototype.parse = function() {
if(this.data){
this.msgType = this.data.MsgType[0] ? this.data.MsgType[0] : "text";
switch(this.msgType) {
case 'text' :
this.parseTextMsg();
break;
case 'image' :
this.parseImageMsg();
break;
case 'location' :
this.parseLocationMsg();
break;
case 'link' :
this.parseLinkMsg();
break;
case 'event' :
this.parseEventMsg();
break;
}
}
}
// 发送信息
Weixin.prototype.sendMsg = function(msg) {
switch(msg.msgType) {
case 'text' :
this.sendTextMsg(msg);
break;
case 'music' :
this.sendMusicMsg(msg);
break;
case 'news' :
this.sendNewsMsg(msg);
break;
}
}
// Loop
Weixin.prototype.loop = function(req, res) {
// 保存res
this.res = res;
var self = this;
// 获取XML内容
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
buf += chunk;
});
// 内容接收完毕
req.on('end', function() {
xml2js.parseString(buf, function(err, json) {
if (err) {
err.status = 400;
} else {
req.body = json;
}
});
if(req.body){
self.data = req.body.xml;
}
self.parse();
});
}
module.exports = Weixin;
var Wx = require("./wx.event");
const system = require("../system");
var dicCache = {};
//创知厚的我想我要的配置
wxconfig = {
AppID: "wx4c91e81bbb6039cd",
Secret: "12048e66dba64f2581e02b306680b232",
Token: "bosstoken",
AccessTokenUrl: "https://api.weixin.qq.com/cgi-bin/token",
};
//智薪云的配置
wxconfig2 = {
AppID: "wxdc08c441c9fdb7a7",
Secret: "379e582e28645585a7def9c1c88de550",
Token: "bosstoken",
AccessTokenUrl: "https://api.weixin.qq.com/cgi-bin/token",
};
wxconfigDic = {
"wx4c91e81bbb6039cd": wxconfig,
"wxdc08c441c9fdb7a7": wxconfig2,
}
var getWeiXin = function (url) {
var weixin = null;
if (!dicCache[url]) {
weixin = new Wx(url);
dicCache[url] = weixin;
} else {
weixin = dicCache[url];
}
weixin.token = wxconfig.Token;
weixin.wxconfig = wxconfig;
weixin.getAccessConfig = function (appkey) {
var cfg = wxconfigDic[appkey];
return {
grant_type: "client_credential",
appid: cfg.AppID,
secret: cfg.Secret,
};
}
// 监听文本消息
weixin.textMsg(function (msg) {
console.log("textMsg received");
console.log(JSON.stringify(msg));
var resMsg = {};
switch (msg.content) {
case "文本":
// 返回文本消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "text",
content: "这是文本回复",
funcFlag: 0
};
break;
case "音乐":
// 返回音乐消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "music",
title: "音乐标题",
description: "音乐描述",
musicUrl: "音乐url",
HQMusicUrl: "高质量音乐url",
funcFlag: 0
};
break;
case "图文":
var articles = [];
articles[0] = {
title: "PHP依赖管理工具Composer入门",
description: "PHP依赖管理工具Composer入门",
picUrl: "http://weizhifeng.net/images/tech/composer.png",
url: "http://weizhifeng.net/manage-php-dependency-with-composer.html"
};
articles[1] = {
title: "八月西湖",
description: "八月西湖",
picUrl: "http://weizhifeng.net/images/poem/bayuexihu.jpg",
url: "http://weizhifeng.net/bayuexihu.html"
};
articles[2] = {
title: "「翻译」Redis协议",
description: "「翻译」Redis协议",
picUrl: "http://weizhifeng.net/images/tech/redis.png",
url: "http://weizhifeng.net/redis-protocol.html"
};
// 返回图文消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
}
}
weixin.sendMsg(resMsg);
});
// 监听图片消息
weixin.imageMsg(function (msg) {
console.log("imageMsg received");
console.log(JSON.stringify(msg));
});
// 监听位置消息
weixin.locationMsg(function (msg) {
console.log("locationMsg received");
console.log(JSON.stringify(msg));
});
// 监听链接消息
weixin.urlMsg(function (msg) {
console.log("urlMsg received");
console.log(JSON.stringify(msg));
});
// 监听事件消息
weixin.eventMsg(function (msg) {
if (msg.event == "subscribe" || msg.event == "SCAN") {
var wxservice = system.getObject("service.wxSve");
//to do msg.toUserName--按照微信号去取得应用,按照应用获取OAUTH
// wxservice.checkAndLogin(msg.fromUserName);
if (weixin.path == "ecwx") {
var urlstr = "https://ec.gongsibao.com/h5";
if (msg.eventKey && msg.eventKey != "") {
if (msg.eventKey.indexOf("_") >= 0) {
var strid = msg.eventKey.split('_')[1];
urlstr = urlstr + "?ecid=" + strid;
} else {
var strid = msg.eventKey;
urlstr = urlstr + "?ecid=" + strid;
}
}
var articles = [];
articles[0] = {
title: "欢迎来到智薪云签约平台",
description: "点击本图文消息,开始签约。",
picUrl: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_476111544670096808201813111368084242271.jpg",
url: urlstr,
};
var resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
};
weixin.sendMsg(resMsg);
} else {
//是否启用派单
var dispatchEnabled = true;
// 通知信息
var articles = [];
// 参数
var eventKey = msg.eventKey;
var userId = 0;
if (eventKey && eventKey.indexOf("_") > -1) {
// 标眼查通知openId保存逻辑
userId = Number(eventKey.split("_")[1] || 0);
if (userId && userId > 0) {
dispatchEnabled = false;
// 标眼查动态通知
articles[0] = {
title: "欢迎使用标眼监测商标监控工具",
description: "实时提醒商标动态,及时处理商标业务",
picUrl: "",
//picUrl: "https://search.gongsibao.com/imgs/biaoyan-logo-mini.png",
url: ""
};
}
}
else {
if (eventKey) {
userId = Number(eventKey);
}
}
if (dispatchEnabled) {
// 派单通知
articles[0] = {
title: "欢迎来到创知厚德智能派单平台",
description: "点击图文消息,开始接单",
picUrl: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_305111544784291353201814184451353distributeneed.png",
url: "https://boss.gongsibao.com/distributeneed",
};
}
if (userId && userId > 0) {
// wxservice.更新通知id
wxservice.updateNotifyOpenId(userId, msg.fromUserName);
}
var resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
};
weixin.sendMsg(resMsg);
}
} else {
//发送空串回微信服务器
weixin.res.send("");
}
});
return weixin;
}
module.exports = getWeiXin;
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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