Commit e647bc09 by 王昆

gsb

parent 7c235e32
......@@ -4,7 +4,7 @@ var settings = require("../../../../config/settings");
class ActionAPI extends APIBase {
constructor() {
super();
this.accountSve = system.getObject("service.account.accountSve");
this.userSve = system.getObject("service.user.userSve");
}
/**
* 接口跳转
......@@ -33,34 +33,16 @@ class ActionAPI extends APIBase {
var opResult = null;
switch (action_type) {
// 测试
case "test":
opResult = await this.accountSve.test(action_body);
// 新增
case "saveAdminUser":
opResult = await this.userSve.saveAdminUser(action_body);
break;
// 创建账户
case "accountCreate":
opResult = await this.accountSve.createAccount(action_body);
// 新增商户账户
case "saveMerchantUser":
opResult = await this.userSve.saveMerchantUser(action_body);
break;
// 账户余额查询
case "accountInfo":
opResult = await this.accountSve.accountInfo(action_body);
break;
// 账户充值
case "accountRecharge":
opResult = await this.accountSve.accountRecharge(action_body);
break;
// 账户充值
case "accountRefund":
opResult = await this.accountSve.accountRefund(action_body);
break;
case "accountTrade":
opResult = await this.accountSve.accountTrade(action_body);
break;
case "accountTradePage":
opResult = await this.accountSve.accountTradePage(action_body);
break;
// 账户交易
case "test4":
opResult = await this.accountSve.test(action_body);
case "login":
opResult = await this.userSve.login(action_body);
break;
default:
opResult = system.getResult(null, "action_type参数错误");
......
var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");
const uuidv4 = require('uuid/v4');
var svgCaptcha = require('svg-captcha');
var cacheBaseComp = null;
class UserCtl extends CtlBase {
constructor() {
super("auth", CtlBase.getServiceName(UserCtl));
this.captchaPrev = "xgg_captcha_";
this.redisClient = system.getObject("util.redisClient");
}
async captcha(qobj, pobj, req) {
var uuid = uuidv4();
var key = uuid.replace(/\-/g, "");
var options = {
size: 4,
noise: 1,
ignoreChars: '0o1i'
};
options.width = this.trim(qobj.width) || 120;
options.height = this.trim(qobj.height) || 32;
options.background = this.trim(qobj.background) || "#E8E8E8";
try {
var redisKey = this.captchaPrev + key;
var cap = svgCaptcha.create(options);
console.log(cap);
await this.redisClient.setWithEx(redisKey, cap.text, 3 * 60);
return system.getResultSuccess({
key: key,
captcha: cap.data,
});
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async smsCode(qobj, pobj, req) {
var mobile = this.trim(qobj.mobile);
// var captchaKey = this.trim(qobj.captchaKey);
// var captchaCode = this.trim(qobj.captchaCode);
try {
if (!/^1[23456789]\d{9}$/.test(mobile)) {
return system.getResult(null, "手机号码格式不正确");
}
// var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";
// if (!code) {
// return system.getResult(null, "图片验证码过期,请刷新重试");
// }
// if (code.toLowerCase() != captchaCode.toLowerCase()) {
// await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
// return system.getResult(null, "图片验证码不一致,请刷新重试");
// }
// TODO 发送短信验证码
return system.getResultSuccess("发送成功");
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async login(qobj, pobj, req, res) {
var loginName = this.trim(pobj.loginName);
var password = this.trim(pobj.password);
var captchaKey = this.trim(qobj.captchaKey);
var captchaCode = this.trim(qobj.captchaCode);
try {
// var code = await await this.redisClient.get(this.captchaPrev + captchaKey) || "";
// if (!code) {
// return system.getResult(null, "图片验证码过期,请点击重试");
// }
// if (code.toLowerCase() != captchaCode.toLowerCase()) {
// await this.redisClient.delete(this.captchaPrev + pobj.emailKey);
// return system.getResult(null, "图片验证码不一致,请点击重试");
// }
var adminUser = await this.service.findById(1);
adminUser.lastLoginTime = new Date();
await adminUser.save();
var xggadminsid = uuidv4();
xggadminsid = "3cb49932-fa02-44f0-90db-9f06fe02e5c7";
await this.redisClient.setWithEx(xggadminsid, JSON.stringify(adminUser), 60 * 60 * 2);
// 处理登录逻辑
var result = {
xggadminsid: xggadminsid,
}
return system.getResultSuccess(result);
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async forgetPassword(qobj, pobj, req, res) {
var mobile = this.trim(pobj.mobile);
var vcode = this.trim(pobj.vcode);
var password = this.trim(qobj.password);
try {
} catch (error) {
return system.getResultFail(500, "接口异常:" + error.message);
}
}
async currentUser(qobj, pobj, req) {
return system.getResultSuccess(req.loginUser);
}
async getMenu(qobj, pobj, req) {
var menu = [
{"name": "首页", "path": "/", "submenu": [] },
{
"name": "商户中心",
"path": "/merchants",
"submenu": [{"name": "客户管理", "team": [{"name": "商户信息", "path": "/merchants/businessInformation"}, {"name": "签约信息", "path": "/merchants/contractInformation"} ] } ]
}, {
"name": "交易中心",
"path": "/trading",
"submenu": [{"name": "资金管理", "team": [{"name": "资金账户", "path": "/trading/capitalAccount"}, {"name": "充值申请", "path": "/trading/topUpApplication"}, {"name": "资金交易", "path": "/trading/cashTransactions"}, {"name": "资金流水", "path": "/trading/capitalFlows"} ] }, {"name": "订单管理", "team": [{"name": "订单信息", "path": "/trading/orderInformation"} ] }, {"name": "用户管理", "team": [{"name": "用户信息", "path": "/trading/userInformation"}, {"name": "用户签约", "path": "/trading/usersSignUp"} ] } ]
}, {
"name": "财务中心",
"path": "/financial",
"submenu": [{"name": "发票管理", "team": [{"name": "发票申请", "path": "/financial/invoiceApplyFor"}, {"name": "发票管理", "path": "/financial/invoiceManagement"} ] } ]
}, {
"name": "数据中心",
"path": "/information",
"submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] } ]
}, {
"name": "系统中心",
"path": "/system",
"submenu": [{"name": "暂无", "team": [{"name": "暂无", "path": ""} ] }
]
}
]
return system.getResultSuccess(menu);
}
/**
* 开放平台回调处理
* @param {*} req
*/
async authByCode(req) {
var opencode = req.query.code;
var user = await this.service.authByCode(opencode);
if (user) {
req.session.user = user;
} else {
req.session.user = null;
}
//缓存opencode,方便本应用跳转到其它应用
// /auth?code=xxxxx,缓存没有意义,如果需要跳转到其它应用,需要调用
//平台开放的登录方法,返回 <待跳转的目标地址>/auth?code=xxxxx
//this.cacheManager["OpenCodeCache"].cacheOpenCode(user.id,opencode);
return user;
}
async navSysSetting(pobj, qobj, req) {
//开始远程登录,返回code
var jumpobj = await this.service.navSysSetting(req.session.user);
if (jumpobj) {
return system.getResultSuccess(jumpobj);
}
return system.getResultFail();
}
async loginUser(qobj, pobj, req) {
return super.findById(req.session.user.id);
}
async initNewInstance(queryobj, req) {
var rtn = {};
rtn.roles = [];
if (rtn) {
return system.getResultSuccess(rtn);
}
return system.getResultFail();
}
async checkLogin(gobj, qobj, req) {
//当前如果缓存中存在user,还是要检查当前user所在的域名,如果不和来访一致,则退出重新登录
if (req.session.user) {
var x = null;
if (req.session.user.Roles) {
x = req.session.user.Roles.map(r => {
return r.code
});
}
var tmp = {
id: req.session.user.id,
userName: req.session.user.userName,
nickName: req.session.user.nickName,
mobile: req.session.user.mobile,
isAdmin: req.session.user.isAdmin,
created_at: req.session.user.created_at,
email: req.session.user.email,
headUrl: req.session.user.headUrl,
roles: x ? x.join(",") : ""
}
return system.getResult(tmp, "用户登录", req);
} else {
req.session.user = null;
//req.session.destroy();
return system.getResult(null, "用户未登录", req);
}
}
async exit(pobj, qobj, req) {
req.session.user = null;
req.session.destroy();
return system.getResultSuccess({
"env": settings.env
});
}
}
module.exports = UserCtl;
\ No newline at end of file
......@@ -12,7 +12,6 @@ var cacheBaseComp = null;
class MetaCtl extends CtlBase {
constructor() {
super("common", CtlBase.getServiceName(MetaCtl));
this.userS = system.getObject("service.auth.userSve");
}
async getOssConfig() {
......
const system = require("../../../system");
const Dao = require("../../dao.base");
class AccountDao extends Dao {
constructor() {
super(Dao.getModelName(AccountDao));
}
async incrementBalance(id, balance, t) {
let sql = [];
sql.push("UPDATE");
sql.push(this.model.tableName);
sql.push("SET");
sql.push("balance = balance + :balance");
sql.push("WHERE id = :id AND balance + :balance >= 0");
let res = await this.customUpdate(sql.join(" "), {id: id, balance: balance}, t);
console.log(res);
if (res.length < 2) {
return 0;
}
return res[1] || 0;
}
async listByIds(ids, attrs) {
if (!ids || ids.length == 0) {
return [];
}
var sql = [];
sql.push("SELECT");
sql.push(attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE id IN (:ids)");
return await this.customQuery(sql.join(" "), {
ids: ids
}) || [];
}
async mapByIds(ids, attrs) {
var result = {};
if (!ids || ids.length == 0) {
return result;
}
var list = await this.findListByIds(ids, attrs);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
}
module.exports = AccountDao;
const system = require("../../../system");
const Dao = require("../../dao.base");
class AccountTradeDao extends Dao {
constructor() {
super(Dao.getModelName(AccountTradeDao));
}
async listByIds(ids, attrs) {
if (!ids || ids.length == 0) {
return [];
}
var sql = [];
sql.push("SELECT");
sql.push(attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE id IN (:ids)");
return await this.customQuery(sql.join(" "), {
ids: ids
}) || [];
}
async mapByIds(ids, attrs) {
var result = {};
if (!ids || ids.length == 0) {
return result;
}
var list = await this.findListByIds(ids, attrs);
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
async countByCondition(params) {
var sql = [];
sql.push("SELECT");
sql.push("count(1) as num");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE deleted_at IS NULL");
this.setCondition(sql, params);
var list = await this.customQuery(sql.join(" "), params);
if (!list || list.length == 0) {
return 0;
}
return list[0].num;
}
async listByCondition(params) {
params.startRow = Number(params.startRow || 0);
params.pageSize = Number(params.pageSize || 10);
var sql = [];
sql.push("SELECT");
sql.push(params.attrs || "*");
sql.push("FROM");
sql.push(this.model.tableName);
sql.push("WHERE deleted_at IS NULL");
this.setCondition(sql, params);
sql.push("ORDER BY created_at DESC");
sql.push("LIMIT :startRow, :pageSize");
return await this.customQuery(sql.join(" "), params);
}
setCondition(sql, params) {
if (!params || !sql) {
return;
}
if (params.account_id) {
sql.push("AND account_id = :account_id");
}
if (params.trade_no) {
sql.push("AND trade_no = :trade_no");
}
if (params.trade_type) {
sql.push("AND trade_type = :trade_type");
}
if (params.tradeTimeBegin) {
sql.push("AND created_at >= :tradeTimeBegin");
}
if (params.tradeTimeEnd) {
sql.push("AND created_at <= :tradeTimeEnd");
}
}
}
module.exports = AccountTradeDao;
const system=require("../../../system");
const Dao=require("../../dao.base");
class UserDao extends Dao{
constructor(){
super(Dao.getModelName(UserDao));
}
async getAuths(userid){
var self=this;
return this.model.findOne({
where:{id:userid},
include:[{model:self.db.models.account,attributes:["id","isSuper","referrerOnlyCode"]},
{model:self.db.models.role,as:"Roles",attributes:["id","code"],include:[
{model:self.db.models.product,as:"Products",attributes:["id","code"]}
]},
],
});
}
extraModelFilter(){
//return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"],joinTableAttributes:['created_at']}]};
return {"key":"include","value":[{model:this.db.models.app,},{model:this.db.models.role,as:"Roles",attributes:["id","name"]}]};
}
extraWhere(obj,w,qc,linkAttrs){
if(obj.codepath && obj.codepath!=""){
// if(obj.codepath.indexOf("userarch")>0){//说明是应用管理员的查询
// console.log(obj);
// w["app_id"]=obj.appid;
// }
}
if(linkAttrs.length>0){
var search=obj.search;
var lnkKey=linkAttrs[0];
var strq="$"+lnkKey.replace("~",".")+"$";
w[strq]= {[this.db.Op.like]:"%"+search[lnkKey]+"%"};
}
return w;
}
async preUpdate(u){
if(u.roles && u.roles.length>0){
var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.in]:u.roles}}});
console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
console.log(roles);
u.roles=roles
}
return u;
}
async update(obj){
var obj2=await this.preUpdate(obj);
console.log("update....................");
console.log(obj2);
await this.model.update(obj2,{where:{id:obj2.id}});
var user=await this.model.findOne({where:{id:obj2.id}});
user.setRoles(obj2.roles);
return user;
}
async findAndCountAll(qobj,t){
var users=await super.findAndCountAll(qobj,t);
return users;
}
async preCreate(u){
// var roles=await this.db.models.role.findAll({where:{id:{[this.db.Op.like]:u.roles}}});
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// console.log(roles);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
// u.roles=roles
return u;
}
async create(u,t){
var self=this;
var u2=await this.preCreate(u);
if(t){
return this.model.create(u2,{transaction: t}).then(user=>{
return user;
});
}else{
return this.model.create(u2).then(user=>{
return user;
});
}
}
//修改用户(user表)公司的唯一码
async putUserCompanyOnlyCode(userId,company_only_code,result){
var customerObj={companyOnlyCode:company_only_code};
var putSqlWhere={where:{id:userId}};
this.updateByWhere(customerObj,putSqlWhere);
return result;
}
}
module.exports=UserDao;
// var u=new UserDao();
// var roledao=system.getObject("db.roleDao");
// (async ()=>{
// var users=await u.model.findAll({where:{app_id:1}});
// var role=await roledao.model.findOne({where:{code:"guest"}});
// console.log(role);
// for(var i=0;i<users.length;i++){
// await users[i].setRoles([role]);
// console.log(i);
// }
//
// })();
const system = require("../../../system");
const Dao = require("../../dao.base");
class UserDao extends Dao {
constructor() {
super(Dao.getModelName(UserDao));
}
/**
* 条件查询
* @param {} params
*/
async findUser(params) {
let sql = [];
sql.push('select * from uc_user where 1 = 1');
if (params.ucname) {
sql.push("AND ucname = :ucname");
}
if (params.uctype) {
sql.push("AND uctype = :uctype");
}
if (params.is_enabled) {
sql.push("AND is_enabled = :is_enabled");
}
sql.push(`AND (deleted_at > NOW() or deleted_at is null)`);
return await this.customQuery(sql.join(" "), params);
}
async getByUcname(ucname, uctype) {
var sql = "SELECT * FROM uc_user WHERE ucname = :ucname AND uctype = :uctype AND deleted_at IS NULL";
var list = await this.customQuery(sql, {
ucname: ucname,
uctype: uctype,
});
if (!list || list.length == 0) {
return null;
}
return list[0];
}
async countByCondition(params) {
var sql = [];
sql.push("SELECT");
sql.push("count(1) as num");
sql.push("FROM uc_user t1");
sql.push("WHERE t1.deleted_at IS NULL");
this.setCondition(sql, params);
var list = await this.customQuery(sql.join(" "), params);
if (!list || list.length == 0) {
return 0;
}
return list[0].num;
}
async listByCondition(params) {
params.startRow = Number(params.startRow || 0);
params.pageSize = Number(params.pageSize || 10);
var sql = [];
sql.push("SELECT");
sql.push("t1.*");
sql.push("FROM uc_user t1");
sql.push("WHERE t1.deleted_at IS NULL");
this.setCondition(sql, params);
sql.push("ORDER BY t1.id DESC");
sql.push("LIMIT :startRow, :pageSize");
return await this.customQuery(sql.join(" "), params);
}
setCondition(sql, params) {
if (!params || !sql) {
return;
}
if (params.uctype) {
sql.push("AND t1.uctype = :uctype");
}
if (params.uctype_id) {
sql.push("AND t1.uctype_id = :uctype_id");
}
if (params.ucname) {
sql.push("AND t1.ucname LIKE :ucname");
}
if (params.mobile) {
sql.push("AND t1.mobile LIKE :mobile");
}
if (params.real_name) {
sql.push("AND t1.real_name LIKE :real_name");
}
if (params.createBegin) {
sql.push("AND t1.created_at >= :createBegin");
}
if (params.createEnd) {
sql.push("AND t1.created_at <= :createEnd");
}
if (params.is_enabled === 0 || params.is_enabled === 1) {
sql.push("AND t1.is_enabled = :is_enabled");
}
if (params.orgpath) {
sql.push("AND t1.orgpath LIKE :orgpath");
}
}
async findMapByIds(ids, attrs) {
let result = {};
if (!ids || ids.length == 0) {
return result;
}
let sql = [];
sql.push("SELECT");
sql.push(attrs || "*");
sql.push("FROM uc_user t1");
sql.push("WHERE t1.id IN (:ids)");
var list = await this.customQuery(sql.join(" "), {
ids: ids
});
if (!list || list.length == 0) {
return result;
}
for (var item of list) {
result[item.id] = item;
}
return result;
}
async updateOrg(org_id, orgpath) {
let sql = "UPDATE uc_user SET orgpath = :orgpath WHERE org_id = :org_id";
await this.customUpdate(sql, {org_id: org_id, orgpath: orgpath});
}
}
module.exports = UserDao;
\ No newline at end of file
const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("accounttrade", {
account_id: DataTypes.BIGINT, // 应用id
trade_type: DataTypes.INTEGER, // 交易类型 1账户交易 2消费交易
trade_no: DataTypes.STRING, // 交易流水号
trade_amt: DataTypes.BIGINT, // 交易金额
trade_desc: DataTypes.STRING, // 交易描述
}, {
paranoid: true, //假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'be_account_trade',
validate: {},
indexes: [
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
],
});
}
\ No newline at end of file
const system=require("../../../system");
const settings=require("../../../../config/settings");
const uiconfig=system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("user", {
userName: {
type:DataTypes.STRING,
allowNull: false,
},
password: {
type:DataTypes.STRING,
allowNull: false,
},
nickName: {
type:DataTypes.STRING,
allowNull: true,
},
sex: {
type:DataTypes.ENUM,
allowNull: true,
values: Object.keys(uiconfig.config.pdict.sex),
},
mobile:DataTypes.STRING,
mail: {
type:DataTypes.STRING,
allowNull: true,
},
headUrl: DataTypes.STRING,
isAdmin:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
isSuper:{
type:DataTypes.BOOLEAN,
defaultValue: false
},
openId:DataTypes.STRING,
app_id:DataTypes.INTEGER,
account_id:DataTypes.INTEGER,
isEnabled:{
type:DataTypes.BOOLEAN,
defaultValue: true
},
},{
paranoid: true,//假的删除
underscored: true,
version: true,
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'p_user',
validate: {
},
indexes:[
// Create a unique index on email
// {
// unique: true,
// fields: ['email']
// },
//
// // Creates a gin index on data with the jsonb_path_ops operator
// {
// fields: ['data'],
// using: 'gin',
// operator: 'jsonb_path_ops'
// },
//
// // By default index name will be [table]_[fields]
// // Creates a multi column partial index
// {
// name: 'public_by_author',
// fields: ['author', 'status'],
// where: {
// status: 'public'
// }
// },
//
// // A BTREE index with a ordered field
// {
// name: 'title_index',
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
]
});
}
......@@ -2,10 +2,27 @@ const system = require("../../../system");
const settings = require("../../../../config/settings");
const uiconfig = system.getUiConfig2(settings.appKey);
module.exports = (db, DataTypes) => {
return db.define("account", {
app_id: DataTypes.STRING, // 应用id
app_data_id: DataTypes.STRING, // 应用数据id
balance: DataTypes.BIGINT, // 账户余额
return db.define("user", {
ucname: DataTypes.STRING,
password: DataTypes.STRING,
real_name: DataTypes.STRING,
mobile: DataTypes.STRING,
uctype: DataTypes.INTEGER,
uctype_id: DataTypes.STRING,
org_id: DataTypes.INTEGER,
orgpath: DataTypes.STRING,
is_enabled: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
is_manager: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
is_main: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
}, {
paranoid: true, //假的删除
underscored: true,
......@@ -13,8 +30,10 @@ module.exports = (db, DataTypes) => {
freezeTableName: true,
//freezeTableName: true,
// define the table's name
tableName: 'be_account',
validate: {},
tableName: 'uc_user',
validate: {
},
indexes: [
// Create a unique index on email
// {
......@@ -45,6 +64,6 @@ module.exports = (db, DataTypes) => {
// method: 'BTREE',
// fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
// }
],
]
});
}
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
class AccountService extends ServiceBase {
constructor() {
super("account", ServiceBase.getDaoName(AccountService));
this.accounttradeDao = system.getObject("db.account.accounttradeDao");
this.dictionary = system.getObject("util.dictionary");
}
async createAccount(params) {
let app_id = this.trim(params.app_id);
let app_data_id = this.trim(params.app_data_id);
let apps = this.dictionary.getDict("APP", "app_id") || {};
if (!apps[app_id]) {
return system.getResult(null, `非法的app_id[${app_id}]`);
}
if (!app_data_id) {
return system.getResult(null, `请输入app_data_id[${app_data_id}]`);
}
let account = await this.dao.findOne({app_id: app_id, app_data_id: app_data_id});
if (account) {
return system.getResult(null, `app_id[${app_id}],app_data_id[${app_data_id}]账户已创建,请不要重复创建`);
}
account = await this.dao.create({
autoIncrement: true,
app_id: app_id,
app_data_id: app_data_id,
balance: 0,
});
return system.getResultSuccess({account_id: account.id});
}
async accountInfo(params) {
let account = await this.dao.getById(params.account_id);
return system.getResultSuccess(account);
}
async accountRecharge(params) {
let p = {trade_type: 2};
p.account_id = params.account_id;
p.trade_amt = Number(params.trade_amt);
p.trade_no = this.trim(params.trade_no);
p.trade_desc = params.trade_desc || "充值";
try {
return await this.trade(p);
} catch (e) {
console.log(e);
return system.getResult(null, "交易错误");
}
}
async accountRefund(params) {
let p = {trade_type: 3};
p.account_id = params.account_id;
p.trade_amt = Number(params.trade_amt);
p.trade_no = this.trim(params.trade_no);
p.trade_desc = params.trade_desc || "退款";
try {
return await this.trade(p);
} catch (e) {
console.log(e);
return system.getResult(null, "交易错误");
}
}
async accountTrade(params) {
let p = {trade_type: 1};
p.account_id = params.account_id;
p.trade_amt = Number(params.trade_amt);
p.trade_no = this.trim(params.trade_no);
p.trade_desc = params.trade_desc || "消费";
try {
return await this.trade(p);
} catch (e) {
console.log(e);
return system.getResult(null, "交易错误");
}
}
async trade(params) {
let accountId = params.account_id;
let trade_no = this.trim(params.trade_no);
let trade_type = params.trade_type;
let trade_amt = Number(params.trade_amt || 0);
if (trade_amt < 0) {
return system.getResult(null, "金额不能为负数");
}
let balance_amt = trade_type == 2 ? trade_amt : -1 * trade_amt;
let trade_desc = params.trade_desc;
if(!accountId) {
return system.getResult(null, "account_id不存在");
}
if(!trade_no) {
return system.getResult(null, "交易流水号不存在");
}
if(!trade_desc) {
return system.getResult(null, "请填写交易描述信息");
}
let _trade = await this.accounttradeDao.findOne({
account_id: accountId,
trade_type: trade_type,
trade_no: trade_no,
});
if (_trade) {
return system.getResult(null, `账户[${accountId}]已存在交易流水号[${trade_no}]`);
}
let res = await this.db.transaction(async t => {
//更新oorder订单记录
let bres = await this.dao.incrementBalance(accountId, balance_amt, t);
console.log(bres);
if (bres === 0) {
return system.getResult(null, "余额不足");
}
//创建orderdeliver记录
await this.accounttradeDao.create({
account_id: accountId,
trade_type: trade_type,
trade_no: trade_no,
trade_amt: trade_amt,
trade_desc: trade_desc,
}, t);
return system.getResultSuccess();
});
return res;
}
async accountTradePage(params) {
if (!params.account_id) {
return {count: 0, rows: []};
}
return await this.tradePageByCondition(params);
}
async tradePageByCondition(params) {
let page = {
count: 0,
rows: []
}
params.currentPage = Number(params.currentPage || 1);
params.pageSize = Number(params.pageSize || 10);
params.startRow = (params.currentPage - 1) * params.pageSize;
page.count = await this.accounttradeDao.countByCondition(params);
if (page.count == 0) {
return system.getResultSuccess(page);
}
page.rows = await this.accounttradeDao.listByCondition(params);
this.dictionary.setRowsName("ACCOUNT_TRADE", page.rows, ["trade_type"]);
this.handleRowsDate(page.rows, ["created_at", "updated_at"]);
return system.getResultSuccess(page);
}
async test(params) {
return system.getResultSuccess("test");
}
}
module.exports = AccountService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
class AccountTradeService extends ServiceBase {
constructor() {
super("account", ServiceBase.getDaoName(AccountTradeService));
this.dictionary = system.getObject("util.dictionary");
}
async test(params) {
return system.getResultSuccess("test");
}
}
module.exports = AccountTradeService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
\ No newline at end of file
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
constructor() {
super("auth", ServiceBase.getDaoName(UserService));
}
async authByCode(opencode) {
var existedUser = null;
var rawUser = null;
var openuser = await this.apiCallWithAk(settings.paasUrl() + "api/auth/accessAuth/authByCode", { opencode: opencode });
if (openuser) {
//先查看自己系统中是否已经存在当前用户
existedUser = await this.dao.model.findOne({ where: { ucname: openuser.userName, ucid: openuser.id }, raw: true });
if (!existedUser) {
existedUser = await this.register(openuser);
}
rawUser = existedUser.get({ raw: true });
rawUser.Roles = openuser.Roles;
}
return rawUser;
}
async getUserLoginInfo(token) {
var acckapp = await this.cacheManager["ApiUserCache"].cache(token, null, settings.usertimeout);
}
async register(openuser) {
var param = {
ucname: openuser.userName, ucid: openuser.id,
last_login_time: new Date()
}
var cruser = await this.dao.create(param);
return cruser;
}
//在平台进行登录,返回目标认证地址
async navSysSetting(user) {
var sysLoginUrl = settings.paasUrl() + "web/auth/userCtl/login?appKey=" + settings.appKey + "\&toKey=" + settings.paasKey;
var x = { userName: user.userName, password: user.password, mobile: user.mobile };
var restResult = await this.restS.execPost({ u: x }, sysLoginUrl);
if (restResult) {
var rtnres = JSON.parse(restResult.stdout);
if (rtnres.status == 0) {
return rtnres.data;
}
}
return null;
}
async getUserByUserNamePwd(u) {
var user = await this.dao.model.findOne({
where: { userName: u.userName, password: u.password, app_id: u.app_id },
include: [
{ model: this.db.models.role, as: "Roles", attributes: ["id", "code"] },
]
});
return user;
}
async checkSameName(uname, appid) {
var ac = await this.dao.model.findOne({ where: { userName: uname, app_id: appid } });
var rtn = { isExist: false };
if (ac) {
rtn.isExist = true;
}
return rtn;
}
}
module.exports = UserService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
// console.log((result));
// }).catch(function(e){
// console.log(e);
// });
const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class UserService extends ServiceBase {
constructor() {
super("user", ServiceBase.getDaoName(UserService));
this.dictionary = system.getObject("util.dictionary");
}
async adminLogin(obj) {
obj.uctype = 1;
let res = await this.login(obj);
return res;
}
async merchantLogin(obj) {
obj.uctype = 2;
let res = await this.login(obj);
return res;
}
async login(obj) {
let uctype = obj.uctype;
if ([1, 2].indexOf(uctype) == -1) {
return system.getResult(null, "用户类型错误");
}
let user = await this.dao.getByUcname(obj.ucname, uctype);
// 验证登录合法
if (!user) {
return system.getResult(null, "用户名或密码错误");
}
if (!user.is_enabled) {
return system.getResult(null, "用户已禁用");
}
if (uctype && uctype != user.uctype) {
return system.getResult(null, "用户类型错误");
}
let loginPwd = await this.getEncryptStr(obj.password);
if (loginPwd != user.password) {
return system.getResult(null, "用户名或密码错误");
}
await this.setLogin(user);
return system.getResultSuccess(user);
}
async setLogin(user) {
console.log("设置登录信息,权限,角色等");
}
async saveAdminUser(obj) {
obj.uctype = 1;
return await this.saveUser(obj);
}
async saveMerchantUser(obj) {
obj.uctype = 2;
if (!obj.uctype_id) {
return system.getResult(null, "未选择用户所属商户");
}
return await this.saveUser(obj);
}
async saveUser(obj) {
let id = obj.id;
let password = this.trim(obj.password);
let uctype_id = this.trim(obj.uctype_id);
let user = {};
try {
if (id) {
user = await this.findById(id);
} else {
if (!password) {
return system.getResult(null, "密码不能为空");
}
}
user.uctype = obj.uctype;
user.uctype_id = uctype_id;
user.ucname = this.trim(obj.ucname);
user.mobile = this.trim(obj.mobile);
user.real_name = this.trim(obj.real_name);
if (password) {
user.password = await this.getEncryptStr(password);
}
if (user.id) {
user = await user.save();
} else {
user.autoIncrement = true;
user = await this.dao.create(user);
}
} catch (e) {
if (e.name == 'SequelizeValidationError') {
return system.getResult(-1, `用户名[${user.ucname}]重复`);
}
console.log(new Date(), e);
return system.getResult(-1, `服务错误`);
}
return system.getResultSuccess(user);
}
async info(params) {
var id = Number(params.id || 0);
var user = await this.dao.getById(id);
if (!user) {
return system.getResult(null, "用户不存在");
}
this.handleDate(user, ["created_at"], null, -8);
return system.getResultSuccess(user);
}
async enabled(params) {
var user = await this.dao.findById(params.id);
if (!user) {
return system.getResult(null, "用户不存在");
}
user.is_enabled = Number(params.is_enabled || 0) == 0 ? false : true;
await user.save();
return system.getResultSuccess();
}
async pageByCondition(params) {
var result = {
count: 0,
rows: []
};
var currentPage = Number(params.currentPage || 1);
var pageSize = Number(params.pageSize || 10);
if (params.orgpath) {
params.orgpath = params.orgpath + "%";
}
var total = await this.dao.countByCondition(params);
if (total == 0) {
return result;
}
result.count = total;
params.startRow = (currentPage - 1) * pageSize;
result.rows = await this.dao.listByCondition(params) || [];
if (result.rows) {
for (let item of result.rows) {
this.handleDate(item, ["created_at"], null, -8);
}
await this.setRoles(result.rows);
await this.setOrg(result.rows);
}
return system.getResultSuccess(result);
}
async delUser(params) {
var user = await this.findById(params.id);
if (!user) {
return system.getResultSuccess();
}
if (user.saas_id != params.saas_id) {
return system.getResult(null, "权限不足");
}
await this.delete({
id: params.id
});
return system.getResultSuccess();
}
async updPassword(params) {
var user = await this.findById(params.id);
if (!user) {
return system.getResult(null, "用户不存在");
}
user.password = await this.getEncryptStr(params.password);
await user.save();
return system.getResultSuccess();
}
async mapByIds(params) {
let rs = await this.dao.findMapByIds(params.ids);
return system.getResultSuccess(rs);
}
async findUsers(params) {
if (params.roleCodes && params.roleCodes.length > 0) {
var roleIds = await this.roleDao.findIdsByCode(params.roleCodes, params.saas_id);
if (!roleIds) {
return [];
}
params.roleIds = roleIds;
}
let rs = await this.dao.findUsers(params);
return system.getResultSuccess(rs);
}
async setOrg(rows) {
if (!rows || rows.length == 0) {
return;
}
let orgIds = [];
for (let row of rows) {
orgIds.push(row.org_id);
}
let map = await this.orgDao.mapByIds(orgIds);
for (let row of rows) {
let org = map[row.org_id] || {};
row.orgname = org.orgname || "";
row.org = org;
}
}
async setRoles(rows) {
if (!rows || rows.length == 0) {
return;
}
let userIds = [];
for (let row of rows) {
userIds.push(row.id);
}
let rolesMap = await this.userroleDao.mapByUserIds2(userIds);
for (let row of rows) {
let roleIds = [];
let roleNames = [];
let roles = rolesMap[row.id] || [];
for (let r of roles) {
roleIds.push(r.id);
roleNames.push(r.name);
}
row.roleIds = roleIds.join(",");
row.roleNames = roleNames.join(",");
row.roles = roles;
}
}
}
module.exports = UserService;
\ No newline at end of file
......@@ -2,9 +2,9 @@ const system = require("../system");
class Dictionary {
constructor() {
// 交易字典
this.APP = {
app_id: {"100001": "电子平台", "10000x": "xxxxxxxxxx"},
// 字典
this.USER = {
UC_TYPE: {"100001": "电子平台", "10000x": "xxxxxxxxxx"},
};
this.ACCOUNT_TRADE = {
trade_type: {1: "交易", 2: "充值", 3: "退款"}
......
var url = require("url");
var system = require("../../base/system");
var userSve = system.getObject("service.auth.userSve");
module.exports = function (app) {
app.get("/auth", async function (req, res) {
if (!req.query.opencode) {
return system.getResult(null, "opencode参数不能为空");
}
return await userSve.authByCode(opencode);
});
app.get('/api/:gname/:qname/:method', function (req, res) {
var classPath = req.params["qname"];
var methodName = req.params["method"];
......
var url = require("url");
var system = require("../../base/system");
var metaCtl = system.getObject("web.common.metaCtl");
var userCtl = system.getObject("web.auth.userCtl");
const system = require("../../base/system");
const redisClient = system.getObject("util.redisClient");
module.exports = function (app) {
......
......@@ -7,8 +7,8 @@ var ENVINPUT = {
REDIS_HOST: process.env.REDIS_HOST,
REDIS_PORT: process.env.REDIS_PORT,
REDIS_PWD: process.env.REDIS_PWD,
DB_NAME: process.env.ESIGNSVEMERCHANT_DB_NAME,
REDIS_DB: process.env.ESIGNSVEMERCHANT_REDIS_DB,
DB_NAME: process.env.ESIGNSVEUC_DB_NAME,
REDIS_DB: process.env.ESIGNSVEUC_REDIS_DB,
APP_ENV: process.env.APP_ENV ? process.env.APP_ENV : "dev"
};
......@@ -21,7 +21,7 @@ var settings = {
cacheprefix: "sjb",
usertimeout: 3600, //单位秒
basepath: path.normalize(path.join(__dirname, '../..')),
port: process.env.NODE_PORT || 3303,
port: process.env.NODE_PORT || 3651,
defaultPassWord: "987456",
paasUrl: function () {
if (this.env == "dev") {
......
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