Commit 21201733 by 王昆

gsb

parent a3978d3d
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.authSve = system.getObject("service.sign.authSve");
// this.userSve = system.getObject("service.user.userSve");
}
/**
* 接口跳转
* action_process 执行的流程
* action_type 执行的类型
* action_body 执行的参数
*/
async springboard(pobj, qobj, req) {
// 接口层请求报文保存
await this.saveApiInfo(pobj.action_process, pobj.action_type, pobj.action_body);
let result;
if (!pobj.action_process) {
return system.getResult(null, "action_process参数不能为空");
}
if (!pobj.action_type) {
return system.getResult(null, "action_type参数不能为空");
}
try {
// 验证签名
await this.validSign(pobj.action_body);
result = await this.handleRequest(pobj.action_process, pobj.action_type, pobj.action_body);
} catch (error) {
console.log(error);
// TODO 抓取validsign error并返回
}
return result;
}
async handleRequest(action_process, action_type, action_body) {
var opResult = null;
switch (action_type) {
// 姓名二要素
case "nameTwo":
opResult = await this.authSve.nameTwo(action_body);
break;
// 银行卡三要素
case "bankThree":
// opResult = await this.userSve.saveMerchantUser(action_body);
break;
// 银行卡四要素
case "bankFour":
// opResult = await this.userSve.adminLogin(action_body);
break;
// 创建账号
case "createAccount":
// opResult = await this.userSve.merchantLogin(action_body);
break;
// 创建模板
case "createTemplate":
// opResult = await this.userSve.merchantLogin(action_body);
break;
// 手动签约
case "sign":
// opResult = await this.userSve.merchantLogin(action_body);
break;
//
case "autoSign":
// opResult = await this.userSve.info(action_body);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
async validSign() {
}
async saveApiInfo() {
}
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();
}
async esign(pobj, query, req) {
// 1. 日志记录
// 2. 转发bpohhr.gongsibao.com
// 3. 调用api服务
// 4.
// let result = {
// code: 1,
// message: "success",
// shopNum: "",
// data: {}
// };
// let thirdOrderNo = req.thirdOrderNo || "";
// let action = req.action == null || req.action == "" || req.action == "undefined" ? "" : req.action;
// let flowId = req.flowId == null || req.flowId == "" || req.flowId == "undefined" ? "" : req.flowId;
// if (action == "" || flowId == "") {
// result.code = -101;
// result.message = "请求参数有误";
// return result;
// }
try {
// if (action != "SIGN_FLOW_FINISH" && action != "SIGN_FLOW_UPDATE") {
// result.code = -102;
// result.message = "action请求参数有误";
// return result;
// }
// let params = {
// flowId: flowId
// };
// let contractDetails = await this.utilesignbaoSve.getContractDetails(params, "eSignBaoApplet");
// if (action == "SIGN_FLOW_UPDATE") { //5.9.3 签署人签署状态更新通知,e签宝签署状态变化完成后调用(拒签、签署完成)
// var signResultStatus = req.signResult == null || req.signResult == "" || req.signResult == "undefined" ? -1 : req.signResult;
// if (signResultStatus >= 0) {
// // 跟进回调----更新db签署人签署状态
// if (thirdOrderNo.indexOf("dk_") == 0) {
// this.dkcontractSve.updateCallbackStatus(req);
// } else if (thirdOrderNo.indexOf("ent_") == 0) {
// this.entcontractSve.updateCallbackStatus(req);
// } else {
// this.econtractSve.updateCallbackStatus(req);
// }
// if (signResultStatus == 2) { //签署人签署完成,调用e签宝归档流程
// var archiveProcess = await this.utilesignbaoSve.archiveProcess(params, "eSignBaoApplet");
// }
// }
// } else if (action == "SIGN_FLOW_FINISH") { //5.9.4 签署任务结束通知,由调用【**归档流程**】后回调此回调
// var flowStatus = req.flowStatus == null || req.flowStatus == "" || req.flowStatus == "undefined" ? -1 : req.flowStatus;
// if (flowStatus >= 0) {
// //TODO:跟进回调----更新db签署流程状态
// }
// }
return result;
} catch (e) {
console.log(e.stack);
// //日志记录
// logCtl.error({
// optitle: "e签宝签署回调异常error",
// op: "wxapplet/impl/esignbao/eSignBaoCallback",
// content: e.stack,
// clientIp: req.clientIp
// });
}
}
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
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")
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 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 UserDao extends Dao {
constructor() {
super(Dao.getModelName(UserDao));
}
/**
* 条件查询
* @param {} params
*/
async findUser(params) {
let sql = [];
sql.push('select * from uc_user where 1 = 1');
if (params.ucname) {
sql.push("AND ucname = :ucname");
}
if (params.uctype) {
sql.push("AND uctype = :uctype");
}
if (params.is_enabled) {
sql.push("AND is_enabled = :is_enabled");
}
sql.push(`AND (deleted_at > NOW() or deleted_at is null)`);
return await this.customQuery(sql.join(" "), params);
}
async getByUcname(ucname, uctype) {
var sql = "SELECT * FROM uc_user WHERE ucname = :ucname AND uctype = :uctype AND deleted_at IS NULL";
var list = await this.customQuery(sql, {
ucname: ucname,
uctype: uctype,
});
if (!list || list.length == 0) {
return null;
}
return list[0];
}
async countByCondition(params) {
var sql = [];
sql.push("SELECT");
sql.push("count(1) as num");
sql.push("FROM uc_user t1");
sql.push("WHERE t1.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("t1.*");
sql.push("FROM uc_user t1");
sql.push("WHERE t1.deleted_at IS NULL");
this.setCondition(sql, params);
sql.push("ORDER BY t1.id DESC");
sql.push("LIMIT :startRow, :pageSize");
return await this.customQuery(sql.join(" "), params);
}
setCondition(sql, params) {
if (!params || !sql) {
return;
}
if (params.uctype) {
sql.push("AND t1.uctype = :uctype");
}
if (params.uctype_id) {
sql.push("AND t1.uctype_id = :uctype_id");
}
if (params.ucname) {
sql.push("AND t1.ucname LIKE :ucname");
}
if (params.mobile) {
sql.push("AND t1.mobile LIKE :mobile");
}
if (params.real_name) {
sql.push("AND t1.real_name LIKE :real_name");
}
if (params.createBegin) {
sql.push("AND t1.created_at >= :createBegin");
}
if (params.createEnd) {
sql.push("AND t1.created_at <= :createEnd");
}
if (params.is_enabled === 0 || params.is_enabled === 1) {
sql.push("AND t1.is_enabled = :is_enabled");
}
if (params.orgpath) {
sql.push("AND t1.orgpath LIKE :orgpath");
}
}
async findMapByIds(ids, attrs) {
let result = {};
if (!ids || ids.length == 0) {
return result;
}
let sql = [];
sql.push("SELECT");
sql.push(attrs || "*");
sql.push("FROM uc_user t1");
sql.push("WHERE t1.id IN (:ids)");
var list = await this.customQuery(sql.join(" "), {
ids: ids
});
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
async updateOrg(org_id, orgpath) {
let sql = "UPDATE uc_user SET orgpath = :orgpath WHERE org_id = :org_id";
await this.customUpdate(sql, {org_id: org_id, orgpath: orgpath});
}
}
module.exports = UserDao;
\ No newline at end of file
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;
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("user", {
ucname: DataTypes.STRING,
password: DataTypes.STRING,
real_name: DataTypes.STRING,
mobile: DataTypes.STRING,
uctype: DataTypes.INTEGER,
uctype_id: DataTypes.STRING,
org_id: DataTypes.INTEGER,
orgpath: DataTypes.STRING,
is_enabled: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
is_manager: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
is_main: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'uc_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}]
// }
]
});
}
\ 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");
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("../../svems.base")
class FeeService extends ServiceBase {
constructor() {
super();
// 引擎不可以引用任何
}
/**
* 账户查询
* @param params
* account_id: 账户id
* @returns
*/
async account(params) {
try {
return await this.callms("engine_fee", "accountInfo", params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* @param params
* {
* "currentPage": 1,
* "pageSize": 10,
* "account_id": "1",
* "trade_type": "1",
* "trade_no": "123313",
* "tradeTimeBegin": "2020-06-26 04:21:31",
* "tradeTimeEnd": "2020-06-26 05:11:31"
* }
* @returns
*/
async accountTradePage(params) {
try {
return await this.callms("engine_fee", "accountTrade", params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
/**
* account_id
* @param params
* {
* "account_id": "1",
* "trade_type": "1",
* "trade_nos": ['1','2'],
* }
* @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}|{msg: string, data, bizmsg: *|string, status: number}|any|undefined>}
*/
async tradeMapByIds(params) {
try {
return await this.callms("engine_fee", "tradeMapByIds", params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
}
module.exports = FeeService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../svems.base")
class AuthService extends ServiceBase {
constructor() {
super();
}
async nameTwo(params) {
try {
// 通过应用id查询商户订单信息,确定产品认证接口
return this.doAuth(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
async bankThree(params) {
try {
return this.doAuth(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
async bankFour(params) {
try {
return this.doAuth(params);
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
async doAuth(params) {
// 1. 扣费
// 2. 调用认证引擎
// 3. 异步调用订单逻辑
// 4. 返回认证结果
}
}
module.exports = AuthService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../svems.base")
class AuthService extends ServiceBase {
constructor() {
super();
}
async createAccount(params) {
try {
// 通过应用id查询商户订单信息,确定产品认证接口
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
async createTemplate(params) {
try {
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
async sign(params) {
try {
} catch (error) {
return system.getResult(null, `系统错误 错误信息 ${error}`);
}
}
}
module.exports = AuthService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
constructor() {
super("user", ServiceBase.getDaoName(UserService));
this.dictionary = system.getObject("util.dictionary");
}
async adminLogin(obj) {
obj.uctype = 1;
let res = await this.login(obj);
return res;
}
async merchantLogin(obj) {
obj.uctype = 2;
let res = await this.login(obj);
return res;
}
async login(obj) {
let uctype = obj.uctype;
if ([1, 2].indexOf(uctype) == -1) {
return system.getResult(null, "用户类型错误");
}
let user = await this.dao.getByUcname(obj.ucname, uctype);
// 验证登录合法
if (!user) {
return system.getResult(null, "用户名或密码错误");
}
if (!user.is_enabled) {
return system.getResult(null, "用户已禁用");
}
if (uctype && uctype != user.uctype) {
return system.getResult(null, "用户类型错误");
}
let loginPwd = await this.getEncryptStr(obj.password);
if (loginPwd != user.password) {
return system.getResult(null, "用户名或密码错误");
}
await this.setLogin(user);
return system.getResultSuccess(user);
}
async setLogin(user) {
console.log("设置登录信息,权限,角色等");
}
async saveAdminUser(obj) {
obj.uctype = 1;
return await this.saveUser(obj);
}
async saveMerchantUser(obj) {
obj.uctype = 2;
if (!obj.uctype_id) {
return system.getResult(null, "未选择用户所属商户");
}
return await this.saveUser(obj);
}
async userResetPassword(params) {
let id = params.id;
let oldPassword = await this.getEncryptStr(this.trim(params.oldPassword));
let newPassword = this.trim(params.newPassword);
let newPasswordConfirm = this.trim(params.newPasswordConfirm);
let user = await this.findById(id);
if (!user) {
return system.getResult(null, "修改密码失败,用户不存在");
}
if (!newPassword) {
return system.getResult(null, "修改密码失败,新密码不能为空");
}
if (newPassword != newPasswordConfirm) {
return system.getResult(null, "修改密码失败,两次密码输入不一致");
}
if (user.password != oldPassword) {
return system.getResult(null, "修改密码失败,原密码错误");
}
user.password = await this.getEncryptStr(newPassword);
await user.save();
return system.getResultSuccess();
}
async saveUser(obj) {
let id = obj.id;
let password = this.trim(obj.password);
let uctype_id = this.trim(obj.uctype_id);
let user = {};
try {
if (id) {
user = await this.findById(id);
} else {
if (!password) {
return system.getResult(null, "密码不能为空");
}
}
user.uctype = obj.uctype;
user.uctype_id = uctype_id;
user.ucname = this.trim(obj.ucname);
user.mobile = this.trim(obj.mobile);
user.real_name = this.trim(obj.real_name);
user.is_enabled = obj.is_enabled || false;
if (password) {
user.password = await this.getEncryptStr(password);
}
let exists = await this.dao.findOne({uctype: user.uctype, ucname: user.ucname});
if (user.id) {
if (exists && exists.id != user.id) {
return system.getResult(-1, `用户名[${user.ucname}]重复`);
}
user = await user.save();
} else {
if (exists) {
return system.getResult(-1, `用户名[${user.ucname}]重复`);
}
user.autoIncrement = true;
user = await this.dao.create(user);
}
} catch (e) {
if (e.name == 'SequelizeValidationError') {
return system.getResult(-1, `用户名[${user.ucname}]重复`);
}
console.log(new Date(), e);
return system.getResult(-1, `服务错误`);
}
return system.getResultSuccess(user);
}
async info(params) {
let id = Number(params.id || 0);
let user = await this.dao.getById(id);
if (!user) {
return system.getResult(null, "用户不存在");
}
user.password = "";
this.handleDate(user, ["created_at", "updated_at"], null);
return system.getResultSuccess(user);
}
async enabled(params) {
let user = await this.dao.findById(params.id);
if (!user) {
return system.getResult(null, "用户不存在");
}
user.is_enabled = Number(params.is_enabled || 0) == 0 ? false : true;
await user.save();
return system.getResultSuccess();
}
async pageByCondition(params) {
let result = {
count: 0,
rows: []
};
params.currentPage = Number(params.currentPage || 1);
params.pageSize = Number(params.pageSize || 10);
params.startRow = (params.currentPage - 1) * params.pageSize;
if (params.orgpath) {
params.orgpath = params.orgpath + "%";
}
var total = await this.dao.countByCondition(params);
if (total == 0) {
return result;
}
result.count = total;
result.rows = await this.dao.listByCondition(params) || [];
if (result.rows) {
for (let item of result.rows) {
this.handleDate(item, ["created_at"], null);
}
}
return system.getResultSuccess(result);
}
async updPassword(params) {
let user = await this.findById(params.id);
if (!user) {
return system.getResult(null, "用户不存在");
}
user.password = await this.getEncryptStr(params.password);
await user.save();
return system.getResultSuccess();
}
async mapByIds(params) {
let rs = await this.dao.findMapByIds(params.ids, params.attrs);
return system.getResultSuccess(rs);
}
}
module.exports = UserService;
\ 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);
}
}
}
}
handleRowsDate(rows, fields, pattern, addHours) {
pattern = pattern || "YYYY-MM-DD HH:mm:ss";
if (!rows) {
return;
}
for (let row of rows) {
this.handleDate(row, fields, pattern, addHours)
}
}
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;
const system = require("../system");
const moment = require('moment')
const settings = require("../../config/settings");
const md5 = require("MD5");
const axios = require('axios');
class ServiceBase {
constructor() {
this.restClient = system.getObject("util.restClient");
this.synlogDao = system.getObject("db.log.synlogDao");
this.micro = system.microsetting();
}
async getEncryptStr(str) {
if (!str) {
throw new Error("字符串不能为空");
}
var md5 = this.md5(str + "_" + settings.salt);
return md5.toString().toLowerCase();
}
/**
* 验证签名
* @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.restClient.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;
}
/*
返回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";
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
};
}
}
async callms(sveName, apiName, params) {
var reqUrl = this.micro[sveName];
console.log(reqUrl, "-----------------------------");
if (!reqUrl) {
return system.getResult(null, "未找到【" + sveName + "】服务,请检查settings文件是否存在");
}
if (!apiName) {
return system.getResult(null, "apiName不能为空");
}
try {
var params = {
"action_process": "esign-api",
"action_type": apiName,
"action_body": params || {},
}
if(settings.env == 'dev') {
let rs = await axios({
method: 'post',
url: reqUrl,
data: params
});
console.log(rs);
return rs.data;
}
var rs = await this.restClient.execPost(params, reqUrl);
if (rs && rs.stdout) {
return JSON.parse(rs.stdout);
}
return system.getResult(null, rs);
} catch (error) {
console.log(error);
this.logCtl.error({
optitle: "微服务请求失败",
op: "sveName = " + sveName + "; apiName = " + apiName,
content: "params = " + JSON.stringify(params),
clientIp: ""
});
return system.getResult(null, error.message);
}
}
async callApi(url, data, name) {
let res;
let log = await this.addSynLog(url, data, name);
try {
res = await axios({
method: 'post',
url: url,
data: data
});
if(log) {
log.apiRes = JSON.stringify(res.data);
log.save();
}
return res.data;
} catch (e) {
console.log(e);
}
return res.data;
}
async addSynLog(url, data, name) {
try {
return await this.synlogDao.create({
apiUrl: url,
apiName: name,
apiReq: JSON.stringify(data),
apiRes: "",
});
} catch (e) {
console.log(e)
}
return null;
}
trim(o) {
if (!o) {
return "";
}
return o.toString().trim();
}
}
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
var fs = require("fs");
var objsettings = require("../config/objsettings");
var settings = require("../config/settings");
class System {
static declare(ns) {
var ar = ns.split('.');
var root = System;
for (var i = 0, len = ar.length; i < len; ++i) {
var n = ar[i];
if (!root[n]) {
root[n] = {};
root = root[n];
} else {
root = root[n];
}
}
}
static register(key, ClassObj) {
if (System.objTable[key] != null) {
throw new Error("相同key的对象已经存在");
} else {
let obj = new ClassObj();
System.objTable[key] = obj;
}
return System.objTable[key];
}
static getResult(data, opmsg = "操作成功", req) {
return {
status: !data ? -1 : 0,
msg: opmsg,
data: data || null,
bizmsg: req && req.session && req.session.bizmsg ? req.session.bizmsg : "empty"
};
}
/**
* 请求返回成功
* @param {*} data 操作成功返回的数据
* @param {*} okmsg 操作成功的描述
*/
static getResultSuccess(data, okmsg = "success") {
return {
status: 0,
msg: okmsg,
data: data || null,
};
}
/**
* 请求返回失败
* @param {*} status 操作失败状态,默认为-1
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
static getResultFail(status = -1, errmsg = "fail", data = null) {
return {
status: status,
msg: errmsg,
data: data,
};
}
static getObject(objpath) {
var pathArray = objpath.split(".");
var packageName = pathArray[0];
var groupName = pathArray[1];
var filename = pathArray[2];
var classpath = "";
if (filename) {
classpath = objsettings[packageName] + "/" + groupName;
} else {
classpath = objsettings[packageName];
filename = groupName;
}
var objabspath = classpath + "/" + filename + ".js";
if (System.objTable[objabspath] != null) {
console.log("get cached obj");
return System.objTable[objabspath];
} else {
console.log("no cached...");
var ClassObj = require(objabspath);
return System.register(objabspath, ClassObj);
}
}
static getUiConfig(appid) {
var configPath = settings.basepath + "/app/base/db/metadata/" + appid + "/index.js";
if (settings.env == "dev") {
delete require.cache[configPath];
}
var configValue = require(configPath);
return configValue;
}
static getUiConfig2(appid) {
var configPath = settings.basepath + "/app/base/db/metadata/index.js";
// if(settings.env=="dev"){
// console.log("delete "+configPath+"cache config");
// delete require.cache[configPath];
// }
delete require.cache[configPath];
var configValue = require(configPath);
return configValue[appid];
}
static get_client_ip(req) {
var ip = req.headers['x-forwarded-for'] ||
req.ip ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket && req.connection.socket.remoteAddress) || '';
var x = ip.match(/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/);
if (x) {
return x[0];
} else {
return "localhost";
}
};
static y2f(y) {
if (!y) {
return 0;
}
return (Number(y) * 100).toFixed(0);
}
static f2y(f) {
if (!f) {
return 0;
}
return parseFloat((Number(f) / 100).toFixed(2));
}
static f2y4list(list, fields, prev) {
if (!list || list.length == 0 || !fields || fields.length == 0) {
return;
}
prev = prev || "";
for (var item of list) {
for (var f of fields) {
var v = item[f] || 0;
try {
item[f + "_y"] = prev + parseFloat((Number(v) / 100).toFixed(2));
} catch (error) {
console.log(error);
}
}
}
}
static getUid(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var uuid = [],
i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
static microsetting() {
console.log(settings.env, "-------------- microsetting env ------------------");
var path = "/api/op/action/springboard";
if (settings.env == "dev") {
let local = "http://127.0.0.1";
let dev = "http://39.107.234.14";
return {
// 产品引擎
engine_product: local + ":3571" + path,
// 计费引擎
engine_fee: local + ":3572" + path,
// 认证引擎
engine_auth: local + ":3573" + path,
// 签约引擎
engine_sign: local + ":3574" + path,
// 用户服务
sve_uc: local + ":3651" + path,
// 商户服务
sve_merchant: local + ":3652" + path,
// 订单服务
sve_order: dev + ":3653" + path,
}
} else {
return {
// common: "xggsvecommon-service" + path,
// // merchant: "xggsvemerchant-service" + path,
// merchant: "http://123.57.217.203:20500" + path,
// order: "xggsveorder-service" + path,
// invoice: "xggsveinvoice-service" + path,
// uc: "xggsveuc-service" + path,
// trade: "xggsvetrade-service" + path,
}
}
}
}
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
System.objTable = {};
//访问token失效,请重新获取
System.tokenFail = 1000;
//appKey授权有误
System.appKeyError = 1100;
//应用处于待审核等待启用状态
System.waitAuditApp = 1110;
//访问appid失效,请重新获取
System.appidFail = 1200;
//签名验证失败,请重新获取
System.signFail = 1300;
//获取访问token失败
System.getAppInfoFail = 1130;
module.exports = System;
\ No newline at end of file
// var twice = {
// apply:function(target, ctx, args) {
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(target);
// console.log("ctx",ctx,"args",args);
// console.log(...arguments);
// return Reflect.apply(...arguments) * 2;
// }
// };
class s{
async apply(target, ctx, args){
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxx");
var rtn=await Reflect.apply(...arguments) * 2;
console.log(arguments);
return rtn
}
}
class obj extends s{
async sum(left, right){
return left + right;
}
}
// var objnew=new obj();
// var proxy = new Proxy(objnew.sum, objnew);
// var y=proxy(5, 6) // 22
// console.log(y.then(n=>console.log(n)));
function x(m,...items){
console.log(m);
console.log(...items);
console.log(items);
}
x(2,3,4,5);
// class A{
// a(params) {
// console.log(params);
// }
// b(params) {
// console.log(params);
// }
// }
// console.log(A.toString());
// var reg1 = /([a-z])*\(.*\)/g;
// var m=A.toString().match(reg1);
// console.log(m);
// var WXPay = require('wx-pay');
// var wxpay = WXPay({
// appid: 'wx6f3ebe44defe336a',
// mch_id: '1232813602',
// partner_key: 'sinotone2014sinotone2014sinotone', //微信商户平台API密钥
// //pfx: fs.readFileSync('./wxpay_cert.p12'), //微信商户平台证书
// //pfx: "sinotone2014sinotone2014sinotone"
// });
// // var out_trade_no='20160203'+Math.random().toString().substr(2, 10);
// // wxpay.createUnifiedOrder({
// // body: '充值兑换宝币',
// // out_trade_no: out_trade_no,
// // total_fee: 1,
// // spbill_create_ip: '192.168.2.210',
// // notify_url: 'http://www.gongsibao.com',
// // trade_type: 'NATIVE',
// // product_id: '1234567890'
// // }, function(err, result){
// // console.log(result);
// // //查询订单
// // //通过微信订单号查
// // wxpay.queryOrder({ out_trade_no:out_trade_no}, function(err, order){
// // console.log(order);
// // });
// //
// // });
// async function queryWxOrder(idkey){
// var p=new Promise((resv,rej)=>{
// wxpay.queryOrder({ out_trade_no:idkey}, function(err, order){
// if(err){
// return rej(err);
// }else{
// return resv(order);
// }
// });
// });
// return p;
// }
// async function testQuery(){
// try{
// var result = await queryWxOrder("d942bc2ccd784034af60c2d92079c897");
// console.log(result);
// }catch(e){
// console.log(e);
// console.log("error.................");
// }
// }
// testQuery();
// 二、框架
// 三、实战
// async function getCacheByKey(k){
// return k;
// }
// async function buildData(data){
// console.log(data);
// console.log("xxxxxxxxxxxxxxxx");
// console.log(data.length);
// var ds=[]
// for(var i=0;i<data.length;i++){
// console.log(i);
// var source={name:""};
// var count=await getCacheByKey(data[i].name);
// source.name=data[i].name;
// source.value=count;
// ds.push(source);
// }
// return ds;
// }
// async function out(){
// var data=[
// {"name":"jy"},
// {"name":"tom"}
// ];
// var ds=await buildData(data);
// console.log(ds);
// }
//
// out();
// async function ok1(){
// var p=new Promise(function(res,rej){
// setTimeout(()=>{
// return res("ok1");
// },2000);
// });
// return p;
// }
// async function ok2(){
// return "ok2";
// }
// async function ok3(){
// var k1=await ok1();
// console.log(k1);
// var k2=await ok2();
// console.log(k2);
// }
// ok3();
// const uuidv4 = require('uuid/v4');
// var u=uuidv4()
// console.log(u.replace(/\-/g,""))
// async function testAsync1(){
// return 5;
// }
//
// async function testAsync2(){
// return 5;
// }
// async function testAsync3(){
// var x= await testAsync1();
// var y= await testAsync2();
// return 5;
// }
// var x=testAsync().then(function(r){
// console.log(r);
// return 6;
// }).then(function(r){
// console.log(r);
// return 7;
// });
// x.then(function(r){
// console.log(r);
// }).catch(function(err){
//
// });
// function getArgs(func){
// //匹配函数括号里的参数
// var args=func.toString().match(/[async|function]\s.*?\(([^)]*)\)/)[1];
// //分解参数成数组
// return args.split(",").map(function (arg){
// //去空格和内联注释
// return arg.replace(/\/\*.*\*\//,"").trim();
// }).filter(function(args) {
// //确保没有undefineds
// return args;
// });
// }
// console.log(convertoss["testMethod"].toString());
// var inObj={a:"hello",b:"ok"}
// var p=convertoss["testMethod"].apply(convertoss,["hello","kkkk"]);
// var args=getArgs(convertoss["testMethod"])
// console.log(args);
//var p=convertoss["testMethod"].call(convertoss,["hello"]);
//var p=Reflect.apply(,convertoss,"hello");
// p.then(function(r){
// console.log(r);
// });
// convertoss.convert2pdf(key).then(function(result){
// console.log(result);
// }).catch(function(e){
// console.log(e);
// });
// var routes=[
// {
// path:'/',components:{
// default:componentFactory("products"),
// // shows:demo
// }
// },
// {
// path:'/products/:id/detail',components:{
// default:componentFactory("detail"),
// //shows:demo
// }
// },
// {
// path:'/platform/apps',components:{
// default:componentFactory("apps"),
// //shows:demo
// }
// },
// {
// path:'/platform/users',components:{
// default:componentFactory("users"),
// //shows:demo
// }
// },
// {
// path:'/platform/op/oplogs',components:{
// default:componentFactory("oplogs"),
// //shows:demo
// }
// },
// ]
class TestBase{
constructor(){
this.apiDoc={
group:"逻辑分组",
desc:"请对当前类进行描述",
exam:"概要示例",
methods:[]
};
this.initClassDoc();
}
initClassDoc(){
throw new Error(`
请定义当前类的API文档,重写initClassDoc方法.
在initClassDoc方法中调用如下方法:
1.descClass(groupName,classDesc,exam)增加当前类的描述和使用示例
2.descMethod(methodName,paramName,paramType,defaultValue,paramDesc)增加方法的说明
`);
}
descClass(groupName,classDesc,exam){
this.group=groupName;
this.apiDoc.desc=classDesc;
this.apiDoc.exam=exam;
}
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
}
);
}
}
}
class Test extends TestBase{
constructor(){
super();
}
initClassDoc(){
this.descClass("class desc",`
xxxxxx
xxxxx
xxxxxxxx
`);
this.descMethod("hello",{
pname:"pname1",
ptype:"int",
pdesc:"xccccc"
});
this.descMethod("hello",{
pname:"pname2",
ptype:"str",
pdesc:"xccccyyyc"
});
}
}
class Test2 extends TestBase{
constructor(){
super();
}
initClassDoc(){
this.descClass("class desc222222",`
xxxxxx
xxxxx
xxxxxxxx
`);
this.descMethod("test2hello",{
pname:"pname1",
ptype:"int",
pdesc:"xccccc"
});
this.descMethod("world",{
pname:"pname2",
ptype:"str",
pdesc:"xccccyyyc"
});
}
}
class Test3 extends TestBase{
constructor(){
super();
}
}
module.exports={cls:Test,doc:new Test().apiDoc};
var t1=new Test();
var t2=new Test2();
console.log(t1.apiDoc);
console.log(t2.apiDoc);
技术总监 职位描述
岗位职责:
负责公司基础平台的设计开发
负责公司开发团队的建设
负责制定项目技术方案,负责系统的架构设计、优化,参与核心架构部分代码编写;
负责软件开发任务的需求分析、技术方案设计、开发计划制定,指导项目团队成员的日常开发工作、解决开发中的技术问题;
职位要求
财务软件开发经验者优先
8年以上Javaphp互联网开发经验,5年以上应用架构经验。
熟悉分布式存储、搜索、异步框架、集群与负载均衡,消息中间件等技术;
有大型分布式、高并发、高负载、高可用系统架构、设计、开发和调优经验;
熟悉各种常用设计模式,能将设计模式应用到日常工作。
熟悉至少一种较为常见的主流数据库及SQL语言,有一定的sql调优经验;熟悉Linux操作系统以及常用版本管理软件操作(如:svn,git)
熟悉至少一种nosql数据库
计算机相关专业本科以上学历。
具有良好的沟通表达能力和团队协作能力。
const system = require("../system");
class Dictionary {
constructor() {
// 字典
this.USER = {
UC_TYPE: {"100001": "电子平台", "10000x": "xxxxxxxxxx"},
};
this.ACCOUNT_TRADE = {
trade_type: {1: "交易", 2: "充值", 3: "退款"}
};
}
getDict(module, field) {
return (this[(module || "")] || {})[field] || {};
}
setRowName(module, row, fields, concat) {
if(!module || !row || !fields || fields.length == 0) {
return;
}
concat = concat || "_";
for (let field of fields) {
row[field + concat + "name"] = this.getDict(module, field)[row[field] || ""] || "";
}
}
setRowsName(module, rows, fields, concat) {
if(!module || !rows || !fields || fields.length == 0) {
return;
}
for(let row of rows) {
this.setRowName(module, row, fields, concat)
}
}
}
module.exports = Dictionary;
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