Commit de770824 by 宋毅

tj

parent 92c8111b
#!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang2/node105:v2
MAINTAINER jy "jiangyong@gongsibao.com"
ADD brg-queue-center /apps/brg-queue-center/
WORKDIR /apps/brg-queue-center/
RUN cnpm install -S
CMD ["node","/apps/brg-queue-center/main.js"]
#!/bin/bash
FROM registry.cn-beijing.aliyuncs.com/hantang2/node105:v2
MAINTAINER jy "jiangyong@gongsibao.com"
ADD brg /apps/brg/
WORKDIR /apps/brg/
RUN cnpm install -S
CMD ["node","/apps/brg/main.js"]
const system = require("../system");
const moment = require('moment');
const settings = require("../../../app/config/settings");
const sha256 = require('sha256');
class APIBase {
constructor() {
this.redisClient = system.getObject("util.redisClient");
this.execClient = system.getObject("util.execClient");
this.esUtils = system.getObject("util.esUtils");
}
//-----------------------新的模式------------------开始
async doexecMethod(gname, methodname, pobj, query, req) {
try {
if (!pobj.actionBody) {
pobj.actionBody = {};
}
var shaStr = await sha256(JSON.stringify(pobj));
this.redisClient.setWithEx(shaStr, 1, 3);
var result = await this[methodname](pobj, query, req);
if (!result) {
result = system.getResult(null, "请求的方法返回值为空");
}
result.requestId = await this.getBusUid("scz");
if ("LOGS-SYTXPUBLIC-MSGQ" != settings.queuedName) {
pobj.actionBody.resultInfo = result;
pobj.actionBody.requestId = result.requestId;
pobj.actionBody.opTitle = "reqPath:" + req.path;
this.esUtils.addEsLogs(settings.queuedName + "-request", pobj.actionBody);
}
return result;
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
// console.log(stackStr, "api.base调用出现异常,请联系管理员..........");
var rtnerror = system.getResultFail(-200, "出现异常,error:" + stackStr);
pobj.actionBody.requestId = await this.getBusUid("err");
pobj.actionBody.errorInfo = stackStr;
pobj.actionBody.opTitle = ",reqPath:" + req.path;
this.esUtils.addEsLogs(settings.queuedName + "-error", pobj.actionBody);
return rtnerror;
}
}
//-----------------------新的模式------------------结束
/**
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
*/
async execPostByTimeOut(params, url, ContentType, headData, timeOut = 60) {
return await this.execClient.execPostTimeOutByBusiness("api.base", params, url, ContentType, headData, timeOut);
}
/**
* 返回20位业务订单号
* @param {*} 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;
}
/**
* 返回指定长度的字符串
* @param {*} len 返回长度
* @param {*} 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('');
}
}
module.exports = APIBase;
var APIBase = require("../../api.base");
var system = require("../../../system");
const settings = require("../../../../config/settings");
class IcQueryAPI extends APIBase {
constructor() {
super();
this.utilsIcSve = system.getObject("service.utilsSve.utilsIcSve");
}
/**
* 接口跳转-POST请求
* actionType 执行的功能模块
* actionBody 执行的参数
*/
async springBoard(pobj, qobj, req) {
if (!pobj.actionType) {
return system.getResult(null, "actionType参数不能为空");
}
var result = await this.opActionType(pobj, pobj.actionType, req);
return result;
}
async opActionType(pobj, actionType, req) {
if (settings.queuedName != "SYTXPUBLIC-MSGQ") {
return system.getResult(null, "请求地址有误!");
}
var opResult = null;
switch (actionType) {
case "getListByLikeCompanyName":
opResult = await this.utilsIcSve.getListByLikeCompanyName(pobj.actionBody);
break;
case "getItemByCompanyName":
opResult = await this.utilsIcSve.getItemByCompanyName(pobj.actionBody);
break;
default:
opResult = system.getResult(null, "actionType参数错误");
break;
}
return opResult;
}
}
module.exports = IcQueryAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
const settings = require("../../../../config/settings");
class ProducerAPI extends APIBase {
constructor() {
super();
this.utilsProduceSve = system.getObject("service.utilsSve.utilsProduceSve");
}
/**
* 接口跳转-POST请求
* actionType 执行的功能模块
* actionBody 执行的参数
*/
async springBoard(pobj, qobj, req) {
if (!pobj.actionType) {
return system.getResult(null, "actionType参数不能为空");
}
var result = await this.opActionType(pobj, pobj.actionType, req);
return result;
}
async opActionType(pobj, actionType, req) {
var opResult = null;
switch (actionType) {
case "produceData":
if (settings.queuedName != "SYTXPUBLIC-MSGQ") {
return system.getResult(null, "请求地址有误!");
}
opResult = await this.utilsProduceSve.produceData(pobj, req);
break;
case "produceLogsData":
if (settings.queuedName != "LOGS-SYTXPUBLIC-MSGQ") {
return system.getResult(null, "请求地址有误!");
}
opResult = await this.utilsProduceSve.produceLogsData(pobj, req);
break;
default:
opResult = system.getResult(null, "actionType参数错误");
break;
}
return opResult;
}
}
module.exports = ProducerAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
class TxCosAPI extends APIBase {
constructor() {
super();
this.utilsTxCosSve = system.getObject("service.utilsSve.utilsTxCosSve");
}
async getCosInfo(pobj, qobj, req) {
var result = await this.utilsTxCosSve.getCosInfo();
return result;
}
}
module.exports = TxCosAPI;
\ No newline at end of file
const system = require("../system");
const moment = require('moment');
const settings = require("../../config/settings");
class ConsumerBase {
constructor(className) {
this.serviceName = className;
this.execClient = system.getObject("util.execClient");
this.pushSuccessLogDao = system.getObject("db.opLogs.pushSuccessLogDao");
this.pushFailureLogDao = system.getObject("db.opLogs.pushFailureLogDao");
this.errorLogDao = system.getObject("db.opLogs.errorLogDao");
this.redisClient = system.getObject("util.redisClient");
this.duplicateInstance = this.redisClient.getDuplicateInstance();
}
static getServiceName(ClassObj) {
return ClassObj["name"];
}
async doConsumer(queuedName, counter) {
try {
if (!counter) {
counter = 1;
}
var self = this;
this.duplicateInstance.brpop(queuedName, 0, async function (err, repl) {
if (err) {
return new Error('doConsumer brpop error :' + err);
}
else {
if (repl[1]) {
self.execSubDoConsumer(queuedName, JSON.parse(repl[1]));
}
self.doConsumer(queuedName, counter);
}
});
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
this.errorLogDao.addOpErrorLogs("队列执行doConsumer存在异常", null, null, stackStr, 3);
//日志
console.log(stackStr, ",队列执行doConsumer存在异常");
}
}
async execSubDoConsumer(queuedName, actionBody) {
var execResult = null;
try {
const notifyQueuedName = "NOTIFY-SYTXPUBLIC-MSGQ";
this.subBeforeConsumer(queuedName, actionBody);
actionBody.requestId = await this.getBusUid("PUB-");
if ("SYTXFAIL-SYTXPUBLIC-MSGQ" != queuedName && "LOGSFAIL-SYTXPUBLIC-MSGQ" != queuedName) {
execResult = await this.subDoConsumer(queuedName, actionBody);
if (notifyQueuedName != queuedName) {
actionBody.resultInfo = execResult;
} else {
actionBody.pushAgainResultInfo = execResult;
}
if (execResult.status === 1) {
if (notifyQueuedName != queuedName) {
if (actionBody.notifyUrl && actionBody.notifyUrl.indexOf("http") >= 0) {
await this.redisClient.lpushData(notifyQueuedName, actionBody);
}
}
if ("LOGS-SYTXPUBLIC-MSGQ" != settings.queuedName) {
await this.pushSuccessLogDao.addOpSuccessLogs("推送成功", actionBody, execResult);
}
return;
}
var failQueuedName = "SYTXFAIL-SYTXPUBLIC-MSGQ";
if ("LOGS-SYTXPUBLIC-MSGQ" === queuedName) {
failQueuedName = "LOGSFAIL-SYTXPUBLIC-MSGQ";
}
actionBody.queuedName = queuedName;
actionBody.counter = actionBody.counter ? actionBody.counter : 1;
await this.redisClient.lpushData(failQueuedName, actionBody);
return;
}
if (actionBody.counter > 4) {
actionBody.pushAgainResultInfo = actionBody.pushAgainResultInfo || actionBody.resultInfo;
await this.pushFailureLogDao.addOpFailureLogs("推送失败", actionBody, actionBody.pushAgainResultInfo);
return;
}
if (actionBody.pushAgainResultInfo) {
delete actionBody["pushAgainResultInfo"];
}
execResult = await this.subDoConsumer(queuedName, actionBody);
} catch (error) {
if (execResult && execResult.status == 1) {
await this.pushSuccessLogDao.addOpSuccessLogs("推送成功", actionBody, execResult);
} else {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
this.errorLogDao.addOpErrorLogs("队列执行execSubDoConsumer存在异常", actionBody, execResult, stackStr, 3);
//日志记录
console.log(stackStr, ",队列执行execSubDoConsumer存在异常");
}
}
}
async subBeforeConsumer(queuedName, actionBody) {
console.log("请在子类中重写此方法进行前置操作......", this.serviceName);
}
async subDoConsumer(queuedName, actionBody) {
throw new Error("请在子类中重写此方法进行操作业务逻辑............................!");
}
sleep(milliSeconds) {
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
/**
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
*/
async execPostByTimeOut(params, url, ContentType, headData, timeOut = 60) {
return await this.execClient.execPostTimeOutByBusiness("consumer.base", params, url, ContentType, headData, timeOut);
}
/*
返回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('');
}
}
module.exports = ConsumerBase;
const ConsumerBase = require("../../consumer.base");
const system = require("../../../system");
const moment = require('moment');
class PublicFailConsumer extends ConsumerBase {
constructor() {
super(ConsumerBase.getServiceName(PublicFailConsumer));
}
async subBeforeConsumer(queuedName, actionBody) {
console.log("前置操作......", this.serviceName);
}
async subDoConsumer(queuedName, actionBody) {
actionBody.counter = actionBody.counter + 1;
var exTime = actionBody.counter * 20;
var mathStr = await this.getUidInfo(3, 10);
var scoreValue = Number(moment().format("YYYYMMDDHHmmssSSS") + mathStr);
await this.redisClient.init(scoreValue);
await this.redisClient.setDelayEventData(queuedName, scoreValue, exTime);
await this.redisClient.zaddSortedSet(queuedName, scoreValue, actionBody);
return system.getResultSuccess();
}
}
module.exports = PublicFailConsumer;
\ No newline at end of file
const ConsumerBase = require("../../consumer.base");
const system = require("../../../system");
class PublicLogsConsumer extends ConsumerBase {
constructor() {
super(ConsumerBase.getServiceName(PublicLogsConsumer));
this.configInfoDao = system.getObject("db.opLogs.configInfoDao");
this.errorLogDao = system.getObject("db.opLogs.errorLogDao");
this.esUtils = system.getObject("util.esUtils");
}
async subBeforeConsumer(queuedName, actionBody) {
console.log("前置操作......", this.serviceName);
}
async subDoConsumer(queuedName, actionBody) {
var execResult = await this.esUtils.addEsLogs(queuedName, actionBody);;
return execResult;
}
}
module.exports = PublicLogsConsumer;
\ No newline at end of file
const ConsumerBase = require("../../consumer.base");
class PublicNotifyConsumer extends ConsumerBase {
constructor() {
super(ConsumerBase.getServiceName(PublicNotifyConsumer));
}
async subBeforeConsumer(queuedName, actionBody) {
console.log("前置操作......", this.serviceName);
}
async subDoConsumer(queuedName, actionBody) {
var params = {
actionType: actionBody.actionType,
identifyCode: actionBody.identifyCode,
actionBody: {
messageBody: actionBody.messageBody,
resultInfo: actionBody.resultInfo
},
requestId: actionBody.requestId
}
var execResult = await this.execPostByTimeOut(params, actionBody.notifyUrl);
return execResult;
}
}
module.exports = PublicNotifyConsumer;
\ No newline at end of file
const ConsumerBase = require("../../consumer.base");
class PublicConsumer extends ConsumerBase {
constructor() {
super(ConsumerBase.getServiceName(PublicConsumer));
}
async subBeforeConsumer(queuedName, actionBody) {
console.log("前置操作......", this.serviceName);
}
async subDoConsumer(queuedName, actionBody) {
var params = {
actionType: actionBody.actionType,
identifyCode: actionBody.identifyCode,
actionBody: actionBody.messageBody,
requestId: actionBody.requestId
}
var execResult = await this.execPostByTimeOut(params, actionBody.pushUrl);
return execResult;
}
}
module.exports = PublicConsumer;
\ No newline at end of file
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
var db = system.getObject("db.common.connection").getCon();
this.db = db;
this.model = db.models[this.modelName];
}
static getModelName(ClassObj) {
var nameStr = ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao"));
var initialStr = nameStr.substring(0, 1);
var resultStr = initialStr.toLowerCase() + nameStr.substring(1, nameStr.length);
return resultStr;
}
preCreate(u) {
return u;
}
/**
*
* @param {*} u 对象
* @param {*} t 事务对象t
*/
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, { transaction: t }).then(u => {
return u;
});
}
}
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' || paras.keys == 0 ? { type: this.db.QueryTypes.SELECT } : { replacements: paras, type: this.db.QueryTypes.SELECT };
}
var result = this.db.query(sql, tmpParas);
return result;
}
}
module.exports = Dao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class ConfigInfoDao extends Dao {
constructor() {
super(Dao.getModelName(ConfigInfoDao));
this.configInfoCacheKey = "queue-configuration:info";
this.redisClient = system.getObject("util.redisClient");
}
/**
* 获取配置信息列表,缓存600s
*/
async getList() {
var cacheStr = await this.redisClient.getCache(this.configInfoCacheKey);
if (cacheStr && cacheStr != "undefined") {
var list = JSON.parse(cacheStr);
return system.getResultSuccess(list);
}
var list = await this.model.findAll({
where: { is_enabled: 1 },
raw: true,
attributes: [
"c_key",
"c_value"
]
});
if (!list || list.length === 0) {
return system.getResult(null, "data is empty!");
}
cacheStr = JSON.stringify(list);
this.redisClient.setWithEx(this.configInfoCacheKey, cacheStr, 600);
var result = await system.getResultSuccess(list);
return result;
}
}
module.exports = ConfigInfoDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
const settings = require("../../../../config/settings");
class ErrorLogDao extends Dao {
constructor() {
super(Dao.getModelName(ErrorLogDao));
}
/**
* 添加错误日志
* @param {*} opTitle 操作标题
* @param {*} actionBody 操作的消息体
* @param {*} execResult 操作的返回信息
* @param {*} error 错误信息
* @param {*} logLevel 日志级别信息,debug: 0, info: 1, warn: 2, error: 3, fatal: 4
*/
async addOpErrorLogs(opTitle, actionBody, execResult, error, logLevel) {
error = typeof error === 'object' ? error : { error_info: error };
var params = {
queued_name: settings.queuedName,
identify_code: actionBody.identifyCode,
op_title: opTitle,
push_content: actionBody || null,
error_info: error || null,
result_info: execResult || null,
request_id: actionBody.requestId,
client_ip: actionBody.clientIp || "",
log_level: logLevel,
created_at: new Date()
}
await this.create(params);
return system.getResultSuccess();
}
}
module.exports = ErrorLogDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
const settings = require("../../../../config/settings");
class PushFailureLogDao extends Dao {
constructor() {
super(Dao.getModelName(PushFailureLogDao));
}
/**
* 添加失败日志
* @param {*} opTitle 操作标题
* @param {*} actionBody 操作的消息体
* @param {*} execResult 操作的返回信息
*/
async addOpFailureLogs(opTitle, actionBody, execResult) {
var params = {
queued_name: settings.queuedName,
identify_code: actionBody.identifyCode,
op_title: opTitle,
push_content: actionBody,
result_info: execResult,
request_id: actionBody.requestId,
client_ip: actionBody.clientIp || "",
created_at: new Date()
}
await this.create(params);
return system.getResultSuccess();
}
}
module.exports = PushFailureLogDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
const settings = require("../../../../config/settings");
class PushSuccessLogDao extends Dao {
constructor() {
super(Dao.getModelName(PushSuccessLogDao));
}
/**
* 添加成功日志
* @param {*} opTitle 操作标题
* @param {*} actionBody 操作的消息体
* @param {*} execResult 操作的返回信息
*/
async addOpSuccessLogs(opTitle, actionBody, execResult) {
var params = {
queued_name: settings.queuedName,
identify_code: actionBody.identifyCode,
op_title: opTitle,
push_content: actionBody,
result_info: execResult,
request_id: actionBody.requestId,
client_ip: actionBody.clientIp || "",
created_at: new Date()
}
await this.create(params);
return system.getResultSuccess();
}
}
module.exports = PushSuccessLogDao;
const system = require("../../../system");
module.exports = (db, DataTypes) => {
return db.define("configInfo", {
c_key: DataTypes.STRING(100),
c_value: DataTypes.STRING(100),
is_enabled: DataTypes.INTEGER,
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt: false,
//freezeTableName: true,
// define the table's name
tableName: 'configuration_info',
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");
module.exports = (db, DataTypes) => {
return db.define("errorLog", {
queued_name: DataTypes.STRING(512), //队列名称
identify_code: DataTypes.STRING(100), //标识code
op_title: DataTypes.STRING(100), // 操作标题
push_content: DataTypes.JSON, //推送的内容
error_info: DataTypes.JSON, //错误内容
result_info: DataTypes.JSON, //返回信息
request_id: DataTypes.STRING(100),
client_ip: DataTypes.STRING(100), //请求ip
log_level: DataTypes.INTEGER,// debug: 0, info: 1, warn: 2, error: 3, fatal: 4
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt: false,
//freezeTableName: true,
// define the table's name
tableName: 'op_error_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}]
// }
]
});
}
const system = require("../../../system");
module.exports = (db, DataTypes) => {
return db.define("pushFailureLog", {
queued_name: DataTypes.STRING(512), //队列名称
identify_code: DataTypes.STRING(100), //标识code
op_title: DataTypes.STRING(100), // 操作标题
push_content: DataTypes.JSON, //推送的内容
result_info: DataTypes.JSON, //返回信息
request_id: DataTypes.STRING(100),
client_ip: DataTypes.STRING(100), //请求ip
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt: false,
//freezeTableName: true,
// define the table's name
tableName: 'x_push_failure_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}]
// }
]
});
}
const system = require("../../../system");
module.exports = (db, DataTypes) => {
return db.define("pushSuccessLog", {
queued_name: DataTypes.STRING(512), //队列名称
identify_code: DataTypes.STRING(100), //标识code
op_title: DataTypes.STRING(100), // 操作标题
push_content: DataTypes.JSON, //推送的内容
result_info: DataTypes.JSON, //返回信息
request_id: DataTypes.STRING(100),
client_ip: DataTypes.STRING(100), //请求ip
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updatedAt: false,
//freezeTableName: true,
// define the table's name
tableName: 'x_push_success_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}]
// }
]
});
}
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class ConfigInfoService extends ServiceBase {
constructor() {
super("opLogs", ServiceBase.getDaoName(ConfigInfoService));
}
}
module.exports = ConfigInfoService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class ErrorLogService extends ServiceBase {
constructor() {
super("opLogs", ServiceBase.getDaoName(ErrorLogService));
}
}
module.exports = ErrorLogService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class PushFailureLogService extends ServiceBase {
constructor() {
super("opLogs", ServiceBase.getDaoName(PushFailureLogService));
}
}
module.exports = PushFailureLogService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class PushSuccessLogService extends ServiceBase {
constructor() {
super("opLogs", ServiceBase.getDaoName(PushSuccessLogService));
}
}
module.exports = PushSuccessLogService;
const system = require("../../../system");
const AppServiceBase = require("../../app.base");
const settings = require("../../../../config/settings");
const moment = require('moment');
//用户权限操作
class UtilsIcService extends AppServiceBase {
constructor() {
super();
this.esUtils = system.getObject("util.esUtils");
}
/**
* 公司模糊查询
* actionBody {companyName:公司名称,currentPage:第几页,pageSize:每页大小}
*/
async getListByLikeCompanyName(actionBody) {
if (!actionBody.companyName) {
return system.getResult(null, "companyName can not be empty");
}
actionBody.companyName = await this.getConvertSemiangleStr(actionBody.companyName);
var pageSize = !actionBody.pageSize ? 15 : Number(actionBody.pageSize);
if (pageSize < 0) {
pageSize = 15;
}
var from = !actionBody.currentPage ? 0 : Number((actionBody.currentPage - 1) * pageSize);
if (from < 0) {
from = 0;
}
var esIndexName = "tx_ic_bigdata_business_heming_index/_search";
var params = {
"query": {
"bool": {
"must": [
{
"query_string": {
"default_field": "company_name_standard",
"query": '\"' + actionBody.companyName + '\"'
}
}
]
}
},
"from": from,
"size": pageSize,
"_source": [
"company_name"//公司名称
]
}
var resultData = null;
try {
resultData = await this.esUtils.execPostEs(settings.queuedName, params, esIndexName);
var sources = [];
var data = {
"totalCount": resultData.data && resultData.data.hits ? resultData.data.hits.total : 0,
"pageSize": pageSize,
"currentPage": from === 0 ? from : (from - 1),
"list": sources
};
if (!resultData.data.hits) {
return system.getResult(null, "data is empty");
}
if (!resultData.data.hits.hits || resultData.data.hits.hits.length === 0) {
return system.getResult(null, "data is empty!");
}
resultData.data.hits.hits.forEach(function (c) {
var source = {
"companyName": c._source.company_name//公司名称
};
sources.push(source);
});
return system.getResultSuccess(data);
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
console.log(stackStr, ".. getListByLikeCompanyName query is error");
//TODO:日志
return system.getResultError("query is error");
}
}
/**
* 公司精确查询
* actionBody {companyName:公司名称}
*/
async getItemByCompanyName(actionBody) {
if (!actionBody.companyName) {
return system.getResult(null, "companyName can not be empty");
}
actionBody.companyName = await this.getConvertSemiangleStr(actionBody.companyName);
var esIndexName = "tx_ic_bigdata_business_index/_search";
var params = {
"query": {
"bool": {
"must": [
{
"term": {
"company_name.raw": actionBody.companyName
}
}
]
}
},
"from": 0,
"size": 1,
"_source": [
"company_name",//公司名称
"company_org_type",//公司类型
"credit_code",//统一社会信用代码
"legal_person",//法人姓名
"from_time",//营业期限开始日期
"to_time",//营业期限结束日期
"estiblish_time",//成立时间
"reg_location",//公司地址
"reg_capital",//注册资本
"reg_unit",//资本单位
"business_scope"//公司经营范围
]
// ,
// "sort": [
// {
// "reg_capital": "desc"
// }
// ]
}
var resultData = null;
try {
resultData = await this.esUtils.execPostEs(settings.queuedName, params, esIndexName);
if (!resultData.data.hits) {
return system.getResult(null, "data is empty");
}
if (!resultData.data.hits.hits || resultData.data.hits.hits.length === 0) {
return system.getResult(null, "data is empty!");
}
var fromTime = resultData.data.hits.hits[0]._source.from_time ? moment(resultData.data.hits.hits[0]._source.from_time * 1000).format("YYYY-MM-DD") : "";//营业期限开始日期
var toTime = resultData.data.hits.hits[0]._source.to_time ? moment(resultData.data.hits.hits[0]._source.to_time * 1000).format("YYYY-MM-DD") : "";//营业期限结束日期
var item = {
companyName: resultData.data.hits.hits[0]._source.company_name,//公司名称
companyOrgType: resultData.data.hits.hits[0]._source.company_org_type || "",//公司类型
creditCode: resultData.data.hits.hits[0]._source.credit_code || "",//统一社会信用代码
legalPerson: resultData.data.hits.hits[0]._source.legal_person,//法人姓名
fromTime: fromTime,//营业期限开始日期
toTime: toTime,//营业期限结束日期
operatingPeriod: (fromTime || "---") + " 至 " + (toTime || "---"),
estiblishTime: resultData.data.hits.hits[0]._source.estiblish_time ? moment(resultData.data.hits.hits[0]._source.estiblish_time * 1000).format("YYYY-MM-DD") : "",//成立时间
regLocation: resultData.data.hits.hits[0]._source.reg_location || "",//公司地址
regCapital: resultData.data.hits.hits[0]._source.reg_capital || "",//注册资本
regUnit: resultData.data.hits.hits[0]._source.reg_unit || "",//资本单位
businessScope: resultData.data.hits.hits[0]._source.business_scope || ""//公司经营范围
};
return system.getResultSuccess(item);
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
//TODO:日志
console.log(stackStr, ".. getItemByCompanyName query is error");
return system.getResultError("query is error");
}
}
async getConvertSemiangleStr(str) {
var result = "";
str = str.replace(/\s+/g, "");
var len = str.length;
for (var i = 0; i < len; i++) {
var cCode = str.charCodeAt(i);
//全角与半角相差(除空格外):65248(十进制)
cCode = (cCode >= 0xFF01 && cCode <= 0xFF5E) ? (cCode - 65248) : cCode;
//处理空格
cCode = (cCode == 0x03000) ? 0x0020 : cCode;
result += String.fromCharCode(cCode);
}
return result;
}
}
module.exports = UtilsIcService;
const system = require("../../../system");
const settings = require("../../../../config/settings");
const AppServiceBase = require("../../app.base");
//用户权限操作
class UtilsProduceService extends AppServiceBase {
constructor() {
super();
}
/**
* 接口跳转-POST请求
* action_type 执行的类型
* action_body 执行的参数
*/
async produceData(pobj, req) {
if (!pobj.actionBody) {
return system.getResult(null, "actionBody不能为空");
}
var keyCount = Object.keys(pobj.actionBody).length;
if (keyCount === 0) {
return system.getResult(null, "actionBody参数不能为空");
}
if (!pobj.actionBody.pushUrl) {
return system.getResult(null, "actionBody.pushUrl参数不能为空");
}
if (!pobj.actionBody.identifyCode) {
return system.getResult(null, "actionBody.identifyCode参数不能为空");
}
if (!pobj.actionBody.messageBody) {
return system.getResult(null, "actionBody.messageBody不能为空");
}
var msgKeyCount = Object.keys(pobj.actionBody.messageBody).length;
if (msgKeyCount === 0) {
return system.getResult(null, "actionBody.messageBody参数不能为空");
}
await this.redisClient.lpushData(settings.queuedName, pobj.actionBody);
return system.getResultSuccess();
}
/**
* 接口跳转-POST请求
* action_type 执行的类型
* action_body 执行的参数
*/
async produceLogsData(pobj, req) {
if (!pobj.actionBody) {
return system.getResult(null, "actionBody不能为空");
}
var keyCount = Object.keys(pobj.actionBody).length;
if (keyCount === 0) {
return system.getResult(null, "actionBody参数不能为空");
}
if (!pobj.actionBody.indexName) {
return system.getResult(null, "actionBody.indexName参数不能为空");
}
if (!pobj.actionBody.identifyCode) {
return system.getResult(null, "actionBody.identifyCode参数不能为空");
}
if (!pobj.actionBody.messageBody) {
return system.getResult(null, "actionBody.messageBody不能为空");
}
var msgKeyCount = Object.keys(pobj.actionBody.messageBody).length;
if (msgKeyCount === 0) {
return system.getResult(null, "actionBody.messageBody参数不能为空");
}
await this.redisClient.lpushData(settings.queuedName, pobj.actionBody);
return system.getResultSuccess();
}
}
module.exports = UtilsProduceService;
const system = require("../../../system");
const AppServiceBase = require("../../app.base");
const { TXCOSCONFIG } = require("../../../../config/platform");
const COSSTS = require('qcloud-cos-sts');
//用户权限操作
class UtilsTxCosService extends AppServiceBase {
constructor() {
super();
this.configInfoDao = system.getObject("db.opLogs.configInfoDao");
}
/**
* 接口跳转-POST请求
* action_type 执行的类型
* action_body 执行的参数
*/
async getCosInfo() {
var result = null;
if (TXCOSCONFIG.allowPrefix === '_ALLOW_DIR_/*') {
result = system.getResult(null, "请修改 allowPrefix 配置项,指定允许上传的路径前缀");
return result;
}
var configInfoResult = await this.configInfoDao.getList();
if (configInfoResult.status != 1) {
result = system.getResult(null, "db-configInfo list is empty");
return result;
}
var cosSecretId = configInfoResult.data.filter(f => f.c_key === "cosSecretId");
var cosSecretKey = configInfoResult.data.filter(f => f.c_key === "cosSecretKey");
var cosBucket = configInfoResult.data.filter(f => f.c_key === "cosBucket");
var cosRegion = configInfoResult.data.filter(f => f.c_key === "cosRegion");
var cosProxy = configInfoResult.data.filter(f => f.c_key === "cosProxy");
if (!cosSecretId || !cosSecretKey || !cosBucket || !cosRegion) {
result = system.getResult(null, "db-configInfo,cos info is empty");
return result;
}
// 获取临时密钥
var LongBucketName = cosBucket[0].c_value;
var ShortBucketName = LongBucketName.substr(0, LongBucketName.lastIndexOf('-'));
var AppId = LongBucketName.substr(LongBucketName.lastIndexOf('-') + 1);
var policy = {
'version': '2.0',
'statement': [{
'action': TXCOSCONFIG.allowActions,
'effect': 'allow',
'resource': [
'qcs::cos:' + cosRegion[0].c_value + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + TXCOSCONFIG.allowPrefix,
],
}],
};
var options = {
secretId: cosSecretId[0].c_value,
secretKey: cosSecretKey[0].c_value,
proxy: cosProxy ? cosProxy[0].c_value || "" : "",
region: cosRegion[0].c_value,
durationSeconds: TXCOSCONFIG.durationSeconds,
policy: policy,
};
console.log(options, "...getCosInfo.....options");
var getParam = await new Promise(function (resv, rej) {
COSSTS.getCredential(options, function (err, tempKeys) {
if (err) {
rej(err);
} else {
if (tempKeys.credentials) {
tempKeys.credentials.tmpBucket = cosBucket[0].c_value;
tempKeys.credentials.tmpRegion = cosRegion[0].c_value;
}
resv(tempKeys);
}
});
});
result = getParam ? system.getResultSuccess(getParam) : system.getResult(null, "获取cos信息失败");
return result;
}
}
module.exports = UtilsTxCosService;
const system = require("../system");
const moment = require('moment')
// const settings = require("../../config/settings");
class ServiceBase {
constructor(gname, daoName) {
this.execClient = system.getObject("util.execClient");
this.db = system.getObject("db.common.connection").getCon();
this.daoName = daoName;
this.dao = system.getObject("db." + gname + "." + daoName);
}
static getDaoName(ClassObj) {
var nameStr = ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")) + "Dao";
var initialStr = nameStr.substring(0, 1);
var resultStr = initialStr.toLowerCase() + nameStr.substring(1, nameStr.length);
return resultStr;
}
/**
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
*/
async execPostByTimeOut(params, url, ContentType, headData, timeOut = 60) {
return await this.execClient.execPostTimeOutByBusiness("sve.base", params, url, ContentType, headData, timeOut);
}
async create(qobj) {
return this.dao.create(qobj);
}
async customQuery(sql, paras, t) {
return this.dao.customQuery(sql, paras, t);
}
/*
返回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('');
}
}
module.exports = ServiceBase;
const system = require("../system");
const settings = require("../../config/settings");
const moment = require('moment');
const axios = require('axios');
class EsUtils {
constructor() {
this.execClient = system.getObject("util.execClient");
this.errorLogDao = system.getObject("db.opLogs.errorLogDao");
this.configInfoDao = system.getObject("db.opLogs.configInfoDao");
}
/**
* 添加es日志
* @param {*} queuedName 队列名称
* @param {*} actionBody 日志信息
*/
async addEsLogs(queuedName, actionBody) {
var esIndexName = queuedName;
if (["SYTXPUBLIC-MSGQ-request", "SYTXPUBLIC-MSGQ-error"].indexOf(esIndexName) < 0) {
esIndexName = queuedName + (actionBody.indexName ? "-" + actionBody.indexName : "");
}
esIndexName = esIndexName.toLocaleLowerCase() + "/_doc?pretty";
actionBody.resultInfo = typeof actionBody.resultInfo === 'object' ? JSON.stringify(actionBody.resultInfo) : actionBody.resultInfo;
actionBody.errorInfo = typeof actionBody.errorInfo === 'object' ? JSON.stringify(actionBody.errorInfo) : actionBody.errorInfo;
actionBody.messageBody = typeof actionBody.messageBody === 'object' ? JSON.stringify(actionBody.messageBody) : actionBody.messageBody;
actionBody.messageBody=actionBody.messageBody+";actionType="+actionBody.actionType+";pushUrl="+actionBody.pushUrl
var params = {
opTitle: moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "," + actionBody.opTitle || "",
identifyCode: actionBody.identifyCode || "",
messageBody: actionBody.messageBody || "",
resultInfo: actionBody.resultInfo || "",
errorInfo: actionBody.errorInfo || "",
requestId: actionBody.requestId,
created_at: new Date()
}
var execResult = await this.execPostEs(queuedName, params, esIndexName);
return execResult;
}
/**
* post日志到Es
* @param {*} queuedName 队列名称
* @param {*} params 参数
* @param {*} esIndexName es索引名称
*/
async execPostEs(queuedName, params, esIndexName) {
try {
var configInfoResult = await this.configInfoDao.getList();
if (configInfoResult.status != 1) {
this.errorLogDao.addOpErrorLogs("publicLogsConsumer,configInfo list is empty", params, null, null, 1);
return system.getResultSuccess();
}
var publicLogsEsName = configInfoResult.data.filter(f => f.c_key === "publicLogsEsName");
var publicLogsEsPwd = configInfoResult.data.filter(f => f.c_key === "publicLogsEsPwd");
var publicLogsEsReqUrl = configInfoResult.data.filter(f => f.c_key === "publicLogsEsReqUrl");
if (!publicLogsEsName || !publicLogsEsPwd || !publicLogsEsReqUrl) {
this.errorLogDao.addOpErrorLogs("publicLogsConsumer,es account info is empty", params, null, null, 1);
return system.getResultSuccess();
}
var reqUrl = publicLogsEsReqUrl[0].c_value + esIndexName
if (settings.env === "dev") {
let result = await axios({
// headers: {'Content-Type': 'application/x-www-form-urlencoded'},
headers: {
'Content-type': 'application/json',
'Authorization': 'Basic YWRtaW5lczphZG1pbkdTQmVzLg=='
},
method: 'POST',
url: reqUrl,
data: JSON.stringify(params),
timeout: 5000
});
if (result.status == 201) {
return system.getResultSuccess();
}
this.errorLogDao.addOpErrorLogs(queuedName + "执行execPostEs存在错误", params, result, null, 3);
return system.getResult(null, "执行execPostEs存在错误");
}
//方式二
var result = await this.execClient.execPostEs(params, reqUrl, publicLogsEsName[0].c_value, publicLogsEsPwd[0].c_value);
if (!result || !result.stdout) {
this.errorLogDao.addOpErrorLogs(queuedName + "执行execPostEs存在错误", params, result, null, 3);
return system.getResult(null, "执行execPostEs存在错误");
return system.getResult(null, "execPostTimeOut data is empty");
}
var stdoutInfo = JSON.parse(result.stdout);
if (stdoutInfo.error) {
this.errorLogDao.addOpErrorLogs(queuedName + "执行execPostEs存在错误", params, result, null, 3);
return system.getResult(null, "执行execPostEs存在错误");
}
return system.getResultSuccess(stdoutInfo);
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
console.log(stackStr, "......execPostEs....error.....");
this.errorLogDao.addOpErrorLogs(queuedName + "执行execPostEs存在异常", params, null, stackStr, 3);
}
}
}
module.exports = EsUtils;
const system = require("../system");
const redis = require("redis");
const settings = require("../../config/settings");
const bluebird = require("bluebird");
bluebird.promisifyAll(redis);
class RedisClient {
constructor() {
this.redisConfig = settings.redis();
this.client = this.getCreateClientInstance();
this.subclient = this.client.duplicate();
this.client.on("error", function (err) {
//TODO:日志处理
console.log(err, "..redisClient........error");
});
const self = this;
// 监听回调
const subExpired = async (err, res) => {
// 这里需要创建一个新的Redis对象
// 因为 连接在订阅服务器模式下,只能使用订阅服务器命令
const sub = self.getCreateClientInstance();
// 设置事件参数
const expired_subKey = `__keyevent@${self.redisConfig.db}__:expired`
sub.subscribe(expired_subKey, function () {
sub.on('message', async function (channel, msg) {
try {
var opResult = msg.split("$$");
if (!opResult || opResult.length == 0) {
return;
}
if ("SYTXFAIL-SYTXPUBLIC-MSGQ" != opResult[0] && "LOGSFAIL-SYTXPUBLIC-MSGQ" != opResult[0]) {
return;
}
var lock = await self.enter(opResult[1]);
if (lock && lock === "1") {
var opData = await self.zrangeList(opResult[0], opResult[1], opResult[1]);
if (!opData || opData.length == 0) {
return;
}
var opDataItem = JSON.parse(opData[0]);
await self.lpushData(opDataItem.queuedName, opDataItem);
await self.zremRangebyscoreData(opResult[0], opResult[1], opResult[1]);
}
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
//TODO:日志处理
console.log(stackStr, ".....message......................error...........");
}
});
});
};
// 创建监听
this.client.send_command('config', ['set', 'notify-keyspace-events', 'Ex'], subExpired)
}
getDuplicateInstance() {
return this.subclient;
}
getCreateClientInstance() {
const self = this;
return redis.createClient({
host: self.redisConfig.host,
port: self.redisConfig.port,
password: self.redisConfig.password,
db: self.redisConfig.db,
retry_strategy: function (options) {
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
return 10000;
}
return Math.min(options.attempt * 100, 3000);
}
});
}
/**
* 生产供消费者消费的数据
* @param {*} queuedName 队列名称
* @param {*} actionBody 业务数据
*/
lpushData(queuedName, messageBody) {
messageBody = typeof messageBody === 'object' ? JSON.stringify(messageBody) : messageBody;
this.client.lpush(queuedName, messageBody, function (err, reply) {
if (err) {
return new Error("lpush message error :" + err + ",queuedName:" + queuedName + ",messageBody:" + messageBody);
} else {
console.log("lpush message success");
}
});
}
/**
* 设置延迟事件redis存储
* @param {*} key key
* @param {*} exSeconds 过期时间-单位秒
* @param {*} value 值
*/
async setDelayEventData(key, value, exSeconds) {
value = typeof value === 'object' ? JSON.stringify(value) : value;
var key = key + "$$" + value;
this.client.set(key, "delay event", 'EX', exSeconds);
}
/**
* 添加集合数据
* @param {*} collectionName 集合名称
* @param {*} score 分数,用于区间查询
* @param {*} param 参数信息(可以是json)
*/
async zaddSortedSet(collectionName, score, param) {
param = typeof param === 'object' ? JSON.stringify(param) : param;
await this.client.zadd([collectionName + "-SORT", score, param], function (err, data) {
if (err) {
return new Error("zaddSortedSet data error :" + err + ",collectionName:" + collectionName + ",param:" + param);
} else {
console.log("zaddSortedSet data success");
}
});
}
/**
* 获取集合的区间值
* @param {*} collectionName 集合名称
* @param {*} minValue 最小值
* @param {*} maxValue 最大值
*/
async zrangeList(collectionName, minValue, maxValue) {
return await this.client.zrangebyscoreAsync(collectionName + "-SORT", minValue, maxValue);
}
/**
* 删除集合的区间值
* @param {*} collectionName 集合名称
* @param {*} minValue 最小值
* @param {*} maxValue 最大值
*/
async zremRangebyscoreData(collectionName, minValue, maxValue) {
return await this.client.zremrangebyscoreAsync(collectionName + "-SORT", minValue, maxValue);
}
/**
* 设置缓存
* @param {*} key key
* @param {*} val 值
* @param {*} t 过期时间,为空则永久存在
*/
async setWithEx(key, val, t) {
var p = this.client.setAsync(key, val);
if (t) {
this.client.expire(key, t);
}
return p;
}
/**
* 获取缓存
* @param {*} key key
*/
async getCache(key) {
return this.client.getAsync(key);
}
/**
* 判断key是否存在
* @param {*} key key
*/
async exists(key) {
return this.client.existsAsync(key);
}
/**
* 删除缓存
* @param {*} key key
*/
async delete(key) {
return this.client.delAsync(key);
}
/**
* 设置业务锁
* @param {*} lockKey 锁key
*/
async init(lockKey, lockValue, lockTime) {
this.client.rpushAsync(lockKey, lockValue || "1");
this.client.expire(lockKey, lockTime || 6000);
}
/**
* 获取业务锁
* @param {*} lockKey 锁key
*/
async enter(lockKey) {
return this.client.rpopAsync(lockKey);
}
}
module.exports = RedisClient;
var express = require('express');
var path = require('path');
var methodOverride = require('method-override');
// var cookierParser = require('cookie-parser');
// var session = require('express-session');
// var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
// var multer = require('multer');
var errorHandler = require('errorhandler');
var settings = require('./settings');
var system = require('../base/system');
var routes = require('./routes');
// const logCtl = system.getObject("service.common.oplogSve");
// const clientRedis = system.getObject("util.redisClient").client;
//const tm=system.getObject("db.taskManager");
module.exports = function (app) {
app.set('port', settings.port);
app.use(methodOverride());
// app.use(cookierParser());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
routes(app);//初始化路由
app.use(express.static(path.join(settings.basepath, '/app/front/entry/public')));
app.all('*', function (req, res, next) {
req.objs = system;
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
//跨域允许的请求方式
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'true');
if (req.method.toLowerCase() == 'options') {
res.send(200); //让options请求快速返回/
}
else {
next();
}
});
// if (settings.env == "dev") {
// app.use(session(
// {
// name: 'devdemosid',
// cookie: { maxAge: 3600000 },
// rolling: true,
// resave: false,
// saveUninitialized: false,
// secret: 'uwotm8',
// store: new RedisStore({
// client: clientRedis,
// }),
// }));
// } else {
// app.use(session(
// {
// name: 'demosid',
// cookie: { maxAge: 3600000 },
// rolling: true,
// resave: false,
// saveUninitialized: false,
// secret: 'uwotm8',
// store: new RedisStore({
// client: clientRedis,
// }),
// }));
// }
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
} else {
app.use(function (err, req, res) {
console.log("prod error handler...........................................");
console.log(err);
logCtl.error({
optitle: "environment 调用异常error:",
op: req.url,
content: e.toString(),
clientIp: system.get_client_ip(req),
agent: req.headers["user-agent"],
});
//logerApp.error("prod error handler",err);
res.send("link index");
});
}
};
module.exports = {
TXCOSCONFIG: {
durationSeconds: 1800,
// 允许操作(上传)的对象前缀,可以根据自己网站的用户登录态判断允许上传的目录,例子: user1/* 或者 * 或者a.jpg
// 请注意当使用 * 时,可能存在安全风险,详情请参阅:https://cloud.tencent.com/document/product/436/40265
// allowPrefix: '_ALLOW_DIR_/*',
allowPrefix: '*',
// 密钥的权限列表
allowActions: [
// 所有 action 请看文档 https://cloud.tencent.com/document/product/436/31923
// 简单上传
'name/cos:PutObject',
'name/cos:PostObject',
// 分片上传
'name/cos:InitiateMultipartUpload',
'name/cos:ListMultipartUploads',
'name/cos:ListParts',
'name/cos:UploadPart',
'name/cos:CompleteMultipartUpload',
//下载操作
"name/cos:GetObject"
],
}
}
\ No newline at end of file
const system = require("./app/base/system");
var settings = require("./app/config/settings");
var http = require('http');
var express = require('express');
var environment = require('./app/config/environment');
const app = express();
// //数据库支持暂缓支持
// var dbf = system.getObject("db.common.connection");
// con = dbf.getCon();
console.log(settings.consumerName, "--consumerName-----start-----");
if (settings.consumerName) {
var consumer = system.getObject("consumer." + settings.consumerName);
(async () => {
await consumer.doConsumer(settings.queuedName);
})();
} else {
console.log("not find consumer,please check ............................");
}
environment(app);//初始化环境
var server = http.createServer(app);
server.listen(settings.port, function () {
console.log('Express server listening on port ' + settings.port);
});
node_modules/
localsettings.js
\ No newline at end of file
## 工商注册项目
const system = require("../system");
const settings = require("../../config/settings");
const uuid = require('uuid');
class APIBase {
constructor() {
this.execClient = system.getObject("util.execClient");
this.exTime = 6 * 3600;//缓存过期时间,6小时
}
//-----------------------新的模式------------------开始
async doexecMethod(gname, methodname, pobj, query, req) {
var param = {
pobj: pobj,
query: query
}
try {
var result = await this[methodname](pobj, query, req);
if (!result) {
result = system.getResult(null, "请求的方法返回值为空");
}
result.requestId = result.requestId || uuid.v1();
var tmpResult = pobj.actionType.indexOf("List") < 0 ? result : { status: result.status, message: result.message, requestId: result.requestId };
this.execClient.execLogs("reqPath:" + req.path + "执行结果", param, "brg-user-apibase", tmpResult, null);
return result;
} catch (error) {
var stackStr = error.stack ? error.stack : JSON.stringify(error);
console.log(stackStr, "api调用出现异常,请联系管理员..........");
var rtnerror = system.getResultFail(-200, "出现异常,error:" + stackStr);
rtnerror.requestId = uuid.v1();
this.execClient.execLogs("reqPath:" + req.path + "执行异常", param, "brg-user-apibase", null, stackStr);
return rtnerror;
}
}
//-----------------------新的模式------------------结束
/**
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
* @param {*} timeOut 超时时间
*/
async execPostByTimeOut(params, url, ContentType, headData, timeOut = 60) {
return await this.execClient.execPostTimeOutByBusiness("api.base", params, url, ContentType, headData, timeOut);
}
}
module.exports = APIBase;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class XBoss extends APIBase {
constructor() {
super();
this.utilsXbossSve = system.getObject("service.utilsSve.utilsXbossSve");
this.serviceInfoSve = system.getObject("service.serviceprovider.serviceInfoSve");
}
/**
* 接口跳转-POST请求
* action_process 执行的流程
* action_type 执行的类型
* action_body 执行的参数
*/
async springBoard(pobj, qobj, req) {
if (!pobj.actionType) {
return system.getResult(null, "actionType参数不能为空");
}
var result = await this.opActionProcess(pobj, pobj.actionType, req);
return result;
}
async opActionProcess(pobj, action_type, req) {
var opResult = null;
switch (action_type) {
case "test"://测试
opResult = system.getResultSuccess("测试接口");
break;
case "xneedList"://需求列表
opResult = await this.utilsXbossSve.xneedList(pobj);
break;
case "xneedDetail"://需求详情
opResult = await this.utilsXbossSve.xneedDetail(pobj);
break;
case "xApplicantList"://主体列表
opResult = await this.utilsXbossSve.xApplicantList(pobj);
break;
case "xApplicantDetail"://主体详情
opResult = await this.utilsXbossSve.xApplicantDetail(pobj);
break;
case "getProductListBySrvicerCode"://服务商产品列表(设置服务商分配规则使用)
opResult = await this.utilsXbossSve.getProductListBySrvicerCode(pobj);
break;
case "getServiceInfoList"://服务商列表
opResult = await this.serviceInfoSve.getServiceInfoList(pobj);
break;
case "getServiceProviderList"://服务商列表(筛选条件)
opResult = await this.serviceInfoSve.getServiceProviderList(pobj);
break;
case "getServiceInfoDetail"://服务商详情
opResult = await this.serviceInfoSve.getServiceInfoDetail(pobj);
break;
case "createServiceProvider"://新增/修改服务商
opResult = await this.serviceInfoSve.createServiceProvider(pobj);
break;
case "getOrderDetail"://用户端查看订单详情
opResult = await this.utilsXbossSve.xOrderDetail(pobj);
break;
case "getContributionInfoByOrderNum"://订单详情-出资比例列表
opResult = await this.utilsXbossSve.getContributionInfoByOrderNum(pobj);
break;
case "getPrincipalInfoByOrderNum"://订单-详情查询--资质证照-公司人员情况
opResult = await this.utilsXbossSve.getPrincipalInfoByOrderNum(pobj);
break;
case "getShareholderDataByOrderNum"://订单-详情查询--资质证照-股权结构
opResult = await this.utilsXbossSve.getShareholderDataByOrderNum(pobj);
break;
case "getWebAppByOrderNum"://订单-详情查询--资质证照-网站或APP信息
opResult = await this.utilsXbossSve.getWebAppByOrderNum(pobj);
break;
case "getServiceProjectByOrderNum"://订单-详情查询--资质证照-拟开展服务项目
opResult = await this.utilsXbossSve.getServiceProjectByOrderNum(pobj);
break;
case "getSpecialApprovalInfoByOrderNum"://订单-详情查询--资质证照-专项审批项目 ICP
opResult = await this.utilsXbossSve.getSpecialApprovalInfoByOrderNum(pobj);
break;
case "getMaterialsInfoByOrderNum"://订单-详情查询--资质证照-材料清单(固定上传项)
opResult = await this.utilsXbossSve.getMaterialsInfoByOrderNum(pobj);
break;
case "getPositionInfoByOrderNum"://订单-详情查询--任职信息列表
opResult = await this.utilsXbossSve.getPositionInfoByOrderNum(pobj);
break;
case "getOrderList"://用户端获取订单列表
opResult = await this.utilsXbossSve.xOrderQueryList(pobj);
break;
case "getQcOrderList"://资质服务列表
opResult = await this.utilsXbossSve.getQcOrderList(pobj);
break;
case "getQcAnnalsOrderList"://资质年报服务列表
opResult = await this.utilsXbossSve.getQcAnnalsOrderList(pobj);
break;
case "getAnnualReportByOrderNum"://资质年报详情-资质年报列表
opResult = await this.utilsXbossSve.getAnnualReportByOrderNum(pobj);
break;
case "getOrderTransactionPipelineList"://用户端获取交易流水列表
opResult = await this.utilsXbossSve.xOrderTransactionPipelineList(pobj);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
}
module.exports = XBoss;
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
var db = system.getObject("db.common.connection").getCon();
this.db = db;
this.model = db.models[this.modelName];
}
preCreate(u) {
return u;
}
/**
*
* @param {*} u 对象
* @param {*} t 事务对象t
*/
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, { transaction: t }).then(u => {
return u;
});
}
}
static getModelName(ClassObj) {
var nameStr = ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao"));
var initialStr = nameStr.substring(0, 1);
var resultStr = initialStr.toLowerCase() + nameStr.substring(1, nameStr.length);
return resultStr;
// return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery(qobj) {
var w = {};
if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
return this.model.findAll({ where: w, attributes: qobj.fields });
} else {
return this.model.findAll({ attributes: qobj.fields });
}
}
async 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 bulkDelete(ids) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en;
}
async delete(qobj) {
var en = await this.model.findOne({ where: qobj });
if (en != null) {
return en.destroy();
}
return null;
}
extraModelFilter() {
//return {"key":"include","value":{model:this.db.models.app}};
return null;
}
extraWhere(obj, where) {
return where;
}
orderBy() {
//return {"key":"include","value":{model:this.db.models.app}};
return [["created_at", "DESC"]];
}
buildAttributes() {
return [];
}
buildQuery(qobj) {
var linkAttrs = [];
const pageNo = qobj.pageInfo.pageNo;
const pageSize = qobj.pageInfo.pageSize;
const search = qobj.search;
const orderInfo = qobj.orderInfo;//格式:[["created_at", 'desc']]
var qc = {};
//设置分页查询条件
qc.limit = pageSize;
qc.offset = (pageNo - 1) * pageSize;
//默认的查询排序
if (orderInfo) {
qc.order = orderInfo;
} else {
qc.order = this.orderBy();
}
//构造where条件
qc.where = {};
if (search) {
Object.keys(search).forEach(k => {
console.log(search[k], ":search[k]search[k]search[k]");
if (search[k] && search[k] != 'undefined' && search[k] != "") {
if ((k.indexOf("Date") >= 0 || k.indexOf("_at") >= 0)) {
if (search[k] != "" && search[k]) {
var stdate = new Date(search[k][0]);
var enddate = new Date(search[k][1]);
qc.where[k] = { [this.db.Op.between]: [stdate, enddate] };
}
}
else if (k.indexOf("id") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("channelCode") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("Type") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("Status") >= 0) {
qc.where[k] = search[k];
}
else if (k.indexOf("status") >= 0) {
qc.where[k] = search[k];
}
else {
if (k.indexOf("~") >= 0) {
linkAttrs.push(k);
} else {
qc.where[k] = { [this.db.Op.like]: "%" + search[k] + "%" };
}
}
}
});
}
this.extraWhere(qobj, qc.where, qc, linkAttrs);
var extraFilter = this.extraModelFilter();
if (extraFilter) {
qc[extraFilter.key] = extraFilter.value;
}
var attributesObj = this.buildAttributes();
if (attributesObj && attributesObj.length > 0) {
qc.attributes = attributesObj;
}
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm");
console.log(qc);
return qc;
}
async findAndCountAll(qobj, t) {
var qc = this.buildQuery(qobj);
var apps = await this.model.findAndCountAll(qc);
return apps;
}
preUpdate(obj) {
return obj;
}
async update(obj, tm) {
var obj2 = this.preUpdate(obj);
if (tm != null && tm != 'undefined') {
return this.model.update(obj2, { where: { id: obj2.id }, transaction: tm });
} else {
return this.model.update(obj2, { where: { id: obj2.id } });
}
}
async updateByWhere(setObj, whereObj, t) {
if (t && t != 'undefined') {
if (whereObj && whereObj != 'undefined') {
whereObj.transaction = t;
} else {
whereObj = { transaction: t };
}
}
return this.model.update(setObj, whereObj);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.db.query(sql, paras);
}
async customQuery(sql, paras, t) {
var tmpParas = null;//||paras=='undefined'?{type: this.db.QueryTypes.SELECT }:{ replacements: paras, type: this.db.QueryTypes.SELECT };
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' || paras.keys == 0 ? { type: this.db.QueryTypes.SELECT } : { replacements: paras, type: this.db.QueryTypes.SELECT };
}
var result = this.db.query(sql, tmpParas);
return result;
}
async customInsert(sql, paras, t) {
var tmpParas = null;
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.INSERT };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.INSERT };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' || paras.keys == 0 ? { type: this.db.QueryTypes.INSERT } : { replacements: paras, type: this.db.QueryTypes.INSERT };
}
var result = this.db.query(sql, tmpParas);
return result;
}
async customDelete(sql, paras, t) {
var tmpParas = null;
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.DELETE };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.DELETE };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' || paras.keys == 0 ? { type: this.db.QueryTypes.DELETE } : { replacements: paras, type: this.db.QueryTypes.DELETE };
}
var result = this.db.query(sql, tmpParas);
return result;
}
async customUpdate(sql, paras, t) {
var tmpParas = null;
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.UPDATE };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.UPDATE };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' ? { type: this.db.QueryTypes.UPDATE } : { replacements: paras, type: this.db.QueryTypes.UPDATE };
}
return this.db.query(sql, tmpParas);
}
async findCount(whereObj = null) {
return this.model.count(whereObj, { logging: false }).then(c => {
return c;
});
}
async findSum(fieldName, whereObj = null) {
return this.model.sum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
var tmpWhere = {};
tmpWhere.limit = pageSize;
tmpWhere.offset = (pageIndex - 1) * pageSize;
if (whereObj != null) {
tmpWhere.where = whereObj;
}
if (orderObj != null && orderObj.length > 0) {
tmpWhere.order = orderObj;
}
if (attributesObj != null && attributesObj.length > 0) {
tmpWhere.attributes = attributesObj;
}
if (includeObj != null && includeObj.length > 0) {
tmpWhere.include = includeObj;
tmpWhere.distinct = true;
}
tmpWhere.raw = true;
return await this.model.findAndCountAll(tmpWhere);
}
async findOne(obj, t) {
var params = { "where": obj };
if (t) {
params.transaction = t;
}
return this.model.findOne(params);
}
async findById(oid) {
return this.model.findById(oid);
}
}
module.exports = Dao;
......@@ -62,49 +62,4 @@ class DbFactory {
return this.db;
}
}
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);
// });
module.exports = DbFactory;
\ No newline at end of file
const system = require("../../../system");
const {PDICT} = require("../../../../config/platform");
/**
* 服务商信息
*/
module.exports = (db, DataTypes) => {
return db.define("serviceInfo", {
servicer_code: DataTypes.STRING(100),//服务商code
apply_type:
{
type: DataTypes.INTEGER,
set: function (val) {
this.setDataValue("apply_type", val);
this.setDataValue("apply_type_name", PDICT.apply_type[val]);
}
},
apply_type_name: DataTypes.STRING(50),
// servicer_about
servicer_name: DataTypes.STRING(255),//服务商名称
servicer_short_name: DataTypes.STRING(255),//服务商简称
bank_account: DataTypes.STRING(255),
bank_account_num: DataTypes.STRING(255),
sub_bank_account: DataTypes.STRING(255),
sub_bank_account_num: DataTypes.STRING(255),
// province_name
// city_name
region_name: DataTypes.STRING(255),
servicer_address: DataTypes.STRING(255),
push_domain_addr: DataTypes.STRING(500),//推送域名地址
is_enabled: DataTypes.INTEGER,//是否启用
principal_name: DataTypes.STRING(255),
principal_mobile: DataTypes.STRING(255),
business_license: DataTypes.STRING(500),//营业执照
// business_license_address: DataTypes.STRING(500),//营业执照地址
credit_code: DataTypes.STRING(50),//统一社会信用代码
legal_identity_card: DataTypes.STRING(200),//法人身份证
legal_name: DataTypes.STRING(20),//法人姓名
legal_mobile: DataTypes.STRING(20),//法人手机号
legal_identity_card_no: DataTypes.STRING(20),//法人身份证号
settlement_cycle:
{
type: DataTypes.INTEGER,
set: function (val) {
this.setDataValue("settlement_cycle", val);
this.setDataValue("settlement_cycle_name", PDICT.settlement_cycle[val]);
}
},
settlement_cycle_name: DataTypes.STRING(50),
}, {
paranoid: false,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
tableName: 'x_service_info',
validate: {
},
indexes: [
]
});
}
\ No newline at end of file
const system = require("../system");
const moment = require('moment');
const moment = require('moment')
const settings = require("../../config/settings");
const md5 = require("MD5");
class AppServiceBase {
constructor() {
this.execClient = system.getObject("util.execClient");
this.redisClient = system.getObject("util.redisClient");
this.pushlogFailType = { OLDRPC: 1, NEWRPC: 2, FAILLOG: 3, FQ: 4 };
}
/**
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
*/
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
* @param {*} timeOut 超时时间
*/
async execPostByTimeOut(params, url, ContentType, headData, timeOut = 60) {
return await this.execClient.execPostTimeOutByBusiness("app.base", params, url, ContentType, headData, timeOut);
return await this.execClient.execPostTimeOutByBusiness("app.base", params, url, ContentType, headData, timeOut);
}
/**
* 验证签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async verifySign(params, app_key) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!params.sign) {
return system.getResult(null, "请求参数sign为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResult(null, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
if (params.sign != resultTmpSign) {
return system.getResult(null, "返回值签名验证失败");
}
return system.getResultSuccess();
}
async opAliyunRpcVerifyParam(pobj) {//参数信息验证
var verify = system.getResultSuccess();
if (!pobj.interface_params) {
verify = system.getResult(null, "interface_params can not be empty,100440");
}
var interface_params_info = JSON.parse(pobj.interface_params);
if (!interface_params_info || !interface_params_info.action) {
verify = system.getResult(null, "interface_params.action can not be empty,100443");
}
verify.data = interface_params_info;
return verify;
}
async getConvertSemiangleStr(str) {//去除空格及全角转半角
......
const system = require("../../../system");
const {PDICT} = require("../../../../config/platform");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class ServiceInfoService extends ServiceBase {
constructor() {
super("serviceprovider", ServiceBase.getDaoName(ServiceInfoService));
}
/**
* 校验组装参数
* @param {*} ab
*/
async verifyAndPackageCreateParams(ab){
var params = {};
if(!ab.isEnabled || ab.isEnabled!=1){
params["is_enabled"] = 0;
}else{
params["is_enabled"] = 1;
}
if(!ab.servicerCode){//新增
if(!ab.pushDomainAddr){
return system.getResultFail(-101,"登录域名不能为空");
}
params["push_domain_addr"]=ab.pushDomainAddr;
if(!ab.applyType){
return system.getResultFail(-102,"账号类型不能为空");
}
params["apply_type"]=ab.applyType;
if(!ab.servicerShortName){
return system.getResultFail(-103,"服务商简称不能为空");
}
params["servicer_short_name"]=ab.servicerShortName;
if(!ab.servicerName){
return system.getResultFail(-104,"企业名称不能为空");
}
params["servicer_name"]=ab.servicerName;
}
if(!ab.bankAccount){
return system.getResultFail(-105,"公司银行开户名不能为空");
}
params["bank_account"]=ab.bankAccount;
if(!ab.bankAccountNum){
return system.getResultFail(-106,"公司银行账号不能为空");
}
params["bank_account_num"]=ab.bankAccountNum;
if(!ab.subBankAccount){
return system.getResultFail(-107,"开户行支行名称不能为空");
}
params["sub_bank_account"]=ab.subBankAccount;
if(!ab.subBankAccountNum){
return system.getResultFail(-108,"开户行支行联行号不能为空");
}
params["sub_bank_account_num"]=ab.subBankAccountNum;
if(!ab.settlementCycle){
return system.getResultFail(-109,"结算周期不能为空");
}
params["settlement_cycle"]=ab.settlementCycle;
if(!ab.regionName){
return system.getResultFail(-110,"所在地区不能为空");
}
params["region_name"]=ab.regionName;
if(!ab.servicerAddress){
return system.getResultFail(-111,"详细地址不能为空");
}
params["servicer_address"]=ab.servicerAddress;
if(!ab.principalName){
return system.getResultFail(-112,"负责人不能为空");
}
params["principal_name"]=ab.principalName;
if(!ab.principalMobile){
return system.getResultFail(-113,"联系电话不能为空");
}
params["principal_mobile"]=ab.principalMobile;
return system.getResultSuccess(params);
}
/**
* 新增/修改服务商
*/
async createServiceProvider(pobj){
if(!pobj || !pobj.actionBody){
return system.getResultFail(-100,"参数错误");
}
var ab = pobj.actionBody;
var params={};
var pakageRes = await this.verifyAndPackageCreateParams(ab);//校验组装参数
if(pakageRes.retcode!=0){
return pakageRes;
}else{
params = pakageRes.data;
}
var servicer_code = "";
if(ab.servicerCode){//传入服务商code 为修改服务商信息
servicer_code = ab.servicerCode;
params["servicer_code"] = servicer_code;
var serviceinfo = await this.dao.model.findOne({
where:{servicer_code:servicer_code},
raw:true
});
if(!serviceinfo || !serviceinfo.id){
return system.getResultFail(-300,"未知服务商");
}
params["id"] = serviceinfo.id;
var self = this;
return this.db.transaction(async function (t) {
await self.dao.update(params,t);//修改服务商信息
await self.editServiceProduct(ab.productList,serviceinfo.servicer_code,serviceinfo.servicer_name,params["is_enabled"],t);//修改服务商产品信息
return system.getResultSuccess();
})
}else{//新增服务商信息
servicer_code = await this.getBusUid("S_");
params["servicer_code"] = servicer_code;
var self = this;
return this.db.transaction(async function (t) {
var serviceinfo = await self.dao.create(params,t);//修改服务商信息
await self.editServiceProduct(ab.productList,serviceinfo.servicer_code,serviceinfo.servicer_name,params["is_enabled"],t);//编辑服务商产品信息
return system.getResultSuccess(serviceinfo);
})
}
}
/**
* 编辑服务商产品
* @param {*} productList 产品id列表
* @param {*} servicerCode 服务商编码
* @param {*} isEnabled 服务商是否启用
* @param {*} t 事务
*/
async editServiceProduct(productList,servicerCode,servicerName,isEnabled,t){
await this.dao.deleteAllProductByServicerCode(servicerCode,t);//根据服务商编码删除该服务商所有产品
// if(isEnabled==1){//服务商已启用
if(productList && productList.length>0){
await this.dao.setProductByServicerCode(productList,servicerCode,servicerName,t);//给服务商设置产品
}
// }
}
/**
* 服务商详情
*/
async getServiceInfoDetail(pobj){
if(!pobj || !pobj.actionBody){
return system.getResultFail(-100,"参数错误");
}
var ab = pobj.actionBody;
if(!ab.servicerCode){
return system.getResultFail(-101,"服务商编码不能为空");
}
var serviceinfo = await this.dao.model.findOne({
where:{servicer_code:ab.servicerCode},
raw:true
});
if(!serviceinfo || !serviceinfo.id){
return system.getResultFail(-300,"未知服务商信息");
}
//获取服务商分配产品列表
var productList = await this.dao.getAssignedProductsByServicerCode(ab.servicerCode);
var plist = [];
if(productList && productList.length>0){
for(var i=0;i<productList.length;i++){
var id = productList[i].id;
if(id){
plist.push(id);
}
}
}
serviceinfo["productList"] = plist;
return system.getResultSuccess(serviceinfo);
}
/**
* 服务商列表
*/
async getServiceInfoList(pobj){
var ab = {};
if(pobj && pobj.actionBody){
ab = pobj.actionBody
}
var result = await this.dao.getServiceProviderList(ab);
return result;
}
/**
* 服务商列表(筛选条件)
*/
async getServiceProviderList(pobj){
var ab = {};
if(pobj && pobj.actionBody){
ab = pobj.actionBody
}
var list = await this.dao.model.findAll({
attributes:["servicer_code","servicer_name","apply_type"],
raw:true,
})
return system.getResultSuccess(list);
}
}
module.exports = ServiceInfoService;
\ No newline at end of file
var system = require("../../../system");
var settings = require("../../../../config/settings");
const AppServiceBase = require("../../app.base");
//用户权限操作
class UtilsAuthService extends AppServiceBase {
constructor() {
super();
}
}
module.exports = UtilsAuthService;
const system = require("../system");
const moment = require('moment')
const settings = require("../../config/settings");
const md5 = require("MD5");
class ServiceBase {
constructor(gname, daoName) {
this.execClient = system.getObject("util.execClient");
this.db = system.getObject("db.common.connection").getCon();
this.daoName = daoName;
this.dao = system.getObject("db." + gname + "." + daoName);
}
/**
* 带超时时间的post请求
* @param {*} params 请求数据-json格式
* @param {*} url 请求地址
* @param {*} ContentType 请求头类型,默认application/json
* @param {*} headData 请求头内容-json格式,如:请求头中传递token,格式:{token:"9098902q849q0434q09439"}
* @param {*} timeOut 超时时间
*/
async execPostByTimeOut(params, url, ContentType, headData, timeOut = 60) {
return await this.execClient.execPostTimeOutByBusiness("sve.base", params, url, ContentType, headData, timeOut);
}
/**
* 验证签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async verifySign(params, app_key) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!params.sign) {
return system.getResult(null, "请求参数sign为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResult(null, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
if (params.sign != resultTmpSign) {
return system.getResult(null, "返回值签名验证失败");
}
return system.getResultSuccess();
}
/**
* 创建签名
* @param {*} params 要验证的参数
* @param {*} app_key 应用的校验key
*/
async createSign(params, app_key) {
if (!params) {
return system.getResultFail(-310, "请求参数为空");
}
var signArr = [];
var keys = Object.keys(params).sort();
if (keys.length == 0) {
return system.getResultFail(-330, "请求参数信息为空");
}
for (let k = 0; k < keys.length; k++) {
const tKey = keys[k];
if (tKey != "sign" && params[tKey] && !(params[tKey] instanceof Array)) {
signArr.push(tKey + "=" + params[tKey]);
}
}
if (signArr.length == 0) {
return system.getResultFail(-350, "请求参数组装签名参数信息为空");
}
var resultSignStr = signArr.join("&") + "&key=" + app_key;
var resultTmpSign = md5(resultSignStr).toUpperCase();
return system.getResultSuccess(resultTmpSign);
}
/**
* 验证参数信息不能为空
* @param {*} params 验证的参数
* @param {*} verifyParamsCount 需要验证参数的数量,如至少验证3个,则传入3
* @param {*} columnList 需要过滤掉的验证参数列表,格式:[]
*/
async verifyParams(params, verifyParamsCount, columnList) {
if (!params) {
return system.getResult(null, "请求参数为空");
}
if (!columnList) {
columnList = [];
}
var keys = Object.keys(params);
if (keys.length == 0) {
return system.getResult(null, "请求参数信息为空");
}
if (keys.length < verifyParamsCount) {
return system.getResult(null, "请求参数不完整");
}
var tResult = system.getResultSuccess();
for (let k = 0; k < keys.length; k++) {
const tKeyValue = keys[k];
if (columnList.length == 0 || columnList.indexOf(tKeyValue) < 0) {
if (!tKeyValue) {
tResult = system.getResult(null, k + "参数不能为空");
break;
}
}//白名单为空或不在白名单中,则需要验证不能为空
}
return tResult;
}
static getDaoName(ClassObj) {
var nameStr = ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Service")) + "Dao";
var initialStr = nameStr.substring(0, 1);
var resultStr = initialStr.toLowerCase() + nameStr.substring(1, nameStr.length);
return resultStr;
// 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 bulkDeleteByWhere(whereParam, t) {
return await this.dao.bulkDeleteByWhere(whereParam, t);
}
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('');
}
}
module.exports = ServiceBase;
......@@ -133,8 +133,8 @@ class System {
*/
static getResult(data, opmsg = "操作成功", req) {
return {
status: !data ? -1 : 1,
message: opmsg,
retcode: !data ? -1 : 1,
msg: opmsg,
data: data
};
}
......@@ -145,9 +145,9 @@ class System {
*/
static getResultSuccess(data, okmsg = "success") {
return {
status: 1,
message: okmsg,
data: data || null,
retcode: 0,
msg: okmsg,
data: data,
};
}
/**
......@@ -158,8 +158,8 @@ class System {
*/
static getResultFail(status = -1, errmsg = "fail", data = null) {
return {
status: status,
message: errmsg,
retcode: status,
msg: errmsg,
data: data,
};
}
......@@ -170,8 +170,8 @@ class System {
*/
static getResultError(errmsg = "fail", data = null) {
return {
status: -200,
message: errmsg,
retcode: -200,
msg: errmsg,
data: data,
};
}
......@@ -216,7 +216,7 @@ class System {
try {
ClassObj = require(objabspath);
} catch (e) {
// console.log(e.stack, "...getObject.....errror");
console.log(e.stack, "......getObject......");
let fname = objsettings[packageName + "base"];
ClassObj = require(fname);
}
......@@ -224,9 +224,6 @@ class System {
let modelname = filename.substring(0, filename.lastIndexOf("Dao"))
return System.register(objabspath, ClassObj, modelname);
}
if (ClassObj.name.indexOf("Ctl") >= 0) {
console.log(ClassObj.name);
}
return System.register(objabspath, ClassObj, groupName, filename);
}
}
......
const system = require("../system");
const redis = require("redis");
const settings = require("../../config/settings");
const bluebird = require("bluebird");
bluebird.promisifyAll(redis);
class RedisClient {
constructor() {
this.client = this.getCreateClientInstance();
this.subclient = this.client.duplicate();
}
getDuplicateInstance() {
return this.subclient;
}
getCreateClientInstance() {
const redisConfig = settings.redis()
return redis.createClient({
host: redisConfig.host,
port: redisConfig.port,
password: redisConfig.password,
db: redisConfig.db,
retry_strategy: function (options) {
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
return 10000;
}
return Math.min(options.attempt * 100, 3000);
}
});
}
/**
* 设置缓存
* @param {*} key key
* @param {*} val 值
* @param {*} t 过期时间,为空则永久存在
*/
async setWithEx(key, val, t) {
var p = this.client.setAsync(key, val);
if (t) {
this.client.expire(key, t);
}
return p;
}
/**
* 获取缓存
* @param {*} key key
*/
async getCache(key) {
return this.client.getAsync(key);
}
/**
* 删除缓存
* @param {*} key key
*/
async delete(key) {
return this.client.delAsync(key);
}
/**
* 判断缓存是否存在
* @param {*} key key
*/
async exists(key) {
return this.client.existsAsync(key);
}
/**
* 设置业务锁
* @param {*} lockKey 锁key
*/
async init(lockKey, lockValue, lockTime) {
this.client.rpushAsync(lockKey, lockValue || "1");
this.client.expire(lockKey, lockTime || 6000);
}
/**
* 获取业务锁
* @param {*} lockKey 锁key
*/
async enter(lockKey) {
return this.client.rpopAsync(lockKey);
}
}
module.exports = RedisClient;
\ No newline at end of file
var express = require('express');
var path = require('path');
var methodOverride = require('method-override');
var cookierParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');
var settings = require('./settings');
var system = require('../base/system');
var routes = require('./routes');
const clientRedis = system.getObject("util.redisClient").client;
//const tm=system.getObject("db.taskManager");
module.exports = function (app) {
app.set('port', settings.port);
app.set('views', settings.basepath + '/app/front/entry');
app.set('view engine', 'ejs');
app.use(methodOverride());
app.use(cookierParser());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
routes(app);//初始化路由
app.use(express.static(path.join(settings.basepath, '/app/front/entry/public')));
app.all('*', function (req, res, next) {
req.objs = system;
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
// res.header('Access-Control-Allow-Credentials', 'true');
if (req.method == 'OPTIONS') {
res.send(200); //让options请求快速返回/
}
else {
next();
}
});
if (settings.env == "dev") {
app.use(session(
{
name: 'devdemosid',
cookie: { maxAge: 3600000 },
rolling: true,
resave: false,
saveUninitialized: false,
secret: 'uwotm8',
store: new RedisStore({
client: clientRedis,
}),
}));
} else {
app.use(session(
{
name: 'demosid',
cookie: { maxAge: 3600000 },
rolling: true,
resave: false,
saveUninitialized: false,
secret: 'uwotm8',
store: new RedisStore({
client: clientRedis,
}),
}));
}
// development only
if ('development' == app.get('env')) {
app.use(errorHandler());
} else {
app.use(function (err, req, res) {
console.log(err.stack, "prod error handler...........................................");
res.send("link index");
});
}
};
......@@ -5,7 +5,7 @@ var settings = {
util:path.join(basepath,"app/base/utils"),
service:path.join(basepath,"app/base/service/impl"),
db:path.join(basepath,"app/base/db/impl"),
tool:path.join(basepath,"app/base/tool"),
service2:path.join(basepath,"app/base/service"),
consumer:path.join(basepath,"app/base/db/consumer"),
}
};
module.exports = settings;
module.exports = {
PDICT: {
logLevel: { "debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4 },
push_return_type: { "0": "推送失败", "1": "推送成功" },
pay_type:{"1":"微信","2":"qq钱包","3":"网银支付","4":"余额支付"},
order_op_type:{"1":"收","2":"支"},
order_status:{"1":"已接单","10":"收集工商注册材料","11":"工商审核环节","12":"刻章环节","13":"证件邮寄环节","14":"您已签收", "310":"部分已退款","320":"已退款","330":"已作废"},
apply_type:{"1":"企业","2":"个人"},
settlement_cycle:{"1":"周结","2":"月结","3":"季结","4":"年结"},
}
}
\ No newline at end of file
const url = require("url");
const system = require("../../base/system");
const sha256 = require('sha256');
const redisClient = system.getObject("util.redisClient");
var url = require("url");
var system = require("../../base/system");
module.exports = function (app) {
//-----------------------新的模式---------api---------开始
app.all("/api/*", async function (req, res, next) {
if (req.path === "/api/uploadAction/txCos/getCosInfo") {
next();
return;
}
//-----------------------新的模式---------web---------开始
app.all("/web/*", async function (req, res, next) {
var result = system.getResult(null, "req method must is post");
if (req.method != "POST") {
res.end(JSON.stringify(result));
return;
}
if (!req.body.actionType) {
result.message = "actionType can not be empty";
result.msg = "actionType can not be empty";
res.end(JSON.stringify(result));
return;
}
next();
});
app.get('/web/:gname/:qname/:method', function (req, res) {
var classPath = req.params["qname"];
var methodName = req.params["method"];
var gname = req.params["gname"];
classPath = gname + "." + classPath;
var tClientIp = system.get_client_ip(req);
req.clientIp = tClientIp; req
req.uagent = req.headers["user-agent"];
req.classname = classPath;
var params = [];
params.push(gname);
params.push(methodName);
params.push(req.body);
params.push(req.query);
params.push(req);
var p = null;
var invokeObj = system.getObject("api." + classPath);
if (invokeObj["doexecMethod"]) {
p = invokeObj["doexecMethod"].apply(invokeObj, params);
}
var shaStr = await sha256(JSON.stringify(req.body));
var existsKey = await redisClient.exists(shaStr);
if (existsKey) {
result.message = "req too often";
p.then(r => {
res.end(JSON.stringify(r));
});
});
app.post('/web/:gname/:qname/:method', function (req, res) {
var classPath = req.params["qname"];
var methodName = req.params["method"];
var gname = req.params["gname"];
var params = [];
classPath = gname + "." + classPath;
var tClientIp = system.get_client_ip(req);
req.clientIp = tClientIp;
req.uagent = req.headers["user-agent"];
req.classname = classPath;
params.push(gname);
params.push(methodName);
params.push(req.body);
params.push(req.query);
params.push(req);
var p = null;
var invokeObj = system.getObject("api." + classPath);
if (invokeObj["doexecMethod"]) {
p = invokeObj["doexecMethod"].apply(invokeObj, params);
}
p.then(r => {
res.end(JSON.stringify(r));
});
});
//-----------------------新的模式---------web---------结束
//-----------------------新的模式---------api---------开始
app.all("/api/*", async function (req, res, next) {
var result = system.getResult(null, "req method must is post");
if (req.method != "POST") {
res.end(JSON.stringify(result));
return;
}
if (!req.body.actionType) {
result.msg = "actionType can not be empty";
res.end(JSON.stringify(result));
return;
}
next();
});
......@@ -38,9 +94,10 @@ module.exports = function (app) {
classPath = gname + "." + classPath;
var tClientIp = system.get_client_ip(req);
req.clientIp = tClientIp;
req.clientIp = tClientIp; req
req.uagent = req.headers["user-agent"];
req.classname = classPath;
var params = [];
params.push(gname);
params.push(methodName);
......
var url = require("url");
var system = require("../../base/system");
var fs = require('fs');
var marked = require("marked");
module.exports = function (app) {
app.get('/doc', function (req, res) {
// if (!req.query.key) {
// res.send("文件不存在!!!");
// return;
// }
// if (req.query.key != "doc12345789") {
// res.send("文件不存在!!!!!!");
// return;
// }
var path = process.cwd() + "/app/front/entry/public/apidoc/README.md";
fs.readFile(path, function (err, data) {
if (err) {
console.log(err);
res.send("文件不存在!");
} else {
console.log(data);
str = marked(data.toString());
res.render('apidoc', { str });
}
});
});
app.get('/doc/:forder', function (req, res) {
var path = process.cwd() + "/app/front/entry/public/apidoc/README.md";
fs.readFile(path, function (err, data) {
if (err) {
console.log(err);
res.send("文件不存在!");
} else {
console.log(data);
str = marked(data.toString());
res.render('apidoc', { str });
}
});
});
app.get('/doc/api/:forder/:fileName', function (req, res) {
// if (req.url != "/doc/api/platform/fgbusinesschance.md") {
// if (!req.query.key) {
// res.send("文件不存在!!!");
// return;
// }
// if (req.query.key != "doc12345789") {
// res.send("文件不存在!!!!!!");
// return;
// }
// }
var forder = req.params["forder"];
var fileName = req.params["fileName"] || "README.md";
var path = process.cwd() + "/app/front/entry/public/apidoc";
if (forder) {
path = path + "/" + forder + "/" + fileName;
} else {
path = path + "/" + fileName;
}
fs.readFile(path, function (err, data) {
if (err) {
console.log(err);
res.send("文件不存在!");
} else {
console.log(data);
str = marked(data.toString());
console.log(str);
res.render('apidoc', { str });
}
});
});
};
var fs=require("fs");
var settings=require("../settings");
var glob = require("glob");
var system = require('../../base/system');
module.exports = function (app) {
app.get('/vue/comp/base',function(req,res){
var vuePath=settings.basepath+"/app/front/vues/base";
var baseComps=[];
var rs=glob.sync(vuePath+"/**/*.vue");
if(rs){
rs.forEach(function(r){
var comp="";
if(settings.env=="dev"){
delete require.cache[r];
comp=require(r).replace(/\n/g,"");
}else{
comp=require(r).replace(/\n/g,"");
}
baseComps.push(comp);
});
res.end(JSON.stringify(baseComps));
}
});
app.get('/vue/comp/:cname',function(req,res){
var componentName=req.params.cname;
var theme=req.headers["theme"];
var hostname=req.hostname;
buildComponent(componentName,theme,hostname).then(function(r){
res.end(escape(r.replace(/\n/g,"")));
// res.end(r);
});
});
};
......@@ -7,18 +7,22 @@ var ENVINPUT = {
REDIS_HOST: process.env.REDIS_HOST,
REDIS_PORT: process.env.REDIS_PORT,
REDIS_PWD: process.env.REDIS_PWD,
REDIS_DB: process.env.QUEUE_REDIS_DB,
DB_NAME: process.env.QUEUE_DB_NAME,
APP_ENV: process.env.APP_ENV ? process.env.APP_ENV : "test",//运行环境
CONSUMER_NAME: process.env.CONSUMER_NAME || "publicServiceAllocation.publicConsumer",//消费者名称
QUEUED_NAME: process.env.QUEUED_NAME || "SYTXPUBLIC-MSGQ",//队列名称,FAIL-失败队列(队列和失败队列一对存在进行部署)
DB_NAME: process.env.BRG_USER_CENTER_DB_NAME,
REDIS_DB: process.env.BRG_USER_CENTER_REDIS_DB,
APP_ENV: process.env.APP_ENV ? process.env.APP_ENV : "dev"
};
var settings = {
env: ENVINPUT.APP_ENV,
consumerName: ENVINPUT.CONSUMER_NAME,
queuedName: ENVINPUT.QUEUED_NAME,
usertimeout: 3600,//单位秒
basepath: path.normalize(path.join(__dirname, '../..')),
port: process.env.NODE_PORT || 4018,
port: process.env.NODE_PORT || 4012,
opLogUrl: function () {
if (this.env == "dev" || this.env == "test") {
return "http://192.168.1.128:4019/api/queueAction/producer/springBoard";
} else {
return "http://logs-sytxpublic-msgq-service/api/queueAction/producer/springBoard";
}
},
redis: function () {
if (this.env == "dev" || this.env == "test") {
var localsettings = require("./localsettings");
......@@ -46,12 +50,10 @@ var settings = {
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
max: 50,
idle: 30000,//断开连接后,连接实例在连接池保持的时间
acquire: 30000,//请求超时时间
evict: 30000,
handleDisconnects: true
acquire: 90000000,
idle: 1000000
},
timezone: '+08:00',
debug: false,
......@@ -64,5 +66,4 @@ var settings = {
}
}
};
settings.ENVINPUT = ENVINPUT;
module.exports = settings;
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="keywords" content="api文档">
<meta name="baidu-site-verification" content="lATAxZAm8y" />
<meta name="viewport" content="width=device-width, initial-scale=0.8, maximum-scale=0.8, user-scalable=1">
<link href="https://cdn.bootcss.com/github-markdown-css/2.8.0/github-markdown.min.css" rel="stylesheet">
</head>
<body>
<div style="width:100%;text-align: center;font-size: 20px;">
API文档
</div>
<div class="markdown-body" style="margin-left:40px;" id="doc-page">
<%- str%>
</div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<body>
<div style="width:100%;text-align: center;font-size: 20px;">
ok
</div>
</body>
</html>
\ No newline at end of file
## 调用接口方式
## 1. XBOSS平台中心
  1 [xboss接口](doc/api/platform/xboss.md)
<a name="menu" href="/doc">返回主目录</a>
1. [产品列表-根据产品大类获取](#getProductListByOneCode)
1. [产品列表-根据产品二类获取](#getProductListByTwoCode)
1. [产品详情](#getProductDetail)
## **<a name="getProductListByOneCode"> 产品列表-根据产品大类编码获取</a>**
[返回到目录](#menu)
##### URL
[/action/product/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:getProductList
``` javascript
{
"pathCode":"sbfu" //查询的路径:大类code
}
```
#### 返回结果 0为成功,否则为失败
```javascript
{
"status": 0,
"msg": "success",
"data": [
{
"uapp_id": 26,//平台id--显示不用
"path_code": "/sbfu/sbzc/",//产品路径编码--显示不用
"path_name": "/商标服务/商标注册/",//产品路径名称--显示不用
"item_code": "zzsbzc",//产品code
"item_name": "商标注册【自助申请】",//产品名称
"channel_item_code": "zzsbzc",//渠道产品code
"channel_item_name": "商标注册【自助申请】",//渠道产品名称
"pic_url": "http://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_qft_pi15755163570461.png",//产品的图片
"product_short_desc": "适合熟知商标注册流程的企业用户", //产品的介绍
"product_desc": "[\"自己检索商标,准备官方所需注册材料\",\"提交迅速,及时反馈\",\"全流程跟踪,掌握申请进度\"]", //产品的描述列表
"desc_url": null,//产品介绍图片地址
"icon_url": null,//产品的icon
"productType_id": 2,//产品类型id--显示用不到
"sort": 1,//排序
"pay_code": "zzsbzc-1", //支付价格code
"service_charge": 30,//服务费
"public_expense": 270,//官费
"price": 300,//价格
"price_type": "mj",//定价类型:mj:每件,mc:每次,mt:每天,my:每月,mn:每年,qj:区间
"price_type_name": "每件",//定价类型名称
"price_desc": "每件(10小项)",//定价描述
"min_qty": null,//区间最小值
"max_qty": null//区间最大值
}
],
"requestId": "c39ee8a924074904b1694dd3bf2d6c4b"
}
```
## **<a name="getProductListByTwoCode"> 产品列表-根据产品二类获取</a>**
[返回到目录](#menu)
##### URL
[/action/product/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:getProductList
``` javascript
{
"pathCode":"sbfu/sbzc" //查询的路径:大类code/二类code
}
```
#### 返回结果 0为成功,否则为失败
```javascript
{
"status": 0,
"msg": "success",
"data": [
{
"uapp_id": 26,//平台id--显示不用
"path_code": "/sbfu/sbzc/",//产品路径编码--显示不用
"path_name": "/商标服务/商标注册/",//产品路径名称--显示不用
"item_code": "zzsbzc",//产品code
"item_name": "商标注册【自助申请】",//产品名称
"channel_item_code": "zzsbzc",//渠道产品code
"channel_item_name": "商标注册【自助申请】",//渠道产品名称
"pic_url": "http://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_qft_pi15755163570461.png",//产品的图片
"product_short_desc": "适合熟知商标注册流程的企业用户", //产品的介绍
"product_desc": "[\"自己检索商标,准备官方所需注册材料\",\"提交迅速,及时反馈\",\"全流程跟踪,掌握申请进度\"]", //产品的描述列表
"desc_url": null,//产品介绍图片地址
"icon_url": null,//产品的icon
"productType_id": 2,//产品类型id--显示用不到
"sort": 1,//排序
"pay_code": "zzsbzc-1", //支付价格code
"service_charge": 30,//服务费
"public_expense": 270,//官费
"price": 300,//价格
"price_type": "mj",//定价类型:mj:每件,mc:每次,mt:每天,my:每月,mn:每年,qj:区间
"price_type_name": "每件",//定价类型名称
"price_desc": "每件(10小项)",//定价描述
"min_qty": null,//区间最小值
"max_qty": null//区间最大值
}
],
"requestId": "c39ee8a924074904b1694dd3bf2d6c4b"
}
```
## **<a name="getProductDetail"> 产品详情</a>**
[返回到目录](#menu)
##### URL
[/action/product/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:getProductDetail
``` javascript
{
"channelItemCode":"zzsbzc"
}
```
#### 返回结果 0为成功,否则为失败
```javascript
{
"status": 0,
"msg": "success",
"data": {
"id": 1,//产品Id
"uapp_id": 26,
"path_code": "/sbfu/sbzc/",
"path_name": "/商标服务/商标注册/",
"item_code": "zzsbzc",
"item_name": "商标注册【自助申请】",
"channel_item_code": "zzsbzc",
"channel_item_name": "商标注册【自助申请】",
"pic_url": "http://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_qft_pi15755163570461.png",
"product_short_desc": "适合熟知商标注册流程的企业用户", //产品的介绍
"product_desc": "[\"自己检索商标,准备官方所需注册材料\",\"提交迅速,及时反馈\",\"全流程跟踪,掌握申请进度\"]", //产品的描述列表
"desc_url": null,
"icon_url": null,
"productType_id": 2,
"price_list": [
{
"pay_code": "zzsbzc-1", //支付价格code
"price": 300,
"supply_price": 270,
"service_charge": 30,
"public_expense": 270,
"is_default": 1,//是否默认,1默认,0不是默认
"is_show": 1,//是否显示在页面进行下单(1是,0不是,0为下单时附加的购买项目)
"price_type": "mj",
"price_type_name": "每件",
"sort": 1,
"price_desc": "每件(10小项)",
"min_qty": null,
"max_qty": null
},
{
"pay_code": "zzsbzc-2", //支付价格code
"price": 30,
"supply_price": 30,
"service_charge": 30,
"public_expense": 30,
"is_default": 0,
"is_show": 0,
"price_type": "mx",
"price_type_name": "项",
"sort": 2,
"price_desc": "每个小项的价格",
"min_qty": null,
"max_qty": null
}
]
},
"requestId": "5913fc3ae97a402e93330c2d488f1f7e"
}
```
\ No newline at end of file
<a name="menu" href="/doc">返回主目录</a>
1. [短信验证码](#smsCode)
1. [密码登录](#pwdLogin)
1. [验证码登录](#userPinByLgoinVcode)
1. [用户注册](#userPinByRegister)
1. [按照手机号和验证码修改密码](#putUserPwdByMobile)
1. [获取用户登录信息](#getLoginInfo)
1. [退出](#logout)
1. [飞书登录](#feishuLogin)
## **<a name="smsCode"> 短信验证码</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:getVerifyCode
``` javascript
{
"mobile":"15010929366" // Y 手机号
}
```
#### 返回结果
```javascript
{
"status": 0, // 0为成功,否则失败
"msg": "success",
"data": null,
"requestId": "4f3ea2afee3542f88d6b938394af84d8"
}
```
## **<a name="pwdLogin"> 帐号密码登录</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`getVerifyCode
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:userPinByLgoin
``` javascript
{
"userName":"15010929366", // Y 用户名
"password":"123456" // Y 密码
}
```
#### 返回结果
``` javascript
{
"status": 0,// 0为成功,2010为账户或密码错误,2060为重复登录,否则失败
"msg": "success",
"data": {
"userpin": "230ecdf3333944ff834f56fba10a02aa" //用户登录后的凭证,增、删、改、查、涉及用户的需要传递此值在请求头中
},
"requestId": "1b12b0e9c190436da000386ddf693c8f"
}
```
## **<a name="userPinByLgoinVcode"> 验证码登录</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:userPinByLgoinVcode
``` javascript
{
"mobile":"15010929366", // Y 手机号
"vcode":"593555" // Y 验证码
}
```
#### 返回结果
``` javascript
{
"status": 0,// 0为成功,2030为验证码错误,2060为重复登录,否则失败
"msg": "success",
"data": {
"userpin": "230ecdf3333944ff834f56fba10a02aa" //用户登录后的凭证,增、删、改、查、涉及用户的需要传递此值在请求头中
},
"requestId": "1b12b0e9c190436da000386ddf693c8f"
}
```
## **<a name="userPinByRegister"> 用户注册</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:userPinByRegister
``` javascript
{
"mobile":"15010929366", // Y 手机号
"vcode":"593555", // Y 验证码
"password":"123456" // Y 密码
}
```
#### 返回结果
``` javascript
{
"status": 0,// 0为成功,2030为验证码错误,2000为已经存在此用户,注册失败,否则失败
"msg": "success",
"data": {
"userpin": "230ecdf3333944ff834f56fba10a02aa" //用户登录后的凭证,增、删、改、查、涉及用户的需要传递此值在请求头中
},
"requestId": "1b12b0e9c190436da000386ddf693c8f"
}
```
## **<a name="putUserPwdByMobile"> 按照手机号和验证码修改密码(修改后得重新登录)</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:putUserPwdByMobile
``` javascriptgetVerifyCode
{
"mobile":"15010929366", // Y 手机号
"vcode":"593555", // Y 验证码
"newPwd":"123456" // Y 新密码
}
```
#### 返回结果
``` javascript
{
"status": 0,// 0为成功,2030为验证码错误,否则失败
"msg": "success",
"data": null,
"requestId": "1b12b0e9c190436da000386ddf693c8f"
}
```
## **<a name="logout"> 退出</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:logout
``` javascript
{
"userpin":"15010929366" // Y 用户登录凭证key
}
```
#### 返回结果
``` javascript
{
"status": 0,// 0为成功,否则失败
"msg": "success",
"data": null,
"requestId": "1b12b0e9c190436da000386ddf693c8f"
}
```
## **<a name="getLoginInfo"> 获取用户登录信息</a>**
[返回到目录](#menu)
##### URL
[/web/auth/accessAuth/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:getLoginInfo
``` javascript
{
"userpin":"15010929366" // Y 用户登录凭证key
}
```
#### 返回结果
``` javascript
{
"status": 0,// 0为成功,否则失败
"msg": "success",
"data": {
"id": 9,
"uapp_id": 26,
"channel_userid": "15010929366",//渠道用户ID
"channel_username": "15010929366",//账户
"channel_nickname": "",
"open_id": null,
"head_url": null,
"mobile": "15010929366",//手机号
"org_name": "",
"org_path": "",
"email": "",
"is_admin": 0,//是否管理员
"is_super": 0,//是否超级管理员
"is_enabled": 1,
"userpin": "18c44186d54a45ea8777ef4c0a4252f6"//用户登录后的凭证key
},
"requestId": "ad31ced9ac7044f69f453185d9c1e241"
}
```
## **<a name="feishuLogin"> 飞书登录</a>**
[返回到目录](#menu)
##### URL
[http://feishu.qifu.gongsibao.com:4012/feishu/login?code={code}&state={state}&open_id={open_id}]
#### HTTP请求方式 `GET`
``` javascript
请求参数说明 :
code:用户飞书登录预授权码 必填
state:前端获取的token信息 必填
open_id:用户openid 非必填
```
#### 返回结果
``` javascript
{
"status":0,
"msg":"success",
"data":{
"userpin":"1508e7f73efd49cda8d2bc7d2552b09b"
}
}
```
<a name="menu" href="/doc">返回主目录</a>
1. [推送需求到服务商](#needSubmit)
1. [推送订单到服务商](#orderSubmit)
1. [关闭需求推送到服务商](#needClose)
1. [关闭订单推送到服务商](#orderClose)
1. [初始化产品表](#getH5PayUrl)
## **<a name="needSubmit"> 推送需求到服务商</a>**
[返回到目录](#menu)
##### URL:
/entService/consultation/springBoard
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 功能模块 actionType:needSubmit
#### 需求类型 consultType:1.公司注册咨询、2个体户注册参数、3增值服务
### 1.公司注册参数、2个体户注册参数
参数名 | 必须 | 字段类型 | 长度限制 | 说明
-|-|-|-|-
needNum | Y | string | 100 | 需求号
userId | Y | string | 100 | 用户id
servicerCode | Y | string | 100 | 服务商code
servicerName | Y | string | 100 | 服务商名称
regionId | Y | string | 100 | 地区id
regionName | Y | string | 100 | 地区名称
contactsName | Y | string | 100 | 用户名称
contactsMoblie | Y | string | 100 | 用户电话
consultType | Y | int | 100 | 需求类型
### 3.增值服务
参数名 | 必须 | 字段类型 | 长度限制 | 说明
-|-|-|-|-
needNum | Y | string | 100 | 需求号
userId | Y | string | 100 | 用户id
servicerCode | Y | string | 100 | 服务商code
servicerName | Y | string | 100 | 服务商名称
regionId | Y | string | 100 | 地区id
regionName | Y | string | 100 | 地区名称
contactsName | Y | string | 100 | 用户名称
contactsMoblie | Y | string | 100 | 用户电话
consultType | Y | int | 100 | 需求类型
``` javascript
{
"actionType": "needSubmit",
"actionBody": {
"needNum":"n0001",
"userId":"tx000111",
"servicerCode":"gsb",
"servicerName":"公司宝",
"regionId":"1",
"regionName":"北京",
"contactsName":"张三",
"contactsMoblie":"17610163853",
"consultType":1
}
}
```
#### 返回结果
```javascript
{
"status":1, //1代表成功,否则失败
"message":"",
"data":"",
"requestId":""
}
```
## **<a name="orderSubmit"> 推送订单到服务商</a>**
[返回到目录](#menu)
##### URL
/entService/order/springBoard
#### 参数格式 `JSON`人
#### HTTP请求方式 `POST`
#### 功能模块 actionType:orderSubmit
#### 产品类型 productType:1.公司注册咨询、2个体户注册参数、3增值服务
### 1.公司注册参数、2个体户注册参数
参数名 | 必须 | 字段类型 | 长度限制 | 说明
-|-|-|-|-
orderNum | Y | string | 100 | 订单号
userId | Y | string | 100 | 用户id
servicerCode | Y | string | 100 | 服务商code
servicerName | Y | string | 100 | 服务商名称
regionId | Y | string | 100 | 地区id
regionName | Y | string | 100 | 地区名称
contactsName | Y | string | 100 | 用户名称
contactsMoblie | Y | string | 100 | 用户电话
productType | Y | int | 100 | 产品类型
### 3.增值服务
参数名 | 必须 | 字段类型 | 长度限制 | 说明
-|-|-|-|-
orderNum | Y | string | 100 | 订单号
userId | Y | string | 100 | 用户id
servicerCode | Y | string | 100 | 服务商code
servicerName | Y | string | 100 | 服务商名称
regionId | Y | string | 100 | 地区id
regionName | Y | string | 100 | 地区名称
contactsName | Y | string | 100 | 用户名称
contactsMoblie | Y | string | 100 | 用户电话
productType | Y | int | 100 | 产品类型
order_snapshot | Y | string | 500 | 订单快照(json转字符串)
``` javascript
{
"actionType": "orderSubmit",
"actionBody": {
"orderNum":"",
"userId":"",
"servicerCode":"",
"servicerName":"",
"regionId":"",
"regionName":"",
"contactsName":"",
"contactsMoblie":"",
"productType":""
"order_snapshot":"{
}"
}
}
```
#### 返回结果
```javascript
{
"status":1, //1代表成功,否则失败
"message":"",
"data":"",
"requestId":""
}
```
## **<a name="needClose"> 关闭需求推送到服务商</a>**
[返回到目录](#menu)
##### URL
/entService/consultation/springBoard
#### 参数格式 `JSON`人
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:needClose
参数名 | 必须 | 字段类型 | 长度限制 | 说明
-|-|-|-|-
needNum | Y | string | 100 | 需求号
desc | Y | string | 100 | 备注信息
``` javascript
{
"needNum":"",
"desc":"" //描述
}
```
#### 返回结果
```javascript
{
"status":1, //1代表成功,否则失败
"msg":"",
"data":"",
"requestId":""
}
```
## **<a name="orderClose"> 关闭订单推送到服务商</a>**
[返回到目录](#menu)
##### URL
/entService/order/springBoard
#### 参数格式 `JSON`人
#### HTTP请求方式 `POST`
#### 渠道执行的类型 actionType:orderClose
参数名 | 必须 | 字段类型 | 长度限制 | 说明
-|-|-|-|-
orderNum | Y | string | 100 | 订单号
desc | Y | string | 100 | 备注信息
``` javascript
{
"orderNum":"",
"desc":"" //描述
}
```
#### 返回结果
```javascript
{
"status":1, //1代表成功,否则失败
"msg":"",
"data":"",
"requestId":""
}
```
<a name="menu" href="/doc">返回主目录</a>
1. [服务商提交方案](#submitSolution)
1. [服务商关闭需求](#closeNeed)
1. [服务商提交交付信息](#submitDeliveryInfo)
1. [服务商修改订单交付状态](#updateOrderStatus)
## **<a name="submitSolution"> 服务商提交方案</a>**
[返回到目录](#menu)
##### URL
[/api/receive/entService/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 功能模块 actionType:submitSolution
#### 参数说明
| 参数名 | 必填 | 类型 | 描述 |
| ---- | ---- | ---- | ---- |
| needNum | 是 | string | 需求编码 |
| solutionNum | 否 | string | 方案编码,修改方案时传入,不传默认新增 |
| solutionContent | 是 | json | 方案内容 |
#### 参数示例
``` javascript
{
"actionType": "submitSolution",
"actionBody": {
"needNum": "N2020052978888",
"solutionNum":"",
"solutionContent": {}
}
}
```
#### 返回结果
```javascript
{
"status":1,// 1为成功,否则失败
"msg":"success",
"data":"NS_202005291451Iy2Gk",//方案号,新增时返回
"requestId":"e52e42676d86423a91623f7474a20963"
}
```
## **<a name="closeNeed"> 服务商关闭需求</a>**
[返回到目录](#menu)
##### URL
[/api/receive/entService/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 功能模块 actionType:closeNeed
#### 参数说明
| 参数名 | 必填 | 类型 | 描述 |
| ---- | ---- | ---- | ---- |
| needNum | 是 | string | 需求编码 |
| note | 是 | string | 关闭原因 |
#### 参数示例
``` javascript
{
"actionType": "closeNeed",
"actionBody": {
"needNum": "N2020052978888",
"note": "xxx"
}
}
```
#### 返回结果
```javascript
{
"status": 1,// 1为成功,否则失败
"msg": "success",
"data":null,
"requestId": "a277fb799d9f4dda9053fb8830f9d252"
}
```
## **<a name="submitDeliveryInfo"> 服务商提交交付信息</a>**
[返回到目录](#menu)
##### URL
[/api/receive/entService/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 功能模块 actionType:submitDeliveryInfo
#### 参数说明
| 参数名 | 必填 | 类型 | 描述 |
| ---- | ---- | ---- | ---- |
| orderNum | 是 | string | 订单编码 |
| deliveryContent | 是 | json | 交付信息 |
#### 参数示例
``` javascript
{
"actionType": "submitDeliveryInfo",
"actionBody": {
"orderNum": "O20201231223384682",
"deliveryContent": {}
}
}
```
#### 返回结果
```javascript
{
"status": 1,// 1为成功,否则失败
"msg": "success",
"data":null,
"requestId": "a277fb799d9f4dda9053fb8830f9d252"
}
```
## **<a name="updateOrderStatus"> 服务商修改订单交付状态</a>**
[返回到目录](#menu)
##### URL
[/api/receive/entService/springBoard]
#### 参数格式 `JSON`
#### HTTP请求方式 `POST`
#### 功能模块 actionType:updateOrderStatus
#### 参数说明
| 参数名 | 必填 | 类型 | 描述 |
| ---- | ---- | ---- | ---- |
| orderNum | 是 | string | 订单编码 |
| orderStatus | 是 | int | 订单状态码 1: 已接单,10:收集工商注册材料,11:工商审核环节,12:刻章环节,13:证件邮寄环节,14:您已签收|
#### 参数示例
``` javascript
{
"actionType": "updateOrderStatus",
"actionBody": {
"orderNum": "O20201231223384682",
"orderStatus": 10
}
}
```
#### 返回结果
```javascript
{
"status": 1,// 1为成功,否则失败
"msg": "success",
"data":null,
"requestId": "a277fb799d9f4dda9053fb8830f9d252"
}
```
var http = require('http');
var express = require('express');
var app = express();
var setttings=require("./app/config/settings");
var environment = require('./app/config/environment');
// all environments
environment(app);//初始化环境
// 错误处理中间件应当在路由加载之后才能加载
var server = http.createServer(app);
server.listen(setttings.port, function(){
console.log('Express server listening on port ' + app.get('port'));
});
......@@ -44,15 +44,13 @@
"nodemailer": "^6.3.0",
"pinyin": "^2.9.0",
"puppeteer": "^1.20.0",
"qcloud-cos-sts": "^3.0.2",
"qr-image": "^3.2.0",
"sequelize": "^4.37.8",
"sequelize-cli": "^4.1.1",
"serve-favicon": "^2.4.5",
"sha1": "^1.1.1",
"sha256": "^0.2.0",
"socket.io": "^2.1.1",
"uuid": "^3.2.1"
"uuid": "^3.4.0"
},
"devDependencies": {
"element-theme": "^2.0.1",
......
++ "b/brg/\346\217\220\347\244\272\347\274\226\347\240\201\344\275\277\347\224\250"
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