Commit 7d79ea60 by 王昆

gsb

parent e6b20bdf
# Default ignored files
/workspace.xml
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/xgg-saas-merchant.iml" filepath="$PROJECT_DIR$/.idea/xgg-saas-merchant.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
{
"editor.tabSize": 2
}
\ 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] && !(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 {*} gname 组名
* @param {*} methodname 方法名
*/
async isCheckWhiteList(gname, methodname) {
// var fullname = gname + "." + methodname;
// var lst = [
// "test.testApi",
// "inner.registerInner",
// "inner.resetPasswordInner",
// ];
// var x = lst.indexOf(fullname);
// return x >= 0;
return true;
}
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) {
appInfo = await this.cacheManager["ApiAppIdCheckCache"].cache(app_id, null, 3000);
if (!appInfo) {
result.status = system.appidFail;
result.msg = "请求头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 {
//验证accesskey或验签
var isPassResult = await this.checkAcck(gname, methodname, pobj, query, req);
if (isPassResult.status != 0) {
isPassResult.requestid = "";
return isPassResult;
}
if (pobj && pobj.action_body) {
pobj.action_body.merchant_id = pobj.action_body.merchant_id || req.headers["app_id"];
}
if (query) {
query.merchant_id = req.headers["app_id"];
}
var rtn = await this[methodname](pobj, query, req);
rtn.requestid = requestid;
this.oplogSve.createDb({
appid: req.headers["app_id"] || "",
appkey: req.headers["accesskey"] || "",
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: req.headers["app_id"] || "",
appkey: req.headers["accesskey"] || "",
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();
}
/**
* 接口跳转
* action_process 执行的流程
* action_type 执行的类型
* action_body 执行的参数
*/
async springboard(pobj, qobj, req) {
console.log(pobj, pobj.action_type, !pobj.action_type, "--------------------------------------this is xgg admin ----------------------");
if (!pobj.action_process) {
return system.getResult(null, "action_process参数不能为空");
}
if (!pobj.action_type) {
return system.getResult(null, "action_type参数不能为空");
}
var result = null;
switch (pobj.action_process) {
case "sijibao"://司机宝
result = await this.sijibaoOpActionProcess(pobj.action_process, pobj.action_type, pobj.action_body);
break;
default:
result = system.getResult(null, "action_process参数错误");
break;
}
return result;
}
async sijibaoOpActionProcess(action_process, action_type, action_body) {
var opResult = null;
switch (action_type) {
// case "testRechargeAudit":// 发票信息查询接口
// opResult = await this.merchantrechargeSve.apiAudit(action_body);
// break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
exam() {
return `<pre><pre/>`;
}
classDesc() {
return {
groupName: "op",
groupDesc: "元数据服务包",
name: "ActionAPI",
desc: "此类是对外提供接口服务",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: `<pre><pre/>`,
methodName: "springboard",
paramdescs: [
{
paramDesc: "请求的行为,传递如:sijibao",
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();
}
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, res) {
try {
var rtn = await this[methodname](pobj, query, req, res);
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;
const system = require("../system");
const settings = require("../../config/settings");
class CtlBase {
constructor() {
this.restClient = system.getObject("util.restClient");
}
async doexec(methodname, pobj, query, req) {
try {
var rtn = await this[methodname](pobj, query, req);
return rtn;
} catch (e) {
console.log(e.stack);
return system.getResultFail(-200, "Ctl出现异常,请联系管理员");
}
}
encryptPasswd(passwd) {
if (!passwd) {
throw new Error("请输入密码");
}
var md5 = this.md5(passwd + "_" + settings.salt);
return md5.toString().toLowerCase();
}
trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
doTimeCondition(params, fields) {
if (!params || !fields || fields.length == 0) {
return;
}
for (var f of fields) {
if (params[f]) {
var suffix = this.endWith(f, 'Begin') ? " 00:00:00" : " 23:59:59";
params[f] = params[f] + suffix;
}
}
}
endWith(source, str){
if(!str || !source || source.length == 0 || str.length > source.length) {
return false;
}
return source.substring(source.length - str.length) == str;
}
}
module.exports = CtlBase;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const md5 = require("MD5");
const uuidv4 = require('uuid/v4');
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
this.redisClient = system.getObject("util.redisClient");
}
async login(pobj, pobj2, req, res) {
let loginName = this.trim(pobj.loginName);
let password = this.trim(pobj.password);
try {
// 查用户
var loginUser = await this.service.findOne({userName: loginName});
if (!loginUser || loginUser.password != this.encryptPasswd(password)) {
return system.getResult(null, "用户名或密码错误");
}
var sid = await this.setLogin(loginUser);
return system.getResultSuccess(sid);
} catch (error) {
console.log(error);
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async setLogin(user) {
var sid = uuidv4();
sid = "3cb49932-fa02-44f0-90db-9f06fe02e5c7";
await this.redisClient.setWithEx(sid, JSON.stringify(user), 60 * 60);
return sid;
// return bdanalysisid;
}
}
module.exports = UserCtl;
\ No newline at end of file
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
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;
var System = require("../../../system")
const crypto = require('crypto');
var fs = require("fs");
var accesskey = '3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId = 'LTAI4GC5tSKvqsH2hMqj6pvd';
var url = "https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class UploadCtl {
constructor() {
this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 '{fileName}'";
this.restS = System.getObject("util.execClient");
this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'";
//sed -i 's/1111/&BBB/' /tmp/input.txt
//sed 's/{position}/{content}/g' {path}
}
async getOssConfig() {
var policyText = {
"expiration": "2119-12-31T16:00:00.000Z",
"conditions": [
["content-length-range", 0, 1048576000],
["starts-with", "$key", "zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature = crypto.createHmac('sha1', accesskey).update(policyBase64).digest().toString('base64'); //base64
var data = {
OSSAccessKeyId: accessKeyId,
policy: policyBase64,
Signature: signature,
Bucket: 'gsb-zc',
success_action_status: 201,
url: url
};
return data;
};
async upfile(srckey, dest) {
var oss = System.getObject("util.ossClient");
var result = await oss.upfile(srckey, "/tmp/" + dest);
return result;
};
async downfile(srckey) {
var oss = System.getObject("util.ossClient");
var downfile = await oss.downfile(srckey).then(function () {
downfile = "/tmp/" + srckey;
return downfile;
});
return downfile;
};
async pdf2html(obj) {
var srckey = obj.key;
var downfile = await this.downfile(srckey);
var cmd = this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
var rtn = await this.restS.exec(cmd);
var path = "/tmp/" + srckey.split(".pdf")[0] + ".html";
var a = await this.insertToFile(path);
fs.unlink("/tmp/" + srckey);
var result = await this.upfile(srckey.split(".pdf")[0] + ".html", srckey.split(".pdf")[0] + ".html");
return result.url;
};
async insertToFile(path) {
var cmd = this.cmdInsertToFilePattern + " " + path;
return await this.restS.exec(cmd);
};
}
module.exports = UploadCtl;
\ No newline at end of file
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 true;
}
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();
// this.merchantSve = system.getObject("service.merchant.merchantSve");
}
desc() {
return "应用中来访访问appid缓存";
}
prefix() {
return settings.cacheprefix + "_verify_appid:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
// var item = await this.merchantSve.getById(inputkey);
// if (!item && item.data) {
// return null;
// }
// return JSON.stringify(item.data);
}
}
module.exports = ApiAppIdCheckCache;
\ No newline at end of file
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) {
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;
});
}
}
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 getRowCodeName(item, field) {
if (!item || !field) {
return "";
}
var map = this[field + "Map"] || {};
if (!item) {
return "";
}
return 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
}) || [];
}
async getMapByIds(ids, attrs) {
var result = {};
var list = await this.getListByIds(ids, attrs);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
}
module.exports = Dao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class UserDao extends Dao{
constructor(){
super(Dao.getModelName(UserDao));
}
async getAuths(userid){
var self=this;
return this.model.findOne({
where:{id:userid},
include:[{model:self.db.models.account,attributes:["id","isSuper","referrerOnlyCode"]},
{model:self.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:self.db.models.product,as:"Products",attributes:["id","code"]}
]},
],
});
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"]}]};
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// console.log(obj);
// w["app_id"]=obj.appid;
// }
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
async preUpdate(u){
if(u.roles && u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var user=await this.model.findOne({where:{id:obj2.id}});
user.setRoles(obj2.roles);
return user;
}
async findAndCountAll(qobj,t){
var users=await super.findAndCountAll(qobj,t);
return users;
}
async preCreate(u){
// var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(roles);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// u.roles=roles
return u;
}
async create(u,t){
var self=this;
var u2=await this.preCreate(u);
if(t){
return this.model.create(u2,{transaction: t}).then(user=>{
return user;
});
}else{
return this.model.create(u2).then(user=>{
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId,company_only_code,result){
var customerObj={companyOnlyCode:company_only_code};
var putSqlWhere={where:{id:userId}};
this.updateByWhere(customerObj,putSqlWhere);
return result;
}
}
module.exports=UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var glob = require("glob");
class APIDocManager{
constructor(){
this.doc={};
this.buildAPIDocMap();
}
async buildAPIDocMap(){
var self=this;
//订阅任务频道
var apiPath=settings.basepath+"/app/base/api/impl";
var rs = glob.sync(apiPath + "/**/*.js");
if(rs){
for(let r of rs){
// var ps=r.split("/");
// var nl=ps.length;
// var pkname=ps[nl-2];
// var fname=ps[nl-1].split(".")[0];
// var obj=system.getObject("api."+pkname+"."+fname);
var ClassObj=require(r);
var obj=new ClassObj();
var gk=obj.apiDoc.group+"|"+obj.apiDoc.groupDesc
if(!this.doc[gk]){
this.doc[gk]=[];
this.doc[gk].push(obj.apiDoc);
}else{
this.doc[gk].push(obj.apiDoc);
}
}
}
}
}
module.exports=APIDocManager;
const fs=require("fs");
const settings=require("../../../../config/settings");
class CacheManager{
constructor(){
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap(){
var self=this;
self.doc={};
var cachePath=settings.basepath+"/app/base/db/cache/";
const files=fs.readdirSync(cachePath);
if(files){
files.forEach(function(r){
var classObj=require(cachePath+"/"+r);
self[classObj.name]=new classObj();
var refTmp=self[classObj.name];
if(refTmp.prefix){
self.doc[refTmp.prefix]=refTmp.desc;
}
else{
console.log("请在"+classObj.name+"缓存中定义prefix");
}
});
}
}
}
module.exports=CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const Sequelize = require('sequelize');
const settings = require("../../../../config/settings")
const fs = require("fs")
const path = require("path");
var glob = require("glob");
class DbFactory {
constructor() {
const dbConfig = settings.database();
this.db = new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
dbConfig.config);
this.db.Sequelize = Sequelize;
this.db.Op = Sequelize.Op;
this.initModels();
this.initRelations();
}
async initModels() {
var self = this;
var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
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 SynlogDao extends Dao {
constructor() {
super(Dao.getModelName(SynlogDao));
}
}
module.exports = SynlogDao;
\ 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.....");
// });
});
const settings = require("../../../../config/settings");
module.exports = {
"appid": settings.appKey,
"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 },
}
}
}
\ No newline at end of file
module.exports={
"bizName":"oplogs",
"list":{
columnMetaData:[
{"width":"200","label":"应用","prop":"appname","isShowTip":true,"isTmpl":false},
{"width":"200","label":"时间","prop":"created_at","isShowTip":true,"isTmpl":false},
{"width":"100","label":"用户名","prop":"username","isShowTip":true,"isTmpl":false},
{"width":"100","label":"性别","prop":"sex","isShowTip":true,"isTmpl":false},
{"width":"200","label":"行为","prop":"op","isShowTip":true,"isTmpl":false},
{"width":"200","label":"内容","prop":"content","isShowTip":true,"isTmpl":false},
{"width":"200","label":"客户端IP","prop":"clientIp","isShowTip":true,"isTmpl":false},
{"width":"200","label":"客户端环境","prop":"agent","isShowTip":true,"isTmpl":false},
]
},
"form":[
{
"title":"应用名称",
"validProp":"name",
"rule": [
{ "required": true, "message": '请输入应用名称', "trigger": 'blur' },
],
ctls:[
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
{
"title":"应用ID",
"ctls":[
{"type":"input","label":"应用ID","prop":"appid","disabled":true,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"应用名称",
ctls:[
{"type":"input","label":"操作用户","prop":"username","placeHolder":"请模糊输入应用名称","style":""},
]
},
{
"title":"客户环境",
ctls:[
{"type":"input","label":"客户环境","prop":"agent","placeHolder":"请模糊输入客户环境","style":""},
]
},
// {
// "title":"",
// "min":1,
// "max":1,
// ctls:[
// {"type":"check","dicKey":"sex","label":"客户环境","prop":"sex","style":""},
// ]
// },
// <gsb-select v-model="formModel[item.prop]"
// :dicKey="item.dicKey"
// :autoComplete="item.autoComplete"
// :isMulti="item.isMulti"
// :modelName="item.modelName"
// :isFilter="item.isFilter"
// :labelField="item.labelField"
// :valueField="item.valueField"></gsb-select>
{
"title":"性别",
ctls:[
{"type":"select","dicKey":"sex","label":"性别","prop":"sex","labelField":"label","valueField":"value","style":""},
]
},
],
"auth":{
"add":[
],
"edit":[
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isOnGrid":true},
],
"common":[
],
}
}
const fs=require("fs");
const path=require("path");
const appsPath=path.normalize(__dirname+"/apps");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
}
function getBizFilePath(appJson,bizCode){
const filePath=bizsPath+"/"+"bizjs"+"/"+bizCode+".js";
return filePath;
}
//异常日志处理todo
function initAppBizs(appJson){
for(var bizCode in appJson.config.bizs)
{
const bizfilePath=getBizFilePath(appJson,bizCode);
try{
delete require.cache[bizfilePath];
const bizConfig=require(bizfilePath);
appJson.config.bizs[bizCode].config=bizConfig;
}catch(e){
console.log("bizconfig meta file not exist........");
}
}
return appJson;
}
//初始化资源树--objJson是rstree
function initRsTree(appjson,appidfolder,objJson,parentCodePath){
if(!parentCodePath){//说明当前是根结点
objJson.codePath=objJson.code;
}else{
objJson.codePath=parentCodePath+"/"+objJson.code;
}
if(objJson["bizCode"]){//表示叶子节点
objJson.auths=[];
if(appjson.config.bizs[objJson["bizCode"]]){
objJson.bizConfig=appjson.config.bizs[objJson["bizCode"]].config;
objJson.path=appjson.config.bizs[objJson["bizCode"]].path;
appjson.config.bizs[objJson["bizCode"]].codepath=objJson.codePath;
}
}else{
if(objJson.children){
objJson.children.forEach(obj=>{
initRsTree(appjson,appidfolder,obj,objJson.codePath);
});
}
}
}
fs.readdirSync(appsPath).forEach(f=>{
const ff=path.join(appsPath,f);
delete require.cache[ff];
var appJson=require(ff);
appJson= initAppBizs(appJson);
initRsTree(appJson,appJson.appid,appJson.config.rstree,null);
appJsons[appJson.appid]=appJson;
});
module.exports=appJsons;
module.exports={
"appid":"wx76a324c5d201d1a4",
"label":"企业服务工具箱",
"config":{
"rstree":{
"code":"toolroot",
"label":"工具箱",
"children":[
{
"code":"toggleHeader",
"icon":"el-icon-sort",
"isMenu":true,
"label":"折叠",
},
{
"code":"personCenter",
"label":"个人信息",
"src":"/imgs/logo.png",
"isSubmenu":true,
"children":[
{"code":"wallet","isGroup":true,"label":"账户","children":[
{"code":"mytraderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"path":""},
{"code":"smallmoney","label":"钱包","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"fillmoney","label":"充值","isMenu":true,},
]},
{"code":"tool","isGroup":true,"label":"工具","children":[
{"code":"entconfirm","label":"企业用户认证","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"fav","label":"收藏夹","isMenu":true,"bizCode":"fav","bizConfig":null,"path":""},
{"code":"filebox","label":"文件柜","isMenu":true,"bizCode":"filebox","bizConfig":null,"path":""},
]},
],
},
{
"code":"fillmoney",
"icon":"fa fa-money",
"isMenu":true,
"label":"充值",
},
{
"code":"platformop",
"label":"平台运营",
"icon":"fa fa-cubes",
"isSubmenu":true,
"children":[
{"code":"papp","isGroup":true,"label":"平台数据","children":[
{"code":"papparch","label":"应用档案","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"userarch","label":"用户档案","isMenu":true,"bizCode":"pusers","bizConfig":null,"path":""},
{"code":"traderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"qp":"my","path":""},
{"code":"pconfigs","label":"平台配置","isMenu":true,"bizCode":"pconfigs","bizConfig":null,"qp":"my","path":""},
]},
{"code":"pop","isGroup":true,"label":"平台运维","children":[
{"code":"cachearch","label":"缓存档案","isMenu":true,"bizCode":"cachearches","bizConfig":null,"path":""},
{"code":"oplogmag","label":"行为日志","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"machinearch","label":"机器档案","isMenu":true,"bizCode":"machines","bizConfig":null,"path":""},
{"code":"codezrch","label":"代码档案","isMenu":true,"bizCode":"codezrch","bizConfig":null,"path":""},
{"code":"imagearch","label":"镜像档案","isMenu":true},
{"code":"containerarch","label":"容器档案","isMenu":true},
]},
],
},
{
"code":"sysmag",
"label":"系统管理",
"icon":"fa fa-cube",
"isSubmenu":true,
"children":[
{"code":"usermag","isGroup":true,"label":"用户管理","children":[
{"code":"rolearch","label":"角色档案","isMenu":true,"bizCode":"roles","bizConfig":null},
{"code":"appuserarch","label":"用户档案","isMenu":true,"bizCode":"appusers","bizConfig":null},
]},
{"code":"productmag","isGroup":true,"label":"产品管理","children":[
{"code":"productarch","label":"产品档案","bizCode":"mgproducts","isMenu":true,"bizConfig":null},
{"code":"products","label":"首页产品档案","bizCode":"products","isMenu":false,"bizConfig":null},
]},
],
},
{
"code":"exit",
"icon":"fa fa-power-off",
"isMenu":true,
"label":"退出",
},
{
"code":"toolCenter",
"label":"工具集",
"src":"/imgs/logo.png",
"isSubmenu":false,
"isMenu":false,
"children":[
{"code":"tools","isGroup":true,"label":"查询工具","children":[
{"code":"xzquery","label":"续展查询","bizCode":"xzsearch","bizConfig":null,"path":""},
{"code":"xzgqquery","label":"续展过期查询","bizCode":"xzgqsearch","bizConfig":null,"path":""},
]},
],
},
],
},
"bizs":{
"cachearches":{"title":"首页产品档案","config":null,"path":"/platform/cachearches","comname":"cachearches"},
"products":{"title":"首页产品档案","config":null,"path":"/","comname":"products"},
"mgproducts":{"title":"产品档案","config":null,"path":"/platform/mgproducts","comname":"mgproducts"},
"codezrch":{"title":"代码档案","config":null,"path":"/platform/codezrch","comname":"codezrch"},
"machines":{"title":"机器档案","config":null,"path":"/platform/machines","comname":"machines"},
"pconfigs":{"title":"平台配置","config":null,"path":"/platform/pconfigs","comname":"pconfigs"},
"apps":{"title":"应用档案","config":null,"path":"/platform/apps","comname":"apps"},
"roles":{"title":"角色档案","config":null,"path":"/platform/roles","comname":"roles"},
"pusers":{"title":"平台用户档案","config":null,"path":"/platform/pusers","comname":"users"},
"appusers":{"title":"某应用用户档案","config":null,"path":"/platform/appusers","comname":"users"},
"oplogs":{"title":"行为日志","config":null,"path":"/platform/op/oplogs","comname":"oplogs"},
"trades":{"title":"交易记录","config":null,"path":"/platform/uc/trades","comname":"trades"},
"xzsearch":{"title":"续展查询","config":null,"isDynamicRoute":true,"path":"/products/xzsearch","comname":"xzsearch"},
"xzgqsearch":{"title":"续展过期查询","config":null,"isDynamicRoute":true,"path":"/products/xzgqsearch","comname":"xzgqsearch"},
},
"pauths":[
"add","edit","delete","export","show"
],
"pdict":{
"sex":{"male":"男","female":"女"},
"configType":{"price":"宝币兑换率","initGift":"初次赠送"},
"productCata":{"ip":"知产","ic":"工商","tax":"财税","hr":"人力","common":"常用"},
"logLevel":{"debug":0,"info":1,"warn":2,"error":3,"fatal":4},
"tradeType":{"fill":"充值","consume":"消费","gift":"赠送","giftMoney":"红包","refund":"退款"},
"tradeStatus":{"unSettle":"未结算","settled":"已结算"}
}
}
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("user", {
ucid: {
type:DataTypes.INTEGER,
allowNull: false,
},
ucname: {
type:DataTypes.STRING,
allowNull: false,
},
lastLoginTime: {
type:DataTypes.DATE,
allowNull: true,
},
passwd: DataTypes.STRING,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
// freezeTableName: true,
// define the table's name
tableName: 'xgg_admin_user',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("oplog", {
appid: DataTypes.STRING,
appkey: DataTypes.STRING,
requestId: DataTypes.STRING,
logLevel: {
type: DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.logLevel),
defaultValue: "info",
},
op: DataTypes.STRING,
content: DataTypes.STRING(5000),
resultInfo: DataTypes.TEXT,
clientIp: DataTypes.STRING,
agent: {
type: DataTypes.STRING,
allowNull: true,
},
opTitle: DataTypes.STRING(500),
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt: false,
//freezeTableName: true,
// define the table's name
tableName: 'xgg_op_log',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("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("synlog", {
apiUrl: DataTypes.STRING,
apiName: DataTypes.STRING,
apiReq: DataTypes.STRING,
apiRes: DataTypes.STRING,
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'xgg_syn_log',
validate: {},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
\ No newline at end of file
const system=require("../system")
const logCtl=system.getObject("web.common.oplogCtl");
class TaskBase{
constructor(className){
this.redisClient=system.getObject("util.redisClient");
this.serviceName=className;
}
async doTask(){
try {
await this.subDoTask();
//日志记录
logCtl.info({
optitle:this.serviceName+",任务成功执行完成",
op:"base/db/task.base.js",
content:"",
clientIp:""
});
} catch (e) {
//日志记录
logCtl.error({
optitle:this.serviceName+"任务执行异常",
op:"base/db/task.base.js",
content:e.stack,
clientIp:""
});
}
}
async subDoTask(){
console.log("请在子类中重写此方法进行操作业务逻辑............................!");
}
static getServiceName(ClassObj){
return ClassObj["name"];
}
}
module.exports=TaskBase;
const TaskBase=require("../task.base");
class TestTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(TestTask));
}
async subDoTask(){
console.log("TestTask1.....");
}
}
module.exports=TestTask;
const TaskBase=require("../task.base");
class TestTask extends TaskBase{
constructor(){
super();
}
async doTask(){
console.log("TestTask.....");
}
}
module.exports=TestTask;
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
constructor() {
super("auth", ServiceBase.getDaoName(UserService));
}
}
module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const system = require("../../../system");
const ServiceBase = require("../../svems.base")
const settings = require("../../../../config/settings")
class BusinessmenService extends ServiceBase {
constructor() {
super();
}
async allPage(params) {
let rs = await this.callms("order", "businessmenPage", params);
if (rs.status != 0 || !rs.data || !rs.data.rows) {
return rs;
}
this.transField(rs.data.rows);
return rs;
}
async mapByCreditCodes(params) {
let rs = await this.callms("order", "businessmenMapByCreditCodes", params);
if(!rs || !rs.data) {
return {};
}
return rs.data;
}
transField(rows) {
if (!rows) {
return;
}
for (var row of rows) {
row.costRate = system.f2y(row.costRate);
row.taxRate = system.f2y(row.taxRate);
row.serviceRate = system.f2y(row.serviceRate);
row.serviceBeginTime = system.f2y(row.serviceRate);
row.serviceRate = system.f2y(row.serviceRate);
this.handleDate(row, ["service_begin_time", "service_end_time", "tax_reg_day", "reg_date", "sign_time"], "YYYY-MM-DD", -8);
this.parseJsonField(row, ["common_tax_ladder", "common_other_ladder", "special_tax_ladder", "special_other_ladder"]);
}
}
parseJsonField(row, fields) {
if (!row || !fields || fields.length == 0) {
return;
}
for (var f of fields) {
if (!f) {
continue;
}
if (!row[f]) {
row[f] = [];
continue;
}
try {
row[f] = JSON.parse(row[f]);
} catch (error) {
console.log(error);
}
}
}
}
module.exports = BusinessmenService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
\ No newline at end of file
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
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 moment = require('moment')
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
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";
if (!row) {
return;
}
for (var field of fields) {
if (row[field]) {
if (addHours) {
row[field] = moment(row[field]).add(addHours, "hours").format(pattern);
} else {
row[field] = moment(row[field]).format(pattern);
}
}
}
}
addWhereTime(where, field, begin, end) {
if (!begin && !end) {
return;
}
if (begin && end) {
where[field] = {
[this.db.Op.between]: [begin, end]
};
} else if (begin && !end) {
where[field] = {
[this.db.Op.gte]: begin
};
} else if (!begin && end) {
where[field] = {
[this.db.Op.lte]: end
};
}
}
trim(o) {
if (!o) {
return "";
}
return o.toString().trim();
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
}
module.exports = ServiceBase;
\ No newline at end of file
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": "xgg-saas-platform",
"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;
\ No newline at end of file
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 toFloat(f, digits) {
digits = digits || 2;
if (!f) {
return 0;
}
return parseFloat((Number(f)).toFixed(digits));
}
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 endWith(source, str){
if(!str || !source || source.length == 0 || str.length > source.length) {
return false;
}
return source.substring(source.length - str.length) == str;
}
static microsetting() {
console.log(settings.env, "-------------- microsetting env ------------------");
var path = "/api/op/action/springboard";
if (settings.env == "dev") {
// var domain = "http://192.168.18.237";
let local = "http://127.0.0.1";
let dev = "http://39.107.234.14";
return {
// 公共服务
common: dev + ":3102" + path,
// 商户服务
merchant: local + ":3101" + path,
// 订单服务
order: dev + ":3103" + path,
// 发票服务
invoice: dev + ":3105" + path,
// 用户服务
uc: dev + ":3106" + path,
// 交易
trade: dev + ":3107" + path,
}
} else {
return {
common: "xggsvecommon-service" + path,
merchant: "xggsvemerchant-service" + 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;
// 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数据库
计算机相关专业本科以上学历。
具有良好的沟通表达能力和团队协作能力。
var excel = require('exceljs');
const system=require("../system");
const uuidv4 = require('uuid/v4');
const fs=require("fs");
class ExcelClient {
constructor() {
this.columns = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
this.ossClient=system.getObject("util.ossClient");
this.filedownloadDao = system.getObject("db.filedownloadDao");
}
async download(params) {
var self = this;
var title = params.title || "";
var code = params.code || uuidv4();
var fileName = params.fileName || code + ".xlsx";
var filePath = params.filePath || "/tmp/" + fileName;
var rows = params.rows || [];
var user = params.user || {};
var wb = new excel.Workbook();
wb.properties.date1904 = true;
var sheet = wb.addWorksheet("sheet1");
var headers = rows[0];
console.log(headers, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2 headers");
if(title) {
sheet.addRow([title]);
sheet.getCell("A1").font = {
    name: '微软雅黑',
    family: 4,
    size: 12,
    bold: true
};
sheet.getCell('A1').alignment = { vertical: 'middle', horizontal: 'center' };
var colkey = 0;
if(headers.length > 0) {
colkey = headers.length - 1;
}
var endColumn = this.columns[colkey] || "A";
sheet.mergeCells("A1:" + endColumn + "1");
}
for(var r of rows) {
sheet.addRow(r);
}
wb.xlsx.writeFile(filePath).then(async function(d) {
var rtn = await self.ossClient.upfile(fileName, filePath);
fs.unlink(filePath,function(err){});
var obj = {
user_id : user.id || 0,
userName : user.userName || "",
code : code,
fileName : fileName,
filePath : rtn.url || "",
isDownload : false,
}
var obj = await self.filedownloadDao.create(obj);
});
}
}
module.exports = ExcelClient;
var childproc = require('child_process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
class ExecClient {
constructor() {
this.cmdPostPattern = "curl -k -H 'Content-type: application/json' -d '{data}' {url}";
this.cmdGetPattern = "curl -G -X GET '{url}'";
}
async exec(cmd) {
//await后面表达式返回的promise对象,是then的语法糖,await返回then函数的返回值
//异常需要try/catch自己捕获或外部catch捕获
const {stdout, stderr} = await exec(cmd);
return {stdout, stderr};
}
async exec2(cmd) {
return exec(cmd, {encoding: "base64"});
}
FetchPostCmd(subData, url) {
var data = JSON.stringify(subData);
var cmd = this.cmdPostPattern.replace(/\{data\}/g,
data).replace(/\{url\}/g, url);
console.log(cmd);
return cmd;
}
async execPost(subData, url) {
let cmd = this.FetchPostCmd(subData, url);
var result = await this.exec(cmd);
return result;
}
async execPost2(subData, url) {
let cmd = this.FetchPostCmd(subData, url);
var result = await this.exec2(cmd);
return result;
}
FetchGetCmd(subData, url) {
var cmd = this.cmdGetPattern.replace(
/\{data\}/g, subData).replace(/\{url\}/g, url);
console.log(cmd);
return cmd;
}
async execGet(subData, url) {
let cmd = this.FetchGetCmd(subData, url);
console.log(cmd);
var result = await this.exec(cmd);
return result;
}
async execGet2(subData, url) {
let cmd = this.FetchGetCmd(subData, url);
console.log(cmd);
var result = await this.exec2(cmd);
return result;
}
async execGetTimeOut(subData, url, timeOut = 5000) {
//timeOut,单位是毫秒
let cmd = this.FetchGetCmd(subData, url);
var options = {
timeout: timeOut,
};
const {stdout, stderr} = await exec(cmd, options);
return {stdout, stderr};
}
}
module.exports = ExecClient;
// var x=new RestClient();
// x.execGet("","http://www.163.com").then(function(r){
// console.log(r.stdout);
// console.log(r.stderr);
// });
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