Commit 229e76fd by 王栋源

wdy

parent c794e075

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

#!/bin/bash #!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang/node105:v2 FROM openjdk:8-jdk-alpine
MAINTAINER jy "jiangyong@gongsibao.com" VOLUME /tmp
ADD jiaxiya /apps/jiaxiya/ ARG JAR_FILE=target/*.jar
WORKDIR /apps/jiaxiya/ COPY ${JAR_FILE} app.jar
RUN cnpm install -S ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
CMD ["node","/apps/jiaxiya/main.js"]
......
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
const DocBase = require("./doc.base");
class APIBase extends DocBase {
constructor() {
super();
this.cacheManager = system.getObject("db.common.cacheManager");
this.logCtl = system.getObject("web.common.oplogCtl");
this.apitradeSvr = system.getObject("service.common.apitradeSve");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async isExistInNoAuthMainfest(gname, methodname) {
var fullname = gname + "." + methodname;
var lst = [
"test.test",
"transfer.acceptOrder",
"transfer.queryOrderState",
"transfer.closeOrder",
"transfer.test",
"transfer.queryOrder",
"transfer.selnotarytype",
"transfer.writecommunicationlog"
];
var x = lst.indexOf(fullname);
return x >= 0;
}
async checkAcck(gname, methodname, pobj, query, req) {
var apptocheck = null;
var isExistInNoAuth = await this.isExistInNoAuthMainfest(gname, methodname);
if (!isExistInNoAuth) {//在验证请单里面,那么就检查访问token
var ak = req.headers["accesskey"];
apptocheck = await this.cacheManager["ApiAccessKeyCheckCache"].cache(ak, { status: true }, 3000);
}
return { apptocheck: apptocheck, ispass: isExistInNoAuth || apptocheck };
}
async doexec(gname, methodname, pobj, query, req) {
try {
var requestid = req.headers["request-id"] || this.getUUID();
//检查访问token
var isPassResult = await this.checkAcck(gname, methodname, pobj, query, req);
if (!isPassResult.ispass) {
return system.getResultFail(system.tokenFail, "访问token失效,请重新获取");
}
pobj.requestid = requestid
var rtn = await this[methodname](pobj, query);
if (isPassResult.apptocheck) {
var app = isPassResult.apptocheck.app;
if (methodname && methodname.indexOf("recvNotificationForCacheCount") < 0) {
this.apitradeSvr.create({
srcappkey: app.appkey,
tradeType: "consume",
op: req.classname + "/" + methodname + "; requestid:" + requestid,
params: JSON.stringify(pobj),
clientIp: req.clientIp,
agent: req.uagent,
destappkey: settings.appKey,
});
}
}
return rtn;
} catch (e) {
console.log(e.stack, "api调用出现异常,请联系管理员..........")
this.logCtl.error({
optitle: "api调用出现异常,请联系管理员",
op: pobj.classname + "/" + methodname + "; requestid:" + requestid,
content: e.stack,
clientIp: pobj.clientIp
});
return system.getResultFail(-200, "出现异常,请联系管理员");
}
}
}
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: "meta",
groupDesc: "元数据服务包",
name: "ConfigAPI",
desc: "关于系统元数据或配置的类",
exam: "",
};
}
methodDescs() {
return [
{
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"
}
];
}
}
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(params) {
if (params.action_type == "findAndCountAll") {
return await this.cacheSve.findAndCountAll(params.body);
} else if (params.action_type == "delCache") {
return await this.cacheSve.delCache(params.body);
} else if (params.action_type == "clearAllCache") {
return await this.cacheSve.clearAllCache(params.body);
} else {
return system.getResultFail();
}
}
//接受缓存计数通知接口
async recvNotificationForCacheCount(p,q,req){
return this.cacheSve.recvNotificationForCacheCount(p);
}
exam(){
return "xxx";
}
classDesc() {
return {
groupName: "meta",
groupDesc: "元数据服务包",
name: "OpCacheAPI",
desc: "关于系统缓存的操作类",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "生成访问token",
methodName: "opCacheData",
paramdescs: [
{
paramDesc: "访问action_type类型:findAndCountAll为查询,delCache为删除,clearAllCache为清理",
paramName: "action_type",
paramType: "string",
defaultValue: null,
},
{
paramDesc: "访问body参数",
paramName: "body",
paramType: "json",
defaultValue: null,
}
],
rtnTypeDesc: "xxxx",
rtnType: "xxx"
}
];
}
}
module.exports = OpCacheAPI;
\ No newline at end of file
var APIBase =require("../../api.base");
var system=require("../../../system");
class TestAPI extends APIBase{
constructor(){super();}
async test(pobj,query){
return system.getResultSuccess({hello:"ok"});
}
exam(){
return "xxx";
}
classDesc(){
return {
groupName:"auth",
groupDesc:"认证相关的包",
name:"AccessAuthAPI",
desc:"关于认证的类",
exam:"",
};
}
methodDescs(){
return [
{
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"
}
];
}
}
module.exports=TestAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
const Client = require('aliyun-api-gateway').Client;
const client = new Client('203756933','1hxwkxz2tyn80i3ucrdbchru59zpxibz');
class TradeTransferAPI extends APIBase {
constructor() {
super();
this.tradetransferSve= system.getObject("service.transfer.tradetransferSve");
this.notarizationflowSve= system.getObject("service.transfer.notarizationflowSve");
}
async acceptOrder(pobj, query) {
pobj.channelParams.fq_ordernum=pobj.orderNo;
return await this.tradetransferSve.createtransfer(pobj.channelParams);
}
async closeOrder(pobj, query) {
return await this.tradetransferSve.orderclose(pobj);
}
async queryOrderState(pobj, query) {
return await this.tradetransferSve.ordersel(pobj);
}
async queryOrder(pobj, query) {
return await this.tradetransferSve.querytradeproducelist(pobj);
}
async selnotarytype(pobj, query) {
return await this.notarizationflowSve.selnotarytype(pobj);
}
async writecommunicationlog(pobj, query) {
return await this.tradetransferSve.writecommunicationlog(pobj);
}
async test(pobj, query){
var url = 'https://jaxiya.gongsibao.com/orders/refuse';
var result = await client.post(url, {
data:{
"BizId":"trademark_prepayment_pre-cn-o401er9gv01",
"UserName":"阿里云",
"Mobile":"18600480430",
"RegisterNumber":"25559504",
"Classification":"20",
"Price":"10"
},
headers: {
accept: 'application/json'
}
});
return result;
console.log(JSON.stringify(result));
}
exam() {
return "xxx";
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: "",
};
}
methodDescs() {
return [
{
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"
}
];
}
}
module.exports = TradeTransferAPI;
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
class CtlBase {
constructor(gname, sname) {
this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname);
this.cacheManager = system.getObject("db.common.cacheManager");
this.redisClient = system.getObject("util.redisClient");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async encryptPasswd(passwd) {
if (!passwd) {
throw new Error("请输入密码");
}
var rtn=await this.service.getEncryptStr(passwd);
return rtn;
}
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);
}
async findAndCountAll(obj, queryobj, req) {
obj.codepath = req.codepath;
if (req.session.user) {
obj.uid = req.session.user.id;
}
//
// if(obj.search){
// obj.search.opath=obj.ppath;
// }
// if(obj.search){
// obj.search.company_id=obj.company_id;
// }
var apps = await this.service.findAndCountAll(obj);
return system.getResult(apps);
}
async refQuery(queryobj, qobj, req) {
// qobj.refwhere = { app_id: req.appid };
var rd = await this.service.refQuery(qobj);
return system.getResult(rd);
}
async bulkDelete(queryobj, ids) {
var rd = await this.service.bulkDelete(ids);
return system.getResult(rd);
}
async delete(queryobj, qobj) {
var rd = await this.service.delete(qobj);
return system.getResult(rd);
}
async create(qobj, queryobj, req) {
if (req && req.session && req.session.app) {
// qobj.app_id = req.appid;
if (req.codepath) {
qobj.codepath = req.codepath;
}
}
var rd = await this.service.create(qobj);
return system.getResult(rd);
}
async update(qobj, queryobj, 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);
}
static getServiceName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async initNewInstance(queryobj, req) {
return system.getResult({});
}
async findById(oid) {
var rd = await this.service.findById(oid);
return system.getResult(rd);
}
//按照单据号查询出单据
async findByCode(qobj,queryobj, req) {
var rd = await this.service.findOne({ id: qobj.code});
if (!rd) {
var rd = await this.service.findOne({ code: qobj.code});
}
return system.getResult(rd);
}
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 setContextParams(pobj, qobj, req) {
pobj.userid = req.session.user ? req.session.user.id : null;
//to do
if( req.session.user){
pobj.company_id=req.session.user.owner.id;
pobj.opath=req.session.user.opath;
pobj.ppath=req.session.user.ppath;
}
req.codepath=req.headers["codepath"];
}
async doexec(methodname, pobj, query, req) {
try {
await this.setContextParams(pobj, query, req);
// //检查appkey
// let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(pobj.appKey);
// if(key==null){
// return system.getResultFail(system.tokenFail,"appKey授权有误");
// }
var rtn = await this[methodname](pobj, query, req);
// await this. apitradeSvr .create({
// appkey: pobj.appKey,
// tradeType: "consume",
// op: pobj.classname + "/" + methodname,
// params: JSON.stringify(pobj),
// clientIp: pobj.clientIp,
// agent: pobj.agent,
// });
return rtn;
} catch (e) {
console.log(e.stack, "出现异常,请联系管理员.......");
// this.logCtl.error({
// optitle: "api调用出错",
// op: pobj.classname + "/" + methodname,
// content: e.stack,
// clientIp: pobj.clientIp
// });
return system.getResultFail(-200, "出现异常,请联系管理员");
}
}
}
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");
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
}
/**
* 开放平台回调处理
* @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) {
if(settings.companyKey){//说明是自主登录
jumpobj.jumpUrl=jumpobj.jumpUrl+"&companyKey="+settings.companyKey;
}
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(",") : "",
owner:req.session.user.owner,
isSelfLogin:settings.companyKey?true:false
}
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;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
class OplogCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve");
}
async initNewInstance(qobj) {
var u = uuidv4();
var aid = u.replace(/\-/g, "");
var rd = { name: "", appid: aid }
return system.getResultSuccess(rd, null);
}
async debug(obj) {
obj.logLevel = "debug";
return this.create(obj);
}
async info(obj) {
obj.logLevel = "info";
return this.create(obj);
}
async warn(obj) {
obj.logLevel = "warn";
return this.create(obj);
}
async error(obj) {
obj.logLevel = "error";
return this.create(obj);
}
async fatal(obj) {
obj.logLevel = "fatal";
return this.create(obj);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
}
module.exports = OplogCtl;
var system=require("../../../system")
const CtlBase = require("../../ctl.base");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='DHmRtFlw2Zr3KaRwUFeiu7FWATnmla';
var accessKeyId='LTAIyAUK8AD04P5S';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class UploadCtl extends CtlBase{
constructor(){
super("common",CtlBase.getServiceName(UploadCtl));
this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 '{fileName}'";
this.restS=system.getObject("util.execClient");
this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'";
//sed -i 's/1111/&BBB/' /tmp/input.txt
//sed 's/{position}/{content}/g' {path}
}
async getOssConfig(){
var policyText = {
"expiration":"2119-12-31T16:00:00.000Z",
"conditions":[
["content-length-range",0,1048576000],
["starts-with","$key","zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64
var data={
OSSAccessKeyId:accessKeyId,
policy:policyBase64,
Signature:signature,
Bucket:'gsb-zc',
success_action_status:201,
url:url
};
return data;
};
async upfile(srckey,dest){
var oss=system.getObject("util.ossClient");
var result=await oss.upfile(srckey,"/tmp/"+dest);
return result;
};
async downfile(srckey){
var oss=system.getObject("util.ossClient");
var downfile=await oss.downfile(srckey).then(function(){
downfile="/tmp/"+srckey;
return downfile;
});
return downfile;
};
async pdf2html(obj){
var srckey=obj.key;
var downfile=await this.downfile(srckey);
var cmd=this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
var rtn=await this.restS.exec(cmd);
var path="/tmp/"+srckey.split(".pdf")[0]+".html";
var a=await this.insertToFile(path);
fs.unlink("/tmp/"+srckey);
var result=await this.upfile(srckey.split(".pdf")[0]+".html",srckey.split(".pdf")[0]+".html");
return result.url;
};
async insertToFile(path){
var cmd=this.cmdInsertToFilePattern+" "+path;
return await this.restS.exec(cmd);
};
}
module.exports=UploadCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var moment = require("moment");
class NotarizationflowCtl extends CtlBase {
constructor() {
super("transfer", CtlBase.getServiceName(NotarizationflowCtl));
//this.appS=system.getObject("service.appSve");
}
//首次加载
async firstload(p, q) {
var notarinfo = await this.service.firstload(p);
return notarinfo;
}
//提交阿里
async submitali(p, q, req) {
var notarinfo = p;
if (notarinfo) {
var rtn = await this.service.update(notarinfo);
if (rtn) {
var alirtn = await this.service.setfiletoali(notarinfo);
if (alirtn) {
return { data: alirtn, status: 0, msg: "提交成功" }
}else{
return { data: null, status: -202, msg: "提交失败" }
}
}else{
return { data: null, status: -201, msg: "保存失败" }
}
}else{
return { data: null, status: -200, msg: "参数异常" }
}
}
}
module.exports = NotarizationflowCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
class TmjsonfileCtl extends CtlBase {
constructor() {
super("transfer", CtlBase.getServiceName(TmjsonfileCtl));
}
async createjsonfile(p, o, q) {
var rtn = await this.service.createjsonfile();
console.log(rtn);
if (rtn.status > -1) {
var oss = system.getObject("util.ossClient");
var newdate = new Date();
var m = newdate.getMonth() + 1;
var d = newdate.getDate();
var strdate = ""
if (newdate.getHours() > 12) {
strdate = newdate.getFullYear() + "" + m + d + "_2.json";
} else {
strdate = newdate.getFullYear() + "" + m + d + "_1.json";
}
var result = await oss.upfile(strdate, "/tmp/20191112_2.json");
if (result.res.status > -1) {
var obj = { zc_url: result.url };
var s = await this.service.create(obj);
if (s) {
return { status: 0, msg: "成功" };
}
}else{
return { status:-201, msg: "创建失败" };
}
}else{
return { status:-200, msg: "json文件生成失败" };
}
}
}
module.exports = TmjsonfileCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
var cacheBaseComp = null;
class TradetransferCtl extends CtlBase {
constructor() {
super("transfer", CtlBase.getServiceName(TradetransferCtl));
this.postfile=system.getObject("util.restClient");
}
async submit(p, q, req) {
if (req && req.session && req.session.user) {
p.onlyCode = req.session.user.unionId;
}
if (req.codepath) {
p.codepath = req.codepath;
}
var a = null;
if (p.tranfer_status == "CONFIRM_ORDER") {
p.aliorder_status = "1",
a = await this.service.confirmorder(p);
console.log(a)
}
if (p.tranfer_status == "CLOSE_ORDER_ONLY") {
p.aliorder_status = "11",
a = await this.service.refuseorder(p)
}
if (p.tranfer_status == "PROVIDE_MATERIAL") {
p.aliorder_status = "3",
a = await this.service.supplymaterail(p)
}
if (p.tranfer_status == "BUYER_EXPRESS") {
p.aliorder_status = "5",
a = await this.service.posttransfermatereial(p)
}
if (p.tranfer_status == "BUYER_PROVIDE_MATERIAL") {
p.aliorder_status = "6",
a = await this.service.receivedtransfermaterail(p)
}
if (p.tranfer_status == "SUBMIT_TO_SBJ") {
p.aliorder_status = "7",
a = await this.service.submittedtransfermaterail(p)
}
if (p.tranfer_status == "SBJ_ACCEPT") {
p.aliorder_status = "8",
a = await this.service.acceptedtransfermaterail(p)
}
if (p.tranfer_status == "SBJ_SUCCESS") {
p.aliorder_status = "8",
a = await this.service.approvedtransfer(p)
}
if (p.tranfer_status == "SBJ_FAIL") {
p.aliorder_status = "8",
a = await this.service.refusetransfer(p)
}
if (p.tranfer_status == "TRANSFER_SUCCESS") {
p.aliorder_status = "12",
a = await this.service.tradesuccess(p)
}
if (p.tranfer_status == "TRANSFER_FAIL") {
p.aliorder_status = "10",
a = await this.service.tradefail(p)
}
if (p.tranfer_status == "RefuseOrder") {
p.aliorder_status = "10",
a = await this.service.tradefail(p)
}
if (a.Success) {
var rd = await this.service.update(p);
return system.getResult(rd);
} else {
return system.getResult(null, "阿里请求失败");
}
}
async findone(p,q,req){
var traninfo = await this.service.findOne({ ali_bizid: p.ali_bizid });
return { data: traninfo.dataValues, status: 0, msg: "操作成功" }
}
//获取签名
async generateuploadfilepolicy(p, q, req) {
var self = this;;
var gobj = {
action: "GenerateUploadFilePolicy",
reqbody: { FileType: "LEGAL_NOTICE" }
}
if (p.mtype && p.mtype == 'json') {
gobj.reqbody.FileType = 'PARTNER_SYNC_FILE';
}
try {
var rst = await self.service.aliclient(gobj);
console.log(rst)
var source = {
OSSAccessKeyId: rst.AccessId,
policy: rst.EncodedPolicy,
Signature: rst.Signature,
Bucket: 'trade-mark-user-upload',
url: "https://trade-mark-user-upload.oss-cn-beijing.aliyuncs.com",
filedir: rst.FileDir
}
if(p.mtype && p.mtype == 'json') {
source.url="https://partner-sync-file.oss-cn-beijing.aliyuncs.com";
source.Bucket="partner-sync-file";
}
console.log(source)
return source;
} catch (e) {
console.log(e)
}
}
}
module.exports = TradetransferCtl;
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),
company_id:DataTypes.INTEGER,
opath:DataTypes.STRING(256),
};
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 = "sadd_children_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");
class ApiAccessControlCache extends CacheBase {
constructor() {
super();
}
desc() {
return "API访问控制缓存";
}
prefix() {
return "api_access_control_:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
return val;
}
}
module.exports = ApiAccessControlCache;
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 "g_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 "g_accesskeycheck_";
}
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");
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "缓存管理";
}
prefix() {
return "magCache:";
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
return val;
}
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 "g_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;
var db = system.getObject("db.common.connection").getCon();
this.db = db;
console.log("........set dao model..........");
this.model = db.models[this.modelName];
console.log(this.modelName);
}
preCreate(u) {
return u;
}
async create(u, t) {
var u2 = this.preCreate(u);
if (t) {
return this.model.create(u2, { transaction: t }).then(u => {
return u;
});
} else {
return this.model.create(u2).then(u => {
return u;
});
}
}
static getModelName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery(qobj) {
var w =qobj.refwhere? qobj.refwhere:{};
if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
}
if (qobj.parentinfo) {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
}
//如果需要控制数据权限
if(qobj.datapriv){
w["id"]={ [this.db.Op.in]: qobj.datapriv};
}
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({ where: w, attributes: qobj.fields });
}
}
async bulkDelete(ids) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en;
}
async bulkDeleteByWhere(whereParam, t) {
var en = null;
if (t != null && t != 'undefined') {
whereParam.transaction = t;
return await this.model.destroy(whereParam);
} else {
return await this.model.destroy(whereParam);
}
}
async delete(qobj, t) {
var en = await this.model.findOne({ where: qobj });
if (t != null && t != 'undefined') {
if (en != null) {
return en.destroy({ transaction: t });
}
} else {
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;
var qc = {};
//设置分页查询条件
qc.limit = pageSize;
qc.offset = (pageNo - 1) * pageSize;
//默认的查询排序
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;
}
return qc;
}
buildaggs(qobj) {
var aggsinfos = [];
if (qobj.aggsinfo) {
qobj.aggsinfo.sum.forEach(aggitem => {
var t1 = [this.db.fn('SUM', this.db.col(aggitem.field)), aggitem.field + "_" + "sum"];
aggsinfos.push(t1);
});
qobj.aggsinfo.avg.forEach(aggitem => {
var t2 = [this.db.fn('AVG', this.db.col(aggitem.field)), aggitem.field + "_" + "avg"];
aggsinfos.push(t2);
});
}
return aggsinfos;
}
async findAggs(qobj, qcwhere) {
var aggArray = this.buildaggs(qobj);
if (aggArray.length != 0) {
qcwhere["attributes"] = {};
qcwhere["attributes"] = aggArray;
qcwhere["raw"] = true;
var aggResult = await this.model.findOne(qcwhere);
return aggResult;
} else {
return {};
}
}
async findAndCountAll(qobj, t) {
var qc = this.buildQuery(qobj);
var apps = await this.model.findAndCountAll(qc);
var aggresult = await this.findAggs(qobj, qc);
var rtn = {};
rtn.results = apps;
rtn.aggresult = aggresult;
return rtn;
}
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 bulkCreate(ids, t) {
if (t != null && t != 'undefined') {
return await this.model.bulkCreate(ids, { transaction: t });
} else {
return await this.model.bulkCreate(ids);
}
}
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 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;
}else{
tmpWhere.raw = true;
}
return await this.model.findAndCountAll(tmpWhere);
}
async findOne(obj) {
return this.model.findOne({ "where": obj });
}
async findById(oid) {
return this.model.findById(oid);
}
}
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");
class ApiTradeDao{
constructor(){
//super(Dao.getModelName(AppDao));
}
}
module.exports=ApiTradeDao;
const fs=require("fs");
const settings=require("../../../../config/settings");
class CacheManager{
constructor(){
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap(){
var self=this;
self.doc={};
var cachePath=settings.basepath+"/app/base/db/cache/";
const files=fs.readdirSync(cachePath);
if(files){
files.forEach(function(r){
var classObj=require(cachePath+"/"+r);
self[classObj.name]=new classObj();
var refTmp=self[classObj.name];
if(refTmp.prefix){
self.doc[refTmp.prefix]=refTmp.desc;
}
else{
console.log("请在"+classObj.name+"缓存中定义prefix");
}
});
}
}
}
module.exports=CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const Sequelize = require('sequelize');
const settings=require("../../../../config/settings")
const fs=require("fs")
const path=require("path");
var glob = require("glob");
class DbFactory{
constructor(){
const dbConfig=settings.database();
this.db=new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
dbConfig.config);
this.dbigirlweb=new Sequelize("igirl",
dbConfig.user,
dbConfig.password,
dbConfig.config);
this.db.Sequelize=Sequelize;
this.db.Op=Sequelize.Op;
this.dbigirlweb.Sequelize=Sequelize;
this.dbigirlweb.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(){
}
//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;
}
getConigirl(){
var that=this;
if(settings.env=="dev"){
}
return this.dbigirlweb;
}
}
module.exports=DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class MetaDao{
constructor(){
//super(Dao.getModelName(AppDao));
}
}
module.exports=MetaDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class OplogDao extends Dao{
constructor(){
super(Dao.getModelName(OplogDao));
}
}
module.exports=OplogDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class TaskDao extends Dao{
constructor(){
super(Dao.getModelName(TaskDao));
}
extraWhere(qobj,qw,qc){
qc.raw=true;
return qw;
}
async delete(task,qobj,t){
return task.destroy({where:qobj,transaction:t});
}
}
module.exports=TaskDao;
const system=require("../../../system");
const fs=require("fs");
const settings=require("../../../../config/settings");
var cron = require('node-cron');
class TaskManager{
constructor(){
this.taskDic={};
this.redisClient=system.getObject("util.redisClient");
this.buildTaskMap();
}
async buildTaskMap(){
var self=this;
//订阅任务频道
await this.redisClient.subscribeTask("task",this);
var taskPath=settings.basepath+"/app/base/db/task/";
const files=fs.readdirSync(taskPath);
if(files){
files.forEach(function(r){
var classObj=require(taskPath+"/"+r);
self[classObj.name]=new classObj();
});
}
}
async addTask(taskClassName,exp){
(async (tn,ep)=>{
if(!this.taskDic[tn]){
this.taskDic[tn]=cron.schedule(ep,()=>{
this[tn].doTask();
});
}
})(taskClassName,exp);
}
async deleteTask(taskClassName){
if(this.taskDic[taskClassName]){
this.taskDic[taskClassName].destroy();
delete this.taskDic[taskClassName];
}
}
async clearlist(){
var x=await this.redisClient.clearlist("tasklist");
return x;
}
async publish(channel,msg){
var x=await this.redisClient.publish(channel,msg);
return x;
}
async newTask(taskstr){
return this.redisClient.rpush("tasklist",taskstr);
}
}
module.exports=TaskManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class UploadDao extends Dao{
constructor(){
super(Dao.getModelName(UploadDao));
}
}
module.exports=UploadDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class NotarizationflowDao extends Dao{
constructor(){
super(Dao.getModelName(NotarizationflowDao));
}
}
module.exports=NotarizationflowDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class TmjsonfileDao extends Dao{
constructor(){
super(Dao.getModelName(TmjsonfileDao));
}
}
module.exports=TmjsonfileDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class TradetransferDao extends Dao{
constructor(){
super(Dao.getModelName(TradetransferDao));
}
}
module.exports=TradetransferDao;
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": "d47f72a7228243a3bad03541d2a2c22c",
"label": "加西亚交付平台",
"config": {
"rstree": {
"code": "projroot",
"label": "projroot",
"children": [
{
"code": "diliverCenter",
"label": "交付中心",
"src": "/imgs/logo.png",
"isSubmenu": true,
"isleft": true,
"children": [
{
"code": "singleMonitor", "isGroup": true, "label": "个人监控", "children": [
{
"code": "mytradetransferdiliver",
"label": "商标转让",
"isMenu": true,
"bizCode": "mytradetransferdiliver",
"bizConfig": null,
"path": "",
"isleft": true,
},
{
"code": "mynotarizationflow",
"label": "公证申请",
"bizCode": "mynotarizationflow",
"bizConfig": null,
"path": "",
"isleft": true,
},
{
"code": "tansfersupplymaterail",
"label": "交易补充资料",
"bizCode": "tansfersupplymaterail",
"bizConfig": null,
"path": "",
"isleft": true,
}
]
},
{
"code": "projMonitor", "isGroup": true, "label": "全局监控", "children": [
{
"code": "alltradetransferdilivers",
"label": "商标转让",
"isMenu": true,
"bizCode": "alltradetransferdilivers",
"bizConfig": null,
"path": "",
"isleft": true,
},
{
"code": "mynotarizationflow",
"label": "公证申请",
"bizCode": "mynotarizationflow",
"bizConfig": null,
"path": ""
},
{
"code": "tansfersupplymaterail",
"label": "公证申请",
"bizCode": "tansfersupplymaterail",
"bizConfig": null,
"path": ""
},
{
"code": "tmjsonfileversion",
"label": "商标文件",
"isMenu": true,
"bizCode": "tmjsonfileversion",
"bizConfig": null,
"path": ""
},
]
},
],
},
],
},
"bizs": {
"home": { "title": "前台首页", "config": null, "path": "/", "comname": "home" },
"admin": { "title": "后台首页", "config": null, "path": "/index", "comname": "admin" },
"mytradetransferdiliver": { "title": "商标转让", "config": null, "path": "/mytradetransferdiliver", "comname": "tradetransferdiliver" },
"tmjsonfileversion": { "title": "商标文件", "config": null, "path": "/tmjsonfileversion", "comname": "tmjsonfileversion" },
"mynotarizationflow": {
"title": "公证申请",
"config": null,
"isDynamicRoute": false,
"path": "/mynotarizationflow",
"comname": "mynotarizationflow"
},
"tansfersupplymaterail": {
"title": "公证申请",
"config": null,
"isDynamicRoute": false,
"path": "/tansfersupplymaterail",
"comname": "tansfersupplymaterail"
},
},
"pauths": [
"add", "edit", "delete", "export", "show"
],
"pdict": {
"app_type": { "api": "数据API", "web": "站点", "app": "移动APP", "xcx": "小程序", "access": "接入" },
"data_priv": { "auth.role": "角色", "auth.user": "用户", "common.app": "应用" },
"noticeType": { "sms": "短信", "email": "邮件", "wechat": "微信" },
"authType": { "add": "新增", "edit": "编辑", "delete": "删除", "export": "导出", "show": "查看" },
"mediaType": { "vd": "视频", "ad": "音频", "qt": "其它" },
"usageType": { "kt": "课堂", "taxkt": "财税课堂", "qt": "其它" },
"opstatus": { "0": "失败", "1": "成功" },
"sex": { "male": "男", "female": "女" },
"configType": { "price": "宝币兑换率", "initGift": "初次赠送", "apiInitGift": "API初次赠送", "apiCallPrice": "api调用价格" },
"logLevel": { "debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4 },
"msgType": { "sys": "系统", "single": "单点", "multi": "群发", "mryzSingle": "每日易照单点", "mryzLicense": "群发", },
"tradeType": {
"fill": "充值宝币", "consume": "消费宝币", "gift": "赠送宝币", "giftMoney": "红包", "refund": "退款", "payment": "付款",
},
"question_status": { "waithandle": "待解决", "inmiddle": "解决中", "waitcheck": "待验证", "success": "成功解决", "invalid": "无效问题" },
"urgent_status": { "urgent": "紧急", "general": "一般" },
"tranfer_status": {
"READY_ORDER": "订单准备",
"CONFIRM_ORDER": "确认订单",
"CLOSE_ORDER_ONLY": "拒绝订单",
"PROVIDE_MATERIAL": "上传卖家资料",
"PAY_OVER": "尾款确认",
"BUYER_EXPRESS": "邮寄资料",
"BUYER_PROVIDE_MATERIAL": "确认收件",
"SUBMIT_TO_SBJ": "提交官方",
"SBJ_ACCEPT": "商标局受理",
"SBJ_SUCCESS": "商标局核准",
"SBJ_FAIL": "商标局不核准",
"TRANSFER_FAIL": "交易失败",
"TRANSFER_SUCCESS": "交易成功",
"CLOSE_ORDER_REFUND":"订单关闭",
"REFUSE_ORDER":"取消订单"
},
"aliorder_status": {
"1": "确认商标状态",
"11": "订单关闭(不退款)",
"2": "文档清单及模板",
"3": "提供交易文件",
"4": "确认交易文档",
"5": "确认展示文档,快递卖家",
"6": "买家提供文件",
"7": "转让申请递交",
"8": "官文转达(受通)",
"8": "官文转达(受通)",
"9": "官文转达(补正)",
"10": "退款",
"12": "订单完成"
},
"tranferperson_type": {
"person": "个人",
"ent": "企业"
},
"certificate_type": {
"1": "身份证",
"2": "护 照"
},
"notary_status": {
"0": "创建订单待提交",
"1": "已提交",
"2": "已受理",
"3": "已出证",
"4": "已终⽌"
}
}
}
}
\ No newline at end of file
module.exports={
"list":{
columnMetaData:[
{"width":"100","label":"买方姓名 ","prop":"user_name","isShowTip":true,"isTmpl":false},
{"width":"80","label":"注册号","prop":"tm_number","isShowTip":true,"isTmpl":false},
{"width":"80","label":"状态","prop":"tranfer_status_name","isShowTip":true,"isTmpl":false},
{"width":"100","label":"买方电话","prop":"mobile","isShowTip":true,"isTmpl":false},
{"width":"100","label":"尼斯大类","prop":"ncl_one","isShowTip":true,"isTmpl":false},
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":true},
]
},
"form":[
{
"title":"控制信息",
ctls:[
{"type":"select","dicKey":"tranfer_status","label":"转让状态","prop":"tranfer_status","labelField":"label","valueField":"value","style":"","isButton":true},
// {"type":"select","refModel":"pmproduct","isMulti":false,"label":"所属产品","prop":"pmproduct_id","labelField":"name","valueField":"id","style":""},
]
},
{
"title":"基本信息",
ctls:[
{"type":"input","label":"买家姓名","prop":"user_name","disabled":true,"placeHolder":"买家姓名","style":""},
{"type":"input","label":"邮寄单号","prop":"logistics","disabled":false,"placeHolder":"邮寄单号","style":""},
]
},
],
"search":[
{
"title":"基本查询",
ctls:[
{"type":"input","label":"买方姓名","prop":"user_name","placeHolder":"请输入买方姓名","style":""},
{"type":"input","label":"注册号","prop":"tm_number","placeHolder":"请输入注册号","style":""},
]
},
],
"auth":{
"add":[
{"icon":"el-icon-save","title":"保存","type":"default","key":"save","isOnForm":true},
{"icon":"el-icon-save","title":"提交","type":"default","key":"submit","isOnForm":true},
],
"edit":[
{"icon":"el-icon-edit","title":"修改","type":"default","key":"edit","isInRow":true},
{"icon":"el-icon-edit","title":"资料上传","type":"default","key":"upfiles","isInRow":true},
{"icon":"el-icon-edit","title":"公证申请","type":"default","key":"notar","isInRow":true},
],
"delete":[
// {"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":true},
],
"common":[
{"icon":"el-icon-cancel","title":"取消","type":"default","key":"cancel","isOnForm":true},
],
}
}
module.exports = {
"list": {
columnMetaData: [
{ "width": "100", "label": "id", "prop": "id", "isShowTip": true, "isTmpl": false },
{ "width": "80", "label": "文件链接", "prop": "jsonfile_url", "isShowTip": true, "isTmpl": false },
{ "width": "80", "label": "zc链接", "prop": "zc_url", "isShowTip": true, "isTmpl": false },
{ "width": "80", "label": "状态", "prop": "status", "isShowTip": true, "isTmpl": false },
{ "width": "80", "label": "修改时间", "prop": "updated_at", "isShowTip": true, "isTmpl": false },
{"width":"null","label":"操作","name":"null","isShowTip":false,"isTmpl":true,"isBtns":true},
]
},
"form": [
],
"search": [
{
"title": "基本查询",
ctls: [
{ "type": "input", "label": "状态", "prop": "status", "placeHolder": "状态", "style": "" },
]
},``
],
"auth": {
"add": [
{"icon":"el-icon-plus","title":"新增","type":"default","key":"create","isOnGrid":true},
],
"edit": [
{"icon":"el-icon-edit","title":"下载","type":"default","key":"openurl","isInRow":true},
{"icon":"el-icon-edit","title":"资料上传","type":"default","key":"upfiles","isInRow":true},
],
"delete": [
// {"icon":"el-icon-remove","title":"删除","type":"default","key":"delete","isInRow":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["config"]=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
},
app_id:DataTypes.INTEGER,
account_id:DataTypes.INTEGER,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
company_id:DataTypes.INTEGER,
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_user',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("oplog", {
appkey: {
type:DataTypes.STRING,
allowNull: true,
},
appname:{
type:DataTypes.STRING,
allowNull: false,
},
userid: { type: DataTypes.INTEGER,allowNull: true},
username:{
type:DataTypes.STRING,
allowNull: true,
},
logLevel: {
type:DataTypes.ENUM,
allowNull: false,
values: Object.keys(uiconfig.config.pdict.logLevel),
defaultValue: "info",
},
op:{
type:DataTypes.STRING,
allowNull: true,
},
content:{
type:DataTypes.STRING(4000),
allowNull: true,
},
clientIp:DataTypes.STRING,
agent:{
type:DataTypes.STRING,
allowNull: true,
},
opTitle:DataTypes.STRING(500),
},{
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt:false,
//freezeTableName: true,
// define the table's name
tableName: 'op_log',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (db, DataTypes) => {
return db.define("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("notarizationflow", {
ali_bizid: DataTypes.STRING, //'阿里订单号'
fq_ordernum: DataTypes.STRING, //合作方订单号
//材料信息
tmRegisterCertificate: DataTypes.STRING, // "商标注册证",
businessLicense: DataTypes.STRING, // "机构营业执照(卖家营业执照证件)",
buyerIdentification: DataTypes.STRING, // "受让人身份证明材料",
tmAcceptCertificate: DataTypes.STRING, // "商标受理通知书",
sellerFrontOfIdCard: DataTypes.STRING, // "卖家身份证正面",
sellerBackOfIdCard: DataTypes.STRING, // "卖家身份证反面",
tmRegisterChangeCertificate: DataTypes.STRING, // "商标注册证变更证明",
//买家信息
buyerType: { // "买方类型",
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.tranferperson_type), //
set: function (val) {
this.setDataValue("buyerType", val);
this.setDataValue("buyerTypeName", uiconfig.config.pdict.tranferperson_type[val]);
}
},
buyerTypeName: DataTypes.STRING, // "买方类型",
buyerCompanyame: DataTypes.STRING, // "买方企业名称",
buyerName: DataTypes.STRING, // "买家姓名",
certificateNo: DataTypes.STRING, // "证件号",
certificateType: { // "证件类型(目前仅支持身份证,支持汉字),枚举取值:1、身份证2、护 照"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.certificate_type), //
set: function (val) {
this.setDataValue("buyerType", val);
this.setDataValue("buyerTypeName", uiconfig.config.pdict.certificate_type[val]);
}
},
certificateTypeame: DataTypes.STRING,   // "证件类型
//卖家信息
sellerType: { // "卖方类型",
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.tranferperson_type),
set: function (val) {
this.setDataValue("sellerType", val);
this.setDataValue("sellerTypeName", uiconfig.config.pdict.tranferperson_type[val]);
}
},
sellerTypeName: DataTypes.STRING, // "卖方类型",
legalPersonPhone: DataTypes.STRING, // "法定代表人手机号",
companyContactName: DataTypes.STRING, // "企业联系人姓名,可以和法人姓名一致",
verifyPhone: DataTypes.STRING, // "验证手机号",
phone: DataTypes.STRING, // "手机号",
businessLicenseId: DataTypes.STRING, // "统一社会信用代码(营业执照)",
sellerCompanyName: DataTypes.STRING, // "企业名称",
sellerCompanyAddress: DataTypes.STRING, // "卖方公司地址",
legalPersonIdCard: DataTypes.STRING, // "法定代表人身份证号码",
companyContactPhone: DataTypes.STRING, // "企业联系人电话,可以和法人手机号一致",
legalPersonName: DataTypes.STRING, // "法定代表人姓名"
//商标信息
tmRegisterNo: DataTypes.STRING, // "商标注册号",
tmClassification: DataTypes.STRING, // "商标第几类"
owner_id: DataTypes.STRING, //业务员id
owner_name: DataTypes.STRING, //业务员姓名
owner_mobile: DataTypes.STRING, //业务员电话
notaryStatus: { // "公证订单状态",
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.tranferperson_type),
set: function (val) {
this.setDataValue("notaryStatus", val);
this.setDataValue("notaryStatusName", uiconfig.config.pdict.tranferperson_type[val]);
}
},
notaryStatusName: DataTypes.STRING, // "公证订单状态",
desc: DataTypes.STRING, //备注
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'notarization_flow',
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("tmjsonfile", {
status: DataTypes.STRING, //'状态'
zc_url: DataTypes.STRING,
jsonfile_url: DataTypes.STRING, //json文件链接
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'tm_jsonfile',
validate: {
},
indexes: [
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("tradetransfer", {
tm_number: DataTypes.STRING, //注册号
ali_bizid: DataTypes.STRING, //'阿里订单号'
user_name: DataTypes.STRING, //买家姓名
mobile: DataTypes.STRING, //买方电话
contact_name: DataTypes.STRING, //买家联系人姓名
contact_mobile: DataTypes.STRING, //联系人联系方式
contact_email: DataTypes.STRING, //买家联系方式
cardno: DataTypes.STRING, //证件编号
complete: DataTypes.STRING, //是否补充完成,补充完成的话会展示给购买人确认资料。
user_type_name: DataTypes.STRING, //买家用户类型
user_type: { // "买家用户类型",
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.tranferperson_type), //
set: function (val) {
this.setDataValue("user_type", val);
this.setDataValue("user_type_name", uiconfig.config.pdict.tranferperson_type[val]);
}
},
buyer_address: DataTypes.STRING, //买家地址
buyer_businesslicense: DataTypes.STRING, //买家营业执照
buyer_name: DataTypes.STRING,//买家姓名
buyer_idcard: DataTypes.STRING,//买家身份证
seller_businesslicense: DataTypes.STRING,//卖家营业执照
seller_idcard: DataTypes.STRING,//卖家身份证
seller_proxy: DataTypes.STRING,//代理委托书
seller_apply:DataTypes.STRING,//申请书
ncl_one: DataTypes.STRING, //尼斯大类
price: DataTypes.STRING, //价格
fq_ordernum: DataTypes.STRING, //合作方订单号
tm_cert_url: DataTypes.STRING, //商标证书
transfer_cert_url: DataTypes.STRING, //转让证明
notarization_url: DataTypes.STRING, //公证书
notarization_flow_id: DataTypes.STRING, //公证流程id
tranfer_status_name: DataTypes.STRING, //流程状态名称
tranfer_status: {
type: DataTypes.ENUM, //
values: Object.keys(uiconfig.config.pdict.tranfer_status), //
set: function (val) {
this.setDataValue("tranfer_status", val);
this.setDataValue("tranfer_status_name", uiconfig.config.pdict.tranfer_status[val]);
}
},
aliorder_status_name: DataTypes.STRING, //阿里订单状态名称
aliorder_status: {
type: DataTypes.ENUM, //
values: Object.keys(uiconfig.config.pdict.aliorder_status), //
set: function (val) {
this.setDataValue("aliorder_status", val);
this.setDataValue("aliorder_status_name", uiconfig.config.pdict.aliorder_status[val]);
}
},
owner_id: DataTypes.STRING, //业务员id
owner_name: DataTypes.STRING, //业务员姓名
owner_mobile: DataTypes.STRING, //业务员电话
mail_zip_url: DataTypes.STRING, //邮寄文件链接 
logistics: DataTypes.STRING //邮寄单编号
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'trade_transfer',
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 logCtl=system.getObject("web.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(code){
var existedUser=null;
var rawUser=null;
var openuser=await this.apiCallWithAk(settings.paasUrl()+"api/auth/accessAuth/authByCode",{opencode:code});
if(openuser){
//先查看是否已经存在当前用户
existedUser=await this.db.models.user.findOne({where:{userName:openuser.userName,app_id:openuser.app_id,company_id:openuser.owner.id}});
if(!existedUser){
openuser.company_id=openuser.owner.id;
existedUser=await this.register(openuser);
}
rawUser=existedUser.get({raw:true});
rawUser.Roles=openuser.Roles;
rawUser.owner=openuser.owner;
rawUser.opath=openuser.opath;
rawUser.ppath=openuser.ppath;
rawUser.password=openuser.password;
}
return rawUser;
}
async register(fmuser){
var self=this;
return this.db.transaction(async function (t){
var cruser=await self.dao.create(fmuser,t);
return cruser;
});
}
//在平台进行登录,返回目标认证地址
//由于是从某个具体应用导航回平台,那么需要带着这个应用所属的公司信息
//todo
async navSysSetting(user){
var sysLoginUrl=settings.paasUrl()+"web/auth/userCtl/login?appKey="+settings.appKey+"\&toKey="+settings.paasKey;
if(settings.companyKey){//说明是自主登录,不需要平台内go登录
sysLoginUrl=settings.paasUrl()+"web/auth/userCtl/login?appKey="+settings.appKey+"\&toKey="+settings.paasKey+"\&companyKey="+settings.companyKey;
}
var x={userName:user.userName,password:user.password,mobile:user.mobile,owner_id:user.owner.id};
var restResult=await this.restS.execPost({u:x},sysLoginUrl);
if(restResult){
var rtnres=JSON.parse(restResult.stdout);
if(rtnres.status==0){
return rtnres.data;
}else{
}
}
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 settings=require("../../../../config/settings");
const ServiceBase=require("../../sve.base")
const uuidv4 = require('uuid/v4');
class ApiTradeService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(ApiTradeService));
}
async create(tradeObj){
return this.apiCallWithAkNoWait(settings.paasUrl()+"api/auth/accessAuth/apiAccessCount",tradeObj);
}
}
module.exports=ApiTradeService;
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);
}
//app调用次数
async findAndCountAlldetail(obj) {
var apicallAccu = await this.cacheManager["ApiAccuCache"].getApiCallAccu(obj);
var result = { rows: [], count: 0 };
var keys = await this.cacheManager["MagCache"].keys("api_call_" + appkey + "*");
var detail = null;
for (let j = 0; j < keys.length; j++) {
var d = keys[j];
var pathdetail = d.substr(d.lastIndexOf("_") + 1, d.length);
var apicalldetailAccu = await this.cacheManager["ApiCallCountCache"].getApiCallCount(appkey, pathdetail);
var detail = { "detailPath": d, "detailCount": apicalldetailAccu.callcount };
}
result.rows = detail;
}
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 };
}
//发送来源APP的访问计数到目标APP,由目标APP根据逻辑进行是否禁止来源APP的访问
//拦截访问之前由拦截器发送给目标程序
async recvNotificationForCacheCount(pobj){
var isHasAuth=false;
//var srcAPPAccessCount=pobj.count;
// var srcAPPAccessAmount=pobj.amount;
//按照来源访问APP,查询来源APP所有者账户余额,如果小于当前
//0为禁止,1或null为正常
console.log("recvNotificationForCacheCountxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
if(isHasAuth){
await this.cacheManager["ApiAccessControlCache"].cache(pobj.srcappkey,1);
}else{
await this.cacheManager["ApiAccessControlCache"].cache(pobj.srcappkey,0);
}
return isHasAuth;
}
}
module.exports = CacheService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
var settings=require("../../../../config/settings");
class MetaService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(MetaService));
}
async getApiDoc(appid){
var p=settings.basepath+"/app/base/db/impl/common/apiDocManager.js";
var ClassObj= require(p) ;
var obj=new ClassObj();
return obj.doc;
}
async getUiConfig(appid){
const cfg=await this.cacheManager["UIConfigCache"].cache(appid,null,60);
return cfg;
}
async getBaseComp(){
var basecomp=await this.apiCallWithAk(settings.paasUrl()+"api/meta/baseComp/getBaseComp",{});
return basecomp.basecom;
}
async findAuthsByRole(rolesarray, appid,comid){
var result =await this.apiCallWithAk(settings.paasUrl()+"api/auth/roleAuth/findAuthsByRole",{
roles:rolesarray,
appid:appid,
companyid:comid,
});
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 > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
} catch (e) {
console.log("addLog------>>>>>>error-----------------------*****************");
console.log(e);
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
}
}
module.exports = OplogService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TaskService));
//this.appDao=system.getObject("db.appDao");
this.taskManager=system.getObject("db.taskManager");
this.emailClient=system.getObject("util.mailClient");
this.personTaxDao=system.getObject("db.individualincometaxDao");
this.ossClient=system.getObject("util.ossClient");
}
//写文件并上传到阿里云,返回上传的路径
async writexls(wb,sharecode){
var that=this;
var uuid=uuidv4();
var u=uuid.replace(/\-/g,"");
var fname="zc_"+u+".xlsx";
var filepath="/tmp/"+fname;
var promise=new Promise((resv,rej)=>{
wb.xlsx.writeFile(filepath).then(async function(d) {
var rtn=await that.ossClient.upfile(fname,filepath);
fs.unlink(filepath,function(err){});
return resv(rtn);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
//读取模板文件
async readxls(){
var promise=new Promise((resv,rej)=>{
var workbook = new excel.Workbook();
workbook.properties.date1904 = true;
var bpth=path.normalize(path.join(__dirname, '../'));
workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
.then(function() {
return resv(workbook);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
async buildworkbook(taxCalcList){
var workbook = await this.readxls();
var sheet = workbook.getWorksheet(1);
sheet.columns = [
{ header: '年度', key: 'statisticalYear', width: 10 },
{ header: '月份', key: 'statisticalMonth', width: 10 },
{ header: '员工姓名', key: 'employeeName', width: 10 },
{ header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
{ header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
// { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '子女教育', key: 'childrenEducation', width: 10 },
{ header: '继续教育', key: 'continuingEducation', width: 10 },
{ header: '房贷利息', key: 'interestExpense', width: 10 },
{ header: '住房租金', key: 'housingRent', width: 10 },
{ header: '赡养老人', key: 'supportElderly', width: 10 },
{ header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
{ header: '专项扣除合计', key: 'specialDeduction', width: 10 },
{ header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
{ header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
{ header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
{ header: '适用税率', key: 'taxRate', width: 10 },
{ header: '速算扣除', key: 'deductionNumber', width: 10 },
{ header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
{ header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
// (累计税前薪资-累计五险一金-累计免征额-累计已扣专项)*税率-速算扣除-累计已纳个税=本月应纳个税
];
taxCalcList.forEach(r=>{
sheet.addRow(r);
});
return workbook;
}
async makerpt(qobj){
var self=this;
return this.db.transaction(async t=>{
const sharecode=qobj.sharecode;
const email=qobj.email;
//按照sharecode获取单位某次个税计算
var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
var sheetNameSufix="个税汇总表";
if(taxCalcList && taxCalcList.length>0){
var year=taxCalcList[0].statisticalYear;
var month=taxCalcList[0].statisticalMonth;
sheetNameSufix=year+month+sheetNameSufix;
}
var wb=await this.buildworkbook(taxCalcList);
//生成excel
var result=await this.writexls(wb,sharecode);
//异步不等待发送邮件给
var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
//发送手机短信
//写到按咋回哦sharecode,修改下载的url
return result.url;
});
}
async create(qobj){
var self=this;
return this.db.transaction(async t=>{
var task=await this.dao.create(qobj,t);
//发布任务事件
var action="new";
var taskClassName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
await self.taskManager.newTask(msg);
await self.taskManager.publish("task","newtask");
return task;
});
}
async restartTasks2(qobj){
return this.restartTasks(qobj);
}
async restartTasks(qobj){
var self=this;
var rtn={};
var tasks=await this.dao.model.findAll({raw:true});
//清空任务列表
await this.taskManager.clearlist();
for(var i=0;i<tasks.length;i++){
var tmpTask2=tasks[i];
try {
(async (tmpTask,that)=>{
var action="new";
var taskClassName=tmpTask.taskClassName;
var exp=tmpTask.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
// await that.taskManager.newTask(msg);
// await that.taskManager.publish("task","newtask");
await that.taskManager.addTask(taskClassName,exp);
})(tmpTask2,self);
} catch (e) {
rtn=null;
}
}
return rtn;
}
async delete(qobj){
var self=this;
return this.db.transaction(async t=>{
var task= await this.dao.model.findOne({where:qobj});
await this.dao.delete(task,qobj,t);
//发布任务事件
var action="delete";
var taskName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskName;
//发布任务,消息是action_taskClassName
await this.taskManager.publish("task",msg,null);
return task;
});
}
}
module.exports=TaskService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class UploadService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(UploadService));
//this.appDao=system.getObject("db.appDao");
}
}
module.exports=UploadService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class MsgHistoryService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(MsgHistoryService));
this.msgnoticeDao = system.getObject("db.msgnoticeDao");
this.userDao = system.getObject("db.userDao");
this.redisClient = system.getObject("util.redisClient");
this.businesslicenseDao = system.getObject("db.businesslicenseDao");
}
getApp(appkey){
return this.cacheManager["AppCache"].cacheApp(appkey);
}
async saveMsg(msg) {
var self = this;
console.log("save msg ", msg);
// 事务
await this.db.transaction(async function (t){
// 1.保存聊天信息
msg = await self.dao.create(msg, t);
// 2.保存好友信息
await self.msgnoticeDao.saveNotice(msg, t);
});
return msg;
}
async pushBusinessLicenseMsg(senderId, targetId, businessLicense_id) {
if(!businessLicense_id) {
return 0;
}
var notice = await this.msgnoticeDao.findOne({fromId : senderId, toId : targetId});
if(notice && notice.businessLicense_id == businessLicense_id) {
return 0;
}
var senderUser = await this.userDao.findById(senderId);
var targetUser = await this.userDao.findById(targetId);
var senderChannel = senderUser.app_id + "¥" + senderUser.id;
var targetChannel = targetUser.app_id + "¥" + targetUser.id;
var sender = senderUser.app_id + "¥" + senderUser.id + "¥" + senderUser.headUrl;
var target = targetUser.app_id + "¥" + targetUser.id + "¥" + targetUser.headUrl;
var msg = {
msgType: "mryzLicense",
sender:sender,
senderId:senderId,
target:target,
targetId:targetId,
content:businessLicense_id,
isRead:false,
businessLicense_id:businessLicense_id
}
var obj = await this.saveMsg(msg);
var bl = await this.businesslicenseDao.findById(businessLicense_id);
msg.businessLicense = bl;
msg.id = obj.id;
msg.created_at = obj.created_at;
this.redisClient.publish(senderChannel, JSON.stringify(msg));
this.redisClient.publish(targetChannel, JSON.stringify(msg));
return 1;
}
async getChatList(senderId, targetId, maxId, pageSize) {
let sql = "SELECT * FROM `msghistory` WHERE id < :maxId AND ((senderId = :senderId AND targetId = :targetId) OR (targetId = :senderId AND senderId = :targetId)) ORDER BY id DESC LIMIT :pageSize "
let params = {senderId:senderId, targetId: targetId, maxId: maxId, pageSize: pageSize};
var list = await this.dao.customQuery(sql, params);
if(!list || list.length == 0) {
return [];
}
var licenseIds = [];
var msgIds = [];
list.forEach(item => {
if(item.msgType == 'mryzLicense') {
licenseIds.push(Number(item.businessLicense_id));
}
msgIds.push(item.id);
});
if(licenseIds.length > 0) {
let licenseSql = "SELECT * FROM yz_business_license WHERE id IN (" + licenseIds.join(",") + ") ";
var licenseList = await this.businesslicenseDao.customQuery(licenseSql);
var licenseMap = [];
licenseList.forEach(item => {
licenseMap["id" + item.id] = item;
});
list.forEach(item => {
if(item.msgType == 'mryzLicense') {
item.businessLicense = licenseMap['id' + item.businessLicense_id];
}
});
}
var self = this;
setTimeout(function(){
self.setRead(senderId, targetId, list);
}, 1000);
return list;
}
async setRead(senderId, targetId, list) {
if(!list || list.length == 0) {
return;
}
var target = await this.userDao.findById(targetId);
if(!target) {
return;
}
var pushIds = [];
for(var item of list) {
if(item.isRead || senderId != item.targetId) {
continue;
}
pushIds.push(item.id);
}
if(pushIds.length == 0) {
return;
}
this.dao.updateByWhere({isRead: true}, {where:{id:{[this.db.Op.in]:pushIds}}});
var channel = target.app_id + "¥" + target.id;
var rs = await this.redisClient.publish(channel, JSON.stringify({type:"readmsg", data : pushIds}));
console.log(rs, "------------------------------------------ publish result ");
}
async readMsg(userId, id) {
var msg = await this.dao.findById(id);
if(!msg || userId != msg.targetId) {
return 0;
}
msg.isRead = true;
await msg.save();
var user = await this.userDao.findById(msg.senderId);
if(!user) {
return 0;
}
var channel = user.app_id + "¥" + user.id;
return await this.redisClient.publish(channel, JSON.stringify({type:"readmsg", data : [msg.id]}));
}
}
module.exports=MsgHistoryService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class MsgNoticeService extends ServiceBase {
constructor() {
super(ServiceBase.getDaoName(MsgNoticeService));
//this.appDao=system.getObject("db.appDao");
this.userDao = system.getObject("db.userDao");
this.businesslicenseDao = system.getObject("db.businesslicenseDao");
this.msghistoryDao = system.getObject("db.msghistoryDao");
}
getApp(appkey) {
return this.cacheManager["AppCache"].cacheApp(appkey);
}
async getUserList(userId) {
var list = await this.dao.model.findAll({
where: {
fromId: userId
},
order: [
["updated_at", "DESC"]
],
raw: true
});
if (!list || list.length == 0) {
return [];
}
var msgIds = [];
var businessLicenseIds = [];
var userIds = [];
for (var item of list) {
msgIds.push(item.lastMsgId);
businessLicenseIds.push(item.businessLicense_id);
userIds.push(item.toId);
}
var msgMap = [];
var businessLicenseMap = [];
var userMap = [];
var unreadMap = [];
// 最后一条聊天记录
if (msgIds.length > 0) {
var msgList = await this.msghistoryDao.customQuery("SELECT * FROM msghistory WHERE id IN (" + msgIds.join(",") + ") ");
msgList.forEach(item => {
msgMap["id" + item.id] = item;
});
}
// 最后一次聊天关联执照
if (businessLicenseIds.length > 0) {
var licenseList = await this.businesslicenseDao.customQuery("SELECT * FROM yz_business_license WHERE id IN (" + businessLicenseIds.join(",") + ") ");
var serviceTypeIds = [];
for (var item of licenseList) {
serviceTypeIds.push(item.serviceTypeOneId);
serviceTypeIds.push(item.serviceTypeTwoId);
}
if (serviceTypeIds.length > 0) {
var sql = "SELECT id, name FROM `p_service_type` WHERE id IN (" + serviceTypeIds.join(",") + ") ";
var typeList = await this.dao.customQuery(sql);
var typeMap = [];
if (typeList && typeList.length > 0) {
for (var t of typeList) {
typeMap["type_id_" + t.id] = t.name;
if (t.id == item.serviceTypeOneId) {
item.serviceTypeOneName = t.name;
} else if (t.id == item.serviceTypeTwoId) {
item.serviceTypeTwoName = t.name;
} else {}
}
}
}
for (var item of licenseList) {
item.serviceTypeOneName = typeMap["type_id_" + item.serviceTypeOneId];
item.serviceTypeTwoName = typeMap["type_id_" + item.serviceTypeTwoId];
}
licenseList.forEach(item => {
businessLicenseMap["id" + item.id] = item;
});
}
// 聊天好友用户信息
if (userIds.length > 0) {
var userList = await this.userDao.customQuery("SELECT * FROM p_user WHERE id IN (" + userIds.join(",") + ") ");
userList.forEach(item => {
userMap["id" + item.id] = item;
});
}
// 未读消息数量
var unreadList = await this.userDao.customQuery("SELECT senderId, COUNT(1) AS num FROM `msghistory` WHERE isRead = 0 AND targetId = " + userId + " GROUP BY senderId ");
unreadList.forEach(item => {
unreadMap["id" + item.senderId] = item.num;
});
var rs = [];
for (var i in list) {
var item = list[i];
item.lastMsg = msgMap["id" + item.lastMsgId];
item.businessLicense = businessLicenseMap["id" + item.businessLicense_id];
item.friend = userMap["id" + item.toId];
item.unreadCount = unreadMap["id" + item.toId] || 0;
rs.push(item);
}
return rs;
}
async countUnread(userId) {
debugger;
var unreadList = await this.userDao.customQuery("SELECT COUNT(1) AS num FROM `msghistory` WHERE isRead = 0 AND targetId = " + userId);
var count = 0;
if (unreadList && unreadList.length > 0) {
count = unreadList[0].num || 0;
}
return count;
}
}
module.exports = MsgNoticeService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class NotarizationflowService extends ServiceBase {
constructor() {
super("transfer", ServiceBase.getDaoName(NotarizationflowService));
this.tradetransferDao = system.getObject("db.transfer.tradetransferDao");
this.aliclient = system.getObject("util.aliApiClient");
}
//公证信息推送阿里
async setfiletoali(obj) {
var uploadContext = {
buyerData: {},
sellerData: {},
transferData: {}
}
console.log(obj.sellerFrontOfIdCard.split("com//")[1]);
obj.sellerFrontOfIdCard = obj.sellerFrontOfIdCard == null ? null : obj.sellerFrontOfIdCard.split("com//")[1];
obj.sellerBackOfIdCard = obj.sellerBackOfIdCard == null ? null : obj.sellerBackOfIdCard.split("com//")[1];
obj.tmRegisterCertificate = obj.tmRegisterCertificate == null ? null : obj.tmRegisterCertificate.split("com//")[1];
obj.businessLicense = obj.businessLicense == null ? null : obj.businessLicense.split("com//")[1];
obj.tmAcceptCertificate = obj.tmAcceptCertificate == null ? null : obj.tmAcceptCertificate.split("com//")[1];
obj.buyerIdentification = obj.buyerIdentification == null ? null : obj.buyerIdentification.split("com//")[1];
obj.tmRegisterChangeCertificate = obj.tmRegisterChangeCertificate == null ? null : obj.tmRegisterChangeCertificate.split("com//")[1];
//买家信息 个人
if (obj.buyerType == "person") {
if (this.isStrEmpty(obj.buyerName) && this.isStrEmpty(obj.certificateNo) && this.isStrEmpty(obj.certificateType)) {
uploadContext.buyerData = {
buyerName: obj.buyerName,
certificateNo: obj.certificateNo,
certificateType: obj.certificateType
}
} else {
return false;
}
} else {//买家信息 企业
if (this.isStrEmpty(obj.buyerCompanyName)) {
uploadContext.buyerData = {
buyerCompanyName: obj.buyerCompanyName
}
} else {
return false;
}
}
//卖家信息 个人
if (obj.sellerType == "person") {
if (this.isStrEmpty(obj.verifyPhone)
&& this.isStrEmpty(obj.phone)
&& this.isStrEmpty(obj.sellerFrontOfIdCard)
&& this.isStrEmpty(obj.sellerBackOfIdCard)
&& this.isStrEmpty(obj.buyerIdentification)
&& (this.isStrEmpty(obj.tmRegisterCertificate) || this.isStrEmpty(obj.tmAcceptCertificate) || this.isStrEmpty(obj.tmRegisterChangeCertificate))) {
uploadContext.sellerData = {
verifyPhone: obj.verifyPhone,
phone: obj.phone
};
uploadContext.transferData = {
sellerFrontOfIdCard: obj.sellerFrontOfIdCard,
sellerBackOfIdCard: obj.sellerBackOfIdCard,
buyerIdentification: obj.buyerIdentification,
tmRegisterCertificate: obj.tmRegisterCertificate,
tmAcceptCertificate: obj.tmAcceptCertificate,
tmRegisterChangeCertificate: obj.tmRegisterChangeCertificate
}
} else {
return false;
}
} else {//卖家信息 企业
if (this.isStrEmpty(obj.legalPersonPhone)
&& this.isStrEmpty(obj.companyContactName)
&& this.isStrEmpty(obj.verifyPhone)
&& this.isStrEmpty(obj.phone)
&& this.isStrEmpty(obj.businessLicenseId)
&& this.isStrEmpty(obj.sellerCompanyName)
&& this.isStrEmpty(obj.sellerCompanyAddress)
&& this.isStrEmpty(obj.legalPersonIdCard)
&& this.isStrEmpty(obj.companyContactPhone)
&& this.isStrEmpty(obj.legalPersonName)
&& this.isStrEmpty(obj.buyerIdentification)
&& this.isStrEmpty(obj.businessLicense)
&& (this.isStrEmpty(obj.tmRegisterCertificate) || this.isStrEmpty(obj.tmAcceptCertificate) || this.isStrEmpty(obj.tmRegisterChangeCertificate))) {
uploadContext.sellerData = {
legalPersonPhone: obj.legalPersonPhone, // "法定代表人手机号",
companyContactName: obj.companyContactName, // "企业联系人姓名,可以和法人姓名一致",
verifyPhone: obj.verifyPhone, // "验证手机号",
phone: obj.phone, // "手机号",
businessLicenseId: obj.businessLicenseId, // "统一社会信用代码(营业执照)",
sellerCompanyName: obj.sellerCompanyName, // "企业名称",
sellerCompanyAddress: obj.sellerCompanyAddress, // "卖方公司地址",
legalPersonIdCard: obj.legalPersonIdCard, // "法定代表人身份证号码",
companyContactPhone: obj.companyContactPhone, // "企业联系人电话,可以和法人手机号一致",
legalPersonName: obj.legalPersonName // "法定代表人姓名"
},
uploadContext.transferData = {
sellerFrontOfIdCard: obj.sellerFrontOfIdCard,
sellerBackOfIdCard: obj.sellerBackOfIdCard,
tmRegisterCertificate: obj.tmRegisterCertificate,
businessLicense: obj.businessLicense,
tmAcceptCertificate: obj.tmAcceptCertificate,
buyerIdentification: obj.buyerIdentification,
tmRegisterChangeCertificate: obj.tmRegisterChangeCertificate
}
} else {
return false;
}
}
var source = {
action: "UploadNotaryData",
reqbody: {
NotaryType: 1,
BizOrderNo: obj.ali_bizid,
UploadContext: JSON.stringify(uploadContext)
}
}
console.log(source);
var a = await this.aliclient(source);
console.log(a);
return a;
}
async selnotarytype(obj){
if (!obj.ali_bizid) {
return {
"errorCode": "error",
"errorMsg": "ali_bizid不能为空",
"module": { "orderNumber": "" },
"requestId": obj.requestid,
"success": false
}
}
if (!obj.token) {
return {
"errorCode": "error",
"errorMsg": "token不能为空",
"module": { "orderNumber": "" },
"requestId": obj.requestid,
"success": false
}
}
var source = {
action: "ListNotaryInfos",
reqbody: {
NotaryType: 1,
BizOrderNo: obj.ali_bizid,
PageNum:1,
PageSize:10,
Token:obj.token
}
}
var a = await this.aliclient(source);
console.log(a);
return a;
}
async firstload(obj) {
var self = this;
var traninfo = await this.tradetransferDao.findOne({ ali_bizid: obj.ali_bizid });
if (traninfo.dataValues) {
if (traninfo.dataValues.notarization_flow_id) {
var notarinfo = await this.dao.findOne({ ali_bizid: obj.ali_bizid });
if (notarinfo) {
return { data: notarinfo.dataValues, status: 0, msg: "操作成功" }
} else {
return { data: null, status: -201, msg: "查询失败失败" }
}
} else {
var source = {
ali_bizid: traninfo.dataValues.ali_bizid,
fq_ordernum: traninfo.dataValues.fq_ordernum,
tmRegisterNo: traninfo.dataValues.tm_number,
tmClassification: traninfo.dataValues.ncl_one
}
return this.db.transaction(async function (t) {
var notarinfo = await self.dao.create(source, t);
if (notarinfo) {
traninfo.dataValues.notarization_flow_id = notarinfo.dataValues.id;
await self.tradetransferDao.update(traninfo.dataValues);
return { data: notarinfo.dataValues, status: 0, msg: "操作成功" }
} else {
return { data: null, status: -202, msg: "创建失败" }
}
})
}
} else {
return { data: null, status: -200, msg: "参数异常" }
}
}
}
module.exports = NotarizationflowService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
var RPCClient = require('@alicloud/pop-core').RPCClient;
var OSS = require('ali-oss');
const crypto = require('crypto');
var fs = require('fs');
class TmjsonfileService extends ServiceBase {
constructor() {
super("transfer", ServiceBase.getDaoName(TmjsonfileService));
this.connectionigirl = system.getObject("db.common.connection").getConigirl();
}
async createjsonfile() {
var sql = "select * from bi_trademarktransaction limit 1000";
var tminfos = await this.connectionigirl.query(sql);
var sources = [];
if (tminfos[0]) {
for (var i = 0; i < tminfos[0].length; i++) {
var a = tminfos[0][i].tm_group;
var strlist = null;
if (a) {
strlist = a.replace(/"/g, "").replace(/\[/g, "").replace(/\]/g, "").split(",");
if (!strlist[0]) {
strlist.shift();
}
}
var des= tminfos[0][i].tm_ncl_third.replace(/\[/g, "").replace(/\]/g, "").replace(/\'/g, "");
var source = {
beginTime: 1574388139000,
classificationCode: tminfos[0][i].ncl_one_code,
description:des,
endTime: 1668089537981,
label: "商标标签",
originalPrice: 10,
// originalPrice: parseInt(tminfos[0][i].platform_quoted_price),
ownerEnName: "",
ownerName: tminfos[0][i].tm_applier,
partnerCode: "gong_si_bao",
regAnnDate: tminfos[0][i].tm_regist_day * 1000,
secondaryClassification: strlist,
status: 1,
thirdClassification: tminfos[0][i].tm_ncl_third,
tmIcon: tminfos[0][i].pic_url,
tmName: tminfos[0][i].name,
tmNumber: tminfos[0][i].code
}
sources.push(source);
}
var jsonstr = JSON.stringify(sources, null, "\t");
return new Promise(function (resv, rej) {
fs.writeFile('/tmp/20191112_2.json', jsonstr, function (err) {
if (err) {
console.error(err);
}
console.log('--------------------修改成功11111111111111');
return resv({ status: 0, msg: "成功" })
})
}
)
console.log('--------------------修改成功');
}
}
}
module.exports = TmjsonfileService;
const system = require("../system");
var moment = require('moment')
var settings = require("../../config/settings");
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");
this.execS = system.getObject("util.execClient");
this.channelApiUrl = settings.channelApiUrl();
this.appInfo = {
aliyuntmtransfer: { appkey: "201912031344", secret: "7cbb846246874167b5c7e01cd0016c88" }
};
}
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
this.restS.execPostWithAK(params, url, acck).then((restResult) => {
if (restResult) {
if (restResult.status == 0) {
var resultRtn = restResult.data;
return resultRtn;
} else {
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('');
}
async aliclient(obj) {
var sobj = {
"actionProcess": "aliyuntmtransfer",
"actionType": "aliclient",
"sign": "2FviZ9PGws8Pt1fBhq0t90mjUvI",
"actionBody": obj
}
var tokenInfo = await this.getToken();
var reqUrl = this.channelApiUrl + "/action/tradetransfer/aliclienttransfer";
var rtn = await this.execS.execPostTK(sobj, reqUrl, tokenInfo.data.token);
//var rtn = await this.execS.execPostTK(sobj, reqUrl,"token");
return rtn;
}
async getToken() {
var self = this;
var reqTokenUrl = this.channelApiUrl + "/auth/accessAuth/getToken";
var reqParam = self.appInfo["aliyuntmtransfer"];
if (!reqParam.appkey || !reqParam.secret) {
return system.getResult(null, "reqType类型有误,请求失败");
}
var rtn = await this.execS.execPost(reqParam, reqTokenUrl);
if (!rtn.stdout) {
return system.getResult(null, "获取token失败");
}
var tokenResult = JSON.parse(rtn.stdout);
if (tokenResult.status == 0) {
tokenResult.data.secret = reqParam.secret;
}
return tokenResult;
}
trim(o) {
if (!o) {
return "";
}
return o.toString().trim();
}
isStrEmpty(str) {
return this.trim(str) ? true : false;
}
}
module.exports = ServiceBase;
var sha1 = require('sha1'),
events = require('events'),
emitter = new events.EventEmitter(),
xml2js = require('xml2js');
// 微信类
var Weixin = function(path) {
this.data = '';
this.msgType = 'text';
this.fromUserName = '';
this.toUserName = '';
this.funcFlag = 0;
this.path=path;
}
// 验证
Weixin.prototype.checkSignature = function(req) {
// 获取校验参数
this.signature = req.query.signature,
this.timestamp = req.query.timestamp,
this.nonce = req.query.nonce,
this.echostr = req.query.echostr;
// 按照字典排序
var array = [this.token, this.timestamp, this.nonce];
array.sort();
// 连接
var str = sha1(array.join(""));
// 对比签名
if(str == this.signature) {
return true;
} else {
return false;
}
}
// ------------------ 监听 ------------------------
// 监听文本消息
Weixin.prototype.textMsg = function(callback) {
emitter.on("weixinTextMsg", callback);
return this;
}
// 监听图片消息
Weixin.prototype.imageMsg = function(callback) {
emitter.on("weixinImageMsg", callback);
return this;
}
// 监听地理位置消息
Weixin.prototype.locationMsg = function(callback) {
emitter.on("weixinLocationMsg", callback);
return this;
}
// 监听链接消息
Weixin.prototype.urlMsg = function(callback) {
emitter.on("weixinUrlMsg", callback);
return this;
}
// 监听事件
Weixin.prototype.eventMsg = function(callback) {
emitter.on("weixinEventMsg", callback);
return this;
}
// ----------------- 消息处理 -----------------------
/*
* 文本消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType text
* Content 文本消息内容
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseTextMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"content" : this.data.Content[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinTextMsg", msg);
return this;
}
/*
* 图片消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType image
* Content 图片链接
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseImageMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"picUrl" : this.data.PicUrl[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinImageMsg", msg);
return this;
}
/*
* 地理位置消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType location
* Location_X x
* Location_Y y
* Scale 地图缩放大小
* Label 位置信息
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseLocationMsg = function(data) {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"locationX" : this.data.Location_X[0],
"locationY" : this.data.Location_Y[0],
"scale" : this.data.Scale[0],
"label" : this.data.Label[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinLocationMsg", msg);
return this;
}
/*
* 链接消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType link
* Title 消息标题
* Description 消息描述
* Url 消息链接
* MsgId 消息id,64位整型
*/
Weixin.prototype.parseLinkMsg = function() {
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"title" : this.data.Title[0],
"description" : this.data.Description[0],
"url" : this.data.Url[0],
"msgId" : this.data.MsgId[0],
}
emitter.emit("weixinUrlMsg", msg);
return this;
}
/*
* 事件消息格式:
* ToUserName 开发者微信号
* FromUserName 发送方帐号(一个OpenID)
* CreateTime 消息创建时间 (整型)
* MsgType event
* Event 事件类型,subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
* EventKey 事件KEY值,与自定义菜单接口中KEY值对应
*/
Weixin.prototype.parseEventMsg = function() {
var eventKey = '';
if (this.data.EventKey) {
eventKey = this.data.EventKey[0];
}
var msg = {
"toUserName" : this.data.ToUserName[0],
"fromUserName" : this.data.FromUserName[0],
"createTime" : this.data.CreateTime[0],
"msgType" : this.data.MsgType[0],
"event" : this.data.Event[0],
"eventKey" : eventKey,
"appk":this.path,
}
emitter.emit("weixinEventMsg", msg);
return this;
}
// --------------------- 消息返回 -------------------------
// 返回文字信息
Weixin.prototype.sendTextMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<Content><![CDATA[" + msg.content + "]]></Content>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// 返回音乐信息
Weixin.prototype.sendMusicMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<Music>" +
"<Title><![CDATA[" + msg.title + "]]></Title>" +
"<Description><![CDATA[" + msg.description + "DESCRIPTION]]></Description>" +
"<MusicUrl><![CDATA[" + msg.musicUrl + "]]></MusicUrl>" +
"<HQMusicUrl><![CDATA[" + msg.HQMusicUrl + "]]></HQMusicUrl>" +
"</Music>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// 返回图文信息
Weixin.prototype.sendNewsMsg = function(msg) {
var time = Math.round(new Date().getTime() / 1000);
//
var articlesStr = "";
for (var i = 0; i < msg.articles.length; i++)
{
articlesStr += "<item>" +
"<Title><![CDATA[" + msg.articles[i].title + "]]></Title>" +
"<Description><![CDATA[" + msg.articles[i].description + "]]></Description>" +
"<PicUrl><![CDATA[" + msg.articles[i].picUrl + "]]></PicUrl>" +
"<Url><![CDATA[" + msg.articles[i].url + "]]></Url>" +
"</item>";
}
var funcFlag = msg.funcFlag ? msg.funcFlag : this.funcFlag;
var output = "" +
"<xml>" +
"<ToUserName><![CDATA[" + msg.toUserName + "]]></ToUserName>" +
"<FromUserName><![CDATA[" + msg.fromUserName + "]]></FromUserName>" +
"<CreateTime>" + time + "</CreateTime>" +
"<MsgType><![CDATA[" + msg.msgType + "]]></MsgType>" +
"<ArticleCount>" + msg.articles.length + "</ArticleCount>" +
"<Articles>" + articlesStr + "</Articles>" +
"<FuncFlag>" + funcFlag + "</FuncFlag>" +
"</xml>";
this.res.type('xml');
this.res.send(output);
return this;
}
// ------------ 主逻辑 -----------------
// 解析
Weixin.prototype.parse = function() {
if(this.data){
this.msgType = this.data.MsgType[0] ? this.data.MsgType[0] : "text";
switch(this.msgType) {
case 'text' :
this.parseTextMsg();
break;
case 'image' :
this.parseImageMsg();
break;
case 'location' :
this.parseLocationMsg();
break;
case 'link' :
this.parseLinkMsg();
break;
case 'event' :
this.parseEventMsg();
break;
}
}
}
// 发送信息
Weixin.prototype.sendMsg = function(msg) {
switch(msg.msgType) {
case 'text' :
this.sendTextMsg(msg);
break;
case 'music' :
this.sendMusicMsg(msg);
break;
case 'news' :
this.sendNewsMsg(msg);
break;
}
}
// Loop
Weixin.prototype.loop = function(req, res) {
// 保存res
this.res = res;
var self = this;
// 获取XML内容
var buf = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
buf += chunk;
});
// 内容接收完毕
req.on('end', function() {
xml2js.parseString(buf, function(err, json) {
if (err) {
err.status = 400;
} else {
req.body = json;
}
});
if(req.body){
self.data = req.body.xml;
}
self.parse();
});
}
module.exports = Weixin;
var Wx = require("./wx.event");
const system = require("../system");
var dicCache = {};
//创知厚的我想我要的配置
wxconfig = {
AppID: "wx4c91e81bbb6039cd",
Secret: "12048e66dba64f2581e02b306680b232",
Token: "bosstoken",
AccessTokenUrl: "https://api.weixin.qq.com/cgi-bin/token",
};
//智薪云的配置
wxconfig2 = {
AppID: "wxdc08c441c9fdb7a7",
Secret: "379e582e28645585a7def9c1c88de550",
Token: "bosstoken",
AccessTokenUrl: "https://api.weixin.qq.com/cgi-bin/token",
};
wxconfigDic = {
"wx4c91e81bbb6039cd": wxconfig,
"wxdc08c441c9fdb7a7": wxconfig2,
}
var getWeiXin = function (url) {
var weixin = null;
if (!dicCache[url]) {
weixin = new Wx(url);
dicCache[url] = weixin;
} else {
weixin = dicCache[url];
}
weixin.token = wxconfig.Token;
weixin.wxconfig = wxconfig;
weixin.getAccessConfig = function (appkey) {
var cfg = wxconfigDic[appkey];
return {
grant_type: "client_credential",
appid: cfg.AppID,
secret: cfg.Secret,
};
}
// 监听文本消息
weixin.textMsg(function (msg) {
console.log("textMsg received");
console.log(JSON.stringify(msg));
var resMsg = {};
switch (msg.content) {
case "文本":
// 返回文本消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "text",
content: "这是文本回复",
funcFlag: 0
};
break;
case "音乐":
// 返回音乐消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "music",
title: "音乐标题",
description: "音乐描述",
musicUrl: "音乐url",
HQMusicUrl: "高质量音乐url",
funcFlag: 0
};
break;
case "图文":
var articles = [];
articles[0] = {
title: "PHP依赖管理工具Composer入门",
description: "PHP依赖管理工具Composer入门",
picUrl: "http://weizhifeng.net/images/tech/composer.png",
url: "http://weizhifeng.net/manage-php-dependency-with-composer.html"
};
articles[1] = {
title: "八月西湖",
description: "八月西湖",
picUrl: "http://weizhifeng.net/images/poem/bayuexihu.jpg",
url: "http://weizhifeng.net/bayuexihu.html"
};
articles[2] = {
title: "「翻译」Redis协议",
description: "「翻译」Redis协议",
picUrl: "http://weizhifeng.net/images/tech/redis.png",
url: "http://weizhifeng.net/redis-protocol.html"
};
// 返回图文消息
resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
}
}
weixin.sendMsg(resMsg);
});
// 监听图片消息
weixin.imageMsg(function (msg) {
console.log("imageMsg received");
console.log(JSON.stringify(msg));
});
// 监听位置消息
weixin.locationMsg(function (msg) {
console.log("locationMsg received");
console.log(JSON.stringify(msg));
});
// 监听链接消息
weixin.urlMsg(function (msg) {
console.log("urlMsg received");
console.log(JSON.stringify(msg));
});
// 监听事件消息
weixin.eventMsg(function (msg) {
if (msg.event == "subscribe" || msg.event == "SCAN") {
var wxservice = system.getObject("service.wxSve");
//to do msg.toUserName--按照微信号去取得应用,按照应用获取OAUTH
// wxservice.checkAndLogin(msg.fromUserName);
if (weixin.path == "ecwx") {
var urlstr = "https://ec.gongsibao.com/h5";
if (msg.eventKey && msg.eventKey != "") {
if (msg.eventKey.indexOf("_") >= 0) {
var strid = msg.eventKey.split('_')[1];
urlstr = urlstr + "?ecid=" + strid;
} else {
var strid = msg.eventKey;
urlstr = urlstr + "?ecid=" + strid;
}
}
var articles = [];
articles[0] = {
title: "欢迎来到智薪云签约平台",
description: "点击本图文消息,开始签约。",
picUrl: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_476111544670096808201813111368084242271.jpg",
url: urlstr,
};
var resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
};
weixin.sendMsg(resMsg);
} else {
//是否启用派单
var dispatchEnabled = true;
// 通知信息
var articles = [];
// 参数
var eventKey = msg.eventKey;
var userId = 0;
if (eventKey && eventKey.indexOf("_") > -1) {
// 标眼查通知openId保存逻辑
userId = Number(eventKey.split("_")[1] || 0);
if (userId && userId > 0) {
dispatchEnabled = false;
// 标眼查动态通知
articles[0] = {
title: "欢迎使用标眼监测商标监控工具",
description: "实时提醒商标动态,及时处理商标业务",
picUrl: "",
//picUrl: "https://search.gongsibao.com/imgs/biaoyan-logo-mini.png",
url: ""
};
}
}
else {
if (eventKey) {
userId = Number(eventKey);
}
}
if (dispatchEnabled) {
// 派单通知
articles[0] = {
title: "欢迎来到创知厚德智能派单平台",
description: "点击图文消息,开始接单",
picUrl: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_305111544784291353201814184451353distributeneed.png",
url: "https://boss.gongsibao.com/distributeneed",
};
}
if (userId && userId > 0) {
// wxservice.更新通知id
wxservice.updateNotifyOpenId(userId, msg.fromUserName);
}
var resMsg = {
fromUserName: msg.toUserName,
toUserName: msg.fromUserName,
msgType: "news",
articles: articles,
funcFlag: 0
};
weixin.sendMsg(resMsg);
}
} else {
//发送空串回微信服务器
weixin.res.send("");
}
});
return weixin;
}
module.exports = getWeiXin;
\ No newline at end of file
var fs = require("fs");
var objsettings = require("../config/objsettings");
var settings = require("../config/settings");
class System {
static declare(ns) {
var ar = ns.split('.');
var root = System;
for (var i = 0, len = ar.length; i < len; ++i) {
var n = ar[i];
if (!root[n]) {
root[n] = {};
root = root[n];
} else {
root = root[n];
}
}
}
static register(key, ClassObj) {
if (System.objTable[key] != null) {
throw new Error("相同key的对象已经存在");
} else {
let obj = new ClassObj();
System.objTable[key] = obj;
}
return System.objTable[key];
}
static getResult(data, opmsg = "操作成功", req) {
return {
status: !data ? -1 : 0,
msg: opmsg,
data: data,
bizmsg: req && req.session && req.session.bizmsg ? req.session.bizmsg : "empty"
};
}
/**
* 请求返回成功
* @param {*} data 操作成功返回的数据
* @param {*} okmsg 操作成功的描述
*/
static getResultSuccess(data, okmsg = "success") {
return {
status: 0,
msg: okmsg,
data: data,
};
}
/**
* 请求返回失败
* @param {*} status 操作失败状态,默认为-1
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
static getResultFail(status = -1, errmsg = "fail", data = null) {
return {
status: status,
msg: errmsg,
data: data,
};
}
static getObject(objpath) {
var pathArray = objpath.split(".");
var packageName = pathArray[0];
var groupName = pathArray[1];
var filename = pathArray[2];
var classpath = "";
if (filename) {
classpath = objsettings[packageName] + "/" + groupName;
} else {
classpath = objsettings[packageName];
filename = groupName;
}
var objabspath = classpath + "/" + filename + ".js";
if (System.objTable[objabspath] != null) {
console.log("get cached obj");
return System.objTable[objabspath];
} else {
console.log("no cached...");
var ClassObj = require(objabspath);
return System.register(objabspath, ClassObj);
}
}
static getUiConfig(appid) {
var configPath = settings.basepath + "/app/base/db/metadata/" + appid + "/index.js";
if (settings.env == "dev") {
delete require.cache[configPath];
}
var configValue = require(configPath);
return configValue;
}
static getUiConfig2(appid) {
var configPath = settings.basepath + "/app/base/db/metadata/index.js";
// if(settings.env=="dev"){
// console.log("delete "+configPath+"cache config");
// delete require.cache[configPath];
// }
delete require.cache[configPath];
var configValue = require(configPath);
return configValue["config"];
}
static get_client_ip(req) {
var ip = req.headers['x-forwarded-for'] ||
req.ip ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket && req.connection.socket.remoteAddress) || '';
var x = ip.match(/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/);
if (x) {
return x[0];
} else {
return "localhost";
}
};
}
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
System.objTable = {};
module.exports = System;
\ 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.
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