Commit 6c5ca1fb by Sxy

fix: 代码规范

parent 73a0f6a4
......@@ -8,7 +8,7 @@ class APIBase {
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
const u = uuid.replace(/-/g, '');
return u;
}
async setContextParams(pobj, qobj, req) {
......
......@@ -26,7 +26,13 @@ class AccessAuthAPI extends APIBase {
return system.getResult(s);
}
async getBizUserForDelivery(p, q, req) {
const s = await this.userSve.getBizUserForDelivery(p.clientMobile, p.spName, p.productCatName, p.skucode, p.regionName);
const s = await this.userSve.getBizUserForDelivery(
p.clientMobile,
p.spName,
p.productCatName,
p.skucode,
p.regionName,
);
return system.getResult(s);
}
classDesc() {
......
......@@ -34,19 +34,19 @@ class OSSAPI extends APIBase {
};
return system.getResult(data);
};
}
async upfile(srckey, dest) {
const oss = System.getObject('util.ossClient');
const result = await oss.upfile(srckey, `/tmp/${dest}`);
return result;
};
}
async downfile(srckey) {
const oss = System.getObject('util.ossClient');
var downfile = await oss.downfile(srckey).then(() => {
let downfile = await oss.downfile(srckey).then(() => {
downfile = `/tmp/${srckey}`;
return downfile;
});
return downfile;
};
}
}
module.exports = OSSAPI;
......@@ -10,7 +10,7 @@ class CtlBase {
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
const u = uuid.replace(/-/g, '');
return u;
}
static getServiceName(ClassObj) {
......
......@@ -79,9 +79,6 @@ class AppCtl extends CtlBase {
// pobj.password=super.encryptPasswd(settings.defaultpwd);
// 构造默认的应用相关的URL
pobj.authUrl = `${settings.protocalPrefix + pobj.domainName}/auth`;
// 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";
const app = await super.create(pobj, queryobj, req);
return system.getResult(app);
}
......
......@@ -12,15 +12,18 @@ class CachSearchesCtl extends CtlBase {
async findAndCountAll(pobj, gobj, req) {
pobj.opCacheUrl = req.session.app.opCacheUrl;
pobj.appid = req.appid;
return await this.service.findAndCountAllCache(pobj);
const result = await this.service.findAndCountAllCache(pobj);
return result;
}
async delCache(queryobj, qobj, req) {
const param = { key: queryobj.key, appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.delCache(param);
const result = await this.service.delCache(param);
return result;
}
async clearAllCache(queryobj, qobj, req) {
const param = { appid: req.appid, opCacheUrl: req.session.app.opCacheUrl };
return await this.service.clearAllCache(param);
const result = await this.service.clearAllCache(param);
return result;
}
}
module.exports = CachSearchesCtl;
......@@ -72,7 +72,8 @@ class CompanyCtl extends CtlBase {
}
async getWatchOrgNodes(p, q, req) {
return await this.service.getWatchOrgNodes(p.company_id);
const result = await this.service.getWatchOrgNodes(p.company_id);
return result;
}
async refQuery(pobj, qobj, req) {
......
......@@ -11,7 +11,7 @@ class OplogCtl extends CtlBase {
async initNewInstance(qobj) {
const u = uuidv4();
const aid = u.replace(/\-/g, '');
const aid = u.replace(/-/g, '');
const rd = { name: '', appid: aid };
return system.getResult(rd);
}
......@@ -40,7 +40,7 @@ class OplogCtl extends CtlBase {
返回20位业务订单号
prefix:业务前缀
*/
async getBusUid_Ctl(prefix) {
async getBusUidCtl(prefix) {
prefix = (prefix || '');
if (prefix) {
prefix = prefix.toUpperCase();
......@@ -49,7 +49,7 @@ prefix:业务前缀
const subLen = 8 - prefixlength;
let uidStr = '';
if (subLen > 0) {
uidStr = await this.getUidInfo_Ctl(subLen, 60);
uidStr = await this.getUidInfoCtl(subLen, 60);
}
const timStr = moment().format('YYYYMMDDHHmm');
return prefix + timStr + uidStr;
......@@ -58,7 +58,7 @@ prefix:业务前缀
len:返回长度
radix:参与计算的长度,最大为62
*/
async getUidInfo_Ctl(len, radix) {
async getUidInfoCtl(len, radix) {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');// 长度62,到yz长度为长36
const uuid = []; let i;
radix = radix || chars.length;
......@@ -66,7 +66,10 @@ prefix:业务前缀
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
let r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[23] = '-';
uuid[18] = uuid[23];
uuid[13] = uuid[18];
uuid[8] = uuid[13];
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
......
......@@ -40,11 +40,11 @@ class PushCtl extends CtlBase {
return system.getResult({
results: {
count: rtn.totalCount,
rows: rtn && rtn.data || [],
rows: (rtn && rtn.data) || [],
},
});
}
return system.getResultFail(rtn && rtn.message || '请联系管理员');
return system.getResultFail((rtn && rtn.message) || '请联系管理员');
}
return system.getResultFail(rtn);
}
......
const system = require('../../../system');
const settings = require('../../../../config/settings');
class SocketNotifyCtl {
constructor() {
}
setSocketServer(s) {
this.socketServer = s;
}
......
......@@ -38,7 +38,7 @@ class UploadCtl extends CtlBase {
};
return data;
};
}
async upfile(srckey, dest) {
const oss = system.getObject('util.ossClient');
const result = await oss.upfile(srckey, `/tmp/${dest}`);
......@@ -46,12 +46,12 @@ class UploadCtl extends CtlBase {
};
async downfile(srckey) {
const oss = system.getObject('util.ossClient');
var downfile = await oss.downfile(srckey).then(() => {
let downfile = await oss.downfile(srckey).then(() => {
downfile = `/tmp/${srckey}`;
return downfile;
});
return downfile;
};
}
async pdf2html(obj) {
const srckey = obj.key;
const downfile = await this.downfile(srckey);
......@@ -62,10 +62,11 @@ class UploadCtl extends CtlBase {
fs.unlink(`/tmp/${srckey}`);
const result = await this.upfile(`${srckey.split('.pdf')[0]}.html`, `${srckey.split('.pdf')[0]}.html`);
return result.url;
};
}
async insertToFile(path) {
const cmd = `${this.cmdInsertToFilePattern} ${path}`;
return await this.restS.exec(cmd);
};
const result = await this.restS.exec(cmd);
return result;
}
}
module.exports = UploadCtl;
......@@ -15,8 +15,9 @@ class logCtl extends CtlBase {
return system.getResult({
results: {
count: rtn.totalCount,
rows: rtn && rtn.list && rtn.list.map((item) => {
let { opTitle, identifyCode, messageBody, resultInfo, errorInfo, requestId, created_at } = item;
rows: (rtn && rtn.list && rtn.list.map((item) => {
let { messageBody, resultInfo } = item;
const { opTitle, identifyCode, errorInfo, requestId, created_at } = item;
messageBody = messageBody ? JSON.parse(messageBody) : {};
resultInfo = resultInfo ? JSON.parse(resultInfo) : {};
let status;
......@@ -31,7 +32,7 @@ class logCtl extends CtlBase {
return {
opTitle,
url: `${messageBody.gname}/${messageBody.qname}/${messageBody.method}`,
user: messageBody.param && messageBody.param.username || '',
user: (messageBody.param && messageBody.param.username) || '',
ip: messageBody.param && messageBody.param.clientIp,
created_at,
requestId,
......@@ -40,7 +41,7 @@ class logCtl extends CtlBase {
opTitle, identifyCode, messageBody, resultInfo, errorInfo, requestId, created_at,
},
};
}) || [],
})) || [],
},
});
} catch (err) {
......
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;
......@@ -44,19 +44,25 @@ class Dao {
}
async bulkDelete(ids, t) {
if (t) {
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } }, transaction: t });
const en = await this.model.destroy({
where: {
id: { [this.db.Op.in]: ids },
}, transaction: t,
});
return en;
}
var en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
const en = await this.model.destroy({ where: { id: { [this.db.Op.in]: ids } } });
return en;
}
async bulkDeleteByWhere(whereParam, t) {
const en = null;
if (t != null && t != 'undefined') {
whereParam.transaction = t;
return await this.model.destroy(whereParam);
const result = await this.model.destroy(whereParam);
return result;
}
return await this.model.destroy(whereParam);
const result = await this.model.destroy(whereParam);
return result;
}
async delete(qobj, t) {
let en = null;
......@@ -204,7 +210,8 @@ class Dao {
if (t != null && t != 'undefined') {
return await this.model.bulkCreate(ids, { transaction: t });
}
return await this.model.bulkCreate(ids);
const result = await this.model.bulkCreate(ids);
return result;
}
async updateByWhere(setObj, whereObj, t) {
......@@ -225,7 +232,7 @@ class Dao {
return this.db.query(sql, paras);
}
async customQuery(sql, paras, t) {
let tmpParas = null;// ||paras=='undefined'?{type: this.db.QueryTypes.SELECT }:{ replacements: paras, type: this.db.QueryTypes.SELECT };
let tmpParas = null;
if (t && t != 'undefined') {
if (paras == null || paras == 'undefined') {
tmpParas = { type: this.db.QueryTypes.SELECT };
......@@ -264,7 +271,8 @@ class Dao {
} else {
tmpWhere.raw = true;
}
return await this.model.findAndCountAll(tmpWhere);
const result = await this.model.findAndCountAll(tmpWhere);
return result;
}
async findOne(obj, attributes = []) {
if (attributes.length > 0) {
......
......@@ -5,7 +5,7 @@ class RoleDao extends Dao {
super(Dao.getModelName(RoleDao));
}
async findOne(paramappid, t) {
const app = await this.model.findOne({ where: { appid: paramappid } }, { transaction: t });
const app = await this.model.findOne({ where: { appid: paramappid } }, { transaction: t });
return app;
}
extraWhere(obj, w, qc, linkAttrs) {
......@@ -38,10 +38,10 @@ class RoleDao extends Dao {
const self = this;
const u2 = await this.preCreate(u);
if (t) {
var role = await this.model.create(u2, { transaction: t });
const role = await this.model.create(u2, { transaction: t });
return role;
}
var role = await this.model.create(u2);
const role = await this.model.create(u2);
return role;
}
}
......
......@@ -72,18 +72,6 @@ class DbFactory {
/* 建立用户和角色之间的关系*/
this.db.models.user.belongsToMany(this.db.models.role, { as: 'Roles', through: 'p_userrole', constraints: false });
this.db.models.role.belongsToMany(this.db.models.user, { as: 'Users', through: 'p_userrole', constraints: false });
/* 组织机构自引用*/
// this.db.models.org.belongsTo(this.db.models.org,{constraints: false,});
// this.db.models.org.hasMany(this.db.models.org,{constraints: false,});
// 组织机构和角色是多对多关系,建立兼职岗位,给岗位赋予多个角色,从而同步修改用户的角色
// 通过岗位接口去修改用户的角色
// this.db.models.role.belongsToMany(this.db.models.org,{through: this.db.models.orgrole,constraints: false,});
// this.db.models.org.belongsToMany(this.db.models.role,{through: this.db.models.orgrole,constraints: false,});
// 组织机构和用户是1对多,
// this.db.models.user.belongsTo(this.db.models.org,{constraints: false,});
// this.db.models.org.hasMany(this.db.models.user,{constraints: false,});
this.db.models.user.belongsTo(this.db.models.app, { constraints: false });
this.db.models.role.belongsTo(this.db.models.app, { constraints: false });
......@@ -129,7 +117,7 @@ class DbFactory {
}
// async getCon(){,用于使用替换table模型内字段数据使用
getCon() {
const that = this;
// const that = this;
// await this.db.authenticate().then(()=>{
// console.log('Connection has been established successfully.');
// }).catch(err => {
......@@ -137,20 +125,9 @@ class DbFactory {
// throw err;
// });
// 同步模型
if (settings.env == 'dev') {
// 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;
}
}
......
......@@ -8,7 +8,7 @@ class MsgNoticeDao extends Dao {
async saveNotice(msg, t) {
let noticeFrom = await super.findOne({ fromId: msg.senderId, toId: msg.targetId });
if (noticeFrom) {
var set = { lastMsgId: msg.id };
const set = { lastMsgId: msg.id };
if (msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
......@@ -28,7 +28,7 @@ class MsgNoticeDao extends Dao {
let noticeTo = await super.findOne({ fromId: msg.targetId, toId: msg.senderId });
if (noticeTo) {
var set = { lastMsgId: msg.id };
const set = { lastMsgId: msg.id };
if (msg.businessLicense_id) {
set.businessLicense_id = msg.businessLicense_id;
}
......
......@@ -19,7 +19,6 @@ class ProductDao extends Dao {
return w;
}
extraModelFilter() {
// return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {
key: 'include', value: [
{ model: this.db.models.productprice, as: 'skus', attributes: ['id', 'pricestrategy_id'] }],
......
......@@ -5,9 +5,10 @@ class ProductcostDao extends Dao {
super(Dao.getModelName(ProductcostDao));
}
extraModelFilter() {
// return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return { key: 'include', value: [
{ model: this.db.models.productprice, attributes: ['id', 'lowpriceref'] }] };
return {
key: 'include', value: [
{ model: this.db.models.productprice, attributes: ['id', 'lowpriceref'] }],
};
}
}
module.exports = ProductcostDao;
......
......@@ -19,10 +19,11 @@ class ProductpriceDao extends Dao {
return w;
}
extraModelFilter() {
// return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return { key: 'include', value: [
{ model: this.db.models.pricestrategy, attributes: ['id', 'optionunion'] },
{ model: this.db.models.product, attributes: ['id', 'name'] }] };
return {
key: 'include', value: [
{ model: this.db.models.pricestrategy, attributes: ['id', 'optionunion'] },
{ model: this.db.models.product, attributes: ['id', 'name'] }],
};
}
}
module.exports = ProductpriceDao;
......
......@@ -22,7 +22,12 @@ db.sync({ force: true }).then(async () => {
// await Role.create({ code: "ta", name: "租户", isSystem: true, app_id: appnew.id, company_id: settings.pmcompanyid })
// await Role.create({ code: "pr", name: "个人", isSystem: true, app_id: appnew.id, company_id: settings.pmcompanyid })
// let usuper = await usS.pmregister({ userName: "sm", password: "951753", isSuper: true, isAdmin: true, isSystem: true, isEnabled: true, nickName: "superman", app_id: appnew.id, company_id: settings.id })
// const usuper = await usS.pmregister({
// userName: 'sm', password: '951753',
// isSuper: true, isAdmin: true, isSystem: true,
// isEnabled: true, nickName: 'superman',
// app_id: appnew.id, company_id: settings.id
// });
// appnew.creator_id = usuper.user.id
// await appnew.save()
......
......@@ -11,9 +11,10 @@ class AuthService extends ServiceBase {
// var newattrs=rolecodestr.split(",");
const aths = await this.dao.model.findAll({
attributes: ['bizcode', 'authstrs', 'codepath'],
where: { role_id: { [this.db.Op.in]: roleids } } });
// 因为是按照角色ID,所以不需要按照公司
// where:{role_id:{[this.db.Op.in]:roleids},app_id:appid,company_id:comid}});
where: { role_id: { [this.db.Op.in]: roleids } },
});
// 因为是按照角色ID,所以不需要按照公司
// where:{role_id:{[this.db.Op.in]:roleids},app_id:appid,company_id:comid}});
return aths;
}
async saveAuths(auths, appid, cmid) {
......@@ -22,8 +23,8 @@ class AuthService extends ServiceBase {
console.log('yyyyyyyyyvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv');
console.log(auths);
return self.db.transaction(async (t) => {
for (let i = 0;i < auths.length;i++) {
var tmpAuth = auths[i];
for (let i = 0; i < auths.length; i++) {
const tmpAuth = auths[i];
tmpAuth.app_id = appid;
tmpAuth.company_id = cmid;
const objrtn = await self.dao.model.findOrCreate({
......@@ -35,10 +36,25 @@ class AuthService extends ServiceBase {
console.log(objrtn);
if (!objrtn[1].created) {
// 就执行更新操作
await objrtn[0].update(tmpAuth, { where: { role_id: tmpAuth.role_id, bizcode: tmpAuth.bizcode }, transaction: t });
await objrtn[0].update(
tmpAuth,
{
where:
{
role_id: tmpAuth.role_id, bizcode: tmpAuth.bizcode,
},
transaction: t,
},
);
}
}
const aths = await self.dao.model.findAll({ where: { role_id: tmpAuth.role_id, app_id: tmpAuth.app_id }, transaction: t });
const aths = await self.dao.model.findAll({
where: {
role_id: tmpAuth.role_id,
app_id: tmpAuth.app_id,
},
transaction: t,
});
return aths;
});
}
......
......@@ -11,7 +11,7 @@ class OrgService extends ServiceBase {
const uone = await this.db.models.user.findOne({ where: { org_id: orgid } });
if (!uone) {
// 先检查是否组织下有人员存在
return this.db.transaction(async (t) => {
return this.db.transaction(async (t) => {
const inst = await self.dao.model.findById(orgid);
const parentid = inst.org_id;
await inst.destroy({ force: true, transaction: t });
......@@ -22,10 +22,13 @@ class OrgService extends ServiceBase {
order: [['code', 'ASC']],
where: { id: parentid }, transaction: t,
include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']] },
] },
] });
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']] },
],
},
],
});
return orgparent.orgs;
});
}
......@@ -34,14 +37,14 @@ class OrgService extends ServiceBase {
async update(p, q, req) {
const self = this;
const cmkey = p.comkey;// 如果是来自租户界面的修改
return this.db.transaction(async (t) => {
return this.db.transaction(async (t) => {
p.isLeaf = p.isPosition;
const orgupdate = await self.dao.model.findOne({ where: { id: p.id }, transaction: t });
await self.dao.model.update(p, { where: { id: p.id }, transaction: t });
const usersupdate = await self.db.models.user.findAll({ where: { org_id: orgupdate.id } });
// 如果节点名称或岗位性质发生变化
// if(p.name!=orgupdate.name || p.isMain!=orgupdate.isMain){
for (var ud of usersupdate) {
for (const ud of usersupdate) {
ud.opath = p.orgpath;
const n = p.orgpath.lastIndexOf('/');
ud.ppath = p.isMain ? p.orgpath.substring(0, n) : p.orgpath;
......@@ -52,7 +55,7 @@ class OrgService extends ServiceBase {
const roles = await self.db.models.role.findAll({ where: { id: { [self.db.Op.in]: p.Roles } } });
await orgupdate.setRoles(roles, { transaction: t });
// 同时要给这个岗位下的user,更新角色 todo
for (var ud of usersupdate) {
for (const ud of usersupdate) {
await ud.setRoles(roles, { transaction: t });
}
}
......@@ -60,14 +63,19 @@ class OrgService extends ServiceBase {
order: [['code', 'ASC']],
where: { id: orgupdate.org_id }, transaction: t,
include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
],
},
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
],
},
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] });
],
});
return orgparent.orgs;
});
}
......@@ -78,10 +86,10 @@ class OrgService extends ServiceBase {
}
return null;
}
async changePos(toorgid, uid) {
async changePos(toorgid, uid) {
// 查询出当前用户,设置当前用户的orgid为修改目标
const self = this;
return this.db.transaction(async (t) => {
return this.db.transaction(async (t) => {
const ufind = await self.db.models.user.findById(uid);
......@@ -89,7 +97,8 @@ class OrgService extends ServiceBase {
where: { id: toorgid },
include: [
{ model: self.db.models.role, as: 'roles' },
] });
],
});
ufind.org_id = toorgid;
ufind.opath = org.orgpath;
if (org.isMain) { // 如果是主岗
......@@ -110,9 +119,9 @@ class OrgService extends ServiceBase {
const self = this;
const cmkey = p.comkey;
return this.db.transaction(async (t) => {
return this.db.transaction(async (t) => {
if (cmkey) {
const tmpcompany = await self.db.models.company.findOne({ where: { companykey: cmkey }, transaction: t });
const tmpcompany = await self.db.models.company.findOne({ where: { companykey: cmkey }, transaction: t });
p.company_id = tmpcompany.id;
}
const roles = await self.db.models.role.findAll({ where: { id: { [self.db.Op.in]: p.Roles } } });
......@@ -126,15 +135,20 @@ class OrgService extends ServiceBase {
order: [['code', 'ASC']],
where: { id: orgnew.org_id }, transaction: t,
include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
],
},
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
],
},
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] });
],
});
return orgparent.orgs;
});
}
......@@ -143,32 +157,42 @@ class OrgService extends ServiceBase {
order: [['code', 'ASC']],
where: { id },
include: [
{ model: this.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: this.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: this.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: this.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: this.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
],
},
{ model: this.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
{ model: this.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
],
},
{ model: this.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] });
],
});
return org.orgs;
}
async initOrgs(company, appid) {
const self = this;
return this.db.transaction(async (t) => {
return this.db.transaction(async (t) => {
const org = await self.dao.model.findOne({
order: [['code', 'ASC']],
// where:{name:company.name,company_id:company.id,app_id:appid},transaction:t,
where: { name: company.name, company_id: company.id }, transaction: t,
include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{
model: self.db.models.org, as: 'orgs', order: [['code', 'ASC']], include: [
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
],
},
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] },
],
},
{ model: self.db.models.role, as: 'roles', attributes: ['id', 'code', 'name'] },
] });
],
});
if (org != null) {
return org;
}
......
......@@ -19,7 +19,8 @@ class RoleService extends ServiceBase {
if (!data) {
throw new Error('无权限');
}
return await this.dao.update(qobj);
const result = await this.dao.update(qobj);
return result;
}
async delete(qobj) {
......@@ -32,7 +33,8 @@ class RoleService extends ServiceBase {
if (!data) {
throw new Error('无权限');
}
return await this.dao.delete(qobj);
const result = await this.dao.delete(qobj);
return result;
}
}
module.exports = RoleService;
......@@ -10,7 +10,7 @@ class CachSearchesSve {
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
const u = uuid.replace(/-/g, '');
return u;
}
async buildCacheRtn(pageValues) {
......@@ -27,24 +27,24 @@ class CachSearchesSve {
const { pageSize } = obj.pageInfo;
const limit = pageSize;
const offset = (pageNo - 1) * pageSize;
const search_name = obj.search && obj.search.name ? obj.search.name : '';
const searchName = obj.search && obj.search.name ? obj.search.name : '';
const cacheCacheKeyPrefix = `sadd_base_appkeys:${settings.appKey}_cachekey`;
if (obj.appid == settings.platformid) {
let cacheList = await this.cacheManager.MagCache.getCacheSmembersByKey(cacheCacheKeyPrefix);
if (search_name) {
cacheList = cacheList.filter(f => f.indexOf(search_name) >= 0);
if (searchName) {
cacheList = cacheList.filter(f => f.indexOf(searchName) >= 0);
}
const pageValues = cacheList.slice(offset, offset + limit);
const kobjs = await this.buildCacheRtn(pageValues);
var tmpList = { results: { rows: kobjs, count: cacheList.length } };
const tmpList = { results: { rows: kobjs, count: cacheList.length } };
return system.getResult(tmpList);
}
const body = {
pageInfo: obj.pageInfo,
search: obj.search,
};
var tmpList = await this.opOtherAppCache('findAndCountAll', body, obj.opCacheUrl);
const tmpList = await this.opOtherAppCache('findAndCountAll', body, obj.opCacheUrl);
return tmpList;
}
async delCache(obj) {
......@@ -60,7 +60,8 @@ class CachSearchesSve {
const body = {
del_cachekey: obj.key,
};
return await this.opOtherAppCache('delCache', body, obj.opCacheUrl);
const result = await this.opOtherAppCache('delCache', body, obj.opCacheUrl);
return result;
}
}
async clearAllCache(obj) {
......@@ -68,24 +69,25 @@ class CachSearchesSve {
await this.cacheManager.MagCache.clearAll();
return { status: 0 };
}
return await this.opOtherAppCache('clearAllCache', {}, obj.opCacheUrl);
const result = await this.opOtherAppCache('clearAllCache', {}, obj.opCacheUrl);
return result;
}
// app调用次数
async findAndCountAlldetail(obj) {
const apicallAccu = await this.cacheManager.ApiAccuCache.getApiCallAccu(obj);
const result = { rows: [], count: 0 };
const keys = await this.cacheManager.MagCache.keys(`api_call_${appkey}*`);
var detail = null;
let detail = null;
for (let j = 0; j < keys.length; j++) {
const d = keys[j];
const pathdetail = d.substr(d.lastIndexOf('_') + 1, d.length);
const apicalldetailAccu = await this.cacheManager.ApiCallCountCache.getApiCallCount(appkey, pathdetail);
var detail = { detailPath: d, detailCount: apicalldetailAccu.callcount };
detail = { detailPath: d, detailCount: apicalldetailAccu.callcount };
}
result.rows = detail;
}
// 操作别的应用的缓存
async opOtherAppCache(action_type, body = null, opCacheUrl) {
async opOtherAppCache(actionType, body = null, opCacheUrl) {
const appData = await this.authUtils.getTokenInfo(settings.appKey, settings.secret);
if (appData.status != 0) {
return appData;
......@@ -94,10 +96,11 @@ class CachSearchesSve {
const restS = await system.getObject('util.restClient');
const restResult = await restS.execPostWithAK(
{
action_type,
action_type: actionType,
body,
},
opCacheUrl, appData.data.accessKey,
opCacheUrl,
appData.data.accessKey,
);
if (restResult && restResult.status == 0) {
......
......@@ -32,7 +32,12 @@ class TxHandler {
}
// 获取分配的业务员信息
const ConsultTypeName = datajson.actionBody.ConsultTypeName.split('/')[2];
const salesmanInfo = await this.userService.getBizUserForBizChance(datajson.actionBody.ContactsMobile, datajson.actionBody.ServicerName, ConsultTypeName, datajson.actionBody.RegionName);
const salesmanInfo = await this.userService.getBizUserForBizChance(
datajson.actionBody.ContactsMobile,
datajson.actionBody.ServicerName,
ConsultTypeName,
datajson.actionBody.RegionName,
);
console.log('salesman ------- ');
console.log(salesmanInfo);
const rc = system.getObject('util.execClient');
......@@ -260,7 +265,8 @@ class TxHandler {
// params.baseInfo.clerkPhone = salesmanInfo.userInfo.mobile
}
// if (!params.servicerCode || params.servicerCode == 'undefined') {
// if (datajson.actionBody.orderSnapshot.servicerCode && datajson.actionBody.orderSnapshot.servicerCode != 'undefined') {
// if (datajson.actionBody.orderSnapshot.servicerCode
// && datajson.actionBody.orderSnapshot.servicerCode != 'undefined') {
// params.servicerCode = datajson.actionBody.orderSnapshot.servicerCode;//fuwushang id
// }
// }
......@@ -270,10 +276,12 @@ class TxHandler {
if (datajson.actionBody.realTotalCost && datajson.actionBody.realTotalCost != 'undefined') {
params.sellingPrice = datajson.actionBody.realTotalCost; // 价格
}
// if (datajson.actionBody.orderSnapshot.channelSource && datajson.actionBody.orderSnapshot.channelSource != 'undefined') {
// if (datajson.actionBody.orderSnapshot.channelSource
// && datajson.actionBody.orderSnapshot.channelSource != 'undefined') {
// params.channelSource = datajson.actionBody.orderSnapshot.channelSource;//渠道名称
// }
// if (datajson.actionBody.orderSnapshot.channelNumber && datajson.actionBody.orderSnapshot.channelNumber != 'undefined') {
// if (datajson.actionBody.orderSnapshot.channelNumber
// && datajson.actionBody.orderSnapshot.channelNumber != 'undefined') {
// params.channelNumber = datajson.actionBody.orderSnapshot.channelNumber;//渠道编码
// }
if (datajson.actionBody.orderSnapshot.hasOwnProperty('isWhether')) {
......
......@@ -12,16 +12,16 @@ class CompanyService extends ServiceBase {
if (isSuper) {
appsrtn = this.db.models.app.findAll({
where:
{
id: { [this.db.Op.ne]: settings.pmappid },
},
{
id: { [this.db.Op.ne]: settings.pmappid },
},
});
} else {
appsrtn = this.db.models.app.findAll({
where:
{
id: { [this.db.Op.in]: appids },
},
{
id: { [this.db.Op.in]: appids },
},
});
}
return appsrtn;
......@@ -93,7 +93,6 @@ class CompanyService extends ServiceBase {
});
// 查询出角色
const 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})
// 需要添加访客角色
if (roleids && roleids.length > 0) {
......
......@@ -16,7 +16,12 @@ class RouteService extends ServiceBase {
let rtn = null;
try {
// 添加路由
const routeobj = await self.cjsonregister(RouteService.newRouteUrl(serviceName), { name: routedata.name, hosts: routedata.hosts, paths: routedata.paths, strip_path: routedata.isstrip });
const 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) {
......
......@@ -20,12 +20,12 @@ class MsgHistoryService extends ServiceBase {
return msg;
}
async pushBusinessLicenseMsg(senderId, targetId, businessLicense_id) {
if (!businessLicense_id) {
async pushBusinessLicenseMsg(senderId, targetId, businessLicenseId) {
if (!businessLicenseId) {
return 0;
}
const notice = await this.msgnoticeDao.findOne({ fromId: senderId, toId: targetId });
if (notice && notice.businessLicense_id == businessLicense_id) {
if (notice && notice.businessLicense_id == businessLicenseId) {
return 0;
}
......@@ -43,14 +43,14 @@ class MsgHistoryService extends ServiceBase {
senderId,
target,
targetId,
content: businessLicense_id,
content: businessLicenseId,
isRead: false,
businessLicense_id,
businessLicense_id: businessLicenseId,
};
const obj = await this.saveMsg(msg);
const bl = await this.businesslicenseDao.findById(businessLicense_id);
const bl = await this.businesslicenseDao.findById(businessLicenseId);
msg.businessLicense = bl;
msg.id = obj.id;
msg.created_at = obj.created_at;
......@@ -139,7 +139,8 @@ class MsgHistoryService extends ServiceBase {
return 0;
}
const channel = `${user.app_id}${user.id}`;
return await this.redisClient.publish(channel, JSON.stringify({ type: 'readmsg', data: [msg.id] }));
const result = await this.redisClient.publish(channel, JSON.stringify({ type: 'readmsg', data: [msg.id] }));
return result;
}
}
module.exports = MsgHistoryService;
......@@ -28,7 +28,7 @@ class MsgNoticeService extends ServiceBase {
const msgIds = [];
const businessLicenseIds = [];
const userIds = [];
for (var item of list) {
for (const item of list) {
msgIds.push(item.lastMsgId);
businessLicenseIds.push(item.businessLicense_id);
userIds.push(item.toId);
......@@ -51,7 +51,7 @@ class MsgNoticeService extends ServiceBase {
const licenseList = await this.businesslicenseDao.customQuery(`SELECT * FROM yz_business_license WHERE id IN (${businessLicenseIds.join(',')}) `);
const serviceTypeIds = [];
for (var item of licenseList) {
for (const item of licenseList) {
serviceTypeIds.push(item.serviceTypeOneId);
serviceTypeIds.push(item.serviceTypeTwoId);
}
......@@ -60,7 +60,7 @@ class MsgNoticeService extends ServiceBase {
const sql = `SELECT id, name FROM \`p_service_type\` WHERE id IN (${serviceTypeIds.join(',')}) `;
const typeList = await this.dao.customQuery(sql);
var typeMap = [];
const typeMap = [];
if (typeList && typeList.length > 0) {
for (const t of typeList) {
typeMap[`type_id_${t.id}`] = t.name;
......@@ -68,12 +68,14 @@ class MsgNoticeService extends ServiceBase {
item.serviceTypeOneName = t.name;
} else if (t.id == item.serviceTypeTwoId) {
item.serviceTypeTwoName = t.name;
} else {}
} else {
console.log('what~~~~');
}
}
}
}
for (var item of licenseList) {
for (const item of licenseList) {
item.serviceTypeOneName = typeMap[`type_id_${item.serviceTypeOneId}`];
item.serviceTypeTwoName = typeMap[`type_id_${item.serviceTypeTwoId}`];
}
......@@ -98,7 +100,7 @@ class MsgNoticeService extends ServiceBase {
const rs = [];
for (const i in list) {
var item = list[i];
const item = list[i];
item.lastMsg = msgMap[`id${item.lastMsgId}`];
item.businessLicense = businessLicenseMap[`id${item.businessLicense_id}`];
item.friend = userMap[`id${item.toId}`];
......@@ -110,7 +112,6 @@ class MsgNoticeService extends ServiceBase {
}
async countUnread(userId) {
debugger;
const unreadList = await this.userDao.customQuery(`SELECT COUNT(1) AS num FROM \`msghistory\` WHERE isRead = 0 AND targetId = ${userId}`);
let count = 0;
if (unreadList && unreadList.length > 0) {
......
......@@ -60,7 +60,7 @@ class ServiceBase {
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
const u = uuid.replace(/-/g, '');
return u;
}
static getDaoName(ClassObj) {
......@@ -143,7 +143,10 @@ class ServiceBase {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
let r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[23] = '-';
uuid[18] = uuid[23];
uuid[13] = uuid[18];
uuid[8] = uuid[13];
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
......@@ -189,8 +192,6 @@ class ServiceBase {
return rtn.data;
}
throw new Error(rtn.data);
return null;
} catch (e) {
console.log(e);
return null;
......
......@@ -129,11 +129,11 @@ class System {
}
/**
* 请求返回成功
* @param {*} data 操作成功返回的数据,有值为成功,无值为失败
* @param {*} okmsg 操作成功的描述
* @param {*} req 请求头信息
*/
* 请求返回成功
* @param {*} data 操作成功返回的数据,有值为成功,无值为失败
* @param {*} okmsg 操作成功的描述
* @param {*} req 请求头信息
*/
static getResult(data, opmsg = '操作成功', req) {
return {
status: !data ? -1 : 0,
......@@ -143,10 +143,10 @@ class System {
};
}
/**
* 请求返回成功
* @param {*} data 操作成功返回的数据
* @param {*} okmsg 操作成功的描述
*/
* 请求返回成功
* @param {*} data 操作成功返回的数据
* @param {*} okmsg 操作成功的描述
*/
static getResultSuccess(data, okmsg = 'success') {
return {
status: 0,
......@@ -155,11 +155,11 @@ class System {
};
}
/**
* 请求返回失败
* @param {*} status 操作失败状态,默认为-1
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
* 请求返回失败
* @param {*} status 操作失败状态,默认为-1
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
static getResultFail(status = -1, errmsg = 'fail', data = null) {
return {
status,
......@@ -168,10 +168,10 @@ class System {
};
}
/**
* 请求处理异常
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
* 请求处理异常
* @param {*} errmsg 操作失败的描述,默认为fail
* @param {*} data 操作失败返回的数据
*/
static getResultError(errmsg = 'fail', data = null) {
return {
status: -200,
......@@ -244,12 +244,12 @@ class System {
const configValue = require(configPath);
return configValue.config;
}
static get_client_ip(req) {
static getClientIp(req) {
const ip = req.headers['x-forwarded-for']
|| req.ip
|| req.connection.remoteAddress
|| req.socket.remoteAddress
|| (req.connection.socket && req.connection.socket.remoteAddress) || '';
|| req.ip
|| req.connection.remoteAddress
|| req.socket.remoteAddress
|| (req.connection.socket && req.connection.socket.remoteAddress) || '';
const x = ip.match(/(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/);
if (x) {
return x[0];
......@@ -257,13 +257,13 @@ class System {
return 'localhost';
}
/**
* 记录日志信息
* @param {*} opTitle 操作的标题
* @param {*} params 参数
* @param {*} identifyCode 业务标识
* @param {*} resultInfo 返回结果
* @param {*} errorInfo 错误信息
*/
* 记录日志信息
* @param {*} opTitle 操作的标题
* @param {*} params 参数
* @param {*} identifyCode 业务标识
* @param {*} resultInfo 返回结果
* @param {*} errorInfo 错误信息
*/
static execLogs(opTitle, params, identifyCode, resultInfo, errorInfo) {
const reqUrl = settings.logUrl();
let isLogData = true;
......@@ -309,9 +309,9 @@ class System {
return cipherStr;
}
/**
* 解密信息
* @param {*} opStr
*/
* 解密信息
* @param {*} opStr
*/
static decryptStr(opStr) {
if (!opStr) {
return '';
......@@ -325,9 +325,9 @@ class System {
return plaintext;
}
/**
* 登录密码解码
* @param {*} desstr
*/
* 登录密码解码
* @param {*} desstr
*/
static desEncript(desstr) {
const deskey = '647a68c9-da01-40d3-9763-1ffa0f64cf3f';
const keyHex = cryptoJS.enc.Utf8.parse(deskey);
......@@ -343,40 +343,40 @@ class System {
static getRysResult(reqId, err = 'not err') {
if (err === 'not err') {
return {
return {
requestId: reqId,
success: true,
errorCode: 0,
errorMsg: 'ok',
data: null,
};
};
}
return {
return {
requestId: reqId,
success: false,
errorCode: -1,
errorMsg: err,
data: null,
};
}
};
}
/**
* 队列操作
* @param {json}
pushUrl string 推送URL地址
actionType string 推送地址接收时的功能名称
notifyUrl string 推送成功后通知的Url
messageBody json 推送的业务消息,必须有一项对象属性值
headData json 请求头信息
requestId string 请求id
*/
* 队列操作
* @param {json}
pushUrl string 推送URL地址
actionType string 推送地址接收时的功能名称
notifyUrl string 推送成功后通知的Url
messageBody json 推送的业务消息,必须有一项对象属性值
headData json 请求头信息
requestId string 请求id
*/
static async rysQueueOper(obj) {
console.log('obj-----------------------', obj);
if (obj.pushUrl && obj.actionType && obj.messageBody) {
try {
const rc = this.getObject('util.execClient');
const reqUrl = settings.bpushUrl;
var reqId = uuidv4();
let reqId = uuidv4();
const param = {
actionType: 'produceData',
actionBody: {
......@@ -401,7 +401,7 @@ class System {
const j = JSON.parse(result.stdout);
if (j.status === 1) {
return this.getRysResult(reqId);
}
}
return this.getRysResult(reqId, result.stderr);
} catch (error) {
return this.getRysResult(reqId, error);
......
......@@ -7,7 +7,7 @@ class AuthUtils {
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
const u = uuid.replace(/-/g, '');
return u;
}
/**
......
......@@ -49,8 +49,8 @@ class ExcelClient {
wb.xlsx.writeFile(filePath).then(async (d) => {
const rtn = await self.ossClient.upfile(fileName, filePath);
fs.unlink(filePath, (err) => {});
var obj = {
fs.unlink(filePath, (err) => { });
let obj = {
user_id: user.id || 0,
userName: user.userName || '',
code,
......@@ -58,7 +58,7 @@ class ExcelClient {
filePath: rtn.url || '',
isDownload: false,
};
var obj = await self.filedownloadDao.create(obj);
obj = await self.filedownloadDao.create(obj);
});
}
}
......
......@@ -7,7 +7,6 @@ class ExecClient {
this.cmdPostPattern = 'curl -k -H \'Content-type: application/json\' -d \'{data}\' {url}';
this.cmdGetPattern = 'curl -G -X GET \'{url}\'';
this.cmdPostPattern3 = 'curl -k -H \'Content-type: application/json\' -H \'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTg0MzQ2ODcsImlzcyI6InJFRVN6TU5ZUlM2RnBWNnZlY09vdExPNWdPcUNXSmFQIiwiaWF0IjoxNTk4NDMxMDg3fQ.isQ40HqHHfJ-rTsUQOhRIdu4XCitZU-AfzeqSH4kPbQ\' -H \'XAPPKEY: f6b59b74-f943-4735-bb86-e05d6b7fd78e\' -d \'{data}\' {url}';
// this.cmdPostPattern3 = "curl -k -H 'Content-type: application/json' -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJvcnpaWmhXRXBKNVVFZzRZUU5uUmlyVEJXa1FQbnZ6UyIsImlhdCI6MTU5MjcwOTYzNn0.TWk_F6Tz3fRMqspoG24VSt5RiC4ldFembFYcLcAbowE' -H 'XAPPKEY: 647a68c9-da01-40d3-9763-1ffa0f64cf3f' -d '{data}' {url}";
}
async exec(cmd) {
......
......@@ -10,13 +10,13 @@ class LogClient {
}
getUUID() {
const uuid = uuidv4();
const u = uuid.replace(/\-/g, '');
const u = uuid.replace(/-/g, '');
return u;
}
async log(pobj, req, rtninfo, errinfo) {
rtninfo.requestId = this.getUUID();
req.params.param = pobj;
if (!['findSystemMsgCount', 'findUnreadCount'].includes(req.params && req.params.method || '')) {
if (!['findSystemMsgCount', 'findUnreadCount'].includes(((req.params && req.params.method) || ''))) {
// 第三个字段应该存公司id
system.execLogs(`${settings.appname}_${req.xctx.codetitle}`, req.params, `_${pobj.company_id}_`, rtninfo, errinfo).then((res) => {
if (res && res.status == 1) {
......@@ -67,29 +67,6 @@ class LogClient {
console.log('请求--------日志');
console.log(settings.logUrl());
console.log(query);
// return {
// "totalCount": 1,
// "pageSize": 20,
// "currentPage": 0,
// "list": [
// {
// "opTitle": "center_manage_首页",
// "identifyCode": "10_",
// "messageBody": "{\"gname\":\"msg\",\"qname\":\"msgCtl\",\"method\":\"findUnreadCount\",\"param\":{\"clientIp\":\"9.223.9.138\",\"agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36\",\"classname\":\"msg.msgCtl\",\"app_id\":1,\"company_id\":\"10\",\"userid\":\"15\",\"username\":\"j2\",\"bizpath\":\"/home\",\"is_read\":false},\"actionType\":\"\",\"pushUrl\":\"\"}",
// "resultInfo": "{\"status\":0}",
// "errorInfo": "null",
// "requestId": "19a258474e384a0db939270580f01407",
// "created_at": "2020-07-16T05:18:48.454Z"
// }, {
// "opTitle": "center_manage_消息中心",
// "identifyCode": "10_",
// "messageBody": "{\"gname\":\"msg\",\"qname\":\"msgCtl\",\"method\":\"findUnreadCount\",\"param\":{\"clientIp\":\"9.223.9.138\",\"agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\",\"classname\":\"msg.msgCtl\",\"app_id\":1,\"company_id\":\"10\",\"userid\":\"15\",\"username\":\"j2\",\"bizpath\":\"/message/message_page\",\"is_read\":false},\"actionType\":\"\",\"pushUrl\":\"\"}",
// "resultInfo": "{\"status\":-1}",
// "errorInfo": "null",
// "requestId": "06d94fbcd05b44a1ae292a21f5931f41",
// "created_at": "2020-07-16T05:51:54.888Z"
// }]
// }
let rtn = await system.postJsonTypeReq(settings.logUrl(), {
actionType: 'queryLogsData', // Y 功能名称
actionBody: query,
......
......@@ -88,7 +88,7 @@ class RedisClient {
}
if (self.chatserver) {
if (channel != 'task') {
var message = JSON.parse(message);
message = JSON.parse(message);
console.log(message, '------------------------------------------ publish message');
if (channel == 'brc') { // 如果是广播频道,则发送广播到客户端
self.chatserver.server.emit('brc', message);
......@@ -248,7 +248,8 @@ module.exports = RedisClient;
// client.sismember("h","ok").then(function(r){
// console.log(r);
// });
// console.dir(client);ti.exec( callback )回调函数参数err:返回null或者Array,出错则返回对应命令序列链中发生错误的错误信息,这个数组中最后一个元素是源自exec本身的一个EXECABORT类型的错误
// console.dir(client);ti.exec( callback )
// 回调函数参数err:返回null或者Array,出错则返回对应命令序列链中发生错误的错误信息,这个数组中最后一个元素是源自exec本身的一个EXECABORT类型的错误
// r.set("hello","oooo").then(function(result){
// console.log(result);
// });
......
......@@ -10,55 +10,50 @@ class RestClient {
this.cmdDownLoadFilePattern = 'curl -G -o {fileName} {url}';
this.cmdPostPattern2 = 'curl -k -H \'Content-type: application/x-www-form-urlencoded\' -d \'{data}\' {url}';
this.cmdPostPatternWithAK = 'curl -k -H \'Content-type: application/json\' -H \'AccessKey:{ak}\' -d \'{data}\' {url}';
// 云帐户
// this.cmdPostPattern3="curl -k -H 'Content-type: application/x-www-form-urlencoded' -H 'dealer-id:"+settings.apiconfig.yunzhanghuDealer_id()+"' -H 'request-id:"+parseInt(Date.now() / 1000)+"_gsb"+"' -d '{data}' {url}";
// this.cmdGetPattern3 = "curl {-G} -k {url} --header 'dealer-id:"+settings.apiconfig.yunzhanghuDealer_id()+"'";
// e签宝
// this.cmdPostPattern4="curl -k -H 'Content-type: application/json' -H 'X-Tsign-Open-App-Id:"+settings.apiconfig.eSignBaoAppId()+"' -H 'X-Tsign-Open-App-Secret:"+settings.apiconfig.eSignBaoAppKey()+"' -d '{data}' {url}";
// form-data形式post data参数类型 md5=2&data=1
this.cmdPostPattern5 = 'curl -k --data \'{data}\' {url}';
}
FetchGetCmd(subData, url) {
const cmd = this.cmdGetPattern.replace(/\{\-G\}/g, '-G').replace(/\{data\}/g, subData)
const cmd = this.cmdGetPattern.replace(/{-G}/g, '-G').replace(/{data}/g, subData)
.replace(/\{url\}/g, url);
return cmd;
}
return cmd;
}
FetchPostCmd(subData, url) {
const data = JSON.stringify(subData);
const cmd = this.cmdPostPattern.replace(
const data = JSON.stringify(subData);
const cmd = this.cmdPostPattern.replace(
/\{data\}/g,
data,
data,
).replace(/\{url\}/g, url);
return cmd;
return cmd;
}
FetchPostCmdWithAK(subData, url, acck) {
const data = JSON.stringify(subData);
const cmd = this.cmdPostPatternWithAK.replace(
const data = JSON.stringify(subData);
const cmd = this.cmdPostPatternWithAK.replace(
/\{data\}/g,
data,
data,
).replace(/\{url\}/g, url)
.replace(/\{ak\}/g, acck);
return cmd;
}
return cmd;
}
FetchPostCmd2(subData, url) {
const data = subData;
const cmd = this.cmdPostPattern2.replace(
const data = subData;
const cmd = this.cmdPostPattern2.replace(
/\{data\}/g,
data,
data,
).replace(/\{url\}/g, url);
return cmd;
}
return cmd;
}
FetchPostCmd3(subData, url) {
const data = subData;
const cmd = this.cmdPostPattern3.replace(
const data = subData;
const cmd = this.cmdPostPattern3.replace(
/\{data\}/g,
data,
data,
).replace(/\{url\}/g, url);
return cmd;
return cmd;
}
FetchGetCmd3(url) {
const cmd = this.cmdGetPattern3.replace(/\{\-G\}/g, '-G').replace(/\{url\}/g, url);
const cmd = this.cmdGetPattern3.replace(/\{-G\}/g, '-G').replace(/\{url\}/g, url);
return cmd;
}
FetchPostCmd4(subData, url) {
......@@ -78,10 +73,10 @@ class RestClient {
return cmd;
}
FetchDownLoadCmd(outfname, url) {
// console.log(this.cmdPattern);
const cmd = this.cmdDownLoadFilePattern.replace(/\{fileName\}/g, outfname).replace(/\{url\}/g, url);
return cmd;
}
// console.log(this.cmdPattern);
const cmd = this.cmdDownLoadFilePattern.replace(/\{fileName\}/g, outfname).replace(/\{url\}/g, url);
return cmd;
}
async exec(cmd) {
// await后面表达式返回的promise对象,是then的语法糖,await返回then函数的返回值
// 异常需要try/catch自己捕获或外部catch捕获
......
......@@ -38,7 +38,7 @@ class SmsClient {
};
return this.restClient.execPost(txtObj, this.smsTeml);
}
async getUidStr(len, radix) {
async getUidStr(len, radix) {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const uuid = []; let i;
radix = radix || chars.length;
......@@ -46,7 +46,10 @@ class SmsClient {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
let r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[23] = '-';
uuid[18] = uuid[23];
uuid[13] = uuid[18];
uuid[8] = uuid[13];
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
......
......@@ -23,8 +23,8 @@ module.exports = function (app) {
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
routes(app);// 初始化路由
app.use(express.static(path.join(settings.basepath, '/app/front/entry/public')));
// development only
if ('development' == app.get('env')) {
// development only
if (app.get('env') === 'development') {
app.use(errorHandler());
} else {
app.use((err, req, res) => {
......
......@@ -6,9 +6,6 @@ const channelCache = {};
module.exports = function (app) {
app.get('/autologin', (req, res, next) => {
// 读取cookie,获取cookie值,
// Authorization:
// Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImRjMmM1MzMwMjNhMTExZTlhOTU3NjliODBiNDI4Y2QxIn0.eyJpZCI6IjViZDk2MWJkZWQxN2E5MmI1MDFjZWQ0ZCIsIm5hbWUiOiLpnZLph4kxMSIsImVtcGxveWVlIjoiNWQ5ZWNlODc1Zjk3ZGQzMzEwNzI4ZjY4IiwicGhvbmUiOiI3TFlYZ29ySkdGM2hBbHdqQTZGelFnPT0iLCJvcmdpZCI6IjViY2ZlOTVjYjBhMDFmMDAwOTI4NGJjMyIsInBsYXRmb3JtIjoiZDVmYTU4Yjk3NGExMjBlZTYxMTMzM2MwMDNjOWZlYzAiLCJ1bmlvbmlkIjoib2RuWjR0OERoV1V0N0lXT09maEF0UTdqM1docyIsImp0aSI6Imo3R0hLRGFzNDEzQTQ2OGkiLCJleHAiOjE1OTYwODEzMTEsImlhdCI6MTU5NTQ3NjUxMX0.I196XbcCR3k7r1O8uwoI2HUhow0UhGHKzii5wOR39vLmuNOUatNY7ccQTCHijqysbSCePP43Iuglrl2gLQASf5uAr9uqTzhTc3O4Z5iF3oR2qR1vlBxrzTDF8xuhKHQ4tO6Hbsib0FdOYVeU8fe0g_GZiIcuYIv-f8VsiAGMF9TEES129CDwZacJfVViw4EXVnXSivAzQG4JgGSwUACvPT140bCZ1XPeHi0GXmgtEN77NjWfOGI5RYGC0Gq3CGevlSWERjb3mUscAIjoXsOxlWNwy7dc1u1A7uX1a6bUhLU1wtiQ6md4TnyeR5OdYeVqGlIe3hZGcH_E3QrQMq988Q
});
app.all('*', async (req, res, next) => {
......@@ -46,7 +43,7 @@ module.exports = function (app) {
const methodName = req.params.method;
const { gname } = req.params;
classPath = `${gname}.${classPath}`;
const tClientIp = System.get_client_ip(req);
const tClientIp = System.getClientIp(req);
req.clientIp = tClientIp;
req.uagent = req.headers['user-agent'];
// req.classname=classPath;
......@@ -74,7 +71,7 @@ module.exports = function (app) {
classPath = `${gname}.${classPath}`;
console.log('====================');
console.log(classPath);
const tClientIp = System.get_client_ip(req);
const tClientIp = System.getClientIp(req);
req.clientIp = tClientIp;
req.uagent = req.headers['user-agent'];
// req.classname=classPath;
......
......@@ -28,7 +28,7 @@ module.exports = function (app) {
const { gname } = req.params;
const params = [];
classPath = `${gname}.${classPath}`;
const tClientIp = system.get_client_ip(req);
const tClientIp = system.getClientIp(req);
req.body.clientIp = tClientIp;
req.body.agent = req.headers['user-agent'];
req.body.classname = classPath;
......
var fs = require('fs');
const fs = require('fs');
// function to encode file data to base64 encoded string
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync("./imgs/sp.png");
// convert binary data to base64 encoded string
var bf=Buffer.alloc(bitmap.length,bitmap);
return bf.toString('base64');
function base64Encode(file) {
// read binary data
const bitmap = fs.readFileSync('./imgs/sp.png');
// convert binary data to base64 encoded string
const bf = Buffer.alloc(bitmap.length, bitmap);
return bf.toString('base64');
}
// function to create file from base64 encoded string
function base64_decode(base64str, file) {
// create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded
var bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
function base64Decode(base64str, file) {
const bitmap = new Buffer(base64str, 'base64');
// write buffer to file
fs.writeFileSync(file, bitmap);
console.log('******** File created from base64 encoded string ********');
}
function getDataUrl(filepath){
var str=base64_encode(filepath);
var mime="";
if(filepath.indexOf("png")>=0){
mime="image/png";
function getDataUrl(filepath) {
const str = base64Encode(filepath);
let mime = '';
if (filepath.indexOf('png') >= 0) {
mime = 'image/png';
}
if(filepath.indexOf("jpg")>=0 || filepath.indexOf("jpeg")>=0){
mime="image/jpg";
if (filepath.indexOf('jpg') >= 0 || filepath.indexOf('jpeg') >= 0) {
mime = 'image/jpg';
}
if(filepath.indexOf("gif")>=0){
mime="image/gif";
if (filepath.indexOf('gif') >= 0) {
mime = 'image/gif';
}
var dataurl=`data:${mime};base64,`+str;
const dataurl = `data:${mime};base64,${str}`;
return dataurl;
}
var str=getDataUrl("./imgs/sp.png");
console.log(str);
\ No newline at end of file
var gulp = require('gulp');
const fs = require('fs');
const tap = require('gulp-tap');
const minimist = require('minimist');
const merge = require('merge-stream');
const rename = require('gulp-rename');
const del = require('del');
const concat = require('gulp-concat');
const gulpif = require('gulp-if');
const knownOptions = {
string: 'name',
string: 'bizfile',
default: { name: process.env.NODE_ENV || 'Test' },
};
const options = minimist(process.argv.slice(2), knownOptions);
const { name } = options;
const { bizfile } = options;
const BUILD_PATH = './extra/build';
const DEST_PATH = './extra/dest';
const CTL_PATH = './app/base/controller/impl';
const SERVICE_PATH = './app/base/service/impl';
const DAO_PATH = './app/base/db/impl';
const PAGE_PATH = './app/front/vues/pages';
const VUECOM_PATH = './app/front/vues';
const CSS_PATH = './app/front/entry/public/css';
const IMG_PATH = './extra/imgs';
const DEST_IMGPATH = './app/front/entry/public/imgs';
const METABIZ_PATH = './app/base/db/metadata/bizs/wx76a324c5d201d1a4';
gulp.task('makefile', (done) => {
// 将你的默认的任务代码放在这
del('./extra/dest/*');
const tmpName = name.toLowerCase();
const fstream = gulp.src('./extra/build/*.js')
.pipe(tap((file) => {
const sfile = file.contents.toString('utf-8');
const rpstr = sfile.replace(/\$\{Name\}/g, name);
file.contents = new Buffer(rpstr, 'utf-8');
}))
.pipe(rename((path) => {
path.basename = path.basename.replace('templ', tmpName);
}))
.pipe(gulp.dest('./extra/dest'));
return fstream;
// var pageStream=gulp.src("./extra/build/page/**/*").pipe(
// gulp.dest("./extra/dest")
// );
// return merge(fstream, pageStream);
});
gulp.task('page', (cbk) => {
const tmpName = name.toLowerCase();
return gulp.src('./extra/build/page/templPage/*.*')
.pipe(rename((path) => {
path.basename = path.basename.replace('templ', tmpName);
}))
.pipe(tap((file) => {
const sfile = file.contents.toString();
const rpstr = sfile.replace(/\$\{COMNAME\}/g, `gsb_${tmpName}`);
file.contents = new Buffer(rpstr, 'utf-8');
}))
.pipe(gulp.dest(`./extra/dest/${tmpName}/`));
});
gulp.task('cpctl', (cbk) => {
const tmpName = name.toLowerCase();
return gulp.src(`./extra/dest/${tmpName}Ctl.js`).pipe(rename((path) => {
path.basename = path.basename.substring(0, 1).toLowerCase() + path.basename.substring(1);
}))
.pipe(gulp.dest(CTL_PATH));
});
gulp.task('cpsve', (cbk) => {
const tmpName = name.toLowerCase();
return gulp.src(`./extra/dest/${tmpName}Sve.js`).pipe(rename((path) => {
path.basename = path.basename.substring(0, 1).toLowerCase() + path.basename.substring(1);
}))
.pipe(gulp.dest(SERVICE_PATH));
});
gulp.task('cpdao', (cbk) => {
const tmpName = name.toLowerCase();
return gulp.src(`./extra/dest/${tmpName}Dao.js`).pipe(rename((path) => {
path.basename = path.basename.substring(0, 1).toLowerCase() + path.basename.substring(1);
}))
.pipe(gulp.dest(DAO_PATH));
});
gulp.task('cppage', (cbk) => {
const tmpName = name.toLowerCase();
return gulp.src(`./extra/dest/${tmpName}/*.*`).pipe(gulp.dest(`${PAGE_PATH}/${tmpName}/`));
});
gulp.task('cpbizfile', cbk => gulp.src('./extra/build/page/meta.js').pipe(rename((path) => {
if (bizfile) {
path.basename = bizfile;
} else {
path.basename = name;
}
}))
.pipe(gulp.dest(`${METABIZ_PATH}/`)));
gulp.task('simple', ['page', 'cppage', 'cpbizfile'], (done) => {
done();
});
gulp.task('all', ['makefile', 'page', 'cpctl', 'cpsve', 'cpdao', 'cppage', 'cpbizfile'], (done) => {
done();
});
const minifycss = require('gulp-minify-css');
gulp.task('pagecss', (cbk) => {
function defaultcondition(file) {
if (file.path.indexOf('spring') >= 0) {
return false;
} if (file.path.indexOf('summer') >= 0) {
return false;
} if (file.path.indexOf('autumn') >= 0) {
return false;
} if (file.path.indexOf('winter') >= 0) {
return false;
}
return true;
}
return gulp.src(`${VUECOM_PATH}/**/*/*.css`).pipe(gulpif(defaultcondition, concat('pagecom.css')))
.pipe(minifycss())
.pipe(gulp.dest(`${CSS_PATH}/`));
});
gulp.task('springcss', (cbk) => {
function springcondition(file) {
if (file.path.indexOf('spring') >= 0) {
return true;
}
return false;
}
return gulp.src(`${VUECOM_PATH}/**/*/*.css`).pipe(gulpif(springcondition, concat('spring.css')))
.pipe(minifycss())
.pipe(gulp.dest(`${CSS_PATH}/`));
});
gulp.task('summercss', (cbk) => {
function summercondition(file) {
if (file.path.indexOf('summer') >= 0) {
return true;
}
return false;
}
return gulp.src(`${VUECOM_PATH}/**/*/*.css`).pipe(gulpif(summercondition, concat('summer.css')))
.pipe(minifycss())
.pipe(gulp.dest(`${CSS_PATH}/`));
});
gulp.task('autumncss', (cbk) => {
function autumncondition(file) {
if (file.path.indexOf('autumn') >= 0) {
return true;
}
return false;
}
return gulp.src(`${VUECOM_PATH}/**/*/*.css`).pipe(gulpif(autumncondition, concat('autumn.css')))
.pipe(minifycss())
.pipe(gulp.dest(`${CSS_PATH}/`));
});
gulp.task('wintercss', (cbk) => {
function wintercondition(file) {
if (file.path.indexOf('winter') >= 0) {
return true;
}
return false;
}
return gulp.src(`${VUECOM_PATH}/**/*/*.css`).pipe(gulpif(wintercondition, concat('winter.css')))
.pipe(minifycss())
.pipe(gulp.dest(`${CSS_PATH}/`));
});
gulp.task('1', (cbk) => {
function mobilecondition(file) {
if (file.path.indexOf('mobile') >= 0) {
return true;
}
return false;
}
return gulp.src(`${VUECOM_PATH}/**/*/*.css`).pipe(gulpif(mobilecondition, concat('mobile.css')))
.pipe(minifycss())
.pipe(gulp.dest(`${CSS_PATH}/`));
});
gulp.task('allcss', ['pagecss', 'springcss', 'summercss', 'autumncss', 'wintercss'], (done) => {
done();
});
gulp.task('watch', () => {
gulp.watch(`${VUECOM_PATH}/**/*/*.css`, gulp.series(['allcss']));
});
gulp.task('basehandle', cbk => gulp.src(`${VUECOM_PATH}/base/**/*.vue`).
pipe(tap((file) => {
file.contents = new Buffer(require(file.path).replace(/\n/g, ''), 'utf-8');
}))
.pipe(gulp.dest(`${VUECOM_PATH}/allie/base/`)));
var gulp = require('gulp');
const imagemin = require('gulp-imagemin');
pngquant = require('imagemin-pngquant'),
gulp.task('testimg', () => {
del('./extra/testimgs/*');
return gulp.src(`${IMG_PATH}/**/*.{png,jpg,gif,ico}`)
.pipe(imagemin({
optimizationLevel: 1, // 类型:Number 默认:3 取值范围:0-7(优化等级)
progressive: true, // 类型:Boolean 默认:false 无损压缩jpg图片
interlaced: true, // 类型:Boolean 默认:false 隔行扫描gif进行渲染
multipass: true, // 类型:Boolean 默认:false 多次优化svg直到完全优化
use: [pngquant({
quality: [0.3],
})],
}))
// .pipe(gulp.dest(DEST_IMGPATH));
.pipe(gulp.dest('./extra/testimgs/'));
});
var http = require('http');
var express = require('express');
var app = express();
var setttings=require("./app/config/settings");
var environment = require('./app/config/environment');
const http = require('http');
const express = require('express');
const app = express();
const setttings = require('./app/config/settings');
const environment = require('./app/config/environment');
// var SocketServer=require("./app/config/socket.server");
//const cluster = require('cluster');
//const numCPUs = require('os').cpus().length;
// const cluster = require('cluster');
// const numCPUs = require('os').cpus().length;
// all environments
environment(app);//初始化环境
environment(app);// 初始化环境
// 错误处理中间件应当在路由加载之后才能加载
// if (cluster.isMaster) {
// console.log(`Master ${process.pid} is running`);
......@@ -26,9 +26,9 @@ environment(app);//初始化环境
// console.log('Express server listening on port ' + app.get('port'));
// });
// }
var server = http.createServer(app);
//var socketServer = new SocketServer(server);
server.listen(setttings.port, function(){
console.log('Express server listening on port ' + app.get('port'));
const server = http.createServer(app);
// var socketServer = new SocketServer(server);
server.listen(setttings.port, () => {
console.log(`Express server listening on port ${app.get('port')}`);
});
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