Commit edc6e4d2 by 庄冰

删除

parent f6fe988c
node_modules/
app/config/localsettings.js
icp_build.sh
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/gsb-marketplat.iml" filepath="$PROJECT_DIR$/.idea/gsb-marketplat.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/main.js"
}
]
}
\ No newline at end of file
const system = require("../system");
const uuidv4 = require('uuid/v4');
const settings = require("../../config/settings");
const sha256 = require('sha256');
class APIBase {
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
this.logClient = system.getObject("util.logClient");
this.queryAction = ["getTemplateAndLinkInfo"];
}
async setContextParams(pobj, qobj, req) {
let custtags = req.headers["x-consumetag"] ? req.headers["x-consumetag"].split("|") : null;
//当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值
req.xctx = {
appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色
companyid: custtags ? custtags[0].split("_")[1] : null,
password: custtags ? custtags[1].split("_")[1] : null,
username: req.headers["x-consumer-username"],
credid: req.headers["x-credential-identifier"],
companykey: req.headers["x-company-key"],//专用于自由用户注册,自由用户用于一定属于某个存在的公司
}
if (!req.xctx.appkey) {
return [-200, "请求头缺少应用x-app-key"]
} else {
// let app = await this.cacheManager["AppCache"].cache(req.xctx.appkey);
// req.xctx.appid = app.id;
// pobj.app_id = app.id;//传递参数对象里注入app_id
}
//平台注册时,companyid,companykey都为空
//自由注册时,companykey不能为空
// if(!req.xctx.companyid && !req.xctx.companykey){
// return [-200,"请求头缺少应用x-app-key"]
// }
if (req.xctx.companyid) {//在请求传递数据对象注入公司id
pobj.company_id = req.xctx.companyid;
}
}
async doexec(gname, methodname, pobj, query, req) {
try {
var shaStr = await sha256(JSON.stringify(pobj));
let xarg = await this.setContextParams(pobj, query, req);
if (xarg && xarg[0] < 0) {
return system.getResultFail(...xarg);
}
var rtn = await this[methodname](pobj, query, req);
this.logClient.log(pobj, req, rtn);
return rtn;
} catch (e) {
this.logClient.log(pobj, req, null, e.stack);
console.log(e.stack, "api调用异常--error...................");
var rtnerror = system.getResultFail(-200, "出现异常,请联系管理员");
return rtnerror;
}
}
}
module.exports = APIBase;
const system = require("../system");
const uuidv4 = require('uuid/v4');
class DocBase {
constructor() {
this.apiDoc = {
group: "逻辑分组",
groupDesc: "",
name: "",
desc: "请对当前类进行描述",
exam: "概要示例",
methods: []
};
this.initClassDoc();
}
initClassDoc() {
this.descClass();
this.descMethods();
}
descClass() {
var classDesc = this.classDesc();
this.apiDoc.group = classDesc.groupName;
this.apiDoc.groupDesc = this.examDescHtml(classDesc.groupDesc);
this.apiDoc.name = classDesc.name;
this.apiDoc.desc = this.examDescHtml(classDesc.desc);
this.apiDoc.exam = this.examHtml();
}
examDescHtml(desc) {
// var tmpDesc = desc.replace(/\\/g, "<br/>");
return desc;
}
examHtml() {
var exam = this.exam();
exam = exam.replace(/\\/g, "<br/>");
return exam;
}
exam() {
throw new Error("请在子类中定义类操作示例");
}
classDesc() {
throw new Error(`
请重写classDesc对当前的类进行描述,返回如下数据结构
{
groupName:"auth",
groupDesc:"认证相关的包"
desc:"关于认证的类",
exam:"",
}
`);
}
descMethods() {
var methoddescs = this.methodDescs();
for (var methoddesc of methoddescs) {
for (var paramdesc of methoddesc.paramdescs) {
this.descMethod(methoddesc.methodDesc, methoddesc.methodName
, paramdesc.paramDesc, paramdesc.paramName, paramdesc.paramType,
paramdesc.defaultValue, methoddesc.rtnTypeDesc, methoddesc.rtnType);
}
}
}
methodDescs() {
throw new Error(`
请重写methodDescs对当前的类的所有方法进行描述,返回如下数据结构
[
{
methodDesc:"生成访问token",
methodName:"getAccessKey",
paramdescs:[
{
paramDesc:"访问appkey",
paramName:"appkey",
paramType:"string",
defaultValue:"x",
},
{
paramDesc:"访问secret",
paramName:"secret",
paramType:"string",
defaultValue:null,
}
],
rtnTypeDesc:"xxxx",
rtnType:"xxx"
}
]
`);
}
descMethod(methodDesc, methodName, paramDesc, paramName, paramType, defaultValue, rtnTypeDesc, rtnType) {
var mobj = this.apiDoc.methods.filter((m) => {
if (m.name == methodName) {
return true;
} else {
return false;
}
})[0];
var param = {
pname: paramName,
ptype: paramType,
pdesc: paramDesc,
pdefaultValue: defaultValue,
};
if (mobj != null) {
mobj.params.push(param);
} else {
this.apiDoc.methods.push(
{
methodDesc: methodDesc ? methodDesc : "",
name: methodName,
params: [param],
rtnTypeDesc: rtnTypeDesc,
rtnType: rtnType
}
);
}
}
}
module.exports = DocBase;
const APIBase = require("../../api.base");
const system = require("../../../system");
/**
* 媒体聚合页项目-移动端调用相关接口
*/
class Mediaaggregation extends APIBase {
constructor() {
super();
this.needinfoSve = system.getObject("service.media.needinfoSve");
this.mediaaggregationSve = system.getObject("service.mediaaggregation.mediaaggregationSve");
this.launchchannelSve = system.getObject("service.configmag.launchchannelSve");
}
/**
* 接口跳转-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;
var self = this;
pobj.xctx = req.xctx;
pobj.clientIp = req.clientIp;
if(pobj.company_id){
pobj["actionBody"]["company_id"] = pobj.company_id ||"10";
}
switch (action_type) {
case "test"://测试
opResult = system.getResultSuccess("测试接口");
break;
case "submitNeed"://提交需求/线索
opResult = this.needinfoSve.submitNeed(pobj);
break;
case "addbrowsingrecord"://添加页面访问记录
opResult = this.needinfoSve.addbrowsingrecord(pobj);
break;
case "getSourceChannelInfo"://获取来源渠道信息
opResult = this.launchchannelSve.getSourceChannelInfo(pobj);
break;
case "getAllProductType"://获取所有渠道信息
opResult = this.needinfoSve.getAllProductType(pobj);
break;
case "productList"://服务列表
opResult = await this.mediaaggregationSve.productList(pobj);
break;
case "rotationChartList"://首页轮播图
opResult = await this.mediaaggregationSve.rotationChartList(pobj);
break;
case "tablePicList"://列表头图
opResult = await this.mediaaggregationSve.tablePicList(pobj);
break;
case "needProductList"://留资表单产品
opResult = await this.mediaaggregationSve.needProductList(pobj);
break;
case "popularRecommendationList"://热门推荐列表
opResult = await this.mediaaggregationSve.popularRecommendationList(pobj);
break;
case "productTypeFirst"://产品分类列表
opResult = await this.mediaaggregationSve.productTypeFirst(pobj);
break;
case "productTypeSecend"://产品分类列表
opResult = await this.mediaaggregationSve.productTypeSecend(pobj);
break;
case "productDetail"://产品详情页
opResult = await this.mediaaggregationSve.productDetail(pobj);
break;
case "bottomMenuConfig"://吸底菜单
opResult = await this.mediaaggregationSve.bottomMenuConfig(pobj);
break;
case "cycleProduct"://周期产品
opResult = await this.mediaaggregationSve.cycleProduct(pobj);
break;
case "secondLevelNeedConfig"://二级留资页
opResult = await this.mediaaggregationSve.secondLevelNeedConfig(pobj);
break;
case "clueMaintenance"://二类产品资质选项(选取数据线索的数据)
opResult = await this.mediaaggregationSve.clueMaintenance(pobj);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
}
module.exports = Mediaaggregation;
const APIBase = require("../../api.base");
const system = require("../../../system");
const settings = require("../../../../config/settings");
/**
* 用户端调用订单相关接口
*/
class Template extends APIBase {
constructor() {
super();
this.templateinfoSve = system.getObject("service.template.templateinfoSve");
this.templatelinkSve = system.getObject("service.template.templatelinkSve");
this.formsubmitrecordSve= system.getObject("service.configmag.formsubmitrecordSve");
this.forminfoSve= system.getObject("service.configmag.forminfoSve");
this.redisClient = system.getObject("util.redisClient");
this.formCache={};
}
/**
* 接口跳转-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;
var self = this;
pobj.clientIp = req.clientIp;
pobj.xctx = req.xctx;
switch (action_type) {
// case "editTemplateContent"://修改模板内容
// opResult = await this.templateinfoSve.editTemplateContent(pobj);
// break;
// case "findOneByCode"://模板查询
// opResult = await this.templateinfoSve.getTemplateInfoByCode(pobj);
// break;
case "getTemplateAndLinkInfo"://根据链接参数获取模板链接信息
console.log("getTemplateAndLinkInfo+++++++++++++++++++++++++++");
console.log(JSON.stringify(pobj));
opResult = await this.templatelinkSve.getTemplateAndLinkInfo2(pobj);
break;
case "submitFormRecord"://提交表单记录
opResult = await this.formsubmitrecordSve.submitFormRecord(pobj);
break;
// case "pushFormInfo2Fq"://推送需求表单信息至蜂擎
// opResult = await this.formsubmitrecordSve.pushFormInfo2Fq();
// break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
async getFormInfoById(pobj, qobj, req){
var shaStr = "forminfo_"+pobj.id;
var rtn = null;
console.log(this.formCache,"+++++++++++++getFormInfoById++++++++++++++++++++++");
if(this.formCache[shaStr]){
rtn = this.formCache[shaStr];
}else{
rtn = await this.redisClient.get(shaStr); // 先试图从redis读取数据
if(rtn){
this.formCache[shaStr] = rtn;
}
}
//---- 从redis中读取到数据
if (rtn) {
var rtnObj = JSON.parse(rtn);
return system.getResult(rtnObj);
} else {
let result = await this.forminfoSve.findOne({id:pobj.id},[]);
// 将数据保存到redis中
await this.redisClient.set(shaStr, JSON.stringify(result));
this.formCache[shaStr] = JSON.stringify(result);
return system.getResult(result);
}
}
//删除表单缓存
async delTemplateFormCache(key){
if(key && this.formCache[key]){
delete this.formCache[key];
}
}
}
module.exports = Template;
const APIBase = require("../../api.base");
const system = require("../../../system");
const settings = require("../../../../config/settings");
var db = system.getObject("db.common.connection").getCon();
/**
* 用户端调用订单相关接口
*/
class Templateconfig extends APIBase {
constructor() {
super();
this.imginfoSve = system.getObject("service.configmag.imginfoSve");
this.forminfoSve = system.getObject("service.configmag.forminfoSve")
this.templateinfoSve = system.getObject("service.template.templateinfoSve");
this.templatelinkSve = system.getObject("service.template.templatelinkSve");
}
/**
* 接口跳转-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;
var self = this;
pobj.clientIp = req.clientIp;
pobj.xctx = req.xctx;
switch (action_type) {
case "test"://测试
opResult = system.getResultSuccess("测试接口");
break;
case "getImgList": // 查询图片
pobj.actionBody["company_id"] = pobj.company_id;
opResult = await this.imginfoSve.getImgList(pobj.actionBody);
break;
case "createImginfo": // 添加图片
opResult = await this.imginfoSve.createImginfo(pobj.actionBody);
break;
// case "getTemplateList": // 获取模板列表
// opResult = await this.templateinfoSve.getTemplateList(pobj.actionBody);
// // opResult = await this.templateinfoSve.findByCompanyId(pobj.actionBody);
// break;
case "editTemplate": // 编辑模板信息
opResult = await this.templateinfoSve.editTemplate(pobj);
break;
case "getFormList": // 获取表单列表
var actionBody = pobj.actionBody || {};
actionBody["company_id"] = pobj.company_id;
opResult = await this.forminfoSve.getFormList(pobj.actionBody);
break;
case "getTemplateAndLinkInfo": // 根据链接参数获取模板链接信息
opResult = await this.templatelinkSve.getTemplateAndLinkInfo2(pobj);
break;
case "copyFormInfo": // 复制表单
opResult = await this.forminfoSve.copyFormInfo(pobj.actionBody);
break;
case "deleteFormInfo": // 删除表单
opResult = await this.forminfoSve.deleteFormInfo(pobj.actionBody);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
break;
}
return opResult;
}
}
module.exports = Templateconfig;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class AccessAuthAPI extends APIBase {
constructor() {
super();
this.appS = system.getObject("service.common.appSve");
this.apitradeSvr = system.getObject("service.common.apitradeSve");
this.authUtils = system.getObject("util.businessManager.authUtils");
this.userSve = system.getObject("service.auth.userSve");
}
//不从平台应用列表入口登录时
//先要调用平台登录接口
//返回token,利用这个token再去登录某个具体APP
//会话存储具体APP的用户信息
//每个前端应用打开时,先检查是否存在token
//如果存在,就去访问获取用户信息,---调用本接口--即刻
//进入或登录某个具体应用
//前提是已经具备了统一管理的账号,并且已经在统一管理账号登录,客户端具备了token
//进入某个具体应用时,需要指定 x-appkey请求头
//
async loginToApp(p,q,req){
let appkey=req.xctx.appkey;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
{
methodDesc: "生成访问token,访问地址:http://......../api/auth/accessAuth/getAccessKey,访问token需要放置到后续API方法调用的请求头中",
methodName: "getAccessKey",
paramdescs: [
{
paramDesc: "访问appkey",
paramName: "appkey",
paramType: "string",
defaultValue: "",
},
{
paramDesc: "访问secret",
paramName: "secret",
paramType: "string",
defaultValue: "",
}
],
rtnTypeDesc: "返回JSON对象字符串",
rtnType: "json object {accessKey: xxxxxx, app: {xxx:xxx}},注意app,是当前app信息,详细见后面示例"
},
];
}
exam() {
return ``
}
}
module.exports = AccessAuthAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class RoleAuthAPI extends APIBase {
constructor() {
super();
this.authS=system.getObject("service.auth.authSve");
}
async findAuthsByRole(p,q,req){
var tmpRoles=p.roles;
var appid=p.appid;
var comid=p.companyid;
var auths=await this.authS.findAuthsByRole(tmpRoles,appid,comid);
return system.getResult(auths);
}
exam(){
return `
xxxxxxxxx
yyyyyyyyy
zzzzzzzzz
ooooooo
`;
}
classDesc() {
return {
groupName: "auth",
groupDesc: "角色授权相关的API",
name: "RoleAuthAPI",
desc: "角色授权相关的API",
exam: "",
};
}
methodDescs() {
return [
{
methodDesc: "按照角色获取权限,访问地址:/api/auth/roleAuth/findAuthsByRole",
methodName: "findAuthsByRole",
paramdescs: [
{
paramDesc: "应用的ID",
paramName: "appid",
paramType: "int",
defaultValue: "x",
},
{
paramDesc: "角色列表",
paramName: "roles",
paramType: "array",
defaultValue: null,
}
],
rtnTypeDesc: "逗号分隔的",
rtnType: "string"
}
];
}
}
module.exports = RoleAuthAPI;
\ No newline at end of file
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
class AppAPI extends APIBase {
constructor() {
super();
this.appS = system.getObject("service.common.appSve");
}
async create(pobj,q,req){
// console.log("oooooooooooooooooooooooooooooooooooooooooooooooo")
// console.log(req.xctx)
let rtn=this.appS.create(pobj,q,req);
return system.getResult(rtn);
}
async del(pobj,q,req){
let rtn=this.appS.delete(pobj,q,req);
return system.getResult(rtn);
}
classDesc() {
return {
groupName: "auth",
groupDesc: "认证相关的包",
name: "AccessAuthAPI",
desc: "关于认证的类",
exam: `
post http://p.apps.com/api/auth/accessAuth/getAccessKey
{
appKey:xxxxx,
secret:yyyyyy
}
`,
};
}
methodDescs() {
return [
];
}
exam() {
return ``
}
}
module.exports = AppAPI;
var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class OSSAPI extends APIBase{
constructor(){
super()
}
async getOssConfig(){
var policyText = {
"expiration":"2119-12-31T16:00:00.000Z",
"conditions":[
["content-length-range",0,1048576000],
["starts-with","$key","zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64
var data={
OSSAccessKeyId:accessKeyId,
policy:policyBase64,
Signature:signature,
Bucket:'gsb-zc',
success_action_status:201,
url:url
};
return system.getResult(data);
};
async upfile(srckey,dest){
var oss=System.getObject("util.ossClient");
var result=await oss.upfile(srckey,"/tmp/"+dest);
return result;
};
async downfile(srckey){
var oss=System.getObject("util.ossClient");
var downfile=await oss.downfile(srckey).then(function(){
downfile="/tmp/"+srckey;
return downfile;
});
return downfile;
};
}
module.exports=OSSAPI;
const system = require("../system");
const settings = require("../../config/settings");
const uuidv4 = require('uuid/v4');
class CtlBase {
constructor(gname, sname) {
this.serviceName = sname;
this.service = system.getObject("service." + gname + "." + sname);
this.cacheManager = system.getObject("db.common.cacheManager");
this.logClient = system.getObject("util.logClient");
}
static getServiceName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Ctl")).toLowerCase() + "Sve";
}
async update(pobj, qobj, req) {
const up = await this.service.update(pobj);
return system.getResult(up);
}
async create(pobj, qobj, req) {
const up = await this.service.create(pobj);
return system.getResult(up);
}
async delete(pobj, qobj, req) {
const up = await this.service.delete(pobj);
return system.getResult(up);
}
async bulkDelete(ids) {
var en = await this.service.bulkDelete(ids);
return system.getResult(en);
}
async findAndCountAll(pobj, qobj, req) {
//设置查询条件
const rs = await this.service.findAndCountAll(pobj);
return system.getResult(rs);
}
async refQuery(pobj, qobj, req) {
pobj.refwhere.app_id = pobj.app_id;
pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj);
return rtn
}
async setContextParams(pobj, qobj, req) {
let custtags = req.headers["x-consumetag"] ? req.headers["x-consumetag"].split("|") : null;
let lastindex = custtags ? custtags.length - 1 : 0;
//当自由用户注册时,需要根据前端传来的companykey,查询出公司,给companyid赋值
req.xctx = {
appkey: req.headers["xappkey"],//用于系统管理区分应用,比如角色
fromappkey: req.headers["xfromappkey"],//来源APP,如果没有来源与appkey相同
companyid: custtags ? custtags[0].split("_")[1] : null,
fromcompanykey: req.headers["xfromcompanykey"],//专用于自由用户注册,自由用户用于一定属于某个存在的公司
password: custtags ? custtags[lastindex].split("_")[1] : null,
username: req.headers["x-consumer-username"],
userid: req.headers["x-consumer-custom-id"],
credid: req.headers["x-credential-identifier"],
regrole: req.headers["xregrole"],
bizpath: req.headers["xbizpath"],
opath: req.headers['xopath'],
ptags: req.headers['xptags'],
codename: req.headers["xcodename"],
codetitle: req.headers["xcodetitle"] ? decodeURI(req.headers["xcodetitle"]) : '',
}
if (req.xctx.ptags && req.xctx.ptags != "") {
pobj.opath = req.xctx.ptags
} else {
pobj.opath = req.xctx.opath
}
if (!req.xctx.appkey) {
return [-200, "请求头缺少应用x-app-key"]
} else {
// let app=await this.cacheManager["AppCache"].cache(req.xctx.fromappkey);
// req.xctx.appid=app.id;
// if(!pobj.app_id){
// pobj.app_id=app.id;//传递参数对象里注入app_id
// }
}
//平台注册时,companyid,companykey都为空
//自由注册时,companykey不能为空
// if(!req.xctx.companyid && !req.xctx.companykey){
// return [-200,"请求头缺少应用x-app-key"]
// }
if (!req.xctx.companyid && req.xctx.fromcompanykey && req.xctx.fromcompanykey != "null" && req.xctx.fromcompanykey != "undefined") {
let comptmp = await this.cacheManager["CompanyCache"].cache(req.xctx.fromcompanykey);
req.xctx.companyid = comptmp.id;
}
if (req.xctx.companyid) {//在请求传递数据对象注入公司id
pobj.company_id = req.xctx.companyid;
}
if (req.xctx.userid) {//在请求传递数据对象注入公司id
pobj.userid = req.xctx.userid;
}
if (req.xctx.username) {//在请求传递数据对象注入公司名称
pobj.username = req.xctx.username;
}
pobj.bizpath = req.xctx.bizpath;
}
async doexec(methodname, pobj, query, req) {
try {
let xarg = await this.setContextParams(pobj, query, req);
if (xarg && xarg[0] < 0) {
return system.getResultFail(...xarg);
}
//从请求头里面取appkey_consumename
// var consumeName=req.headers[""]
// var appkey=
// if( this.session["appkey_consumename"]) {
// }else{
// //从头里取,从redis中取出缓存对象赋值到控制基类的session属性
// //appkey_consumename
// this.session={};
// }
//req.session=redis缓存的上下文对象
var rtn = await this[methodname](pobj, query, req);
this.logClient.log(pobj, req, rtn)
return rtn;
} catch (e) {
this.logClient.log(pobj, req, null, e.stack);
console.log(e.stack, "出现异常,请联系管理员.......");
return system.getResultFail(-200, "出现异常,请联系管理员");
}
}
}
module.exports = CtlBase;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class AppCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(AppCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async findAllApps(p, q, req) {
var rtns = await this.service.findAllApps(p.userid);
return system.getResult(rtns);
}
async getApp(p,q,req) {
let app= await this.cacheManager["AppCache"].cache(p.appkey, null);
return system.getResult({funcJson:JSON.parse(app.functionJSON)});
}
async translateToRouter(funarray,results,parent){
funarray.forEach(item=>{
let result={}
result.path=item.code
result.name=item.code
result.meta={
hideInMenu: false,
hideInBread:false,
notCache: true,
title:item.title,
icon:'replaceIconName'
}
result.component="replaceRightPath"
if(parent){
parent.children.push(result)
}else{
results.push(result)
}
if(item.children && item.children.length>0){
result.children=[]
this.translateToRouter(item.children,results,result)
}
})
}
async buildFrontRouter(p,q,req){
let appkey=p.appkey
let app= await this.cacheManager["AppCache"].cache(appkey, null);
let funobj=JSON.parse(app.functionJSON)
let results=[]
await this.translateToRouter(funobj,results,null)
let rtns=await this.service.upFrontRoute(results,app.id)
await this.cacheManager["AppCache"].invalidate(appkey, null);
return system.getResult({url:rtns.url})
}
async getFuncs(p,q,req){
let appkey=p.appkey
let app= await this.cacheManager["AppCache"].cache(appkey, null);
return system.getResult({funcJson:JSON.parse(app.functionJSON)})
//return system.getResult({funcJson:[]})
}
async saveFuncTree(p,q,req){
let rtn=await this.service.saveFuncTree(p)
return system.getResult(rtn)
}
async create(pobj, queryobj, req) {
pobj.creator_id = pobj.userid;//设置创建者
return super.create(pobj, queryobj, req)
}
async update(pobj, queryobj, req) {
return super.update(pobj, queryobj, req);
}
async initNewInstance(pobj, queryobj, req) {
var rtn = {};
rtn.appkey = this.getUUID();
rtn.secret = this.getUUID();
return system.getResult(rtn);
}
async resetPass(pobj, queryobj, req) {
pobj.password = await super.encryptPasswd(settings.defaultpwd);
var rtn = this.service.resetPass(pobj);
return system.getResult(rtn);
}
async createAdminUser(pobj, queryobj, req) {
pobj.password = settings.defaultpwd;
var rtn = this.service.createAdminUser(pobj);
return system.getResult(rtn);
}
async create(pobj, queryobj, req) {
//设置创建者,需要同时创建app管理员、默认密码、电话
pobj.creator_id = pobj.userid;
// pobj.password=super.encryptPasswd(settings.defaultpwd);
//构造默认的应用相关的URL
pobj.authUrl = settings.protocalPrefix + pobj.domainName + "/auth";
pobj.docUrl = settings.protocalPrefix + pobj.domainName + "/web/common/metaCtl/getApiDoc";
pobj.uiconfigUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/config/fetchAppConfig";
pobj.opCacheUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/opCacheData";
pobj.notifyCacheCountUrl = settings.protocalPrefix + pobj.domainName + "/api/meta/opCache/recvNotificationForCacheCount";
var app = await super.create(pobj, queryobj, req);
return system.getResult(app);
}
async fetchApiCallData(pobj, queryobj, req) {
var curappkey = pobj.curappkey;
//检索出作为访问时的app呼出调用数据
var rtn = await this.service.fetchApiCallData(curappkey);
return system.getResultSuccess(rtn);
}
//接受缓存计数通知接口
async recvNotificationForCacheCount(p, q, req) {
return this.service.recvNotificationForCacheCount(p);
}
}
module.exports = AppCtl;
var p={"appkey":"08cb8300-ef1e-4e35-ba49-3de36ba497d2"}
let acl=new AppCtl()
acl.buildFrontRouter(p).then(res=>{
console.log(res.data)
})
\ No newline at end of file
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
class CachSearchesCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(CachSearchesCtl));
}
async initNewInstance(queryobj, qobj) {
return system.getResultSuccess({});
}
async findAndCountAll(pobj, gobj, req) {
pobj.opCacheUrl = req.session.app.opCacheUrl;
pobj.appid = req.appid;
return await this.service.findAndCountAllCache(pobj);
}
async delCache(queryobj, qobj, req) {
var param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param);
}
async clearAllCache(queryobj, qobj, req) {
var param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param);
}
}
module.exports = CachSearchesCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class MetaCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(MetaCtl));
}
}
module.exports = MetaCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require("moment");
class OplogCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(OplogCtl));
//this.appS=system.getObject("service.appSve");
}
async initNewInstance(qobj) {
var u = uuidv4();
var aid = u.replace(/\-/g, "");
var rd = { name: "", appid: aid }
return system.getResult(rd);
}
async debug(obj) {
obj.logLevel = "debug";
return this.create(obj);
}
async info(obj) {
obj.logLevel = "info";
return this.create(obj);
}
async warn(obj) {
obj.logLevel = "warn";
return this.create(obj);
}
async error(obj) {
obj.logLevel = "error";
return this.create(obj);
}
async fatal(obj) {
obj.logLevel = "fatal";
return this.create(obj);
}
/*
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
prefix = (prefix || "");
if (prefix) {
prefix = prefix.toUpperCase();
}
var prefixlength = prefix.length;
var subLen = 8 - prefixlength;
var uidStr = "";
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
}
var timStr = moment().format("YYYYMMDDHHmm");
return prefix + timStr + uidStr;
}
/*
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');//长度62,到yz长度为长36
var uuid = [], i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
}
module.exports = OplogCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings=require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class PConfigCtl extends CtlBase {
constructor() {
super("common",CtlBase.getServiceName(PConfigCtl));
this.userCtl = system.getObject("service.auth.userSve");
}
async initNewInstance(pobj,queryobj, req) {
var rtn = {};
return system.getResult(rtn);
}
async create(pobj,queryobj, req) {
pobj.app_id=req.appid;
pobj.appkey=req.appkey;
var rtn=await super.create(pobj,queryobj, req);
return system.getResult(rtn);
}
async update(pobj,queryobj, req) {
pobj.app_id=req.appid;
pobj.appkey=req.appkey;
var rtn=await super.update(pobj);
return system.getResult(rtn);
}
}
module.exports = PConfigCtl;
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class RouteCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(RouteCtl));
this.appS=system.getObject("service.common.appSve")
}
async create(p,q,req){
let appid=p.app_id;
let apptmp= await this.appS.findById(appid)
let routedata={
name:p.name,
hosts:p.shosts.split(","),
paths:p.spaths.split(","),
isstrip:false,
app_id:appid,
shosts:p.shosts,
spaths:p.spaths
}
let rtn= await this.service.create(apptmp.name, routedata, req);
return system.getResult(rtn)
}
}
module.exports = RouteCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
class SocketNotifyCtl{
constructor(){
}
setSocketServer(s){
this.socketServer=s;
}
//异步推送消息到客户端
notifyClientMsg(user,msg){
var uk= this.buildPrivateChannel(user);
var msgHandler=this.socketServer.users[uk];
msgHandler.notifyClient(uk,msg);
}
buildPrivateChannel(user){
var ukchannel= user.app_id+"¥"+user.id;
return ukchannel;
}
buildMsgTarget(user){
var ukchannel= user.app_id+"¥"+user.id;
var nickName=user.nickName;
var imgUrl=user.imgUrl;
var rtn=ukchannel+"¥"+nickName+"¥"+imgUrl;
return rtn;
}
}
module.exports=SocketNotifyCtl;
var system=require("../../../system")
const CtlBase = require("../../ctl.base");
const crypto = require('crypto');
var fs=require("fs");
var accesskey='3KV9nIwW8qkTGlrPmAe3HnR3fzM6r5';
var accessKeyId='LTAI4GC5tSKvqsH2hMqj6pvd';
var url="https://gsb-zc.oss-cn-beijing.aliyuncs.com";
class UploadCtl extends CtlBase{
constructor(){
super("common",CtlBase.getServiceName(UploadCtl));
this.cmdPdf2HtmlPattern = "docker run -i --rm -v /tmp/:/pdf 0c pdf2htmlEX --zoom 1.3 '{fileName}'";
this.restS=system.getObject("util.execClient");
this.cmdInsertToFilePattern = "sed -i 's/id=\"page-container\"/id=\"page-container\" contenteditable=\"true\"/'";
//sed -i 's/1111/&BBB/' /tmp/input.txt
//sed 's/{position}/{content}/g' {path}
}
async getOssConfig(){
var policyText = {
"expiration":"2119-12-31T16:00:00.000Z",
"conditions":[
["content-length-range",0,1048576000],
["starts-with","$key","zc"]
]
};
var b = new Buffer(JSON.stringify(policyText));
var policyBase64 = b.toString('base64');
var signature= crypto.createHmac('sha1',accesskey).update(policyBase64).digest().toString('base64'); //base64
var data={
OSSAccessKeyId:accessKeyId,
policy:policyBase64,
Signature:signature,
Bucket:'gsb-zc',
success_action_status:201,
url:url
};
return data;
};
async upfile(srckey,dest){
var oss=system.getObject("util.ossClient");
var result=await oss.upfile(srckey,"/tmp/"+dest);
return result;
};
async downfile(srckey){
var oss=system.getObject("util.ossClient");
var downfile=await oss.downfile(srckey).then(function(){
downfile="/tmp/"+srckey;
return downfile;
});
return downfile;
};
async pdf2html(obj){
var srckey=obj.key;
var downfile=await this.downfile(srckey);
var cmd=this.cmdPdf2HtmlPattern.replace(/\{fileName\}/g, srckey);
var rtn=await this.restS.exec(cmd);
var path="/tmp/"+srckey.split(".pdf")[0]+".html";
var a=await this.insertToFile(path);
fs.unlink("/tmp/"+srckey);
var result=await this.upfile(srckey.split(".pdf")[0]+".html",srckey.split(".pdf")[0]+".html");
return result.url;
};
async insertToFile(path){
var cmd=this.cmdInsertToFilePattern+" "+path;
return await this.restS.exec(cmd);
};
}
module.exports=UploadCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class BusinesstypeCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(BusinesstypeCtl));
}
async refQuery(pobj, qobj, req) {
pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj);
return rtn
}
async create(pobj, qobj, req) {
if(!pobj.p_id || pobj.p_id.length<1){
pobj["p_id"] = 0;
}
const up = await this.service.create(pobj);
return system.getResult(up);
}
}
module.exports = BusinesstypeCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class FormInfoCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(FormInfoCtl));
}
/**
* 重写保存方法
* @param pobj
* @returns {Promise<void>}
*/
async create(pobj){
let result = await this.service.createForm(pobj);
return result;
}
/**
* 重写添加方法
* @param pobj
* @returns {Promise<void>}
*/
async update(pobj) {
let result = await this.service.updateForm(pobj);
return result;
}
/**
* 复制表单
* @returns {Promise<void>}
*/
async copy(pobj){
let result = await this.service.copy(pobj);
return result;
}
/**
* 删除
* @param pobj
* @returns {Promise<*>}
*/
async delete(pobj){
let result = await this.service.deleteForm(pobj);
return result;
}
/**
* 根据id获取表单
* @param pobj
* @returns {Promise<void>}
*/
async findById(pobj){
let result = await this.service.findOne({id:pobj.id},[]);
return system.getResult(result);
}
}
module.exports = FormInfoCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class FormItemCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(FormItemCtl));
}
async getFormItemListByFormId(pobj){
return this.service.getFormItemListByFormId(pobj);
}
/**
* 重写添加方法
* @param pobj
* @returns {Promise<void>}
*/
async create(pobj){
let result = this.service.createItem(pobj);
return result;
}
/**
* 重写修改方法
* @param pobj
* @returns {Promise<void>}
*/
async update(pobj){
let result = this.service.updateItem(pobj);
return result;
}
/**
* 删除
* @param pobj
* @returns {Promise<*>}
*/
async delete(pobj){
let result = this.service.deleteItem(pobj);
return result;
}
}
module.exports = FormItemCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class FormsubmitrecordCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(FormsubmitrecordCtl));
}
}
module.exports = FormsubmitrecordCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class ImgInfoCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(ImgInfoCtl));
}
async create(pobj, qobj, req) {
pobj.company_id = req && req.xctx && req.xctx.companyid ?req.xctx.companyid : "";
const up = await this.service.create(pobj);
return up;
}
async update(pobj, qobj, req) {
const up = await this.service.update(pobj);
return up;
}
}
module.exports = ImgInfoCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class LaunchchannelCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(LaunchchannelCtl));
}
/**
* 重写添加方法
* @param pobj
* @returns {Promise<{msg: string, data: *, bizmsg: string, status: number}>}
*/
async create(pobj){
const result = await this.service.createChannel(pobj);
return result;
}
async refQuery(pobj, qobj, req) {
pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj);
return rtn
}
/**
* 重写update方法
* @returns {Promise<void>}
*/
async update(pobj){
let result = await this.service.updateChannel(pobj);
return result ;
}
/**
* 重写删除
* @param pobj
* @returns {Promise<void>}
*/
async delete(pobj){
let result = await this.service.deleteChannel(pobj);
return result;
}
}
module.exports = LaunchchannelCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class LaunchtypeCtl extends CtlBase {
constructor() {
super("launchtypemag", CtlBase.getServiceName(LaunchtypeCtl));
}
async refQuery(pobj, qobj, req) {
pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj);
return rtn
}
}
module.exports = LaunchtypeCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class MainInfoCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(MainInfoCtl));
}
async create(pobj, qobj, req) {
pobj.company_id = req && req.xctx && req.xctx.companyid ?req.xctx.companyid : "";
const up = await this.service.create(pobj);
return up;
}
async refQuery(pobj, qobj, req) {
pobj.refwhere.company_id = pobj.company_id;
let rtn = await this.service.refQuery(pobj);
return rtn;
}
async update(pobj, qobj, req) {
const up = await this.service.update(pobj);
return up;
}
async delete(pobj, qobj, req) {
const up = await this.service.delete(pobj);
return up;
}
}
module.exports = MainInfoCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class PutTypeCtl extends CtlBase {
constructor() {
super("configmag", CtlBase.getServiceName(PutTypeCtl));
}
async create(pobj, qobj, req) {
pobj.company_id = req && req.xctx && req.xctx.companyid ?req.xctx.companyid : "";
const up = await this.service.create(pobj);
return up;
}
async update(pobj, qobj, req) {
const up = await this.service.update(pobj);
return up;
}
async delete(pobj, qobj, req) {
const up = await this.service.delete(pobj);
return up;
}
}
module.exports = PutTypeCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class TemplateinfoCtl extends CtlBase {
constructor() {
super("template", CtlBase.getServiceName(TemplateinfoCtl));
this.templateinfoSve = system.getObject('service.template.templateinfoSve');
}
/**
* 创建模板
* @param {*} pobj
*/
async createTemplate(pobj){
return this.templateinfoSve.createTemplate(pobj);
}
/**
* 重写查询方法
* @param pobj
* @returns {Promise<{msg: string, data: *, bizmsg: string, status: number}>}
*/
async findAndCountAll(pobj) {
let result = await this.templateinfoSve.findByCompanyId(pobj);
return result;
}
/**
* 根据编码获取模板信息
* @param {*} pobj
*/
async getTemplateInfoByCode(pobj){
let result = await this.templateinfoSve.findOneByCode(pobj);
return result;
}
/**
* 根据id获取模板信息
* @param {*} pobj
*/
async getTemplateInfoById(pobj){
let result = await this.templateinfoSve.getTemplateInfoById(pobj);
return result;
}
async setTemplateBusinessId(pobj){
let result = await this.templateinfoSve.setTemplateBusinessId(pobj);
return result;
}
/**
* 重写保存方法
* @param pobj
* @returns {Promise<void>}
*/
async create(pobj){
let result = await this.templateinfoSve.editTemplateTdk(pobj);
return result;
}
/**
* 修改启用状态
* @param {*} pobj
*/
async updateSwitchStatus(pobj){
let result = await this.templateinfoSve.updateSwitchStatus(pobj);
return result;
}
}
module.exports = TemplateinfoCtl;
var system = require("../../../system")
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
var cacheBaseComp = null;
class TemplatelinkCtl extends CtlBase {
constructor() {
super("template", CtlBase.getServiceName(TemplatelinkCtl));
this.templatelinkSve = system.getObject('service.template.templatelinkSve');
}
/**
* 重写保存方法
* @param pobj
* @returns {Promise<void>}
*/
async create(pobj){
let result = await this.templatelinkSve.createTemplateLink(pobj);
return result;
}
/**
* 修改投放状态
* @param {*} pobj
*/
async updateLaunchStatus(pobj){
var result = await this.service.updateLaunchStatus(pobj);
return result;
}
async delete(pobj, qobj, req) {
const up = await this.templatelinkSve.deleteTemplateLink(pobj);
return system.getResult(up);
}
}
module.exports = TemplatelinkCtl;
const system = require("../../../system");
const settings = require("../../../../config/settings");
function exp(db, DataTypes) {
var base = {
code: {
type: DataTypes.STRING(50),
unique: true
},
name: DataTypes.STRING(1000),
};
return base;
}
module.exports = exp;
const system = require("../../system");
const settings = require("../../../config/settings");
const appconfig = system.getSysConfig();
function exp(db, DataTypes) {
var base = {
//继承的表引用用户信息user_id
code: DataTypes.STRING(100),
name: DataTypes.STRING(500),
creator: DataTypes.STRING(100),//创建者
updator: DataTypes.STRING(100),//更新者
auditor: DataTypes.STRING(100),//审核者
opNotes: DataTypes.STRING(500),//操作备注
auditStatusName: {
type:DataTypes.STRING(50),
defaultValue:"待审核",
},
auditStatus: {//审核状态"dsh": "待审核", "btg": "不通过", "tg": "通过"
type: DataTypes.ENUM,
values: Object.keys(appconfig.pdict.audit_status),
set: function (val) {
this.setDataValue("auditStatus", val);
this.setDataValue("auditStatusName", appconfig.pdict.audit_status[val]);
},
defaultValue:"dsh",
},
sourceTypeName: DataTypes.STRING(50),
sourceType: {//来源类型 "order": "订单","expensevoucher": "费用单","receiptvoucher": "收款单", "trademark": "商标单"
type: DataTypes.ENUM,
values: Object.keys(uiconfig.config.pdict.source_type),
set: function (val) {
this.setDataValue("sourceType", val);
this.setDataValue("sourceTypeName", appconfig.pdict.source_type[val]);
}
},
sourceOrderNo: DataTypes.STRING(100),//来源单号
};
return base;
}
module.exports = exp;
const system = require("../system")
const settings = require("../../config/settings.js");
class CacheBase {
constructor() {
this.db = system.getObject("db.common.connection").getCon();
this.redisClient = system.getObject("util.redisClient");
this.desc = this.desc();
this.prefix = this.prefix();
this.cacheCacheKeyPrefix = "sadd_base:cachekey";
this.isdebug = this.isdebug();
}
isdebug() {
return false;
}
desc() {
throw new Error("子类需要定义desc方法,返回缓存描述");
}
prefix() {
throw new Error("子类需要定义prefix方法,返回本缓存的前缀");
}
async cache(inputkey, val, ex, ...items) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null" || this.isdebug) {
var objvalstr = await this.buildCacheVal(cachekey, inputkey, val, ex, ...items);
if (!objvalstr) {
return null;
}
if (ex) {
await this.redisClient.setWithEx(cachekey, objvalstr, ex);
} else {
await this.redisClient.set(cachekey, objvalstr);
}
//缓存当前应用所有的缓存key及其描述
this.redisClient.sadd(this.cacheCacheKeyPrefix, [cachekey + "|" + this.desc]);
return JSON.parse(objvalstr);
} else {
// this.redisClient.setWithEx(cachekey, cacheValue, ex);
return JSON.parse(cacheValue);
}
}
async getCache(inputkey, ex) {
const cachekey = this.prefix + inputkey;
var cacheValue = await this.redisClient.get(cachekey);
if (!cacheValue || cacheValue == "undefined" || cacheValue == "null") {
return null;
} else {
if (ex) {
this.redisClient.set(cachekey, cacheValue, ex);
}
return JSON.parse(cacheValue);
}
}
async invalidate(inputkey) {
const cachekey = this.prefix + inputkey;
this.redisClient.delete(cachekey);
return 0;
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
throw new Error("子类中实现构建缓存值的方法,返回字符串");
}
}
module.exports = CacheBase;
const CacheBase=require("../cache.base");
const system=require("../../system");
//缓存首次登录的赠送的宝币数量
class CacheLocker extends CacheBase{
constructor(){
super();
this.prefix="locker_";
}
desc(){
}
prefix(){
}
async init(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
async enter(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpop(key);
}
async release(tradekey){
const key=this.prefix+tradekey;
return this.redisClient.rpushWithEx(key,"1",1800);
}
}
module.exports=CacheLocker;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class AppCache extends CacheBase{
constructor(){
super();
this.prefix="g_centerappkey:";
this.appDao=system.getObject("db.common.appDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存本地应用对象";
}
prefix(){
return "g_applocal_"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue=await this.appDao.findOne({appkey:inputkey});
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports=AppCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class CompanyCache extends CacheBase{
constructor(){
super();
this.prefix="g_centercompanykey:";
this.companyDao=system.getObject("db.common.companyDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存统一公司对象";
}
prefix(){
return "gc_companylocal_"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue=await this.companyDao.findOne({companykey:inputkey});
if (configValue) {
return JSON.stringify(configValue);
}
return null;
}
}
module.exports=CompanyCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
class MagCache extends CacheBase {
constructor() {
super();
this.prefix = "magCache";
}
desc() {
return "管理当前缓存的key";
}
prefix() {
return "g_magcache:";
}
async getCacheSmembersByKey(key) {
return this.redisClient.smembers(key);
}
async delCacheBySrem(key, value) {
return this.redisClient.srem(key, value)
}
async keys(p) {
return this.redisClient.keys(p);
}
async get(k) {
return this.redisClient.get(k);
}
async del(k) {
return this.redisClient.delete(k);
}
async clearAll() {
console.log("xxxxxxxxxxxxxxxxxxxclearAll............");
return this.redisClient.flushall();
}
}
module.exports = MagCache;
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
class UserCache extends CacheBase{
constructor(){
super();
this.userDao=system.getObject("db.auth.userDao");
}
isdebug(){
return settings.env=="dev";
}
desc(){
return "缓存本地应用对象";
}
prefix(){
return "g_userlocal_"
}
async buildCacheVal(cachekey,inputkey, val, ex, ...items) {
const configValue = await this.userDao.model.findAll({
where: { userName: inputkey, app_id: settings.pmappid },
attributes: ['id','userName', 'nickName','headUrl','jwtkey','jwtsecret','created_at','isSuper','isAdmin','mail'],
include: [
{ model: this.db.models.company,raw:true},
{model:this.db.models.role,as:"Roles",attributes:["id","code"],}
],
});
if (configValue && configValue[0]) {
return JSON.stringify(configValue[0]);
}
return null;
}
}
module.exports=UserCache;
\ No newline at end of file
const CacheBase = require("../cache.base");
const system = require("../../system");
const settings = require("../../../config/settings");
//缓存首次登录的赠送的宝币数量
class VCodeCache extends CacheBase {
constructor() {
super();
this.smsUtil = system.getObject("util.smsClient");
}
// isdebug() {
// return settings.env == "dev";
// }
desc() {
return "缓存给手机发送的验证码60妙";
}
prefix() {
return "g_vcode_"
}
async buildCacheVal(cachekey, inputkey, val, ex, ...items) {
//inputkey采用appkey_mobile的形式
var mobile = inputkey;
var tmplCode = val;
var signName = items ? items[0] : "";
var vcode = await this.smsUtil.getUidStr(6, 10);
if (!tmplCode && !signName) {
this.smsUtil.sendMsg(mobile, vcode);
} //tmplCode为发送短信编码,需在阿里开通,signName为短信头描述信息,二者没有传递则用默认的发送验证码
else {
this.smsUtil.aliSendMsg(mobile, tmplCode, signName, JSON.stringify({ code: vcode }));
}
return JSON.stringify({ vcode: vcode });
}
}
module.exports = VCodeCache;
const system = require("../system");
class Dao {
constructor(modelName) {
this.modelName = modelName;
var db = system.getObject("db.common.connection").getCon();
this.db = db;
console.log("........set dao model..........");
console.log(this.modelName)
this.model = db.models[this.modelName];
console.log(this.modelName);
}
preCreate(u) {
return u;
}
async create(u, t) {
var u2 = this.preCreate(u);
if (t) {
return this.model.create(u2, { transaction: t }).then(u => {
return u;
});
} else {
return this.model.create(u2).then(u => {
return u;
});
}
}
static getModelName(ClassObj) {
return ClassObj["name"].substring(0, ClassObj["name"].lastIndexOf("Dao")).toLowerCase()
}
async refQuery(qobj) {
var w = qobj.refwhere ? qobj.refwhere : {};
if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
}
if (qobj.parentinfo) {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
}
//如果需要控制数据权限
if (qobj.datapriv) {
w["id"] = { [this.db.Op.in]: qobj.datapriv };
}
if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
return this.model.findAll({ where: w, attributes: qobj.fields });
} else {
return this.model.findAll({ where: w, attributes: qobj.fields });
}
}
async bulkDelete(ids) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en;
}
async bulkDeleteByWhere(whereParam, t) {
var en = null;
if (t != null && t != 'undefined') {
whereParam.transaction = t;
return await this.model.destroy(whereParam);
} else {
return await this.model.destroy(whereParam);
}
}
async delete(qobj, t) {
var en = null
if (t != null && t != 'undefined') {
en = await this.model.findOne({ where: { id: qobj.id }, transaction: t });
if (en != null) {
await en.destroy({ transaction: t });
return en
}
} else {
en = await this.model.findOne({ where: { id: qobj.id } });
if (en != null) {
return en.destroy();
}
}
return null;
}
extraModelFilter(pobj) {
//return {"key":"include","value":{model:this.db.models.app}};
return null;
}
extraWhere(obj, where) {
return where;
}
orderBy() {
//return {"key":"include","value":{model:this.db.models.app}};
return [["created_at", "DESC"]];
}
buildQuery(qobj) {
var linkAttrs = [];
const pageNo = qobj.pageInfo.pageNo;
const pageSize = qobj.pageInfo.pageSize;
const search = qobj.search;
var qc = {};
//设置分页查询条件
qc.limit = pageSize;
qc.offset = (pageNo - 1) * pageSize;
//默认的查询排序
qc.order = this.orderBy();
//构造where条件
qc.where = {};
if (search) {
Object.keys(search).forEach(k => {
// console.log(search[k], ":search[k]search[k]search[k]");
if ((search[k] && search[k] != 'undefined' && search[k] != "") || search[k] === 0) {
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("is_enabled") >= 0) {
qc.where[k] = search[k];
}
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(qobj);
if (extraFilter) {
qc[extraFilter.key] = extraFilter.value;
}
console.log(" ------------ 传入 的 查询 条件 ------------- ");
console.log(qc);
return qc;
}
buildaggs(qobj) {
var aggsinfos = [];
if (qobj.aggsinfo) {
qobj.aggsinfo.sum.forEach(aggitem => {
var t1 = [this.db.fn('SUM', this.db.col(aggitem.field)), aggitem.field + "_" + "sum"];
aggsinfos.push(t1);
});
qobj.aggsinfo.avg.forEach(aggitem => {
var t2 = [this.db.fn('AVG', this.db.col(aggitem.field)), aggitem.field + "_" + "avg"];
aggsinfos.push(t2);
});
}
return aggsinfos;
}
async findAggs(qobj, qcwhere) {
var aggArray = this.buildaggs(qobj);
if (aggArray.length != 0) {
qcwhere["attributes"] = {};
qcwhere["attributes"] = aggArray;
qcwhere["raw"] = true;
var aggResult = await this.model.findOne(qcwhere);
return aggResult;
} else {
return {};
}
}
async findAndCountAll(qobj, t) {
var qc = this.buildQuery(qobj);
var apps = await this.model.findAndCountAll(qc);
var aggresult = await this.findAggs(qobj, qc);
var rtn = {};
rtn.results = apps;
rtn.aggresult = aggresult;
return rtn;
}
preUpdate(obj) {
return obj;
}
async update(obj, tm) {
var obj2 = this.preUpdate(obj);
if (tm != null && tm != 'undefined') {
return this.model.update(obj2, { where: { id: obj2.id }, transaction: tm });
} else {
return this.model.update(obj2, { where: { id: obj2.id } });
}
}
async bulkCreate(ids, t) {
if (t != null && t != 'undefined') {
return await this.model.bulkCreate(ids, { transaction: t });
} else {
return await this.model.bulkCreate(ids);
}
}
async updateByWhere(setObj, whereObj, t) {
let inWhereObj = {}
if (t && t != 'undefined') {
if (whereObj && whereObj != 'undefined') {
inWhereObj["where"] = whereObj;
inWhereObj["transaction"] = t;
} else {
inWhereObj["transaction"] = t;
}
} else {
inWhereObj["where"] = whereObj;
}
return this.model.update(setObj, inWhereObj);
}
async customExecAddOrPutSql(sql, paras = null) {
return this.db.query(sql, paras);
}
async customQuery(sql, paras, t) {
var tmpParas = null;//||paras=='undefined'?{type: this.db.QueryTypes.SELECT }:{ replacements: paras, type: this.db.QueryTypes.SELECT };
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
} else {
tmpParas = { replacements: paras, type: this.db.QueryTypes.SELECT };
tmpParas.transaction = t;
}
} else {
tmpParas = paras == null || paras == 'undefined' ? { type: this.db.QueryTypes.SELECT } : { replacements: paras, type: this.db.QueryTypes.SELECT };
}
return this.db.query(sql, tmpParas);
}
async findCount(whereObj = null) {
return this.model.count(whereObj, { logging: false }).then(c => {
return c;
});
}
async findSum(fieldName, whereObj = null) {
return this.model.sum(fieldName, whereObj);
}
async getPageList(pageIndex, pageSize, whereObj = null, orderObj = null, attributesObj = null, includeObj = null) {
var tmpWhere = {};
tmpWhere.limit = pageSize;
tmpWhere.offset = (pageIndex - 1) * pageSize;
if (whereObj != null) {
tmpWhere.where = whereObj;
}
if (orderObj != null && orderObj.length > 0) {
tmpWhere.order = orderObj;
}
if (attributesObj != null && attributesObj.length > 0) {
tmpWhere.attributes = attributesObj;
}
if (includeObj != null && includeObj.length > 0) {
tmpWhere.include = includeObj;
tmpWhere.distinct = true;
} else {
tmpWhere.raw = true;
}
return await this.model.findAndCountAll(tmpWhere);
}
async findOne(obj, attributes = []) {
if (attributes.length > 0) {
return this.model.findOne({ "where": obj, attributes, row: true });
} else {
return this.model.findOne({ "where": obj, row: true });
}
}
async findById(oid) {
return this.model.findById(oid);
}
async findAll(obj, include = []) {
return this.model.findAll({ "where": obj, include, row: true });
}
}
module.exports = Dao;
const fs=require("fs");
const settings=require("../../../../config/settings");
class CacheManager{
constructor(){
//await this.buildCacheMap();
this.buildCacheMap();
}
buildCacheMap(){
var self=this;
self.doc={};
var cachePath=settings.basepath+"/app/base/db/cache/";
const files=fs.readdirSync(cachePath);
if(files){
files.forEach(function(r){
var classObj=require(cachePath+"/"+r);
self[classObj.name]=new classObj();
var refTmp=self[classObj.name];
if(refTmp.prefix){
self.doc[refTmp.prefix]=refTmp.desc;
}
else{
console.log("请在"+classObj.name+"缓存中定义prefix");
}
});
}
}
}
module.exports=CacheManager;
// var cm= new CacheManager();
// cm["InitGiftCache"].cacheGlobalVal("hello").then(function(){
// cm["InitGiftCache"].cacheGlobalVal().then(x=>{
// console.log(x);
// });
// });
const Sequelize = require('sequelize');
const settings = require("../../../../config/settings")
const Op = Sequelize.Op
const fs = require("fs")
const path = require("path");
var glob = require("glob");
class DbFactory {
constructor() {
const dbConfig = settings.database();
this.db = new Sequelize(dbConfig.dbname,
dbConfig.user,
dbConfig.password,
{
...dbConfig.config,
operatorsAliases: {
$eq: Op.eq,
$ne: Op.ne,
$gte: Op.gte,
$gt: Op.gt,
$lte: Op.lte,
$lt: Op.lt,
$not: Op.not,
$in: Op.in,
$notIn: Op.notIn,
$is: Op.is,
$like: Op.like,
$notLike: Op.notLike,
$iLike: Op.iLike,
$notILike: Op.notILike,
$regexp: Op.regexp,
$notRegexp: Op.notRegexp,
$iRegexp: Op.iRegexp,
$notIRegexp: Op.notIRegexp,
$between: Op.between,
$notBetween: Op.notBetween,
$overlap: Op.overlap,
$contains: Op.contains,
$contained: Op.contained,
$adjacent: Op.adjacent,
$strictLeft: Op.strictLeft,
$strictRight: Op.strictRight,
$noExtendRight: Op.noExtendRight,
$noExtendLeft: Op.noExtendLeft,
$and: Op.and,
$or: Op.or,
$any: Op.any,
$all: Op.all,
$values: Op.values,
$col: Op.col
}
});
this.db.Sequelize = Sequelize;
this.db.Op = Op;
this.initModels();
this.initRelations();
}
async initModels() {
var self = this;
var modelpath = path.normalize(path.join(__dirname, '../..')) + "/models/";
var models = glob.sync(modelpath + "/**/*.js");
console.log(models.length);
models.forEach(function (m) {
console.log(m);
self.db.import(m);
});
console.log("init models....");
}
async initRelations() {
}
//async getCon(){,用于使用替换table模型内字段数据使用
getCon() {
var that = this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
// console.error('Unable to connect to the database:', err);
// throw err;
// });
//同步模型
if (settings.env == "dev") {
//console.log(pa);
// pconfigObjs.forEach(p=>{
// console.log(p.get({plain:true}));
// });
// await this.db.models.user.create({nickName:"dev","description":"test user",openId:"testopenid",unionId:"testunionid"})
// .then(function(user){
// var acc=that.db.models.account.build({unionId:"testunionid",nickName:"dev"});
// acc.save().then(a=>{
// user.setAccount(a);
// });
// });
}
return this.db;
}
}
module.exports = DbFactory;
// const dbf=new DbFactory();
// dbf.getCon().then((db)=>{
// //console.log(db);
// // db.models.user.create({nickName:"jy","description":"cccc",openId:"xxyy",unionId:"zz"})
// // .then(function(user){
// // var acc=db.models.account.build({unionId:"zz",nickName:"jy"});
// // acc.save().then(a=>{
// // user.setAccount(a);
// // });
// // console.log(user);
// // });
// // db.models.user.findAll().then(function(rs){
// // console.log("xxxxyyyyyyyyyyyyyyyyy");
// // console.log(rs);
// // })
// });
// const User = db.define('user', {
// firstName: {
// type: Sequelize.STRING
// },
// lastName: {
// type: Sequelize.STRING
// }
// });
// db
// .authenticate()
// .then(() => {
// console.log('Co+nnection has been established successfully.');
//
// User.sync(/*{force: true}*/).then(() => {
// // Table created
// return User.create({
// firstName: 'John',
// lastName: 'Hancock'
// });
// });
//
// })
// .catch(err => {
// console.error('Unable to connect to the database:', err);
// });
//
// User.findAll().then((rows)=>{
// console.log(rows[0].firstName);
// });
const system=require("../../../system");
const Dao=require("../../dao.base");
class ImginfoDao extends Dao{
constructor(){
super(Dao.getModelName(ImginfoDao));
}
// extraWhere(obj,w,qc,linkAttrs){
// w["company_id"]=obj.company_id;
// return w;
// }
}
module.exports=ImginfoDao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class BusinesstypeDao extends Dao{
constructor(){
super(Dao.getModelName(BusinesstypeDao));
}
async refQuery(qobj) {
var w = qobj.refwhere ? qobj.refwhere : {};
w["p_id"] = 0;
if (qobj.levelinfo) {
w[qobj.levelinfo.levelfield] = qobj.levelinfo.level;
}
if (qobj.parentinfo) {
w[qobj.parentinfo.parentfield] = qobj.parentinfo.parentcode;
}
//如果需要控制数据权限
if (qobj.datapriv) {
w["id"] = { [this.db.Op.in]: qobj.datapriv };
}
if (qobj.likestr) {
w[qobj.fields[0]] = { [this.db.Op.like]: "%" + qobj.likestr + "%" };
return this.model.findAll({ where: w, attributes: qobj.fields });
} else {
return this.model.findAll({ where: w, attributes: qobj.fields });
}
}
}
module.exports=BusinesstypeDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ForminfoDao extends Dao{
constructor(){
super(Dao.getModelName(ForminfoDao));
}
extraWhere(qobj, qw, qc) {
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw
}
}
module.exports=ForminfoDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class FormitemDao extends Dao{
constructor(){
super(Dao.getModelName(FormitemDao));
}
}
module.exports=FormitemDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class ImginfoDao extends Dao{
constructor(){
super(Dao.getModelName(ImginfoDao));
}
extraWhere(qobj, qw, qc) {
console.log(qobj)
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw
}
}
module.exports=ImginfoDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class LaunchchannelDao extends Dao{
constructor(){
super(Dao.getModelName(LaunchchannelDao));
}
extraWhere(qobj, qw, qc) {
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw;
}
}
module.exports=LaunchchannelDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class LaunchtypeDao extends Dao{
constructor(){
super(Dao.getModelName(LaunchtypeDao));
}
extraWhere(qobj, qw, qc) {
console.log(qobj)
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw
}
}
module.exports=LaunchtypeDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MaininfoDao extends Dao{
constructor(){
super(Dao.getModelName(MaininfoDao));
}
extraWhere(qobj, qw, qc) {
console.log(qobj)
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw
}
}
module.exports=MaininfoDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class MarketingsubjectDao extends Dao{
constructor(){
super(Dao.getModelName(MarketingsubjectDao));
}
extraWhere(qobj, qw, qc) {
console.log(qobj)
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw
}
}
module.exports=MarketingsubjectDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class PuttypeDao extends Dao{
constructor(){
super(Dao.getModelName(PuttypeDao));
}
extraWhere(qobj, qw, qc) {
console.log(qobj)
if(!qobj.company_id){
qw["company_id"] = "";
}else{
qw["company_id"] = Number(qobj.company_id);
}
return qw
}
}
module.exports=PuttypeDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class NeedinfoDao extends Dao{
constructor(){
super(Dao.getModelName(NeedinfoDao));
}
// extraWhere(obj,w,qc,linkAttrs){
// w["company_id"]=obj.company_id;
// return w;
// }
async getAllProductType(cid){
var params = {
company_id: cid
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var sql = "select id,p_id,p_code,p_name,code,name,pic_url,jump_link_type,jump_link,sequence from mc_product_type where deleted_at is null and p_id = 0 and company_id = :company_id order by sequence desc ";
var list = await this.customQuery(sql, params);
for(var i=0;i<list.length;i++){
if(list[i] && list[i].id)
var sql2 = "select id,p_id,p_code,p_name,code,name,pic_url,sequence from mc_product_type where deleted_at is null and p_id = "+list[i].id+" and company_id = :company_id order by sequence desc ";
var childlist = await this.customQuery(sql2, params);
list[i].children = childlist;
}
returnRes.rows = list;
returnRes.total = list.length;
return returnRes;
}
}
module.exports=NeedinfoDao;
\ No newline at end of file
const system = require("../../../system");
const Dao = require("../../dao.base");
class MediaaggregationDao extends Dao {
constructor() {
super(Dao.getModelName(MediaaggregationDao));
}
/**
* 服务列表
*/
async productList(req) {
var params = {
product_type_code: req.actionBody.product_type_code,
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_product where deleted_at is null and product_type_code = :product_type_code and is_enabled = 1 and company_id = :company_id ";
var sql = "select * from mc_product where deleted_at is null and product_type_code = :product_type_code and is_enabled = 1 and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 轮播图
*/
async rotationChartList(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_rotation_chart where deleted_at is null and pic_type = 2 and is_enabled = 1 and company_id = :company_id ";
var sql = "select * from mc_rotation_chart where deleted_at is null and pic_type = 2 and is_enabled = 1 and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 列表头图
*/
async tablePicList(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_rotation_chart where deleted_at is null and pic_type = 1 and is_enabled = 1 and company_id = :company_id ";
var sql = "select * from mc_rotation_chart where deleted_at is null and pic_type = 1 and is_enabled = 1 and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 留资表单产品
*/
async needProductList(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_second_level_need_config where deleted_at is null and company_id = :company_id ";
var sql = "select * from mc_second_level_need_config where deleted_at is null and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 热门推荐
*/
async popularRecommendationList(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_popular_recommendation where deleted_at is null and is_enabled = 1 and company_id = :company_id ";
var sql = "select * from mc_popular_recommendation where deleted_at is null and is_enabled = 1 and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 产品分类一类
*/
async productTypeFirst(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_product_type where deleted_at is null and p_id = 0 and company_id = :company_id ";
var sql = "select * from mc_product_type where deleted_at is null and p_id = 0 and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 产品分类二类
*/
async productTypeSecend(req) {
var params = {
p_product_type_code: req.actionBody.p_product_type_code,
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_product left join mc_product_type on mc_product.product_type_id = mc_product_type.id where mc_product.deleted_at is null and mc_product_type.deleted_at is null and mc_product.is_enabled = 1 and p_product_type_code = :p_product_type_code and mc_product_type.company_id = :company_id ";
var sql = "select * from mc_product left join mc_product_type on mc_product.product_type_id = mc_product_type.id where mc_product.deleted_at is null and mc_product_type.deleted_at is null and mc_product.is_enabled = 1 and mc_product.p_product_type_code = :p_product_type_code and mc_product_type.company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 获取产品详情
*/
async productDetail(req) {
var params = {
code: req.actionBody.code,
company_id: req.actionBody.company_id
};
var sql = "select * from mc_product where deleted_at is null and is_enabled = 1 and code = :code and company_id = :company_id ";
var list = await this.customQuery(sql, params);
return list;
}
/**
* 吸底菜单
*/
async bottomMenuConfig(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_bottom_menu_config where deleted_at is null and company_id = :company_id ";
var sql = "select * from mc_bottom_menu_config where deleted_at is null and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 周期产品
*/
async cycleProduct(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_cycle_product where deleted_at is null and company_id = :company_id ";
var sql = "select * from mc_cycle_product where deleted_at is null and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 二级留资页热门推荐
*/
async secondLevelNeedConfig(req) {
var params = {
company_id: req.actionBody.company_id,
code: req.actionBody.code
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_second_level_need_config where deleted_at is null and company_id = :company_id and code = :code ";
var sql = "select * from mc_second_level_need_config where deleted_at is null and company_id = :company_id and code = :code";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
/**
* 二级产品资质选项
*/
async clueMaintenance(req) {
var params = {
company_id: req.actionBody.company_id
};
var returnRes = {
total: 0,//总记录条数
rows: []
};
var dataCount = "select count(1) as dataCount from mc_clue_maintenance where deleted_at is null and company_id = :company_id ";
var sql = "select * from mc_clue_maintenance where deleted_at is null and company_id = :company_id ";
var list = await this.customQuery(sql, params);
returnRes.rows = list;
var tmpResultCount = await this.customQuery(dataCount, params);
returnRes.total = tmpResultCount && tmpResultCount.length > 0 ? tmpResultCount[0].dataCount : 0;
return returnRes;
}
}
module.exports = MediaaggregationDao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class BrowsingrecordsDao extends Dao{
constructor(){
super(Dao.getModelName(BrowsingrecordsDao));
}
}
module.exports=BrowsingrecordsDao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class TemplateinfoDao extends Dao{
constructor(){
super(Dao.getModelName(TemplateinfoDao));
}
extraWhere(obj,w,qc,linkAttrs){
w["company_id"]=obj.company_id;
return w;
}
}
module.exports=TemplateinfoDao;
\ No newline at end of file
const system=require("../../../system");
const Dao=require("../../dao.base");
class TemplatelinkDao extends Dao{
constructor(){
super(Dao.getModelName(TemplatelinkDao));
}
extraWhere(obj,w,qc,linkAttrs){
w["company_id"]=obj.company_id;
return w;
}
}
module.exports=TemplatelinkDao;
\ No newline at end of file
const system = require("../system");
const settings = require("../../config/settings.js");
const reclient = system.getObject("util.redisClient");
const md5 = require("MD5");
var dbf = system.getObject("db.common.connection");
var db = dbf.getCon();
db.sync({ force: true }).then(async () => {
console.log("init 完毕");
});
module.exports = {
"config": {
"pdict": {
"app_type": { "api": "API服务","web": "PCWEB","app":"移动APP","xcx":"小程序","access":"接入"},
"data_priv": { "auth.role": "角色", "auth.user": "用户" },
"noticeType": {"sms": "短信", "email": "邮件","wechat":"微信"},
"authType": {"add": "新增", "edit": "编辑","delete":"删除","export":"导出","show":"查看"},
"mediaType": {"vd": "视频", "ad": "音频","qt":"其它"},
"usageType": {"kt": "课堂","taxkt":"财税课堂", "qt": "其它"},
"opstatus": {"0": "失败", "1": "成功"},
"sex": {"male": "男", "female": "女"},
"logLevel": {"debug": 0, "info": 1, "warn": 2, "error": 3, "fatal": 4},
"msgType": { "sys": "系统", "single": "单点", "multi": "群发"},
"node_type":{"org":"组织","arc":"文档"},
"item_type":{
"phone": "手机号",
"singleBtn": "单选按钮",
"multipleBtn": "多选按钮",
"downOptions": "下拉选项",
"singleText": "单行文本",
"multipleText": "多行文本",
"dateTime": "日期",
"area": "省市"
},
"record_status":{
"1":"未读", "2":"已读", "3":"无效"
}
}
}
}
const fs=require("fs");
const path=require("path");
const appPath=path.normalize(__dirname+"/app");
const bizsPath=path.normalize(__dirname+"/bizs");
var appJsons={
config:require(appPath+"/"+"platform.js").config
}
module.exports=appJsons;
/**
* 业务类型表
* @param db
* @param DataTypes
* @returns {Model|void|*}
*/
module.exports = (db, DataTypes) => {
return db.define("businesstype", {
p_id: DataTypes.INTEGER(11),//产品一类id
p_name: DataTypes.STRING,//产品一类id
code: DataTypes.STRING(100),//渠道编码
name: DataTypes.STRING(100),//渠道名称
notes: DataTypes.STRING(255),//备注
user_id: DataTypes.INTEGER(11),//创建用户id
user_name: DataTypes.STRING(60),//创建用户名称
company_id: DataTypes.INTEGER(11)
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updated_at: true,
tableName: 'c_business_type',
validate: {},
indexes: []
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 表单信息表
*/
module.exports = (db, DataTypes) => {
return db.define("forminfo", {
code: DataTypes.STRING,
name: DataTypes.STRING,
form_items: DataTypes.STRING,
form_describe: DataTypes.STRING,
notes: DataTypes.STRING,
user_id: DataTypes.STRING(100),
user_name: DataTypes.STRING(100),
company_id: DataTypes.INTEGER(11),
record_num:DataTypes.INTEGER(11),
form_table:DataTypes.JSON
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'c_form_info',
validate: {},
indexes: [
]
});
}
/**
* 表单信息表
* @param db
* @param DataTypes
* @returns {Model|void|*}
*/
module.exports = (db, DataTypes) => {
return db.define("formitem", {
form_id: {//表单id
type: DataTypes.INTEGER
},
code: {//表单编码
type: DataTypes.STRING
},
name: {//表单名称
type: DataTypes.STRING
},
item_type: {//表单类型
type: DataTypes.STRING
},
item_type_name: {//表单类型名称
type: DataTypes.STRING
},
config_params: {//表单配置参数
type: DataTypes.JSON
},
is_enabled: {//显示状态
type: DataTypes.BOOLEAN
},
is_required: {//是否必填
type: DataTypes.BOOLEAN
},
sequence: {//次序
type: DataTypes.INTEGER
},
notes: {//备注
type: DataTypes.STRING()
},
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'c_form_item',
validate: {},
indexes: []
});
}
/**
* 表单提交记录表
* @param db
* @param DataTypes
* @returns {Model|void|*}
*/
const record_status = {"1":"未读", "2":"已读", "3":"无效"};
module.exports = (db, DataTypes) => {
return db.define("formsubmitrecord", {
business_code:DataTypes.STRING(100),
template_id: DataTypes.INTEGER(11),//模板id
templatelink_id: DataTypes.INTEGER(11),//模板链接id
form_id: DataTypes.INTEGER(11),//表单id
record_status :{//记录状态 1未读 2已读 3无效
type: DataTypes.STRING(60),
set: function (val) {
this.setDataValue("record_status", val);
this.setDataValue("record_status_name",record_status[val]);
}
},
record_status_name: DataTypes.STRING(60),//记录状态名称
templatelink_snapshot:DataTypes.JSON,//模板链接快照
form_snapshot:DataTypes.JSON,//表单快照
ali_code:DataTypes.STRING,
record_content:DataTypes.JSON,//记录内容
push_status:DataTypes.INTEGER,//推送状态 0:未推送,1:已推送 2:异常
op_notes:DataTypes.STRING,//操作备注
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updated_at: true,
tableName: 'c_form_submit_record',
validate: {},
indexes: []
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 表单信息表
*/
module.exports = (db, DataTypes) => {
return db.define("imginfo", {
code: {
allowNull: false,
type: DataTypes.STRING
},
name: {
allowNull: false,
type: DataTypes.STRING
},
pic_size:DataTypes.STRING,
company_id: {
allowNull: false,
type: DataTypes.INTEGER
},
pic_url: {
allowNull: false,
type: DataTypes.STRING
}
,
pic_size: {
allowNull: false,
type: DataTypes.STRING
}
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'c_picture_warehouse',
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}]
// }
]
});
}
/**
* 投放渠道信息表
* @param db
* @param DataTypes
* @returns {Model|void|*}
*/
module.exports = (db, DataTypes) => {
return db.define("launchchannel", {
code: DataTypes.STRING(100),//表单编码
name: DataTypes.STRING(100),//表单名称
notes: DataTypes.STRING(255),//备注
user_id: DataTypes.INTEGER(11),//创建用户id
user_name: DataTypes.STRING(60),//创建用户名称
company_id: DataTypes.INTEGER(11)
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updated_at: true,
tableName: 'c_launch_channel',
validate: {},
indexes: []
});
}
/**
* 投放渠道信息表
* @param db
* @param DataTypes
* @returns {Model|void|*}
*/
module.exports = (db, DataTypes) => {
return db.define("launchtype", {
code: DataTypes.STRING(100),//表单编码
name: DataTypes.STRING(100),//表单名称
notes: DataTypes.STRING(255),//备注
user_id: DataTypes.INTEGER(11),//创建用户id
user_name: DataTypes.STRING(60),//创建用户名称
company_id: DataTypes.INTEGER(11)
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
timestamps: true,
updated_at: true,
tableName: 'c_launch_type',
validate: {},
indexes: []
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 表单信息表
*/
module.exports = (db, DataTypes) => {
return db.define("maininfo", {
code: {
allowNull: false,
type: DataTypes.STRING
},
name: {
allowNull: false,
type: DataTypes.STRING
},
company_id: {
allowNull: true,
type: DataTypes.INTEGER
}
,
notes: {
allowNull: true,
type: DataTypes.STRING
}
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'c_marketing_subject',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
module.exports = (sequelize, DataType) => {
return sequelize.define("marketingsubject", {
code: DataType.STRING(100),
name: DataType.STRING(100),
notes: DataType.STRING(255),
user_name: DataType.STRING(100),
user_id: DataType.STRING(100),
company_id: DataType.INTEGER,
}, {
// 不添加时间戳属性 (updatedAt, createdAt)
timestamps: true,
// 不删除数据库条目,但将新添加的属性deletedAt设置为当前日期(删除完成时)。
// paranoid 只有在启用时间戳时才能工作
paranoid: true,
// 将自动设置所有属性的字段选项为下划线命名方式。
// 不会覆盖已经定义的字段选项
underscored: true,
// 禁用修改表名; 默认情况下,sequelize将自动将所有传递的模型名称(define的第一个参数)转换为复数。 如果你不想这样,请设置以下内容
freezeTableName: true,
// 定义表的名称
tableName: 'c_marketing_subject',
// 启用乐观锁定。 启用时,sequelize将向模型添加版本计数属性,
// 并在保存过时的实例时引发OptimisticLockingError错误。
// 设置为true或具有要用于启用的属性名称的字符串。
version: true
});
};
\ No newline at end of file
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 表单信息表
*/
module.exports = (db, DataTypes) => {
return db.define("puttype", {
code: {
allowNull: false,
type: DataTypes.STRING
},
name: {
allowNull: false,
type: DataTypes.STRING
},
company_id: {
allowNull: true,
type: DataTypes.INTEGER
}
,
notes: {
allowNull: true,
type: DataTypes.STRING
}
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'c_launch_type',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
const submit_type={"1":"页面","2":"弹窗"};
/**
* 表单信息表
*/
module.exports = (db, DataTypes) => {
return db.define("needinfo", {
product_type_code:DataTypes.STRING,//产品类型编码
product_type_name:DataTypes.STRING,//产品类型名称
submit_type_name:DataTypes.STRING,//提交方式名称
submit_type:{
type: DataTypes.STRING(60),
set: function (val) {
this.setDataValue("submit_type", val);
this.setDataValue("submit_type_name",submit_type[val]);
}
},
channel_code:DataTypes.STRING,//渠道编码
channel_name:DataTypes.STRING,//渠道名称
page_code:DataTypes.STRING,//页面编码
page_name:DataTypes.STRING,//页面名称
contact_mobile:DataTypes.STRING,//联系电话
contact_name:DataTypes.STRING,//联系人
original_need:DataTypes.STRING,//原始需求
region:DataTypes.STRING,//地区
business_id:DataTypes.STRING,//云服产品id
push_status:DataTypes.INTEGER,
notes: DataTypes.STRING
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
tableName: 'mc_need_info',
validate: {},
indexes: [
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 模板信息表
*/
module.exports = (db, DataTypes) => {
return db.define("browsingrecords", {
template_id: DataTypes.INTEGER,
link_code: DataTypes.STRING,
link_name: DataTypes.STRING,
else_channel_param:DataTypes.STRING,
channel_name: DataTypes.STRING,
channel_code: DataTypes.STRING,
business_type_code: DataTypes.STRING,
business_type_name: DataTypes.STRING,
lauch_type_code: DataTypes.STRING,
lauch_type_name: DataTypes.STRING,
marketing_subject_code: DataTypes.STRING,
marketing_subject_name: DataTypes.STRING,
device: DataTypes.STRING,
client_ip: DataTypes.STRING
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'b_browsing_records',
validate: {
},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
const system = require("../../../system");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 模板信息表
*/
module.exports = (db, DataTypes) => {
//TODO:
return db.define("templateinfo", {
code: DataTypes.STRING,
name: DataTypes.STRING,
title: DataTypes.STRING,
keyword: DataTypes.STRING,
describe: DataTypes.STRING,
pic_url: DataTypes.STRING,
is_enabled: DataTypes.INTEGER,
template_content: DataTypes.TEXT,
form_id: DataTypes.INTEGER,
business_code:DataTypes.STRING,
notes: DataTypes.STRING,
user_id: DataTypes.STRING(100),
user_name: DataTypes.STRING(100), //user_name 用户名称
company_id: DataTypes.INTEGER,
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'b_template_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");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
/**
* 模板信息表
*/
module.exports = (db, DataTypes) => {
//TODO:
return db.define("templatelink", {
code: DataTypes.STRING,
name: DataTypes.STRING,
delivery_word:DataTypes.STRING,
else_channel_param:DataTypes.STRING,
template_id: DataTypes.INTEGER,
// channel_id: DataTypes.INTEGER,
// business_type_id: DataTypes.INTEGER,
// lauch_type_id: DataTypes.INTEGER,
// marketing_subject_id: DataTypes.INTEGER,
// template_name: DataTypes.STRING,
channel_name: DataTypes.STRING,
business_type_name: DataTypes.STRING,
lauch_type_name: DataTypes.STRING,
marketing_subject_name: DataTypes.STRING,
channel_code: DataTypes.STRING,
business_type_code: DataTypes.STRING,
lauch_type_code: DataTypes.STRING,
marketing_subject_code: DataTypes.STRING,
is_enabled: DataTypes.INTEGER,
link_url_pc: DataTypes.STRING,
link_url_mobile: DataTypes.STRING,
notes: DataTypes.STRING,
user_id: DataTypes.STRING(100),
user_name: DataTypes.STRING(100), //user_name 用户名称
company_id: DataTypes.INTEGER,
}, {
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'b_template_link',
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");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
const fs=require("fs")
class AppService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(AppService));
this.userS = system.getObject("service.auth.userSve");
this.routeDao = system.getObject("db.common.routeDao");
this.ossC= system.getObject("util.ossClient");
}
async getApp(p) {
let app = this.cacheManager["AppCache"].cache(p.appkey, null);
return app;
}
async upFrontRoute(jsonObject,app_id){
var self=this
return this.db.transaction(async function (t) {
let keyfile=self.getUUID()+".json"
let tmpdirfile="/tmp"+keyfile
let str=JSON.stringify(jsonObject[0].children)
fs.writeFileSync(tmpdirfile,str)
let result=await self.ossC.upfile(keyfile,tmpdirfile)
fs.unlinkSync(tmpdirfile)
await self.db.models.app.update({docUrl:result.url,id:app_id},{where:{id:app_id},transaction:t})
return result
})
}
async findAllApps(uid) {
var apps = null;
var dicRtn = {};
var wheresql = {};
if (uid) {
wheresql[this.db.Op.and] = {
[this.db.Op.or]:
[
{ isPublish: false, creator_id: uid },
{ isEnabled: true, isPublish: true }
],
};
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl', 'homePage']
});
} else {
wheresql = { isEnabled: true, isPublish: true };
apps = await this.dao.model.findAll({
where: wheresql,
attributes: ['id', 'name', 'appkey', 'showimgUrl', 'appType', 'docUrl', 'homePage']
});
}
for (var app of apps) {
var tmk = uiconfig.config.pdict.app_type[app.appType];
if (!dicRtn[tmk]) {
dicRtn[tmk] = [];
dicRtn[tmk].push(app);
} else {
dicRtn[tmk].push(app);
}
}
return dicRtn;
}
//创建应用
//每个应用建立两个路由,一个api路由
//对api路由启用jwt插件
async create(pobj, qobj, req) {
var self = this;
return this.db.transaction(async function (t) {
var app = await self.dao.create(pobj, t);
//创建后台应用服务
let svobj = await self.cjsonregister(AppService.newServiceUrl(), { name: app.name, url: "http://" + app.backend })
//添加路由
let ps = ["/web/auth/userCtl/pmlogin", "/web/auth/userCtl/pmregister", "/web/auth/userCtl/pmSendVCode", "/web/auth/userCtl/pmloginByVCode"]
let routeobj = await self.cjsonregister(AppService.newRouteUrl(app.name),
{ name: app.name, paths: ps, hosts: [app.domainName], strip_path: false })
let ps2 = ["/api", "/web"]
let routeapi = await self.cjsonregister(AppService.newRouteUrl(app.name), { name: app.name + "_api", hosts: [app.domainName], paths: ps2, strip_path: false })
let r1 = await self.routeDao.create({ name: app.name, center_id: routeobj.id, app_id: app.id, shosts: app.domainName, spaths: ps.join(",") }, t);
let r2 = await self.routeDao.create({ name: app.name + "_api", center_id: routeapi.id, app_id: app.id, shosts: app.domainName, spaths: ps2.join(",") }, t);
//给api路由启动插件
await self.cjsonregister(AppService.bindPluginUrl(app.name + "_api"), { name: "jwt" })
if (svobj && routeobj && r1 && r2) {
try {
app.appkey = svobj.id;
await app.save({ transaction: t });
} catch (e) {
await self.cdel(AppService.routeUrl(app.name))
await self.cdel(AppService.routeUrl(app.name + "_api"))
await self.cdel(AppService.serviceUrl(app.name))
}
} else {
throw new Error("创建应用服务失败");
}
return app;
});
}
async translateInitSels(funcobjs) {
funcobjs.forEach((item) => {
console.log(item.title)
if (item.children && item.children.length>0) {
this.translateInitSels(item.children)
} else {
if(item.auths && item.auths.length>0){
item.sels=[]
}
}
})
}
async saveFuncTree(pobj){
var self = this;
return this.db.transaction(async function (t) {
//如果存在functionJSON,那么就需要转换,构建编码路径
if (pobj.funcJson) {
// let funcobjs = JSON.parse(pobj.functionJSON)
await self.translateInitSels(pobj.funcJson)
pobj.functionJSON= JSON.stringify(pobj.funcJson)
}
let appcache=await self.cacheManager["AppCache"].cache(pobj.appkey);
let upobj={id:appcache.id,functionJSON:pobj.functionJSON}
await self.dao.update(upobj, t)
//令缓存失效
await self.cacheManager["AppCache"].invalidate(pobj.appkey);
let appcache2=await self.dao.model.findById(appcache.id,{transaction:t});
return {funcJson:JSON.parse(appcache2.functionJSON)}
})
}
//删除应用
async update(pobj, qobj) {
var self = this;
return this.db.transaction(async function (t) {
//如果存在functionJSON,那么就需要转换,构建编码路径
if (pobj.functionJSON != "") {
let funcobjs = JSON.parse(pobj.functionJSON)
await self.translateWithBizCode(funcobjs,null)
pobj.functionJSON= JSON.stringify(funcobjs)
}
await self.dao.update(pobj, t)
let upobj = await self.dao.findById(pobj.id)
//令缓存失效
await self.cacheManager["AppCache"].invalidate(upobj.appkey);
return upobj
})
}
//删除应用
async delete(pobj, qobj) {
var self = this;
return this.db.transaction(async function (t) {
let delobj = await self.dao.delete(pobj, t)
//令缓存失效
await self.cacheManager["AppCache"].invalidate(delobj.appkey);
//删除路由
await self.cdel(AppService.routeUrl(pobj.name));
//删除api路由
await self.cdel(AppService.routeUrl(pobj.name + "_api"));
//删除服务
await self.cdel(AppService.serviceUrl(pobj.name));
return {}
})
}
async findAndCountAll(obj) {
var self = this;
const apps = await super.findAndCountAll(obj);
return apps;
}
}
module.exports = AppService;
// (async ()=>{
// let u=new AppService();
// // let x=await u.cregister("jiangong")
// // console.log(x)
// // let x=await u.cunregister("jiangong")
// // console.log(x)
// // let t=await u.cmakejwt()
// // console.log(t)
// //let ux=await u.cjsonregister(AppService.newRouteUrl("test-service2"),{name:"test-service2",hosts:["ttest1.com"]})
// //let ux=await u.cjsonregister(AppService.newServiceUrl(),{name:"test-service3",url:"http://zhichan.gongsibao.com"})
// //let ux=await u.cdel(AppService.routeUrl("test-service2"))
// //let ux=await u.cdel(AppService.serviceUrl("test-service2"))
// // let ux=await u.create({name:"test4-service",backend:"zhichan-service",domainName:"domain.com"})
// // console.log(ux);
// // let delrtn=await u.delete({id:2,name:"test4-service"})
// // console.log(delrtn);
// })()
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const uuidv4 = require('uuid/v4');
class CachSearchesSve {
constructor() {
this.cacheManager = system.getObject("db.common.cacheManager");
this.appDao = system.getObject("db.common.appDao");
this.authUtils = system.getObject("util.businessManager.authUtils");
}
getUUID() {
var uuid = uuidv4();
var u = uuid.replace(/\-/g, "");
return u;
}
async buildCacheRtn(pageValues) {
var ps = pageValues.map(k => {
var tmpList = k.split("|");
if (tmpList.length == 2) {
return { name: tmpList[0], val: tmpList[1], key: k };
}
});
return ps;
}
async findAndCountAllCache(obj) {
const pageNo = obj.pageInfo.pageNo;
const pageSize = obj.pageInfo.pageSize;
const limit = pageSize;
const offset = (pageNo - 1) * pageSize;
var search_name = obj.search && obj.search.name ? obj.search.name : "";
var cacheCacheKeyPrefix = "sadd_base_appkeys:" + settings.appKey + "_cachekey";
if (obj.appid == settings.platformid) {
var cacheList = await this.cacheManager["MagCache"].getCacheSmembersByKey(cacheCacheKeyPrefix);
if (search_name) {
cacheList = cacheList.filter(f => f.indexOf(search_name) >= 0);
}
var pageValues = cacheList.slice(offset, offset + limit);
var kobjs = await this.buildCacheRtn(pageValues);
var tmpList = { results: { rows: kobjs, count: cacheList.length } };
return system.getResult(tmpList);
} else {
var body = {
pageInfo: obj.pageInfo,
search: obj.search
};
var tmpList = await this.opOtherAppCache("findAndCountAll", body, obj.opCacheUrl);
return tmpList;
}
}
async delCache(obj) {
if (obj.appid == settings.platformid) {
var keyList = obj.key.split("|");
if (keyList.length == 2) {
var cacheCacheKeyPrefix = "sadd_base_appkeys:" + settings.appKey + "_cachekey";
await this.cacheManager["MagCache"].delCacheBySrem(cacheCacheKeyPrefix, obj.key);
await this.cacheManager["MagCache"].del(keyList[0]);
return { status: 0 };
}
} else {
var body = {
del_cachekey: obj.key
};
return await this.opOtherAppCache("delCache", body, obj.opCacheUrl);
}
}
async clearAllCache(obj) {
if (obj.appid == settings.platformid) {
await this.cacheManager["MagCache"].clearAll();
return { status: 0 };
}
return await this.opOtherAppCache("clearAllCache", {}, obj.opCacheUrl);
}
//app调用次数
async findAndCountAlldetail(obj) {
var apicallAccu = await this.cacheManager["ApiAccuCache"].getApiCallAccu(obj);
var result = { rows: [], count: 0 };
var keys = await this.cacheManager["MagCache"].keys("api_call_" + appkey + "*");
var detail = null;
for (let j = 0; j < keys.length; j++) {
var d = keys[j];
var pathdetail = d.substr(d.lastIndexOf("_") + 1, d.length);
var apicalldetailAccu = await this.cacheManager["ApiCallCountCache"].getApiCallCount(appkey, pathdetail);
var detail = { "detailPath": d, "detailCount": apicalldetailAccu.callcount };
}
result.rows = detail;
}
//操作别的应用的缓存
async opOtherAppCache(action_type, body = null, opCacheUrl) {
var appData = await this.authUtils.getTokenInfo(settings.appKey, settings.secret);
if (appData.status != 0) {
return appData;
}
//按照访问token
const restS = await system.getObject("util.restClient");
var restResult = await restS.execPostWithAK(
{
action_type: action_type,
body: body
},
opCacheUrl, appData.data.accessKey);
if (restResult && restResult.status == 0) {
return restResult;
}
return system.getResultFail();
}
}
module.exports = CachSearchesSve;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class CompanyService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(CompanyService));
}
async setOrgs(p,cmk) {
var self=this
return this.db.transaction(async function (t) {
let strjson = JSON.stringify(p.orgJson)
p.id = p.company_id
p.orgJson = strjson
//更新组织机构
let u = await self.dao.update(p,t)
//更新,还得传输当前节点,查询出当前节点的角色
//按照当前节点的opath查询出所有的用户,更新这些用户的角色信息
let curNodeData=p.curdata
if(curNodeData && curNodeData.isPosition){
let opathstr=curNodeData.orgpath
let us=await self.db.models.user.findAll({where:{opath:opathstr},transaction:t})
//查询出角色
let roleids=curNodeData.roles
let rs=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:roleids},app_id:p.app_id,company_id:p.company_id},transaction:t})
for(let u of us){
await u.setRoles(rs,{transaction:t})
}
// users.forEach((u)=>{
// await u.setRoles(rs, { transaction: t });
// })
}
//用户缓存也要失效
//缓存失效
await self.cacheManager["CompanyCache"].invalidate(cmk)
let companytmp=await self.dao.model.findOne({where:{companykey:cmk},transaction:t});
return {orgJson:JSON.parse(companytmp.orgJson)}
})
}
}
module.exports = CompanyService;
const system = require("../../../system");
const settings = require("../../../../config/settings");
// const fqBaseUrl="https://fq.gongsibao.com";//生产环境
const fqBaseUrl="https://fqdev.gongsibao.com";//测试环境
class FqUtilsService {
constructor() {
this.execClient = system.getObject("util.execClient");
this.logClient = system.getObject("util.logClient");
}
async pushNeedInfo2Fq(pobj,code){
try {
var url = fqBaseUrl+"/open/ex/flux/advisory?code="+code;
var rtn = await this.execClient.execPost(pobj, url);
var data = JSON.parse(rtn.stdout);
this.logClient.pushlog("测试数据---推送需求数据至蜂擎返回结果-pushNeedInfo2Fq-success",pobj, rtn, null);
return data;
} catch (e) {
this.logClient.pushlog("测试数据---推送需求数据至蜂擎返回异常-pushNeedInfo2Fq-error", pobj, null, e.stack);
return null;
}
}
}
module.exports = FqUtilsService;
\ No newline at end of file
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const settings=require("../../../../config/settings");
class MetaService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(MetaService));
this.restS=system.getObject("util.restClient");
}
async getApiDoc(appid){
var p=settings.basepath+"/app/base/db/impl/common/apiDocManager.js";
var ClassObj= require(p) ;
var obj=new ClassObj();
return obj.doc;
}
async getApiDocRemote(appid,docUrl){
var rtn=await this.restS.execPost({}, docUrl);
if(rtn.stdout){
var dod=JSON.parse(rtn.stdout);
if(dod.data){
return dod.data;
}
}
return null;
}
async getUiConfig(appid){
const cfg=await this.cacheManager["UIConfigCache"].cache(appid,null,60);
return cfg;
}
async getRemoteUiConfig(appkey,uiconfigUrl){
const cfg=await this.cacheManager["UIRemoteConfigCache"].cache(appkey,null,120,uiconfigUrl);
return cfg;
}
}
module.exports=MetaService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class PluginService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(AppService));
this.userS = system.getObject("service.auth.userSve");
}
}
module.exports = PluginService;
// (async ()=>{
// let u=new AppService();
// // let x=await u.cregister("jiangong")
// // console.log(x)
// // let x=await u.cunregister("jiangong")
// // console.log(x)
// // let t=await u.cmakejwt()
// // console.log(t)
// //let ux=await u.cjsonregister(AppService.newRouteUrl("test-service2"),{name:"test-service2",hosts:["ttest1.com"]})
// //let ux=await u.cjsonregister(AppService.newServiceUrl(),{name:"test-service3",url:"http://zhichan.gongsibao.com"})
// //let ux=await u.cdel(AppService.routeUrl("test-service2"))
// //let ux=await u.cdel(AppService.serviceUrl("test-service2"))
// // let ux=await u.create({name:"test4-service",backend:"zhichan-service",domainName:"domain.com"})
// // console.log(ux);
// // let delrtn=await u.delete({id:2,name:"test4-service"})
// // console.log(delrtn);
// })()
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const appconfig = system.getSysConfig();
class RouteService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(RouteService));
}
//创建应用
//每个应用建立两个路由,一个api路由
//对api路由启用jwt插件
async create(serviceName, routedata, req) {
var self = this;
return this.db.transaction(async function (t) {
var rtn=null;
try {
//添加路由
let routeobj = await self.cjsonregister(RouteService.newRouteUrl(serviceName), { name: routedata.name, hosts: routedata.hosts, paths: routedata.paths, strip_path: routedata.isstrip })
routedata.center_id = routeobj.id;
rtn = await self.dao.create(routedata, t);
} catch (e) {
console.log(e)
await self.cdel(RouteService.routeUrl(routedata.name));
}
return rtn;
});
}
async delete(qobj) {
var self = this;
return this.db.transaction(async function (t) {
let a=await self.dao.delete(qobj,t);
await self.cdel(RouteService.routeUrl(a.name));
return a
});
}
async findAndCountAll(obj) {
var self = this;
const apps = await super.findAndCountAll(obj);
return apps;
}
}
module.exports = RouteService;
// (async ()=>{
// let u=new AppService();
// // let x=await u.cregister("jiangong")
// // console.log(x)
// // let x=await u.cunregister("jiangong")
// // console.log(x)
// // let t=await u.cmakejwt()
// // console.log(t)
// //let ux=await u.cjsonregister(AppService.newRouteUrl("test-service2"),{name:"test-service2",hosts:["ttest1.com"]})
// //let ux=await u.cjsonregister(AppService.newServiceUrl(),{name:"test-service3",url:"http://zhichan.gongsibao.com"})
// //let ux=await u.cdel(AppService.routeUrl("test-service2"))
// //let ux=await u.cdel(AppService.serviceUrl("test-service2"))
// // let ux=await u.create({name:"test4-service",backend:"zhichan-service",domainName:"domain.com"})
// // console.log(ux);
// // let delrtn=await u.delete({id:2,name:"test4-service"})
// // console.log(delrtn);
// })()
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class BusinesstypeService extends ServiceBase {
constructor() {
super("configmag", ServiceBase.getDaoName(BusinesstypeService));
}
}
module.exports = BusinesstypeService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class FormitemService extends ServiceBase {
constructor() {
super("configmag", ServiceBase.getDaoName(FormitemService));
this.templateDao = system.getObject('db.template.templateinfoDao');
}
async getFormItemListByFormId(pobj){
if(!pobj || !pobj.form_id){
return system.getResultFail(-101,"表单id不能为空");
}
var list = await this.dao.model.findAll({
attributes:[["code","key"],["name","title"]],
where:{form_id:pobj.form_id,is_enabled:1},
raw:true,
order:[["sequence","asc"]]
});
return system.getResultSuccess(list);
}
/**
* 创建表单项
* @param pobj
* @returns {Promise<void>}
*/
async createItem(pobj) {
if(!pobj.name){
return system.getResultFail(-1,'表单项名称不能为空');
}
if(!pobj.sequence){
return system.getResultFail(-1,'排序不能为空')
}
let template = await this.templateDao.findOne({form_id:pobj.form_id},[]);
if(template && template.is_enabled == 1){
return system.getResultFail(-1,'表单已投入使用,不能新增表单项');
}
let configRet = await this.packageConfigParams(pobj);
if(configRet.status !== 0){
return configRet;
}
let code = await this.getBusUid('it');
pobj.config_params = configRet.data;
pobj.code = code;
//保存表单项
let result = await this.create(pobj);
return system.getResult(result)
}
/**
*
* @param pobj
* @returns {Promise<void>}
*/
async deleteItem(pobj){
let itemInfo = await this.findOne({id:pobj.id},[]);
if(['contact_mobile','contact_name'].includes(itemInfo.code)){
return system.getResultFail(-1,'默认表单项,不能删除');
}
let template = await this.templateDao.findOne({form_id:itemInfo.form_id},[]);
if(template && template.is_enabled == 1){
return system.getResultFail(-1,'表单已投入使用,不能删除表单项');
}
let delRet = await this.delete(pobj);
return system.getResult(delRet);
}
/**
* 修改表表单项
* @param pobj
* @returns {Promise<void>}
*/
async updateItem(pobj) {
//参数重组
if(!pobj.name){
return system.getResultFail(-1,'表单名称不能为空');
}
if(!pobj.sequence){
return system.getResultFail(-1,'表单排序不能为空')
}
let template = await this.templateDao.findOne({form_id:pobj.form_id},[]);
if(template && template.is_enabled == 1){
return system.getResultFail(-1,'表单已投入使用,不能修改表单项');
}
let configRet = await this.packageConfigParams(pobj);
if(configRet.status !== 0){
return configRet;
}
pobj.config_params = configRet.data;
if(['contact_mobile','contact_name'].includes(pobj.code)){
// return system.getResultFail(-1,'默认表单项,不能修改');
delete pobj["item_type"];
delete pobj["item_type_name"];
delete pobj["is_required"];
delete pobj["is_enabled"];
delete pobj["name"];
delete pobj["sequence"];
delete pobj["code"];
//item_type\item_type_name\is_required\is_enabled\name\sequence\code
}
let upResult = await this.update(pobj);
return system.getResult(upResult);
}
/**
* 组装表单项参数
* @param pobj
* @returns {Promise<void>}
*/
async packageConfigParams(pobj){
let config_params = {};
switch (pobj.item_type) {
case "phone":
if(!pobj.mobile_input_length){
return system.getResultFail(-1,'手机号位数选择有误');
}
config_params["mobile_input_length"]=pobj.mobile_input_length =="specific" ?1:2;
config_params["verify_sms"]=pobj.verify_sms==true?1:0;
break;
case "singleBtn":
case "multipleBtn":
case "downOptions":
if(!pobj.options){
return system.getResultFail(-1,'选项内容不能为空')
}
config_params["options"] = pobj.options;
break;
case "singleText":
case "multipleText":
if(!pobj.input_les || !pobj.input_lar){
return system.getResultFail(-1,'请填写字数限制');
}
if(pobj.input_lar<pobj.input_les){
return system.getResultFail(-1,'字数范围有误');
}
let length = []
length.push(pobj.input_les);
length.push(pobj.input_lar);
config_params["input_length"] = length;
break;
case "area":
config_params["is_show_county"] = pobj.is_show_county==true?1:0;
break;
default:
break;
}
return system.getResult(config_params);
}
}
module.exports = FormitemService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class FormsubmitrecordService extends ServiceBase {
constructor() {
super("configmag", ServiceBase.getDaoName(FormsubmitrecordService));
this.templateinfoDao = system.getObject("db.template.templateinfoDao");
this.templatelinkDao = system.getObject("db.template.templatelinkDao");
this.forminfoDao = system.getObject("db.configmag.forminfoDao");
this.formitemDao = system.getObject("db.configmag.formitemDao");
this.fqUtilsSve = system.getObject("service.common.fqUtilsSve");
this.execClient = system.getObject("util.execClient");
}
/**
* 提交表单记录
* @param {*} pobj
*/
async submitFormRecord(pobj) {
var ab = pobj.actionBody;
var xctx = pobj.xctx;
if (!ab) {
return system.getResultFail(-100, "参数错误");
}
if (!ab.link_code) {
return system.getResultFail(-101, "模板链接编码不能为空");
}
if (!ab.form_id) {
return system.getResultFail(-102, "表单id不能为空");
}
if (!ab.ali_code) {
return system.getResultFail(-103, "校验编码不能为空");
}
//获取模板链接信息
var linkInfo = await this.templatelinkDao.model.findOne({
where: { code: ab.link_code }, raw: true
});
if (!linkInfo || !linkInfo.id) {
return system.getResultFail(-300, "未知模板链接");
}
if (!linkInfo.template_id) {
return system.getResultFail(-301, "链接模板信息错误")
}
var templateinfo = await this.templateinfoDao.model.findOne({
where: { id: linkInfo.template_id }, raw: true,
attributes: ["id", "business_code"]
});
if (!templateinfo || !templateinfo.id) {
return system.getResultFail(-500, "未知模板信息");
}
//获取表单信息
var forminfo = await this.forminfoDao.model.findOne({
where: { id: ab.form_id }, raw: true
});
if (!forminfo || !forminfo.id) {
return system.getResultFail(-400, "未知表单")
}
//获取表单项
var formitems = await this.formitemDao.model.findAll({
where: { form_id: ab.form_id }, raw: true, order: [["sequence", "asc"]]
});
//校验封装参数
var res = await this.checkAndPackageFormItems(formitems, ab);
if (res && res.status && res.status < 0) {
return res;
}
var params = res;
var addObj = {
ali_code: ab.ali_code,
template_id: linkInfo.template_id, templatelink_id: linkInfo.id,
form_id: forminfo.id, record_status: 1, templatelink_snapshot: linkInfo,
form_snapshot: forminfo,
record_content: params, business_code: templateinfo.business_code,
push_status: 0
}
// if(ab.push_status==1){
// addObj.push_status=1;
// }
var createRes = await this.dao.create(addObj);//创建记录
this.pushNeed2Queue(createRes.id);
return system.getResultSuccess();
}
//推送需求至队列
async pushNeed2Queue(id) {
try {
if (!id) {
return;
}
var url = "http://sytxpublic-msgq-service.chaolai/api/queueAction/producer/springBoard";
var obj = {
"actionType": "produceData",// Y 功能名称
"actionBody": {
"pushUrl": "https://mmc.gongsibao.com/external/action/template/springBoard",// Y 推送地址
"actionType": "pushMarketplatFormInfo2Fq",// Y 推送地址接收时的功能名称
"identifyCode": "marketplat-pushneed2fq",// Y 操作的业务标识
"messageBody": { // Y 推送的业务消息,必须有一项对象属性值
"id": id
},
"headData":{"xappkey": "f6b59b74-f943-4735-bb86-e05d6b7fdwsv"} //N 请求头信息,Json格式,如:{token:"XXXXXXX"}
}
};
var result = await this.execClient.execPost(obj, url);
console.log(JSON.stringify(result), "result....push....");
} catch (e) {
console.log(e, "pushNeed2Queue++++++++++++++++++++++++++++++++++++")
}
}
/**
* 参数校验
* @param {*} formitems 表单项
* @param {*} ab 表单提交数据
*/
async checkAndPackageFormItems(formitems, ab) {
var params = {};
for (var i = 0; i < formitems.length; i++) {
var item = formitems[i];
var itemConfig = item.config_params;
if (item && item.code && item.is_enabled) {//显示状态的表单项
var value = ab[item.code];
if (item.is_required === 1) {//必填
if (!ab[item.code] || ab[item.code].length < 1) {
return system.getResultFail(-100, item.name + "参数不能为空");
}
}
if (itemConfig.mobile_input_length === 1) {//手机号 1:限定11位 2:限定7-11位
if (value && value.length != 11) {
return system.getResultFail(-101, item.name + "参数限定11位");
}
}
if (itemConfig.mobile_input_length === 2) {//手机号 1:限定11位 2:限定7-11位
if (value && (value.length < 7 || value.length > 11)) {
return system.getResultFail(-102, item.name + "参数限定7-11位");
}
}
if (itemConfig.input_length && itemConfig.input_length.length == 2) {//输入长度区间
if (value && (value.length < itemConfig.input_length[0] || value.length > itemConfig.input_length[1])) {
return system.getResultFail(-103, item.name + "参数输入长度为" + itemConfig.input_length[0] + "-" + itemConfig.input_length[1] + "位");
}
}
params[item.code] = value;
}
}
return params;
}
//将需求信息推送至蜂擎
async pushFormInfo2Fq() {
var limit = 100;
var formRecords = await this.dao.model.findAll({
attributes: ["id", "templatelink_snapshot", "form_snapshot", "ali_code", "record_content"],
where: {
push_status: 0,
ali_code: { [this.db.Op.ne]: null }, form_snapshot: { [this.db.Op.ne]: null },
ali_code: { [this.db.Op.ne]: '' }, templatelink_snapshot: { [this.db.Op.ne]: null },
record_content: { [this.db.Op.ne]: null }
},
limit: limit,
order: [["id", "asc"]],
raw: true
});
var recordList = await this.packageRecordList(formRecords);
for (var a = 0; a < recordList.length; a++) {
var pushRes = await this.fqUtilsSve.pushNeedInfo2Fq(recordList[a], recordList[a].code);
console.log(pushRes, "pushRes############################3");
if (pushRes && pushRes.data && pushRes.data == "success") {//推送成功
await this.dao.update({ id: recordList[a].id, push_status: 1 });
} else {
await this.dao.update({ id: recordList[a].id, push_status: 2 });
}
}
}
//封装表单记录信息
async packageRecordList(formRecords) {
var recordList = [];
for (var i = 0; i < formRecords.length; i++) {
var fr = formRecords[i];
var rc = fr.record_content;
var linkinfo = fr.templatelink_snapshot;
var forminfo = fr.form_snapshot;
if (forminfo && forminfo.form_table && forminfo.form_table.main && forminfo.form_table.main[0] && forminfo.form_table.main[0].ctls) {
var ctls = forminfo.form_table.main[0].ctls;
var pushInfo = {
id: fr.id,
customer_name: rc.contact_name, customer_phone: rc.contact_mobile, source: "marketplat",
source_type: linkinfo.name || "未知", code: fr.ali_code
};
var advisory_content = "";
for (var j = 0; j < ctls.length; j++) {
var ctl = ctls[j];
if (ctl.label && ctl.prop && rc[ctl.prop]) {
advisory_content = advisory_content + ctl.label + ":" + rc[ctl.prop] + ";"
}
}
pushInfo["advisory_content"] = advisory_content || "未知";
recordList.push(pushInfo);
}
}
return recordList;
}
}
module.exports = FormsubmitrecordService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class ImginfoService extends ServiceBase {
constructor() {
super("configmag", ServiceBase.getDaoName(ImginfoService));
}
async getImgList(pobj) {
let res = await this.dao.findAndCountAll(pobj);
return system.getResultSuccess(res);
}
async createImginfo(pobj) {
let code = await this.getBusUid("img");
pobj.imginfo.code = code;
if (pobj.imginfo.company_id === undefined) {
pobj.imginfo.company_id = 10;
}
let res = await this.dao.create(pobj.imginfo);
return system.getResultSuccess(res);
}
async create(pobj) {
let code = await this.getBusUid("img");
pobj.code = code;
if (!pobj.pic_url) {
return system.getResultFail(-123, "图片不能为空");
}
return system.getResultSuccess(this.dao.create(pobj));
}
async update(pobj) {
let whereParams = {
id: pobj.id
}
let res = await this.dao.findOne(whereParams,[]);
if(!pobj.id){
return system.getResultFail(-124, "未知图片信息");
}
if(!pobj.pic_url){
pobj.pic_url = res.pic_url;
}
if(!pobj.pic_size){
pobj.pic_size = res.pic_size;
}
if(!pobj.name){
pobj.name = res.name;
}
return system.getResultSuccess(this.dao.update(pobj));
}
}
module.exports = ImginfoService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
class LaunchchannelService extends ServiceBase {
constructor() {
super("configmag", ServiceBase.getDaoName(LaunchchannelService));
this.templatelinkSve = system.getObject("service.template.templatelinkSve");
}
/**
* 根据company_id 和 code 去重
* @param pobj
* @returns {Promise<{msg: string, data: *, bizmsg: string, status: number}|{msg: *, data: *, status: *}>}
*/
async createChannel(pobj) {
if (!pobj.company_id) {
return system.getResultFail(-1, 'company_id can not be empty');
}
if (!pobj.name) {
return system.getResultFail(-1, 'name can not be empty');
}
if (!pobj.code) {
return system.getResultFail(-1, 'code can not be empty');
}
let whereParams = {
code: pobj.code,
company_id: pobj.company_id
}
let searchResult = await this.findOne(whereParams, []);
if (searchResult) {
return system.getResultFail(-1,'渠道已存在,请勿重复添加');
}
let channelData = {
name: pobj.name,
code: pobj.code,
user_id: pobj.userid,
user_name: pobj.username,
company_id: pobj.company_id
}
let result = await this.create(channelData);
return system.getResult(result);
}
/**
* 编辑渠道
* @param pobj
* @returns {Promise<void>}
*/
async updateChannel(pobj){
let link = await this.templatelinkSve.findAll({channel_code:pobj.code,is_enabled:1},[]);
if(link.length>0){
return system.getResultFail(-1,'该业务正在投放中,不能修改');
}
let up = await this.update(pobj);
return system.getResult(up);
}
/**
* 删除
* @param pobj
* @returns {Promise<void>}
*/
async deleteChannel(pobj){
let channael = await this.findOne({id:pobj.id},['code'])
let link = await this.templatelinkSve.findAll({channel_code:channael.code},[]);
if(link.length>0){
return system.getResultFail(-1,'该业务正在投放中,不能删除');
}
let de = await this.delete(pobj);
return system.getResult(de);
}
//根据渠道编码获取渠道信息(用于媒体聚合页移动端)
async getSourceChannelInfo(pobj){
if(!pobj || !pobj.actionBody){
return system.getResultSuccess(-100,"参数错误");
}
if(!pobj.actionBody.code){
return system.getResultSuccess(-101,"来源渠道编码错误");
}
var channelinfo = await this.dao.model.findOne({
attributes:["code","name"],
where:{code:pobj.actionBody.code},raw:true
});
if(!channelinfo || !channelinfo.code){
return system.getResultFail(-300,"未知渠道")
}
return system.getResultSuccess(channelinfo);
}
}
module.exports = LaunchchannelService;
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const { getResultSuccess } = require("../../../system");
class MaininfoService extends ServiceBase {
constructor() {
super("configmag", ServiceBase.getDaoName(MaininfoService));
this.templateLink = system.getObject("db.template.templatelinkDao");
}
async create(pobj) {
if (!pobj.name) {
return system.getResultFail(-101, 'name can not be empty');
}
if (!pobj.code) {
return system.getResultFail(-102, 'code can not be empty');
}
let whereParams = {
code: pobj.code,
}
let searchResult = await this.findOne(whereParams, []);
if (searchResult) {
return system.getResultFail(-103, '主体参数已存在,请勿重复添加');
}
return system.getResultSuccess(this.dao.create(pobj));
}
async update(pobj) {
let whereParams = {
id: pobj.id
}
let searchResult = await this.findOne(whereParams, []);
if (searchResult && searchResult.code) {
let linkWhere = {
marketing_subject_code: searchResult.code,
is_enabled: 1
}
let searchLink = await this.templateLink.findOne(linkWhere, []);
if (searchLink) {
return system.getResultFail(-104, '该业务正在投放中,不能修改');
}
}
return system.getResultSuccess(this.dao.update(pobj));
}
async delete(pobj) {
let whereParams = {
id: pobj.id
}
let searchResult = await this.findOne(whereParams, []);
if (searchResult && searchResult.code) {
let linkWhere = {
marketing_subject_code: searchResult.code,
is_enabled: 1
}
let searchLink = await this.templateLink.findOne(linkWhere, []);
if (searchLink) {
return system.getResultFail(-105, '该业务正在投放中,不能删除');
}
}
return system.getResultSuccess(this.dao.delete(pobj));
}
}
module.exports = MaininfoService;
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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