Commit 173e833e by 王昆

gsb

parent b7bb986a
const system = require("../system");
const settings = require("../../config/settings");
const DocBase = require("./doc.base");
const uuidv4 = require('uuid/v4');
const md5 = require("MD5");
class APIBase extends DocBase {
constructor() {
super();
this.cacheManager = system.getObject("db.common.cacheManager");
this.logCtl = system.getObject("web.common.oplogCtl");
this.oplogSve = system.getObject("service.common.oplogSve");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
/**
* 验证签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async verifySign(params, app_key) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!params.sign) {
return system.getResult(null, "请求参数sign为空");
}
if (!params.times_tamp) {
return system.getResult(null, "请求参数times_tamp为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey]) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResult(null, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
if (params.sign != resultTmpSign) {
return system.getResult(null, "签名验证失败");
}
return system.getResultSuccess();
}
/**
* 白名单验证
* @param {*} gname 组名
* @param {*} methodname 方法名
*/
async isCheckWhiteList(gname, methodname) {
var fullname = gname + "." + methodname;
var lst = [
"test.testApi"
];
var x = lst.indexOf(fullname);
return x >= 0;
}
async checkAcck(gname, methodname, pobj, query, req) {
var appInfo = null;
var result = system.getResultSuccess();
var ispass = await this.isCheckWhiteList(gname, methodname);
var appkey = req.headers["accesskey"];
var app_id = req.headers["app_id"];
if (ispass) {
return result;
}//在白名单里面
if (app_id) {
// var signResult = await this.verifySign(pobj.action_body, appInfo.appSecret);
// if (signResult.status != 0) {
// result.status = system.signFail;
// result.msg = signResult.msg;
// }
}//验签
else if (appkey) {
appInfo = await this.cacheManager["ApiAccessKeyCheckCache"].cache(appkey, { status: true }, 3000);
if (!appInfo || !appInfo.app) {
result.status = system.tokenFail;
result.msg = "请求头accesskey失效,请重新获取";
}
}//验证accesskey
else {
result.status = -1;
result.msg = "请求头没有相关访问参数,请验证后在进行请求";
}
return result;
}
async doexec(gname, methodname, pobj, query, req) {
var requestid = this.getUUID();
try {
var rtn = await this[methodname](pobj, query, req);
rtn.requestid = requestid;
this.oplogSve.createDb({
appid: req.headers["app_id"] || "",
appkey: "",
requestId: requestid,
op: req.classname + "/" + methodname,
content: JSON.stringify(pobj),
resultInfo: JSON.stringify(rtn),
clientIp: req.clientIp,
agent: req.uagent,
opTitle: "api服务提供方appKey:" + settings.appKey,
});
return rtn;
} catch (e) {
console.log(e.stack, "api调用出现异常,请联系管理员..........")
this.logCtl.error({
appid: "" + pobj.action_process,
appkey: "",
requestId: requestid,
op: pobj.classname + "/" + methodname,
content: e.stack,
clientIp: pobj.clientIp,
agent: req.uagent,
optitle: "api调用出现异常,请联系管理员",
});
var rtnerror = system.getResultFail(-200, "出现异常,请联系管理员");
rtnerror.requestid = requestid;
return rtnerror;
}
}
}
module.exports = APIBase;
const system=require("../system");
const uuidv4 = require('uuid/v4');
class DocBase{
constructor(){
this.apiDoc={
group:"逻辑分组",
groupDesc:"",
name:"",
desc:"请对当前类进行描述",
exam:"概要示例",
methods:[]
};
this.initClassDoc();
}
initClassDoc(){
this.descClass();
this.descMethods();
}
descClass(){
var classDesc= this.classDesc();
this.apiDoc.group=classDesc.groupName;
this.apiDoc.groupDesc=classDesc.groupDesc;
this.apiDoc.name=classDesc.name;
this.apiDoc.desc=classDesc.desc;
this.apiDoc.exam=this.examHtml();
}
examHtml(){
var exam= this.exam();
exam=exam.replace(/\\/g,"<br/>");
return exam;
}
exam(){
throw new Error("请在子类中定义类操作示例");
}
classDesc(){
throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构
{
groupName:"auth",
groupDesc:"认证相关的包"
desc:"关于认证的类",
exam:"",
}
`);
}
descMethods(){
var methoddescs=this.methodDescs();
for(var methoddesc of methoddescs){
for(var paramdesc of methoddesc.paramdescs){
this.descMethod(methoddesc.methodDesc,methoddesc.methodName
,paramdesc.paramDesc,paramdesc.paramName,paramdesc.paramType,
paramdesc.defaultValue,methoddesc.rtnTypeDesc,methoddesc.rtnType);
}
}
}
methodDescs(){
throw new Error(`
请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[
{
methodDesc:"生成访问token",
methodName:"getAccessKey",
paramdescs:[
{
paramDesc:"访问appkey",
paramName:"appkey",
paramType:"string",
defaultValue:"x",
},
{
paramDesc:"访问secret",
paramName:"secret",
paramType:"string",
defaultValue:null,
}
],
rtnTypeDesc:"xxxx",
rtnType:"xxx"
}
]
`);
}
descMethod(methodDesc,methodName,paramDesc,paramName,paramType,defaultValue,rtnTypeDesc,rtnType){
var mobj=this.apiDoc.methods.filter((m)=>{
if(m.name==methodName){
return true;
}else{
return false;
}
})[0];
var param={
pname:paramName,
ptype:paramType,
pdesc:paramDesc,
pdefaultValue:defaultValue,
};
if(mobj!=null){
mobj.params.push(param);
}else{
this.apiDoc.methods.push(
{
methodDesc:methodDesc?methodDesc:"",
name:methodName,
params:[param],
rtnTypeDesc:rtnTypeDesc,
rtnType:rtnType
}
);
}
}
}
module.exports=DocBase;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class ConfigAPI extends APIBase {
constructor() {
super();
this.metaS = system.getObject("service.common.metaSve");
}
//返回
async fetchAppConfig(pobj, qobj, req) {
var cfg = await this.metaS.getUiConfig(settings.appKey, null, 100);
if (cfg) {
return system.getResultSuccess(cfg);
}
return system.getResultFail();
}
exam(){
return "xxx";
}
classDesc() {
return {
groupName: "",
groupDesc: "",
name: "",
desc: "",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "",
methodName: "",
paramdescs: [
{
paramDesc: "",
paramName: "",
paramType: "",
defaultValue: "",
}
],
rtnTypeDesc: "",
rtnType: ""
}
];
}
}
module.exports = ConfigAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class OpCacheAPI extends APIBase {
constructor() {
super();
this.cacheSve = system.getObject("service.common.cacheSve");
}
//返回
async opCacheData(pobj, qobj, req) {
if (pobj.action_type == "findAndCountAll") {
return await this.cacheSve.findAndCountAll(pobj.body);
} else if (pobj.action_type == "delCache") {
return await this.cacheSve.delCache(pobj.body);
} else if (pobj.action_type == "clearAllCache") {
return await this.cacheSve.clearAllCache(pobj.body);
} else {
return system.getResultFail();
}
}
exam() {
return "xxx";
}
classDesc() {
return {
groupName: "",
groupDesc: "",
name: "",
desc: "",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "",
methodName: "",
paramdescs: [
{
paramDesc: "",
paramName: "",
paramType: "",
defaultValue: null,
}
],
rtnTypeDesc: "",
rtnType: ""
}
];
}
// exam() {
// return "";
// }
// classDesc() {
// return {
// groupName: "",
// groupDesc: "",
// name: "",
// desc: "",
// exam: "",
// };
// }
// methodDescs() {
// return [
// {
// methodDesc: "",
// methodName: "",
// paramdescs: [
// {
// paramDesc: "",
// paramName: "",
// paramType: "",
// defaultValue: "",
// }
// ],
// rtnTypeDesc: "",
// rtnType: ""
// }
// ];
// }
}
module.exports = OpCacheAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class ActionAPI extends APIBase {
constructor() {
super();
this.domicileSve = system.getObject("service.common.domicileSve");
this.businessscopeSve = system.getObject("service.common.businessscopeSve");
this.captchaSve = system.getObject("service.common.captchaSve");
this.deliverSve = system.getObject("service.deliver.deliverSve");
this.invoicecontentSve = system.getObject("service.common.invoicecontentSve");
}
/**
* 接口跳转
* action_process 执行的流程
* action_type 执行的类型
* action_body 执行的参数
*/
async springboard(pobj, qobj, req) {
var result;
if (!pobj.action_process) {
return system.getResult(null, "action_process参数不能为空");
}
if (!pobj.action_type) {
return system.getResult(null, "action_type参数不能为空");
}
try {
result = await this.handleRequest(pobj.action_process, pobj.action_type, pobj.action_body);
} catch (error) {
console.log(error);
}
return result;
}
async handleRequest(action_process, action_type, action_body) {
var opResult = null;
switch (action_type) {
// 图片验证码
case "getCaptha":
opResult = await this.captchaSve.apiGenerate(action_body);
break;
case "validCaptha":
opResult = await this.captchaSve.apiValidator(action_body);
break;
// 注册地
case "domicileNameList":
opResult = await this.domicileSve.apiNameList(action_body);
break;
case "domicileTree":
opResult = await this.domicileSve.apiTree(action_body);
break;
case "domicilePage":
opResult = await this.domicileSve.apiPage(action_body);
break;
case "domicileSave":
opResult = await this.domicileSve.apiSave(action_body);
break;
case "domicileInfo":
opResult = await this.domicileSve.apiInfo(action_body);
break;
case "domicileDelete":
opResult = await this.domicileSve.apiDeleteByIds(action_body);
break;
// 经营范围
case "businessscopeByDomicileId":
opResult = await this.businessscopeSve.apiDomicileList(action_body);
break;
case "businessscopePage":
opResult = await this.businessscopeSve.apiPage(action_body);
break;
case "businessscopeSave":
opResult = await this.businessscopeSve.apiSave(action_body);
break;
case "businessscopeInfo":
opResult = await this.businessscopeSve.apiInfo(action_body);
break;
case "businessscopeDelete":
opResult = await this.businessscopeSve.apiDeleteByIds(action_body);
break;
// 交付商
case "deliverAll":
opResult = await this.deliverSve.apiAll(action_body);
break;
case "deliverPage":
opResult = await this.deliverSve.apiPage(action_body);
break;
case "deliverSave":
opResult = await this.deliverSve.apiSave(action_body);
break;
case "deliverInfo":
opResult = await this.deliverSve.apiInfo(action_body);
break;
case "deliverDelete":
opResult = await this.deliverSve.apiDeleteByIds(action_body);
break;
// 发票内容
case "invoicecontentSave":
opResult = await this.invoicecontentSve.apiSave(action_body);
break;
case "invoicecontentDelete":
opResult = await this.invoicecontentSve.apiDelete(action_body);
break;
case "invoiceList":
opResult = await this.invoicecontentSve.apiList(action_body);
break;
case "invoicecontent":
opResult = await this.invoicecontentSve.apiGetById(action_body);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
exam() {
return `<pre><pre/>`;
}
classDesc() {
return {
groupName: "op",
groupDesc: "元数据服务包",
name: "ActionAPI",
desc: "此类是对外提供接口服务",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: `<pre><pre/>`,
methodName: "springboard",
paramdescs: [
{
paramDesc: "请求的行为,传递如:sjb",
paramName: "action_process",
paramType: "string",
defaultValue: null,
},
{
paramDesc: "业务操作类型,详情见方法中的描述",
paramName: "action_type",
paramType: "string",
defaultValue: null,
},
{
paramDesc: "业务操作类型的参数,action_body必须传递的参数有,times_tamp(时间戳,类型int)、sign(签名,类型string),其余的为业务需要的参数",
paramName: "action_body",
paramType: "json",
defaultValue: null,
}
],
rtnTypeDesc: `<pre><pre/>`,
rtnType: `<pre><pre/>`
}
];
}
}
module.exports = ActionAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
class TestAPI extends APIBase {
constructor() {
super();
this.orderSve = system.getObject("service.order.orderSve");
this.platformUtils = system.getObject("util.businessManager.opPlatformUtils");
}
async test(pobj, query, req) {
// var tmp = await this.orderSve.createLicense(pobj.action_body);
//获取验证码
// await this.platformUtils.fetchVCode(pobj.action_body.mobile);
//创建用户
// var result = await this.platformUtils.createUserInfo("13075556691", "13075556693", "9366");
//创建用户
var result = await this.platformUtils.login("13075556691", "9366");
return result;
}
exam() {
return "";
}
classDesc() {
return {
groupName: "",
groupDesc: "",
name: "",
desc: "",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "",
methodName: "",
paramdescs: [
{
paramDesc: "",
paramName: "",
paramType: "",
defaultValue: "",
}
],
rtnTypeDesc: "",
rtnType: ""
}
];
}
}
module.exports = TestAPI;
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings");
class CtlBase {
constructor(gname, sname) {
this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname);
this.cacheManager = system.getObject("db.common.cacheManager");
this.md5 = require("MD5");
}
encryptPasswd(passwd) {
if (!passwd) {
throw new Error("请输入密码");
}
var md5 = this.md5(passwd + "_" + settings.salt);
return md5.toString().toLowerCase();
}
notify(req, msg) {
if (req.session) {
req.session.bizmsg = msg;
}
}
async findOne(queryobj, qobj) {
var rd = await this.service.findOne(qobj);
return system.getResult(rd, null);
}
async findAndCountAll(queryobj, obj, req) {
obj.codepath = req.codepath;
if (req.session.user) {
obj.uid = req.session.user.id;
obj.appid = req.session.user.app_id;
obj.onlyCode = req.session.user.unionId;
obj.account_id = req.session.user.account_id;
obj.ukstr = req.session.user.app_id + "¥" + req.session.user.id + "¥" + req.session.user.nickName + "¥" + req.session.user.headUrl;
}
var apps = await this.service.findAndCountAll(obj);
return system.getResult(apps, null);
}
async refQuery(queryobj, qobj) {
var rd = await this.service.refQuery(qobj);
return system.getResult(rd, null);
}
async bulkDelete(queryobj, ids) {
var rd = await this.service.bulkDelete(ids);
return system.getResult(rd, null);
}
async delete(queryobj, qobj) {
var rd = await this.service.delete(qobj);
return system.getResult(rd, null);
}
async create(queryobj, qobj, req) {
if (req && req.session && req.session.app) {
qobj.app_id = req.session.app.id;
qobj.onlyCode = req.session.user.unionId;
if (req.codepath) {
qobj.codepath = req.codepath;
}
}
var rd = await this.service.create(qobj);
return system.getResult(rd, null);
}
async update(queryobj, qobj, req) {
if (req && req.session && req.session.user) {
qobj.onlyCode = req.session.user.unionId;
}
if (req.codepath) {
qobj.codepath = req.codepath;
}
var rd = await this.service.update(qobj);
return system.getResult(rd, null);
}
static getServiceName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async initNewInstance(queryobj, req) {
return system.getResult({}, null);
}
async findById(oid) {
var rd = await this.service.findById(oid);
return system.getResult(rd, null);
}
async timestampConvertDate(time) {
if (time == null) {
return "";
}
var date = new Date(Number(time * 1000));
var y = 1900 + date.getYear();
var m = "0" + (date.getMonth() + 1);
var d = "0" + date.getDate();
return y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
}
async universalTimeConvertLongDate(time) {
if (time == null) {
return "";
}
var d = new Date(time);
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}
async universalTimeConvertShortDate(time) {
if (time == null) {
return "";
}
var d = new Date(time);
return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
}
async doexec(methodname, pobj, query, req) {
try {
var rtn = await this[methodname](pobj, query, req);
return rtn;
} catch (e) {
console.log(e.stack);
// this.logCtl.error({
// optitle: "Ctl调用出错",
// op: pobj.classname + "/" + methodname,
// content: e.stack,
// clientIp: pobj.clientIp
// });
return system.getResultFail(-200, "Ctl出现异常,请联系管理员");
}
}
trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
doTimeCondition(params, fields) {
if (!params || !fields || fields.length == 0) {
return;
}
for (var f of fields) {
if (params[f]) {
var suffix = this.endWith(f, 'Begin') ? " 00:00:00" : " 23:59:59";
params[f] = params[f] + suffix;
}
}
}
endWith(source, str){
if(!str || !source || source.length == 0 || str.length > source.length) {
return false;
}
return source.substring(source.length - str.length) == str;
}
}
module.exports = CtlBase;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const uuidv4 = require('uuid/v4');
var svgCaptcha = require('svg-captcha');
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
this.captchaPrev = "xgg_captcha_";
this.redisClient = system.getObject("util.redisClient");
}
async captcha(qobj, pobj, req) {
var uuid = uuidv4();
var key = uuid.replace(/\-/g, "");
var options = {
size: 4,
noise: 1,
ignoreChars: '0o1i'
};
options.width = this.trim(qobj.width) || 120;
options.height = this.trim(qobj.height) || 32;
options.background = this.trim(qobj.background) || "#E8E8E8";
try {
var redisKey = this.captchaPrev + key;
var cap = svgCaptcha.create(options);
console.log(cap);
await this.redisClient.setWithEx(redisKey, cap.text, 3 * 60);
return system.getResultSuccess({
key: key,
captcha: cap.data,
});
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async smsCode(qobj, pobj, req) {
var mobile = this.trim(qobj.mobile);
// var captchaKey = this.trim(qobj.captchaKey);
// var captchaCode = this.trim(qobj.captchaCode);
try {
if (!/^1[23456789]\d{9}$/.test(mobile)) {
return system.getResult(null, "手机号码格式不正确");
}
// var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";
// if (!code) {
// return system.getResult(null, "图片验证码过期,请刷新重试");
// }
// if (code.toLowerCase() != captchaCode.toLowerCase()) {
// await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
// return system.getResult(null, "图片验证码不一致,请刷新重试");
// }
// TODO 发送短信验证码
return system.getResultSuccess("发送成功");
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async login(qobj, pobj, req, res) {
var loginName = this.trim(pobj.loginName);
var password = this.trim(pobj.password);
var captchaKey = this.trim(qobj.captchaKey);
var captchaCode = this.trim(qobj.captchaCode);
try {
// var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";
// if (!code) {
// return system.getResult(null, "图片验证码过期,请点击重试");
// }
// if (code.toLowerCase() != captchaCode.toLowerCase()) {
// await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
// return system.getResult(null, "图片验证码不一致,请点击重试");
// }
var adminUser = await this.service.findById(1);
adminUser.lastLoginTime = new Date();
await adminUser.save();
var xggadminsid = uuidv4();
xggadminsid = "3cb49932-fa02-44f0-90db-9f06fe02e5c7";
await this.redisClient.setWithEx(xggadminsid, JSON.stringify(adminUser), 60 * 60 * 2);
// 处理登录逻辑
var result = {
xggadminsid: xggadminsid,
}
return system.getResultSuccess(result);
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async forgetPassword(qobj, pobj, req, res) {
var mobile = this.trim(pobj.mobile);
var vcode = this.trim(pobj.vcode);
var password = this.trim(qobj.password);
try {
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async currentUser(qobj, pobj, req) {
return system.getResultSuccess(req.loginUser);
}
async getMenu(qobj, pobj, req) {
var menu = [
{"name": "首页", "path": "/", "submenu": [] },
{
"name": "商户中心",
"path": "/merchants",
"submenu": [{"name": "客户管理", "team": [{"name": "商户信息", "path": "/merchants/businessInformation"}, {"name": "签约信息", "path": "/merchants/contractInformation"} ] } ]
}, {
"name": "交易中心",
"path": "/trading",
"submenu": [{"name": "资金管理", "team": [{"name": "资金账户", "path": "/trading/capitalAccount"}, {"name": "充值申请", "path": "/trading/topUpApplication"}, {"name": "资金交易", "path": "/trading/cashTransactions"}, {"name": "资金流水", "path": "/trading/capitalFlows"} ] }, {"name": "订单管理", "team": [{"name": "订单信息", "path": "/trading/orderInformation"} ] }, {"name": "用户管理", "team": [{"name": "用户信息", "path": "/trading/userInformation"}, {"name": "用户签约", "path": "/trading/usersSignUp"} ] } ]
}, {
"name": "财务中心",
"path": "/financial",
"submenu": [{"name": "发票管理", "team": [{"name": "发票申请", "path": "/financial/invoiceApplyFor"}, {"name": "发票管理", "path": "/financial/invoiceManagement"} ] } ]
}, {
"name": "数据中心",
"path": "/information",
"submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] } ]
}, {
"name": "系统中心",
"path": "/system",
"submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] }
]
}
]
return system.getResultSuccess(menu);
}
/**
* 开放平台回调处理
* @param {*} req
*/
async authByCode(req) {
var opencode = req.query.code;
var user = await this.service.authByCode(opencode);
if (user) {
req.session.user = user;
} else {
req.session.user = null;
}
//缓存opencode,方便本应用跳转到其它应用
// /auth?code=xxxxx,缓存没有意义,如果需要跳转到其它应用,需要调用
//平台开放的登录方法,返回 <待跳转的目标地址>/auth?code=xxxxx
//this.cacheManager["OpenCodeCache"].cacheOpenCode(user.id,opencode);
return user;
}
async navSysSetting(pobj, qobj, req) {
//开始远程登录,返回code
var jumpobj = await this.service.navSysSetting(req.session.user);
if (jumpobj) {
return system.getResultSuccess(jumpobj);
}
return system.getResultFail();
}
async loginUser(qobj, pobj, req) {
return super.findById(req.session.user.id);
}
async initNewInstance(queryobj, req) {
var rtn = {};
rtn.roles = [];
if (rtn) {
return system.getResultSuccess(rtn);
}
return system.getResultFail();
}
async checkLogin(gobj, qobj, req) {
//当前如果缓存中存在user,还是要检查当前user所在的域名,如果不和来访一致,则退出重新登录
if (req.session.user) {
var x = null;
if (req.session.user.Roles) {
x = req.session.user.Roles.map(r => {
return r.code
});
}
var tmp = {
id: req.session.user.id,
userName: req.session.user.userName,
nickName: req.session.user.nickName,
mobile: req.session.user.mobile,
isAdmin: req.session.user.isAdmin,
created_at: req.session.user.created_at,
email: req.session.user.email,
headUrl: req.session.user.headUrl,
roles: x ? x.join(",") : ""
}
return system.getResult(tmp, "用户登录", req);
} else {
req.session.user = null;
//req.session.destroy();
return system.getResult(null, "用户未登录", req);
}
}
async exit(pobj, qobj, req) {
req.session.user = null;
req.session.destroy();
return system.getResultSuccess({
"env": settings.env
});
}
}
module.exports = UserCtl;
\ No newline at end of file
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
var svgCaptcha = require('svg-captcha');
class CaptchaCtl {
constructor() {
//this.appS=system.getObject("service.appSve");
}
async randomkey() {
return uuidv4();
}
}
module.exports = CaptchaCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
class OplogCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve");
}
async initNewInstance(qobj) {
var u = uuidv4();
var aid = u.replace(/\-/g, "");
var rd = { name: "", appid: aid }
return system.getResultSuccess(rd, null);
}
async debug(obj) {
obj.logLevel = "debug";
return this.create(obj);
}
async info(obj) {
obj.logLevel = "info";
return this.create(obj);
}
async warn(obj) {
obj.logLevel = "warn";
return this.create(obj);
}
async error(obj) {
obj.logLevel = "error";
return this.create(obj);
}
async fatal(obj) {
obj.logLevel = "fatal";
return this.create(obj);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
}
module.exports = OplogCtl;
const system = require("../../../system");
const settings = require("../../../../config/settings");
function exp(db, DataTypes) {
var base = {
code: {
type: DataTypes.STRING(50),
unique: true
},
name: DataTypes.STRING(1000),
};
return base;
}
module.exports = exp;
const system = require("../../system");
const settings = require("../../../config/settings");
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", uiconfig.config.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", uiconfig.config.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
constructor() {
this.redisClient = system.getObject("util.redisClient");
this.desc = this.desc();
this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "s_sadd_appkeys:" + settings.appKey + "_cachekey";
this.isdebug = this.isdebug();
}
isdebug() {
return false;
}
desc() {
throw new Error("子类需要定义desc方法,返回缓存描述");
}
prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀");
}
async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) {
return null;
}
if (ex) {
await this.redisClient.setWithEx(cachekey, objvalstr, ex);
} else {
await this.redisClient.set(cachekey, objvalstr);
}
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
return JSON.parse(objvalstr);
} else {
return JSON.parse(cacheValue);
}
}
async invalidate(inputkey) {
const cachekey = this.prefix + inputkey;
this.redisClient.delete(cachekey);
return 0;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串");
}
}
module.exports = CacheBase;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class ApiAccessKeyCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "应用中缓存访问token";
}
prefix() {
return settings.cacheprefix + "_accesskey:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var acckapp = await this.restS.execPost({ appkey: settings.appKey, secret: settings.secret }, settings.paasUrl() + "api/auth/accessAuth/getAccessKey");
var s = acckapp.stdout;
if (s) {
var tmp = JSON.parse(s);
if (tmp.status == 0) {
return JSON.stringify(tmp.data);
}
}
return null;
}
}
module.exports = ApiAccessKeyCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class ApiAccessKeyCheckCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "应用中来访访问token缓存";
}
prefix() {
return settings.cacheprefix + "_verify_reqaccesskey:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var cacheManager = system.getObject("db.common.cacheManager");
//当来访key缓存不存在时,需要去开放平台检查是否存在来访key缓存
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
if (checkresult.status == 0) {
var s = checkresult.data;
return JSON.stringify(s);
} else {
await cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
var s = checkresult.data;
return JSON.stringify(s);
}
}
}
module.exports = ApiAccessKeyCheckCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class ApiAppIdCheckCache extends CacheBase {
constructor() {
super();
}
desc() {
return "应用中来访访问appid缓存";
}
prefix() {
return settings.cacheprefix + "_verify_appid:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
}
}
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class ApiUserCache extends CacheBase {
constructor() {
super();
this.restS = system.getObject("util.restClient");
}
desc() {
return "应用中来访访问token缓存";
}
prefix() {
return settings.cacheprefix + "_userdata:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var cacheManager = system.getObject("db.common.cacheManager");
//当来访key缓存不存在时,需要去开放平台检查是否存在来访key缓存
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
if (checkresult.status == 0) {
var s = checkresult.data;
return JSON.stringify(s);
} else {
await cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
var acckapp = await cacheManager["ApiAccessKeyCache"].cache(settings.appKey, null, ex);//先获取本应用accessKey
var checkresult = await this.restS.execPostWithAK({ checkAccessKey: inputkey }, settings.paasUrl() + "api/auth/accessAuth/authAccessKey", acckapp.accessKey);
var s = checkresult.data;
return JSON.stringify(s);
}
}
}
module.exports = ApiUserCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "应用UI配置缓存";
}
//暂时没有用到,只是使用其帮助的方法
prefix() {
return settings.cacheprefix + "_uiconfig:";
}
async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key);
}
async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value)
}
async keys(p) {
return this.redisClient.keys(p);
}
async get(k) {
return this.redisClient.get(k);
}
async del(k) {
return this.redisClient.delete(k);
}
async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............");
return this.redisClient.flushall();
}
}
module.exports = MagCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class UIConfigCache extends CacheBase {
constructor() {
super();
}
isdebug() {
return settings.env == "dev";
}
desc() {
return "应用UI配置缓存";
}
prefix() {
return settings.cacheprefix + "_appself_uiconfig:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
var configValue = system.getUiConfig2(inputkey);
return JSON.stringify(configValue);
}
}
module.exports = UIConfigCache;
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
this.redisClient = system.getObject("util.redisClient");
var db = system.getObject("db.common.connection").getCon();
this.db = db;
console.log("........set dao model..........");
this.model = db.models[this.modelName];
}
async preCreate(u) {
if (!u.id) {
u.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 getById(id, attrs) {
if (!id) {
return null;
}
attrs = attrs || "*";
var sql = "SELECT " + attrs + " FROM " + this.model.tableName + " where id = :id ";
var list = await this.customQuery(sql, {
id: id
});
return list && list.length > 0 ? list[0] : null;
}
async getListByIds(ids, attrs) {
if (!ids || ids.length == 0) {
return [];
}
attrs = attrs || "*";
var sql = "SELECT " + attrs + " FROM " + this.model.tableName + " where id IN (:ids) ";
return await this.customQuery(sql, {
ids: ids
}) || [];
}
}
module.exports = Dao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class UserDao extends Dao{
constructor(){
super(Dao.getModelName(UserDao));
}
async getAuths(userid){
var self=this;
return this.model.findOne({
where:{id:userid},
include:[{model:self.db.models.account,attributes:["id","isSuper","referrerOnlyCode"]},
{model:self.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:self.db.models.product,as:"Products",attributes:["id","code"]}
]},
],
});
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"]}]};
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// console.log(obj);
// w["app_id"]=obj.appid;
// }
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
async preUpdate(u){
if(u.roles && u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var user=await this.model.findOne({where:{id:obj2.id}});
user.setRoles(obj2.roles);
return user;
}
async findAndCountAll(qobj,t){
var users=await super.findAndCountAll(qobj,t);
return users;
}
async preCreate(u){
// var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(roles);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// u.roles=roles
return u;
}
async create(u,t){
var self=this;
var u2=await this.preCreate(u);
if(t){
return this.model.create(u2,{transaction: t}).then(user=>{
return user;
});
}else{
return this.model.create(u2).then(user=>{
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId,company_only_code,result){
var customerObj={companyOnlyCode:company_only_code};
var putSqlWhere={where:{id:userId}};
this.updateByWhere(customerObj,putSqlWhere);
return result;
}
}
module.exports=UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var glob = require("glob");
class APIDocManager{
constructor(){
this.doc={};
this.buildAPIDocMap();
}
async buildAPIDocMap(){
var self=this;
//订阅任务频道
var apiPath=settings.basepath+"/app/base/api/impl";
var rs = glob.sync(apiPath + "/**/*.js");
if(rs){
for(let r of rs){
// var ps=r.split("/");
// var nl=ps.length;
// var pkname=ps[nl-2];
// var fname=ps[nl-1].split(".")[0];
// var obj=system.getObject("api."+pkname+"."+fname);
var ClassObj=require(r);
var obj=new ClassObj();
var gk=obj.apiDoc.group+"|"+obj.apiDoc.groupDesc
if(!this.doc[gk]){
this.doc[gk]=[];
this.doc[gk].push(obj.apiDoc);
}else{
this.doc[gk].push(obj.apiDoc);
}
}
}
}
}
module.exports=APIDocManager;
const system = require("../../../system");
const Dao = require("../../dao.base");
class BusinessscopeDao extends Dao {
constructor() {
super(Dao.getModelName(BusinessscopeDao));
}
async findListByDomicileIds(domicileIds) {
if (!domicileIds || domicileIds.length == 0) {
return [];
}
var sql = [];
sql.push("SELECT");
sql.push("id, domicile_id, businessType,");
sql.push("businessscope, isEnabled, created_at ");
sql.push("FROM d_businessscope");
sql.push("WHERE domicile_id IN (:domicileIds)");
return await this.customQuery(sql.join(" "), {
domicileIds: domicileIds
}) || [];
}
async findMapByDomicileIds(domicileIds) {
var result = {};
if (!domicileIds || domicileIds.length == 0) {
return result;
}
var list = await this.findListByDomicileIds(domicileIds);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
var domicileList = result[item.domicile_id] || [];
domicileList.push(item);
result[item.domicile_id] = domicileList;
}
return result;
}
async delById(id, t) {
var sql = "DELETE FROM d_businessscope WHERE id = :id";
return await this.customUpdate(sql, {
id: id
}, t);
}
async delByDomicileId(domicileId, t) {
var sql = "DELETE FROM d_businessscope WHERE domicile_id = :domicileId";
return await this.customUpdate(sql, {
domicileId: domicileId
}, t);
}
}
module.exports = BusinessscopeDao;
// 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);
// }
//
// })();
\ No newline at end of file
const fs = require("fs");
const settings = require("../../../../config/settings");
class CacheManager {
constructor() {
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap() {
var self = this;
self.doc = {};
var cachePath = settings.basepath + "/app/base/db/cache/";
const files = fs.readdirSync(cachePath);
if (files) {
files.forEach(function (r) {
var classObj = require(cachePath + "/" + r);
if (classObj.name) {
self[classObj.name] = new classObj();
var refTmp = self[classObj.name];
if (refTmp.prefix) {
self.doc[refTmp.prefix] = refTmp.desc;
} else {
console.log("请在" + classObj.name + "缓存中定义prefix");
}
}
});
}
}
}
module.exports = CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
\ No newline at end of file
const Sequelize = require('sequelize');
const settings = require("../../../../config/settings")
const fs = require("fs")
const path = require("path");
var glob = require("glob");
class DbFactory {
constructor() {
const dbConfig = settings.database();
this.db = new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
dbConfig.config);
this.db.Sequelize = Sequelize;
this.db.Op = Sequelize.Op;
this.initModels();
this.initRelations();
}
async initModels() {
var self = this;
var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
console.log("modelpath=====================================================");
console.log(modelpath);
var models = glob.sync(modelpath + "/**/*.js");
console.log(models.length);
models.forEach(function (m) {
console.log(m);
self.db.import(m);
});
console.log("init models....");
}
async initRelations() {
/**
一个账户对应多个登陆用户
一个账户对应一个commany
一个APP对应多个登陆用户
一个APP有多个角色
登陆用户和角色多对多
**/
/*建立账户和用户之间的关系*/
//account--不属于任何一个app,是统一用户
//用户登录时首先按照用户名和密码检查account是否存在,如果不存在则提示账号或密码不对,如果
//存在则按照按照accountid和应用key,查看user,后台实现对应user登录
}
//async getCon(){,用于使用替换table模型内字段数据使用
getCon() {
var that = this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// throw err;
// });
//同步模型
if (settings.env == "dev") {
//console.log(pa);
// pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true}));
// });
// await this.db.models.user.create({nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
// .then(function(user){
// var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
// acc.save().then(a=>{
// user.setAccount(a);
// });
// });
}
return this.db;
}
getConhb() {
var that = this;
if (settings.env == "dev") {
}
return this.dbhb;
}
}
module.exports = DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system = require("../../../system");
const Dao = require("../../dao.base");
class DomicileDao extends Dao {
constructor() {
super(Dao.getModelName(DomicileDao));
}
async getList(isEnabled, attrs) {
attrs = attrs || "*"
var sql = [];
sql.push("SELECT ");
sql.push(attrs);
sql.push("FROM d_domicile");
if (isEnabled == 1) {
sql.push("WHERE isEnabled = 1");
}
return await this.customQuery(sql.join(" ")) || [];
}
async delById(id, t) {
var sql = "DELETE FROM d_domicile WHERE id = :id";
return await this.customUpdate(sql, {
id: id
}, t);
}
async findListByIds(ids) {
if (!ids || ids.length == 0) {
return [];
}
var sql = [];
sql.push("SELECT");
sql.push("id, name, isEnabled, created_at ");
sql.push("FROM d_domicile");
sql.push("WHERE id IN (:ids)");
return await this.customQuery(sql.join(" "), {
ids: ids
}) || [];
}
async findMapByIds(ids) {
var result = {};
if (!ids || ids.length == 0) {
return result;
}
var list = await this.findListByIds(ids);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
}
module.exports = DomicileDao;
// 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);
// }
//
// })();
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class InvoicecontentDao extends Dao{
constructor(){
super(Dao.getModelName(InvoicecontentDao));
}
}
module.exports=InvoicecontentDao;
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 DeliverDao extends Dao {
constructor() {
super(Dao.getModelName(DeliverDao));
}
async getList(isEnabled, attrs) {
attrs = attrs || "*"
var sql = [];
sql.push("SELECT ");
sql.push(attrs);
sql.push("FROM d_deliver");
if (isEnabled == 1) {
sql.push("WHERE isEnabled = 1");
}
return await this.customQuery(sql.join(" ")) || [];
}
async delById(id, t) {
var sql = "DELETE FROM d_deliver WHERE id = :id";
return await this.customUpdate(sql, {
id: id
}, t);
}
async findListByIds(ids) {
if (!ids || ids.length == 0) {
return [];
}
var sql = [];
sql.push("SELECT");
sql.push("id, name, businessmenDivide, invoiceDivide, isEnabled, created_at ");
sql.push("FROM d_deliver");
sql.push("WHERE id IN (:ids)");
return await this.customQuery(sql.join(" "), {
ids: ids
}) || [];
}
async findMapByIds(ids) {
var result = {};
if (!ids || ids.length == 0) {
return result;
}
var list = await this.findListByIds(ids);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
}
module.exports = DeliverDao;
// 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);
// }
//
// })();
\ No newline at end of file
const system=require("../system");
const settings=require("../../config/settings.js");
const reclient=system.getObject("util.redisClient");
const md5 = require("MD5");
//获取平台配置兑换率
//初次登录的赠送数量
//创建一笔交易
//同时增加账户数量,增加系统平台账户
var dbf=system.getObject("db.common.connection");
var db=dbf.getCon();
db.sync({force:true}).then(async ()=>{
console.log("sync complete...");
//创建role
// if(settings.env=="prod"){
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
// }
// reclient.flushall(()=>{
// console.log("clear caches ok.....");
// });
});
module.exports = {
"appid": "40d64e586551405c9bcafab87266bb04",
"label": "研发开放平台",
"config": {
"rstree": {
"code": "paasroot",
"label": "paas",
"children": [
// {
// "code": "register",
// "icon": "fa fa-power-off",
// "path": "register",
// "isMenu": false,
// "label": "注册",
// "isctl": "no"
// },
],
},
"bizs": {
},
"pdict": {
"logLevel": { "debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4 },
"sex": {"male": "男", "female": "女"},
}
}
}
\ No newline at end of file
module.exports={
"bizName":"oplogs",
"list":{
columnMetaData:[
{"width":"200","label":"应用","prop":"appname","isShowTip":true,"isTmpl":false},
{"width":"200","label":"时间","prop":"created_at","isShowTip":true,"isTmpl":false},
{"width":"100","label":"用户名","prop":"username","isShowTip":true,"isTmpl":false},
{"width":"100","label":"性别","prop":"sex","isShowTip":true,"isTmpl":false},
{"width":"200","label":"行为","prop":"op","isShowTip":true,"isTmpl":false},
{"width":"200","label":"内容","prop":"content","isShowTip":true,"isTmpl":false},
{"width":"200","label":"客户端IP","prop":"clientIp","isShowTip":true,"isTmpl":false},
{"width":"200","label":"客户端环境","prop":"agent","isShowTip":true,"isTmpl":false},
]
},
"form":[
{
"title":"应用名称",
"validProp":"name",
"rule": [
{ "required": true, "message": '请输入应用名称', "trigger": 'blur' },
],
ctls:[
{"type":"input","label":"应用名称","prop":"name","placeHolder":"应用名称","style":""},
]
},
{
"title":"应用ID",
"ctls":[
{"type":"input","label":"应用ID","prop":"appid","disabled":true,"placeHolder":"","style":""},
]
},
],
"search":[
{
"title":"应用名称",
ctls:[
{"type":"input","label":"操作用户","prop":"username","placeHolder":"请模糊输入应用名称","style":""},
]
},
{
"title":"客户环境",
ctls:[
{"type":"input","label":"客户环境","prop":"agent","placeHolder":"请模糊输入客户环境","style":""},
]
},
// {
// "title":"",
// "min":1,
// "max":1,
// ctls:[
// {"type":"check","dicKey":"sex","label":"客户环境","prop":"sex","style":""},
// ]
// },
// <gsb-select v-model="formModel[item.prop]"
// :dicKey="item.dicKey"
// :autoComplete="item.autoComplete"
// :isMulti="item.isMulti"
// :modelName="item.modelName"
// :isFilter="item.isFilter"
// :labelField="item.labelField"
// :valueField="item.valueField"></gsb-select>
{
"title":"性别",
ctls:[
{"type":"select","dicKey":"sex","label":"性别","prop":"sex","labelField":"label","valueField":"value","style":""},
]
},
],
"auth":{
"add":[
],
"edit":[
],
"delete":[
{"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isOnGrid":true},
],
"common":[
],
}
}
const fs=require("fs");
const path=require("path");
const appsPath=path.normalize(__dirname+"/apps");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
}
function getBizFilePath(appJson,bizCode){
const filePath=bizsPath+"/"+"bizjs"+"/"+bizCode+".js";
return filePath;
}
//异常日志处理todo
function initAppBizs(appJson){
for(var bizCode in appJson.config.bizs)
{
const bizfilePath=getBizFilePath(appJson,bizCode);
try{
delete require.cache[bizfilePath];
const bizConfig=require(bizfilePath);
appJson.config.bizs[bizCode].config=bizConfig;
}catch(e){
console.log("bizconfig meta file not exist........");
}
}
return appJson;
}
//初始化资源树--objJson是rstree
function initRsTree(appjson,appidfolder,objJson,parentCodePath){
if(!parentCodePath){//说明当前是根结点
objJson.codePath=objJson.code;
}else{
objJson.codePath=parentCodePath+"/"+objJson.code;
}
if(objJson["bizCode"]){//表示叶子节点
objJson.auths=[];
if(appjson.config.bizs[objJson["bizCode"]]){
objJson.bizConfig=appjson.config.bizs[objJson["bizCode"]].config;
objJson.path=appjson.config.bizs[objJson["bizCode"]].path;
appjson.config.bizs[objJson["bizCode"]].codepath=objJson.codePath;
}
}else{
if(objJson.children){
objJson.children.forEach(obj=>{
initRsTree(appjson,appidfolder,obj,objJson.codePath);
});
}
}
}
fs.readdirSync(appsPath).forEach(f=>{
const ff=path.join(appsPath,f);
delete require.cache[ff];
var appJson=require(ff);
appJson= initAppBizs(appJson);
initRsTree(appJson,appJson.appid,appJson.config.rstree,null);
appJsons[appJson.appid]=appJson;
});
module.exports=appJsons;
module.exports={
"appid":"wx76a324c5d201d1a4",
"label":"企业服务工具箱",
"config":{
"rstree":{
"code":"toolroot",
"label":"工具箱",
"children":[
{
"code":"toggleHeader",
"icon":"el-icon-sort",
"isMenu":true,
"label":"折叠",
},
{
"code":"personCenter",
"label":"个人信息",
"src":"/imgs/logo.png",
"isSubmenu":true,
"children":[
{"code":"wallet","isGroup":true,"label":"账户","children":[
{"code":"mytraderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"path":""},
{"code":"smallmoney","label":"钱包","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"fillmoney","label":"充值","isMenu":true,},
]},
{"code":"tool","isGroup":true,"label":"工具","children":[
{"code":"entconfirm","label":"企业用户认证","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"fav","label":"收藏夹","isMenu":true,"bizCode":"fav","bizConfig":null,"path":""},
{"code":"filebox","label":"文件柜","isMenu":true,"bizCode":"filebox","bizConfig":null,"path":""},
]},
],
},
{
"code":"fillmoney",
"icon":"fa fa-money",
"isMenu":true,
"label":"充值",
},
{
"code":"platformop",
"label":"平台运营",
"icon":"fa fa-cubes",
"isSubmenu":true,
"children":[
{"code":"papp","isGroup":true,"label":"平台数据","children":[
{"code":"papparch","label":"应用档案","isMenu":true,"bizCode":"apps","bizConfig":null,"path":""},
{"code":"userarch","label":"用户档案","isMenu":true,"bizCode":"pusers","bizConfig":null,"path":""},
{"code":"traderecord","label":"交易记录","isMenu":true,"bizCode":"trades","bizConfig":null,"qp":"my","path":""},
{"code":"pconfigs","label":"平台配置","isMenu":true,"bizCode":"pconfigs","bizConfig":null,"qp":"my","path":""},
]},
{"code":"pop","isGroup":true,"label":"平台运维","children":[
{"code":"cachearch","label":"缓存档案","isMenu":true,"bizCode":"cachearches","bizConfig":null,"path":""},
{"code":"oplogmag","label":"行为日志","isMenu":true,"bizCode":"oplogs","bizConfig":null,"path":""},
{"code":"machinearch","label":"机器档案","isMenu":true,"bizCode":"machines","bizConfig":null,"path":""},
{"code":"codezrch","label":"代码档案","isMenu":true,"bizCode":"codezrch","bizConfig":null,"path":""},
{"code":"imagearch","label":"镜像档案","isMenu":true},
{"code":"containerarch","label":"容器档案","isMenu":true},
]},
],
},
{
"code":"sysmag",
"label":"系统管理",
"icon":"fa fa-cube",
"isSubmenu":true,
"children":[
{"code":"usermag","isGroup":true,"label":"用户管理","children":[
{"code":"rolearch","label":"角色档案","isMenu":true,"bizCode":"roles","bizConfig":null},
{"code":"appuserarch","label":"用户档案","isMenu":true,"bizCode":"appusers","bizConfig":null},
]},
{"code":"productmag","isGroup":true,"label":"产品管理","children":[
{"code":"productarch","label":"产品档案","bizCode":"mgproducts","isMenu":true,"bizConfig":null},
{"code":"products","label":"首页产品档案","bizCode":"products","isMenu":false,"bizConfig":null},
]},
],
},
{
"code":"exit",
"icon":"fa fa-power-off",
"isMenu":true,
"label":"退出",
},
{
"code":"toolCenter",
"label":"工具集",
"src":"/imgs/logo.png",
"isSubmenu":false,
"isMenu":false,
"children":[
{"code":"tools","isGroup":true,"label":"查询工具","children":[
{"code":"xzquery","label":"续展查询","bizCode":"xzsearch","bizConfig":null,"path":""},
{"code":"xzgqquery","label":"续展过期查询","bizCode":"xzgqsearch","bizConfig":null,"path":""},
]},
],
},
],
},
"bizs":{
"cachearches":{"title":"首页产品档案","config":null,"path":"/platform/cachearches","comname":"cachearches"},
"products":{"title":"首页产品档案","config":null,"path":"/","comname":"products"},
"mgproducts":{"title":"产品档案","config":null,"path":"/platform/mgproducts","comname":"mgproducts"},
"codezrch":{"title":"代码档案","config":null,"path":"/platform/codezrch","comname":"codezrch"},
"machines":{"title":"机器档案","config":null,"path":"/platform/machines","comname":"machines"},
"pconfigs":{"title":"平台配置","config":null,"path":"/platform/pconfigs","comname":"pconfigs"},
"apps":{"title":"应用档案","config":null,"path":"/platform/apps","comname":"apps"},
"roles":{"title":"角色档案","config":null,"path":"/platform/roles","comname":"roles"},
"pusers":{"title":"平台用户档案","config":null,"path":"/platform/pusers","comname":"users"},
"appusers":{"title":"某应用用户档案","config":null,"path":"/platform/appusers","comname":"users"},
"oplogs":{"title":"行为日志","config":null,"path":"/platform/op/oplogs","comname":"oplogs"},
"trades":{"title":"交易记录","config":null,"path":"/platform/uc/trades","comname":"trades"},
"xzsearch":{"title":"续展查询","config":null,"isDynamicRoute":true,"path":"/products/xzsearch","comname":"xzsearch"},
"xzgqsearch":{"title":"续展过期查询","config":null,"isDynamicRoute":true,"path":"/products/xzgqsearch","comname":"xzgqsearch"},
},
"pauths":[
"add","edit","delete","export","show"
],
"pdict":{
"sex":{"male":"男","female":"女"},
"configType":{"price":"宝币兑换率","initGift":"初次赠送"},
"productCata":{"ip":"知产","ic":"工商","tax":"财税","hr":"人力","common":"常用"},
"logLevel":{"debug":0,"info":1,"warn":2,"error":3,"fatal":4},
"tradeType":{"fill":"充值","consume":"消费","gift":"赠送","giftMoney":"红包","refund":"退款"},
"tradeStatus":{"unSettle":"未结算","settled":"已结算"}
}
}
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("user", {
userName: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
nickName: {
type:DataTypes.STRING,
allowNull: true,
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
mobile:DataTypes.STRING,
mail: {
type:DataTypes.STRING,
allowNull: true,
},
headUrl: DataTypes.STRING,
isAdmin:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
isSuper:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
openId:DataTypes.STRING,
app_id:DataTypes.INTEGER,
account_id:DataTypes.INTEGER,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_user',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("businessscope", {
domicile_id: DataTypes.STRING,
businessType: DataTypes.STRING,
businessscope: DataTypes.STRING,
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: true,
},
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'd_businessscope',
validate: {},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
\ No newline at end of file
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("domicile", {
name: DataTypes.STRING,
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: true,
},
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'd_domicile',
validate: {},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
\ No newline at end of file
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("invoicecontent", {
name: DataTypes.STRING,
isEnabled: {
type:DataTypes.BOOLEAN,
allowNull:false,
defaultValue:false
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
//freezeTableName: true,
// define the table's name
tableName: 'd_invoicecontent',
validate: {
},
indexes: [
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("oplog", {
appid: DataTypes.STRING,
appkey: DataTypes.STRING,
requestId: DataTypes.STRING,
logLevel: {
type: DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.logLevel),
defaultValue: "info",
},
op: DataTypes.STRING,
content: DataTypes.STRING(5000),
resultInfo: DataTypes.TEXT,
clientIp: DataTypes.STRING,
agent: {
type: DataTypes.STRING,
allowNull: true,
},
opTitle: DataTypes.STRING(500),
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt: false,
//freezeTableName: true,
// define the table's name
tableName: 'op_log',
validate: {
},
indexes: [
]
});
}
module.exports = (db, DataTypes) => {
return db.define("task", {
app_id:DataTypes.STRING,//需要在后台补充
taskClassName: {
type:DataTypes.STRING(100),
allowNull: false,
unique: true
},//和user的from相同,在注册user时,去创建
taskexp: {
type:DataTypes.STRING,
allowNull: false,
},//和user的from相同,在注册user时,去创建
desc:DataTypes.STRING,//需要在后台补充
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_task',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("deliver", {
name: DataTypes.STRING,
businessmenDivide: DataTypes.INTEGER,
invoiceDivide: DataTypes.INTEGER,
remark: DataTypes.STRING,
isEnabled: {
type: DataTypes.BOOLEAN,
allowNull: true,
},
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'd_deliver',
validate: {},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
\ No newline at end of file
const system=require("../system")
const logCtl=system.getObject("web.common.oplogCtl");
class TaskBase{
constructor(className){
this.redisClient=system.getObject("util.redisClient");
this.serviceName=className;
}
async doTask(){
try {
await this.subDoTask();
//日志记录
logCtl.info({
optitle:this.serviceName+",任务成功执行完成",
op:"base/db/task.base.js",
content:"",
clientIp:""
});
} catch (e) {
//日志记录
logCtl.error({
optitle:this.serviceName+"任务执行异常",
op:"base/db/task.base.js",
content:e.stack,
clientIp:""
});
}
}
async subDoTask(){
console.log("请在子类中重写此方法进行操作业务逻辑............................!");
}
static getServiceName(ClassObj){
return ClassObj["name"];
}
}
module.exports=TaskBase;
const TaskBase=require("../task.base");
class TestTask extends TaskBase{
constructor(){
super(TaskBase.getServiceName(TestTask));
}
async subDoTask(){
console.log("TestTask1.....");
}
}
module.exports=TestTask;
const TaskBase=require("../task.base");
class TestTask extends TaskBase{
constructor(){
super();
}
async doTask(){
console.log("TestTask.....");
}
}
module.exports=TestTask;
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
constructor() {
super("auth", ServiceBase.getDaoName(UserService));
}
async authByCode(opencode) {
var existedUser = null;
var rawUser = null;
var openuser = await this.apiCallWithAk(settings.paasUrl() + "api/auth/accessAuth/authByCode", { opencode: opencode });
if (openuser) {
//先查看自己系统中是否已经存在当前用户
existedUser = await this.dao.model.findOne({ where: { ucname: openuser.userName, ucid: openuser.id }, raw: true });
if (!existedUser) {
existedUser = await this.register(openuser);
}
rawUser = existedUser.get({ raw: true });
rawUser.Roles = openuser.Roles;
}
return rawUser;
}
async getUserLoginInfo(token) {
var acckapp = await this.cacheManager["ApiUserCache"].cache(token, null, settings.usertimeout);
}
async register(openuser) {
var param = {
ucname: openuser.userName, ucid: openuser.id,
last_login_time: new Date()
}
var cruser = await this.dao.create(param);
return cruser;
}
//在平台进行登录,返回目标认证地址
async navSysSetting(user) {
var sysLoginUrl = settings.paasUrl() + "web/auth/userCtl/login?appKey=" + settings.appKey + "\&toKey=" + settings.paasKey;
var x = { userName: user.userName, password: user.password, mobile: user.mobile };
var restResult = await this.restS.execPost({ u: x }, sysLoginUrl);
if (restResult) {
var rtnres = JSON.parse(restResult.stdout);
if (rtnres.status == 0) {
return rtnres.data;
}
}
return null;
}
async getUserByUserNamePwd(u) {
var user = await this.dao.model.findOne({
where: { userName: u.userName, password: u.password, app_id: u.app_id },
include: [
{ model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
]
});
return user;
}
async checkSameName(uname, appid) {
var ac = await this.dao.model.findOne({ where: { userName: uname, app_id: appid } });
var rtn = { isExist: false };
if (ac) {
rtn.isExist = true;
}
return rtn;
}
}
module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class BusinessscopeService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(BusinessscopeService));
this.domicileDao = system.getObject("db.common.domicileDao");
}
async apiPage(params) {
try {
return await this.page(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiSave(params) {
try {
return await this.save(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiInfo(params) {
try {
return await this.info(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiDomicileList(params) {
try {
return await this.ListByDomicileId(params.domicileId);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiDeleteByIds(params) {
var ids = params.ids || [];
try {
for(var id of ids) {
// 单条删除,方便以后有级联删除时使用事务
await this.delById(id);
}
return system.getResultSuccess(1);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
// where: {
// id: id
// },
// attrs: ["id", "domicile_id", "businessType", "businessscope", "isEnabled", "created_at",],
// raw: true
// -----------------------以此间隔,上面为API,下面为service---------------------------------
async ListByDomicileId(domicileId) {
var list = await this.dao.findListByDomicileIds([domicileId]) || [];
for(var item of list) {
this.handleDate(item, ["created_at"], null, -8);
}
await this.setDomicile(list);
return system.getResultSuccess(list);
}
async info(params) {
var id = params.id;
var sqlWhere = {
where: {
id: id
},
attributes: ["id", "domicile_id", "businessType", "businessscope", "isEnabled", "created_at",],
raw: true
};
var item = await this.dao.model.findOne(sqlWhere);
if(!item) {
return system.getResult(null, "经营范围不存在");
}
this.handleDate(item, ["created_at"], null, -8);
await this.setDomicile([item]);
return system.getResultSuccess(item);
}
async delById(id) {
if(!id) {
return;
}
await this.dao.delById(id);
return system.getResultSuccess(1);
}
async save(params) {
var domicileId = params.domicileId;
if (!domicileId) {
return system, getResult(null, domicileId);
}
var id = params.id;
var bsc;
if (id) {
bsc = await this.dao.findById(id);
} else {
bsc = {domicile_id: domicileId};
}
bsc.businessType = this.trim(params.businessType);
bsc.businessscope = this.trim(params.businessscope);
bsc.isEnabled = params.isEnabled == 1 ? true : false;
if(bsc.id) {
bsc = await bsc.save();
} else {
bsc = await this.dao.create(bsc);
}
return system.getResultSuccess(bsc);
}
async page(params) {
var currentPage = Number(params.currentPage || 1);
var pageSize = Number(params.pageSize || 10);
var where = {};
if (params.domicileId) {
where.domicile_id = params.domicileId;
}
var orderby = [
["id", 'desc']
];
var attributes = ["id", "domicile_id", "businessType", "businessscope", "isEnabled", "created_at"];
var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
if (page && page.rows) {
for (var row of page.rows) {
this.handleDate(row, ["created_at"], null, -8);
}
await this.setDomicile(page.rows);
}
return system.getResultSuccess(page);
}
async setDomicile(rows) {
if(!rows || rows.length == 0) {
return;
}
var ids = [];
for(var item of rows) {
ids.push(item.domicile_id);
}
var map = await this.domicileDao.findMapByIds(ids);
for(var item of rows) {
item.domicile = map[item.domicile_id] || {};
this.handleDate(item.domicile, ["created_at"], null, -8);
}
}
}
module.exports = BusinessscopeService;
// 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 CacheService {
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
}
async buildCacheRtn(pageValues) {
var ps = pageValues.map(k => {
var tmpList = k.split("|");
if (tmpList.length == 2) {
return { name: tmpList[0], val: tmpList[1], key: k };
}
});
return ps;
}
async findAndCountAll(obj) {
const pageNo = obj.pageInfo.pageNo;
const pageSize = obj.pageInfo.pageSize;
const limit = pageSize;
const offset = (pageNo - 1) * pageSize;
var search_name = obj.search && obj.search.name ? obj.search.name : "";
var cacheCacheKeyPrefix = "sadd_children_appkeys:" + settings.appKey + "_cachekey";
var cacheList = await this.cacheManager["MagCache"].getCacheSmembersByKey(cacheCacheKeyPrefix);
if (search_name) {
cacheList = cacheList.filter(f => f.indexOf(search_name) >= 0);
}
var pageValues = cacheList.slice(offset, offset + limit);
var kobjs = await this.buildCacheRtn(pageValues);
var tmpList = { results: { rows: kobjs, count: cacheList.length } };
return system.getResultSuccess(tmpList);
}
async delCache(obj) {
var keyList = obj.del_cachekey.split("|");
if (keyList.length == 2) {
var cacheCacheKeyPrefix = "sadd_children_appkeys:" + settings.appKey + "_cachekey";
await this.cacheManager["MagCache"].delCacheBySrem(cacheCacheKeyPrefix, obj.del_cachekey);
await this.cacheManager["MagCache"].del(keyList[0]);
return { status: 0 };
}
}
async clearAllCache(obj) {
await this.cacheManager["MagCache"].clearAll();
return { status: 0 };
}
}
module.exports = CacheService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
const uuidv4 = require('uuid/v4');
var svgCaptcha = require('svg-captcha');
class CaptchaService {
constructor() {
this.redisClient = system.getObject("util.redisClient");
}
async apiGenerate(params) {
var key = uuidv4();
var options = {
size: 4,
noise: 1,
ignoreChars: '0o1i'
};
options.width = this.trim(params.width) || 120;
options.height = this.trim(params.height) || 32;
options.background = this.trim(params.background) || "#E8E8E8";
var captchaPrev = this.trim(params.captchaPrev);
var expire = Number(params.expire || 3 * 60)
try {
var cap = svgCaptcha.create(options);
console.log(cap);
await this.redisClient.setWithEx(key, cap.text, expire);
return system.getResultSuccess({
key: key,
text: cap.text,
captcha: cap.data,
});
} catch (error) {
return system.getResult(null, "接口异常:" + error.message);
}
}
async apiValidator(params) {
var key = this.trim(params.key);
var code = this.trim(params.code);
var cacheCode = await this.redisClient.get(key);
if(!cacheCode) {
return system.getResult(null, "验证码已过期,请点击重试");
}
if(code.toLowerCase() != cacheCode.toLowerCase()) {
await this.redisClient.delete(key);
return system.getResult(null, "验证码输入错误,清点击重试");
}
return system.getResultSuccess(1);
}
trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
}
module.exports = CaptchaService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class DomicileService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(DomicileService));
this.businessscopeDao = system.getObject("db.common.businessscopeDao");
}
async apiNameList(params) {
try {
return await this.nameList();
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiTree(params) {
try {
return await this.tree(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiPage(params) {
try {
return await this.page(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiSave(params) {
try {
return await this.save(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiInfo(params) {
try {
return await this.info(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiDeleteByIds(params) {
var ids = params.ids;
if (!ids || ids.length == 0) {
return system.getResult(null, "传入参数错误:ids=" + JSON.stringify(ids));
}
try {
for (var id of ids) {
try {
await this.delById(id);
} catch (error) {
console.log(error);
}
}
return system.getResultSuccess(1);
} catch (error) {
return system.getResult(null, "接口异常");
}
}
// -----------------------以此间隔,上面为API,下面为service---------------------------------
async info(params) {
var id = params.id;
if (!id) {
return system.getResult(null, "注册地不存在");
}
var sqlWhere = {
where: {
id: id
},
attributes: ["id", "name", "isEnabled", "created_at"],
raw: true
};
var item = await this.dao.model.findOne(sqlWhere);
if (!item) {
return system.getResult(null, "注册地不存在");
}
this.handleDate(item, ["created_at"], null, -8);
await this.setBusinessscopeList([item]);
return system.getResultSuccess(item);
}
async save(params) {
var id = params.id;
var domicile;
if (id) {
domicile = await this.dao.findById(id);
} else {
domicile = {};
}
domicile.name = this.trim(params.name);
domicile.isEnabled = params.isEnabled == 1 ? true : 0;
if (id) {
domicile = await domicile.save();
} else {
domicile = await this.dao.create(domicile);
}
return system.getResultSuccess(domicile);
}
async nameList() {
var list = await this.dao.getList(1, "id, name");
return system.getResultSuccess(list);
}
async tree(isEnabled) {
var tree = await this.dao.getList(isEnabled, "id, name, created_at");
if (tree) {
for (var row of tree) {
this.handleDate(row, ["created_at"], null, -8);
}
await this.setBusinessscopeList(tree);
}
return system.getResultSuccess(tree);
}
async delById(id) {
if (!id) {
return system.getResult(null, "删除失败");
}
var self = this;
await this.db.transaction(async function (t) {
await self.dao.delById(id, t);
await self.businessscopeDao.delByDomicileId(id, t);
});
return system.getResultSuccess(1);
}
async page(params) {
var currentPage = Number(params.currentPage || 1);
var pageSize = Number(params.pageSize || 10);
var where = {};
if (params.id > 0) {
where.id = params.id;
}
var orderby = [
["id", 'desc']
];
var attributes = ["id", "name", "isEnabled", "created_at"];
var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
if (page && page.rows) {
for (var row of page.rows) {
this.handleDate(row, ["created_at"], null, -8);
}
await this.setBusinessscopeList(page.rows);
}
return system.getResultSuccess(page);
}
async setBusinessscopeList(rows) {
if (!rows || rows.length == 0) {
return rows;
}
var ids = [];
for (var item of rows) {
ids.push(item.id);
}
var bsmap = await this.businessscopeDao.findMapByDomicileIds(ids)
for (var row of rows) {
row.businessscopeList = bsmap[row.id] || [];
for (var item of row.businessscopeList) {
this.handleDate(item, ["created_at"], null, -8);
}
}
}
}
module.exports = DomicileService;
// 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 InvoicecontentService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(InvoicecontentService));
// this.invoicecontentDao=system.getObject("db.common.invoicecontentDao");
}
async apiSave(params) {
try {
return await this.save(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiGetById(params) {
try {
if(!params.id){
return system.getResult(null, "参数错误");
}
return await this.getById(params.id);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiList(params) {
try {
console.log("--"+JSON.stringify(params));
return await this.invoiceList(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiDelete(params) {
var ids = params.ids;
if (!ids || ids.length == 0) {
return system.getResult(null, "传入参数错误:ids=" + JSON.stringify(ids));
}
try {
try {
await this.bulkDelete(ids);
} catch (error) {
console.log(error);
}
return system.getResultSuccess(1);
} catch (error) {
return system.getResult(null, "接口异常");
}
}
/**--------------------------------------------------------------------- */
async getById(id){
let res = await this.dao.findById(id);
return system.getResultSuccess(res);
}
async save(params) {
let id = params.id;
let invoicecontent;
if(id){
invoicecontent=await this.dao.findById(id);
}else{
invoicecontent={};
}
invoicecontent.name=this.trim(params.name);
invoicecontent.isEnabled=(params.isEnabled)==1?true:false;
if(id){
await invoicecontent.save();
}else{
invoicecontent = await this.dao.create(invoicecontent);
}
return system.getResultSuccess(invoicecontent);
}
async bulkDelete(ids) {
if (!ids || ids.length == 0) {
return system.getResult(null, "删除失败");
}
await this.dao.bulkDelete(ids);
}
async invoiceList(params) {
console.log(JSON.stringify(params));
var currentPage = Number(params.currentPage || 1);
var pageSize = Number(params.pageSize || 10);
var where = {};
if (params.domicileId) {
where.domicile_id = params.domicileId;
}
if (params.name) {
where.name = {
[this.db.Op.like]: "%" + decodeURIComponent(params.name) + "%"
};
}
var orderby = [
["id", 'desc']
];
var attributes = ["id", "name", "isEnabled", "created_at", "updated_at", "deleted_at"];
let res = await this.dao.getPageList(currentPage, pageSize, where, orderby, attributes);
return res;
}
}
module.exports = InvoicecontentService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
var settings=require("../../../../config/settings");
class MetaService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(MetaService));
}
async getApiDoc(appid){
var p=settings.basepath+"/app/base/db/impl/common/apiDocManager.js";
var ClassObj= require(p) ;
var obj=new ClassObj();
return obj.doc;
}
async getUiConfig(appid){
const cfg=await this.cacheManager["UIConfigCache"].cache(appid,null,60);
return cfg;
}
async getBaseComp(){
var basecomp=await this.apiCallWithAk(settings.paasUrl()+"api/meta/baseComp/getBaseComp",{});
return basecomp.basecom;
}
async findAuthsByRole(rolesarray, appid){
var result =await this.apiCallWithAk(settings.paasUrl()+"api/auth/roleAuth/findAuthsByRole",{
roles:rolesarray,
appid:appid
});
return result;
}
}
module.exports=MetaService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class OplogService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(OplogService));
//this.appDao=system.getObject("db.appDao");
this.opLogUrl = settings.apiconfig.opLogUrl();
this.opLogEsIsAdd = settings.apiconfig.opLogEsIsAdd();
}
async create(qobj) {
if (!qobj || !qobj.op || qobj.op.indexOf("metaCtl/getUiConfig") >= 0 ||
qobj.op.indexOf("userCtl/checkLogin") >= 0 ||
qobj.op.indexOf("oplogCtl") >= 0 ||
qobj.op.indexOf("getDicConfig") >= 0 ||
qobj.op.indexOf("getRouteConfig") >= 0 ||
qobj.op.indexOf("getRsConfig") >= 0) {
return null;
}
var rc = system.getObject("util.execClient");
var rtn = null;
try {
// var myDate = new Date();
// var tmpTitle=myDate.toLocaleString()+":"+qobj.optitle;
qobj.optitle = (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":" + qobj.optitle;
if (this.opLogEsIsAdd == 1) {
qobj.content = qobj.content.replace("field list", "字段列表")
qobj.created_at = (new Date()).getTime();
//往Es中写入日志
var addEsData = JSON.stringify(qobj);
rc.execPost(qobj, this.opLogUrl);
} else {
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
}
} catch (e) {
console.log(e.stack, "addLog------error-----------------------*****************");
qobj.content = e.stack;
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
}
}
async createDb(qobj) {
if (!qobj || !qobj.op || qobj.op.indexOf("metaCtl/getUiConfig") >= 0 ||
qobj.op.indexOf("userCtl/checkLogin") >= 0 ||
qobj.op.indexOf("oplogCtl") >= 0 ||
qobj.op.indexOf("getDicConfig") >= 0 ||
qobj.op.indexOf("getRouteConfig") >= 0 ||
qobj.op.indexOf("getRsConfig") >= 0) {
return null;
}
try {
qobj.optitle = (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":" + qobj.optitle;
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
} catch (e) {
console.log(e.stack, "addLog------error-----------------------*****************");
qobj.content = e.stack;
//解决日志大于4000写入的问题
if (qobj.content.length > 4980) {
qobj.content = qobj.content.substring(0, 4980);
}
this.dao.create(qobj);
}
}
}
module.exports = OplogService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TaskService));
//this.appDao=system.getObject("db.appDao");
this.taskManager=system.getObject("db.taskManager");
this.emailClient=system.getObject("util.mailClient");
this.personTaxDao=system.getObject("db.individualincometaxDao");
this.ossClient=system.getObject("util.ossClient");
}
//写文件并上传到阿里云,返回上传的路径
async writexls(wb,sharecode){
var that=this;
var uuid=uuidv4();
var u=uuid.replace(/\-/g,"");
var fname="zc_"+u+".xlsx";
var filepath="/tmp/"+fname;
var promise=new Promise((resv,rej)=>{
wb.xlsx.writeFile(filepath).then(async function(d) {
var rtn=await that.ossClient.upfile(fname,filepath);
fs.unlink(filepath,function(err){});
return resv(rtn);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
//读取模板文件
async readxls(){
var promise=new Promise((resv,rej)=>{
var workbook = new excel.Workbook();
workbook.properties.date1904 = true;
var bpth=path.normalize(path.join(__dirname, '../'));
workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
.then(function() {
return resv(workbook);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
async buildworkbook(taxCalcList){
var workbook = await this.readxls();
var sheet = workbook.getWorksheet(1);
sheet.columns = [
{ header: '年度', key: 'statisticalYear', width: 10 },
{ header: '月份', key: 'statisticalMonth', width: 10 },
{ header: '员工姓名', key: 'employeeName', width: 10 },
{ header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
{ header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
// { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '子女教育', key: 'childrenEducation', width: 10 },
{ header: '继续教育', key: 'continuingEducation', width: 10 },
{ header: '房贷利息', key: 'interestExpense', width: 10 },
{ header: '住房租金', key: 'housingRent', width: 10 },
{ header: '赡养老人', key: 'supportElderly', width: 10 },
{ header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
{ header: '专项扣除合计', key: 'specialDeduction', width: 10 },
{ header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
{ header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
{ header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
{ header: '适用税率', key: 'taxRate', width: 10 },
{ header: '速算扣除', key: 'deductionNumber', width: 10 },
{ header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
{ header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
// (累计税前薪资-累计五险一金-累计免征额-累计已扣专项)*税率-速算扣除-累计已纳个税=本月应纳个税
];
taxCalcList.forEach(r=>{
sheet.addRow(r);
});
return workbook;
}
async makerpt(qobj){
var self=this;
return this.db.transaction(async t=>{
const sharecode=qobj.sharecode;
const email=qobj.email;
//按照sharecode获取单位某次个税计算
var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
var sheetNameSufix="个税汇总表";
if(taxCalcList && taxCalcList.length>0){
var year=taxCalcList[0].statisticalYear;
var month=taxCalcList[0].statisticalMonth;
sheetNameSufix=year+month+sheetNameSufix;
}
var wb=await this.buildworkbook(taxCalcList);
//生成excel
var result=await this.writexls(wb,sharecode);
//异步不等待发送邮件给
var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
//发送手机短信
//写到按咋回哦sharecode,修改下载的url
return result.url;
});
}
async create(qobj){
var self=this;
return this.db.transaction(async t=>{
var task=await this.dao.create(qobj,t);
//发布任务事件
var action="new";
var taskClassName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
await self.taskManager.newTask(msg);
await self.taskManager.publish("task","newtask");
return task;
});
}
async restartTasks2(qobj){
return this.restartTasks(qobj);
}
async restartTasks(qobj){
var self=this;
var rtn={};
var tasks=await this.dao.model.findAll({raw:true});
//清空任务列表
await this.taskManager.clearlist();
for(var i=0;i<tasks.length;i++){
var tmpTask2=tasks[i];
try {
(async (tmpTask,that)=>{
var action="new";
var taskClassName=tmpTask.taskClassName;
var exp=tmpTask.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
// await that.taskManager.newTask(msg);
// await that.taskManager.publish("task","newtask");
await that.taskManager.addTask(taskClassName,exp);
})(tmpTask2,self);
} catch (e) {
rtn=null;
}
}
return rtn;
}
async delete(qobj){
var self=this;
return this.db.transaction(async t=>{
var task= await this.dao.model.findOne({where:qobj});
await this.dao.delete(task,qobj,t);
//发布任务事件
var action="delete";
var taskName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskName;
//发布任务,消息是action_taskClassName
await this.taskManager.publish("task",msg,null);
return task;
});
}
}
module.exports=TaskService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class DeliverService extends ServiceBase {
constructor() {
super("deliver", ServiceBase.getDaoName(DeliverService));
}
async apiAll(params) {
try {
return await this.allList();
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiPage(params) {
try {
return await this.page(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiSave(params) {
try {
return await this.save(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiInfo(params) {
try {
return await this.info(params);
} catch (error) {
console.log(error);
return system.getResult(null, "接口异常");
}
}
async apiDeleteByIds(params) {
var ids = params.ids;
if(!ids || ids.length == 0) {
return system.getResult(null, "传入参数错误:ids=" + JSON.stringify(ids));
}
try {
for(var id of ids) {
try {
await this.delById(id);
} catch (error) {
console.log(error);
}
}
return system.getResultSuccess(1);
} catch (error) {
return system.getResult(null, "接口异常");
}
}
// -----------------------以此间隔,上面为API,下面为service---------------------------------
async info(params) {
var id = params.id;
var sqlWhere = {
where: {
id: id
},
attributes: ["id", "name", "businessmenDivide", "invoiceDivide", "isEnabled", "remark", "created_at"],
raw: true
};
var item = await this.dao.model.findOne(sqlWhere);
this.handleDate(item, ["created_at"], null, -8);
return system.getResultSuccess(item);
}
async save(params) {
var id = params.id;
var deliver;
if (id) {
deliver = await this.dao.findById(id);
} else {
deliver = {};
}
deliver.name = this.trim(params.name);
deliver.businessmenDivide = Number(params.businessmenDivide);
deliver.invoiceDivide = Number(params.invoiceDivide);
deliver.isEnabled = params.isEnabled == 1 ? true : 0;
deliver.remark = this.trim(params.remark);
if (id) {
deliver = await deliver.save();
} else {
deliver = await this.dao.create(deliver);
}
return system.getResultSuccess(deliver);
}
async allList() {
var list = await this.dao.getList(1, "id, name, businessmenDivide, invoiceDivide, remark");
return system.getResultSuccess(list);
}
async delById(id) {
if (!id) {
return system.getResult(null, "删除失败");
}
await this.dao.delById(id);
return system.getResultSuccess(1);
}
async page(params) {
var currentPage = Number(params.currentPage || 1);
var pageSize = Number(params.pageSize || 10);
var where = {};
var orderby = [
["id", 'desc']
];
var attributes = ["id", "name", "businessmenDivide", "invoiceDivide", "isEnabled", "remark", "created_at"];
var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
if (page && page.rows) {
for (var row of page.rows) {
this.handleDate(row, ["created_at"], null, -8);
}
}
return system.getResultSuccess(page);
}
}
module.exports = DeliverService;
// 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 moment = require('moment')
const settings = require("../../config/settings");
const md5 = require("MD5");
class ServiceBase {
constructor(gname, daoName) {
//this.dbf=system.getObject("db.connection");
this.db = system.getObject("db.common.connection").getCon();
this.cacheManager = system.getObject("db.common.cacheManager");
this.daoName = daoName;
this.dao = system.getObject("db." + gname + "." + daoName);
this.restS = system.getObject("util.restClient");
}
/**
* 验证签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async verifySign(params, app_key) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!params.sign) {
return system.getResult(null, "请求参数sign为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResult(null, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
if (params.sign != resultTmpSign) {
return system.getResult(null, "返回值签名验证失败");
}
return system.getResultSuccess();
}
/**
* 创建签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async createSign(params, app_key) {
if (!params) {
return system.getResultFail(-310, "请求参数为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResultFail(-330, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResultFail(-350, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
return system.getResultSuccess(resultTmpSign);
}
/**
* 验证参数信息不能为空
* @param {*} params 验证的参数
* @param {*} verifyParamsCount 需要验证参数的数量,如至少验证3个,则传入3
* @param {*} columnList 需要过滤掉的验证参数列表,格式:[]
*/
async verifyParams(params, verifyParamsCount, columnList) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!columnList) {
columnList = [];
}
var keys = Object.keys(params);
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
if (keys.length < verifyParamsCount) {
return system.getResult(null, "请求参数不完整");
}
var tResult = system.getResultSuccess();
for (let k = 0; k < keys.length; k++) {
const tKeyValue = keys[k];
if (columnList.length == 0 || columnList.indexOf(tKeyValue) < 0) {
if (!tKeyValue) {
tResult = system.getResult(null, k + "参数不能为空");
break;
}
}//白名单为空或不在白名单中,则需要验证不能为空
}
return tResult;
}
async apiCallWithAk(url, params) {
var acckapp = await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey);
var acck = acckapp.accessKey;
//按照访问token
var restResult = await this.restS.execPostWithAK(params, url, acck);
if (restResult) {
if (restResult.status == 0) {
var resultRtn = restResult.data;
return resultRtn;
} else {
await this.cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
return null;
}
}
return null;
}
// async apiCallWithAkNoWait(url,params){
// var acckapp=await this.cacheManager["ApiAccessKeyCache"].cache(settings.appKey);
// var acck=acckapp.accessKey;
// //按照访问token
// var restResult=await this.restS.execPostWithAK(params,url,acck);
// if(restResult){
// if(restResult.status==0){
// var resultRtn=restResult.data;
// return resultRtn;
// }else{
// await this.cacheManager["ApiAccessKeyCache"].invalidate(settings.appKey);
// return null;
// }
// }
// return null;
// }
static getDaoName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")).toLowerCase() + "Dao";
}
async findAndCountAll(obj) {
const apps = await this.dao.findAndCountAll(obj);
return apps;
}
async refQuery(qobj) {
return this.dao.refQuery(qobj);
}
async bulkDelete(ids) {
var en = await this.dao.bulkDelete(ids);
return en;
}
async delete(qobj) {
return this.dao.delete(qobj);
}
async create(qobj) {
return this.dao.create(qobj);
}
async update(qobj, tm = null) {
return this.dao.update(qobj, tm);
}
async updateByWhere(setObj, whereObj, t) {
return this.dao.updateByWhere(setObj, whereObj, t);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.dao.customExecAddOrPutSql(sql, paras);
}
async customQuery(sql, paras, t) {
return this.dao.customQuery(sql, paras, t);
}
async findCount(whereObj = null) {
return this.dao.findCount(whereObj);
}
async findSum(fieldName, whereObj = null) {
return this.dao.findSum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
return this.dao.getPageList(pageIndex, pageSize, whereObj, orderObj, attributesObj, includeObj);
}
async findOne(obj) {
return this.dao.findOne(obj);
}
async findById(oid) {
return this.dao.findById(oid);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
handleDate(row, fields, pattern, addHours) {
pattern = pattern || "YYYY-MM-DD HH:mm:ss";
if (!row) {
return;
}
for (var field of fields) {
if (row[field]) {
if(addHours) {
row[field] = moment(row[field]).add(addHours,"hours").format(pattern);
} else {
row[field] = moment(row[field]).format(pattern);
}
}
}
}
addWhereTime(where, field, begin, end) {
if(!begin && !end) {
return;
}
if (begin && end) {
where[field] = {
[this.db.Op.between]: [begin, end]
};
} else if (begin && !end) {
where[field] = {
[this.db.Op.gte]: begin
};
} else if (!begin && end) {
where[field] = {
[this.db.Op.lte]: end
};
}
}
trim(o) {
if(!o) {
return "";
}
return o.toString().trim();
}
}
module.exports = ServiceBase;
var sha1 = require('sha1'),
events = require('events'),
emitter = new events.EventEmitter(),
xml2js = require('xml2js');
// 微信类
var Weixin = function(path) {
this.data = '';
this.msgType = 'text';
this.fromUserName = '';
this.toUserName = '';
this.funcFlag = 0;
this.path=path;
}
// 验证
Weixin.prototype.checkSignature = function(req) {
// 获取校验参数
this.signature = req.query.signature,
this.timestamp = req.query.timestamp,
this.nonce = req.query.nonce,
this.echostr = req.query.echostr;
// 按照字典排序
var array = [this.token, this.timestamp, this.nonce];
array.sort();
// 连接
var str = sha1(array.join(""));
// 对比签名
if(str == this.signature) {
return true;
} else {
return false;
}
}
// ------------------ 监听 ------------------------
// 监听文本消息
Weixin.prototype.textMsg = function(callback) {
emitter.on("weixinTextMsg", callback);
return this;
}
// 监听图片消息
Weixin.prototype.imageMsg = function(callback) {
emitter.on("weixinImageMsg", callback);
return this;
}
// 监听地理位置消息
Weixin.prototype.locationMsg = function(callback) {
emitter.on("weixinLocationMsg", callback);
return this;
}
// 监听链接消息
Weixin.prototype.urlMsg = function(callback) {
emitter.on("weixinUrlMsg", callback);
return this;
}
// 监听事件
Weixin.prototype.eventMsg = function(callback) {
emitter.on("weixinEventMsg", callback);
return this;
}
// ----------------- 消息处理 -----------------------
/*
* 文本消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType text
* Content 文本消息内容
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseTextMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"content" : this.data.Content[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinTextMsg", msg);
return this;
}
/*
* 图片消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType image
* Content 图片链接
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseImageMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"picUrl" : this.data.PicUrl[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinImageMsg", msg);
return this;
}
/*
* 地理位置消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType location
* Location_X x
* Location_Y y
* Scale 地图缩放大小
* Label 位置信息
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseLocationMsg = function(data) {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"locationX" : this.data.Location_X[0],
"locationY" : this.data.Location_Y[0],
"scale" : this.data.Scale[0],
"label" : this.data.Label[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinLocationMsg", msg);
return this;
}
/*
* 链接消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType link
* Title 消息标题
* Description 消息描述
* Url 消息链接
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseLinkMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"title" : this.data.Title[0],
"description" : this.data.Description[0],
"url" : this.data.Url[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinUrlMsg", msg);
return this;
}
/*
* 事件消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType event
* Event 事件类型,subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
* EventKey 事件KEY值,与自定义菜单接口中KEY值对应
*/
Weixin.prototype.parseEventMsg = function() {
var eventKey = '';
if (this.data.EventKey) {
eventKey = this.data.EventKey[0];
}
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"event" : this.data.Event[0],
"eventKey" : eventKey,
"appk":this.path,
}
emitter.emit("weixinEventMsg", msg);
return this;
}
// --------------------- 消息返回 -------------------------
// 返回文字信息
Weixin.prototype.sendTextMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<Content><![CDATA[" + msg.content + "]]></Content>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// 返回音乐信息
Weixin.prototype.sendMusicMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<Music>" +
"<Title><![CDATA[" + msg.title + "]]></Title>" +
"<Description><![CDATA[" + msg.description + "DESCRIPTION]]></Description>" +
"<MusicUrl><![CDATA[" + msg.musicUrl + "]]></MusicUrl>" +
"<HQMusicUrl><![CDATA[" + msg.HQMusicUrl + "]]></HQMusicUrl>" +
"</Music>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// 返回图文信息
Weixin.prototype.sendNewsMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
//
var articlesStr = "";
for (var i = 0; i < msg.articles.length; i++)
{
articlesStr += "<item>" +
"<Title><![CDATA[" + msg.articles[i].title + "]]></Title>" +
"<Description><![CDATA[" + msg.articles[i].description + "]]></Description>" +
"<PicUrl><![CDATA[" + msg.articles[i].picUrl + "]]></PicUrl>" +
"<Url><![CDATA[" + msg.articles[i].url + "]]></Url>" +
"</item>";
}
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<ArticleCount>" + msg.articles.length + "</ArticleCount>" +
"<Articles>" + articlesStr + "</Articles>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// ------------ 主逻辑 -----------------
// 解析
Weixin.prototype.parse = function() {
if(this.data){
this.msgType = this.data.MsgType[0] ? this.data.MsgType[0] : "text";
switch(this.msgType) {
case 'text' :
this.parseTextMsg();
break;
case 'image' :
this.parseImageMsg();
break;
case 'location' :
this.parseLocationMsg();
break;
case 'link' :
this.parseLinkMsg();
break;
case 'event' :
this.parseEventMsg();
break;
}
}
}
// 发送信息
Weixin.prototype.sendMsg = function(msg) {
switch(msg.msgType) {
case 'text' :
this.sendTextMsg(msg);
break;
case 'music' :
this.sendMusicMsg(msg);
break;
case 'news' :
this.sendNewsMsg(msg);
break;
}
}
// Loop
Weixin.prototype.loop = function(req, res) {
// 保存res
this.res = res;
var self = this;
// 获取XML内容
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
buf += chunk;
});
// 内容接收完毕
req.on('end', function() {
xml2js.parseString(buf, function(err, json) {
if (err) {
err.status = 400;
} else {
req.body = json;
}
});
if(req.body){
self.data = req.body.xml;
}
self.parse();
});
}
module.exports = Weixin;
var Wx = require("./wx.event");
const system = require("../system");
var dicCache = {};
//创知厚的我想我要的配置
wxconfig = {
AppID: "wx4c91e81bbb6039cd",
Secret: "12048e66dba64f2581e02b306680b232",
Token: "bosstoken",
AccessTokenUrl: "https://api.weixin.qq.com/cgi-bin/token",
};
//智薪云的配置
wxconfig2 = {
AppID: "wxdc08c441c9fdb7a7",
Secret: "379e582e28645585a7def9c1c88de550",
Token: "bosstoken",
AccessTokenUrl: "https://api.weixin.qq.com/cgi-bin/token",
};
wxconfigDic = {
"wx4c91e81bbb6039cd": wxconfig,
"wxdc08c441c9fdb7a7": wxconfig2,
}
var getWeiXin = function (url) {
var weixin = null;
if (!dicCache[url]) {
weixin = new Wx(url);
dicCache[url] = weixin;
} else {
weixin = dicCache[url];
}
weixin.token = wxconfig.Token;
weixin.wxconfig = wxconfig;
weixin.getAccessConfig = function (appkey) {
var cfg = wxconfigDic[appkey];
return {
grant_type: "client_credential",
appid: cfg.AppID,
secret: cfg.Secret,
};
}
// 监听文本消息
weixin.textMsg(function (msg) {
console.log("textMsg received");
console.log(JSON.stringify(msg));
var resMsg = {};
switch (msg.content) {
case "文本":
// 返回文本消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "text",
content: "这是文本回复",
funcFlag: 0
};
break;
case "音乐":
// 返回音乐消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "music",
title: "音乐标题",
description: "音乐描述",
musicUrl: "音乐url",
HQMusicUrl: "高质量音乐url",
funcFlag: 0
};
break;
case "图文":
var articles = [];
articles[0] = {
title: "PHP依赖管理工具Composer入门",
description: "PHP依赖管理工具Composer入门",
picUrl: "http://weizhifeng.net/images/tech/composer.png",
url: "http://weizhifeng.net/manage-php-dependency-with-composer.html"
};
articles[1] = {
title: "八月西湖",
description: "八月西湖",
picUrl: "http://weizhifeng.net/images/poem/bayuexihu.jpg",
url: "http://weizhifeng.net/bayuexihu.html"
};
articles[2] = {
title: "「翻译」Redis协议",
description: "「翻译」Redis协议",
picUrl: "http://weizhifeng.net/images/tech/redis.png",
url: "http://weizhifeng.net/redis-protocol.html"
};
// 返回图文消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
}
}
weixin.sendMsg(resMsg);
});
// 监听图片消息
weixin.imageMsg(function (msg) {
console.log("imageMsg received");
console.log(JSON.stringify(msg));
});
// 监听位置消息
weixin.locationMsg(function (msg) {
console.log("locationMsg received");
console.log(JSON.stringify(msg));
});
// 监听链接消息
weixin.urlMsg(function (msg) {
console.log("urlMsg received");
console.log(JSON.stringify(msg));
});
// 监听事件消息
weixin.eventMsg(function (msg) {
if (msg.event == "subscribe" || msg.event == "SCAN") {
var wxservice = system.getObject("service.wxSve");
//to do msg.toUserName--按照微信号去取得应用,按照应用获取OAUTH
// wxservice.checkAndLogin(msg.fromUserName);
if (weixin.path == "ecwx") {
var urlstr = "https://ec.gongsibao.com/h5";
if (msg.eventKey && msg.eventKey != "") {
if (msg.eventKey.indexOf("_") >= 0) {
var strid = msg.eventKey.split('_')[1];
urlstr = urlstr + "?ecid=" + strid;
} else {
var strid = msg.eventKey;
urlstr = urlstr + "?ecid=" + strid;
}
}
var articles = [];
articles[0] = {
title: "欢迎来到智薪云签约平台",
description: "点击本图文消息,开始签约。",
picUrl: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_476111544670096808201813111368084242271.jpg",
url: urlstr,
};
var resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
};
weixin.sendMsg(resMsg);
} else {
//是否启用派单
var dispatchEnabled = true;
// 通知信息
var articles = [];
// 参数
var eventKey = msg.eventKey;
var userId = 0;
if (eventKey && eventKey.indexOf("_") > -1) {
// 标眼查通知openId保存逻辑
userId = Number(eventKey.split("_")[1] || 0);
if (userId && userId > 0) {
dispatchEnabled = false;
// 标眼查动态通知
articles[0] = {
title: "欢迎使用标眼监测商标监控工具",
description: "实时提醒商标动态,及时处理商标业务",
picUrl: "",
//picUrl: "https://search.gongsibao.com/imgs/biaoyan-logo-mini.png",
url: ""
};
}
}
else {
if (eventKey) {
userId = Number(eventKey);
}
}
if (dispatchEnabled) {
// 派单通知
articles[0] = {
title: "欢迎来到创知厚德智能派单平台",
description: "点击图文消息,开始接单",
picUrl: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_305111544784291353201814184451353distributeneed.png",
url: "https://boss.gongsibao.com/distributeneed",
};
}
if (userId && userId > 0) {
// wxservice.更新通知id
wxservice.updateNotifyOpenId(userId, msg.fromUserName);
}
var resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
};
weixin.sendMsg(resMsg);
}
} else {
//发送空串回微信服务器
weixin.res.send("");
}
});
return weixin;
}
module.exports = getWeiXin;
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment