Commit 23ceb212 by 蒋勇

d

parent cfe3f473
...@@ -22,7 +22,7 @@ class CtlBase { ...@@ -22,7 +22,7 @@ class CtlBase {
return system.getResult(apps); return system.getResult(apps);
} }
async refQuery(pobj, qobj, req) { async refQuery(pobj, qobj, req) {
return this.dao.refQuery(pobj); return this.service.refQuery(pobj);
} }
async setContextParams(pobj, qobj, req) { async setContextParams(pobj, qobj, req) {
let custtags = req.headers["x-consumetag"]?req.headers["x-consumetag"].split("|"):null; let custtags = req.headers["x-consumetag"]?req.headers["x-consumetag"].split("|"):null;
......
...@@ -8,8 +8,6 @@ var cacheBaseComp = null; ...@@ -8,8 +8,6 @@ var cacheBaseComp = null;
class RoleCtl extends CtlBase { class RoleCtl extends CtlBase {
constructor() { constructor() {
super("auth",CtlBase.getServiceName(RoleCtl)); super("auth",CtlBase.getServiceName(RoleCtl));
//this.loginS=system.getObject("service.userSve");
this.roleS=system.getObject("service.auth.roleSve");
this.redisClient=system.getObject("util.redisClient"); this.redisClient=system.getObject("util.redisClient");
} }
async initNewInstance(pobj,queryobj, req) { async initNewInstance(pobj,queryobj, req) {
......
...@@ -5,6 +5,7 @@ class Dao { ...@@ -5,6 +5,7 @@ class Dao {
var db = system.getObject("db.common.connection").getCon(); var db = system.getObject("db.common.connection").getCon();
this.db = db; this.db = db;
console.log("........set dao model.........."); console.log("........set dao model..........");
console.log(this.modelName)
this.model = db.models[this.modelName]; this.model = db.models[this.modelName];
console.log(this.modelName); console.log(this.modelName);
} }
......
...@@ -6,7 +6,7 @@ class UserService extends ServiceBase { ...@@ -6,7 +6,7 @@ class UserService extends ServiceBase {
constructor() { constructor() {
super("auth", ServiceBase.getDaoName(UserService)); super("auth", ServiceBase.getDaoName(UserService));
this.companyDao = system.getObject("db.common.companyDao"); this.companyDao = system.getObject("db.common.companyDao");
this.roleDao = system.getObject("db.common.roleDao"); this.roleDao = system.getObject("db.auth.roleDao");
} }
//平台注册,默认角色,不具备平台级别的管理或运营功能 //平台注册,默认角色,不具备平台级别的管理或运营功能
......
const system=require("../../../system");
const settings=require("../../../../config/settings");
const ServiceBase=require("../../sve.base")
var WXPay = require('wx-pay');
const uuidv4 = require('uuid/v4');
class ApiTradeService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(ApiTradeService));
}
async create(tradeObj){
var self=this;
return this.db.transaction(async function (t){
//获取缓存二个值,一个是赠送次数,一个是调用价格
var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
var apiInitGift = pconfig.find(item => {
return item.configType === "apiInitGift";
});
var apiCallPrice = pconfig.find(item => {
return item.configType === "apiCallPrice";
});
var app=await self.cacheManager["AppCache"].cacheApp(tradeObj.appkey,null,1);
tradeObj.app_id=app.id;
var callCache=await self.cacheManager["ApiCallCountCache"].getApiCallCount(tradeObj.appkey,tradeObj.op);
var callAccuCache=await self.cacheManager["ApiAccuCache"].getApiCallAccu(tradeObj.appkey);
var calledCount=Number(callCache.callcount);
var balance=Number(callCache.amount);
if(calledCount>Number(apiInitGift.configValue)){//调用次数大于免费次数
tradeObj.amount=Number(apiCallPrice.configValue);
}else{
tradeObj.amount=0;
}
//解决日志大于4000写入的问题
if(tradeObj.params.length>3980){
tradeObj.params=tradeObj.params.substring(0,3980);
}
var apitrade=await self.dao.model.create(tradeObj,{transaction:t});
//按照调用方法缓存
await self.cacheManager["ApiCallCountCache"].addCallCount(tradeObj.appkey,tradeObj.op,1);
await self.cacheManager["ApiCallCountCache"].addCallBalance(tradeObj.appkey,tradeObj.op,tradeObj.amount);
//累计缓存调用次数和金额
await self.cacheManager["ApiAccuCache"].addCallCount(tradeObj.appkey,1);
await self.cacheManager["ApiAccuCache"].addCallBalance(tradeObj.appkey,tradeObj.amount);
// await self.cacheManager["ApiCircuitBreakers"].addCallCount(-1);
return apitrade;
});
}
async beforesel(tradeObj){
var self=this;
var callCaches=await self.cacheManager["ApiCircuitBreakers"].getApiCall();
var calledCounts=Number(callCaches.callcount);
if( calledCounts>100 ){
// return {status:-1,msg:"服务器繁忙,请稍候再试",data:null};
}
else {
// await self.cacheManager["ApiCircuitBreakers"].addCallCount(1);
}
var callCache=await self.cacheManager["ApiCircuitBreakerCache"].getApiCall(tradeObj.appkey);
var calledCount=Number(callCache.callcount);
if( calledCount>1000 ){
return {status:-1,msg:"调用次数太多,请稍候再试",data:null};
}
else {
var result=await self.cacheManager["ApiCircuitBreakerCache"].addCallCount(tradeObj.appkey,1);
}
return {status:1,msg:"OK"};
}
}
module.exports=ApiTradeService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class AppdetailService{
constructor(){
this.cacheManager=system.getObject("db.cacheManager");
}
//app调用次数
async findAndCountAlldetail(obj){
var details=[];
var apicallAccu= await this.cacheManager["ApiAccuCache"].getApiCallAccu(obj);
var result={rows:[],count:0};
var keys=await this.cacheManager["MagCache"].keys("api_call_" + obj + "*");
var detail=null;
for(let j=0;j<keys.length;j++){
var d=keys[j];
var pathdetail=d.substr(d.lastIndexOf("_")+1,d.length);
var apicalldetailAccu= await this.cacheManager["ApiCallCountCache"].getApiCallCount(obj,pathdetail);
var detail={"detailPath":d,"detailCount":apicalldetailAccu.callcount,"detailAmount":apicalldetailAccu.amount};
details.push(detail);
}
result.rows=details;
result.count=details.length;
return result;
}
async delCache(obj){
return this.cacheManager["MagCache"].del(obj.key);
}
async clearAllCache(obj){
return this.cacheManager["MagCache"].clearAll();
}
}
module.exports=AppdetailService;
const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
class OplogService extends ServiceBase {
constructor() {
super("common", ServiceBase.getDaoName(OplogService));
//this.appDao=system.getObject("db.appDao");
this.opLogUrl = settings.apiconfig.opLogUrl();
this.opLogEsIsAdd = settings.apiconfig.opLogEsIsAdd();
}
async create(qobj) {
if (!qobj || !qobj.op || qobj.op.indexOf("metaCtl/getUiConfig") >= 0 ||
qobj.op.indexOf("userCtl/checkLogin") >= 0 ||
qobj.op.indexOf("oplogCtl") >= 0 ||
qobj.op.indexOf("getDicConfig") >= 0 ||
qobj.op.indexOf("getRouteConfig") >= 0 ||
qobj.op.indexOf("getRsConfig") >= 0) {
return null;
}
var rc = system.getObject("util.execClient");
var rtn = null;
try {
// var myDate = new Date();
// var tmpTitle=myDate.toLocaleString()+":"+qobj.optitle;
qobj.optitle = (new Date()).Format("yyyy-MM-dd hh:mm:ss") + ":" + qobj.optitle;
if (this.opLogEsIsAdd == 1) {
qobj.content = qobj.content.replace("field list", "字段列表")
qobj.created_at = (new Date()).getTime();
//往Es中写入日志
var addEsData = JSON.stringify(qobj);
rc.execPost(qobj, this.opLogUrl);
} else {
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
} catch (e) {
console.log("addLog------>>>>>>error-----------------------*****************");
console.log(e);
//解决日志大于4000写入的问题
if (qobj.content.length > 3980) {
qobj.content = qobj.content.substring(0, 3980);
}
this.dao.create(qobj);
}
}
}
module.exports = OplogService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class PConfigService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(PConfigService));
//this.appDao=system.getObject("db.appDao");
}
async findOrSetPrice(num,appkey){
return this.cacheManager["PriceConfigCache"].cacheGlobalVal(num,appkey);
}
async create(pobj){
await this.cacheManager["PConfigCache"].invalidate(pobj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(pobj.appkey);
return this.dao.create(pobj);
}
async update(pobj,tm=null){
await this.cacheManager["PConfigCache"].invalidate(pobj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(pobj.appkey);
return this.dao.update(pobj,tm);
}
async updateByWhere(setObj,whereObj,t){
await this.cacheManager["PConfigCache"].invalidate(setObj.appkey);
await this.cacheManager["InitGiftCache"].invalidate(setObj.appkey);
return this.dao.updateByWhere(setObj,whereObj,t);
}
//获取配置的发票税率
async getInvoiceTaxRate(){
var tmpInvoiceTaxRate=7;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "invoiceTaxRate";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
tmpInvoiceTaxRate=Number(pconfigResult.configValue);
}
return tmpInvoiceTaxRate;
}
//获取配置的信息
async getConfigValue(configName){
var configValue=0;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === configName;
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
configValue=Number(pconfigResult.configValue);
}
return configValue;
}
//获取配置的推荐人分润比例
async getReferrerProfitRatio(){
var tmpInvoiceTaxRate=10;
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "referrerProfitRatio";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
tmpInvoiceTaxRate=Number(pconfigResult.configValue);
}
return tmpInvoiceTaxRate;
}
//商机分配渠道配置,格式:wssyh5,yzc等
async getBussinessAllotChannelConfig(){
var bussinessAllotChannel="wssyh5";
var pconfig=await this.cacheManager["PConfigCache"].cachePConfig();
var pconfigResult= pconfig.find(item => {
return item.configType === "bussinessAllotChannelConfig";
});
if(pconfigResult!=null && pconfigResult.configValue!=null && pconfigResult.configValue!=""){
bussinessAllotChannel=pconfigResult.configValue;
}
return bussinessAllotChannel;
}
}
module.exports=PConfigService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TaskService));
//this.appDao=system.getObject("db.appDao");
this.taskManager=system.getObject("db.taskManager");
this.emailClient=system.getObject("util.mailClient");
this.personTaxDao=system.getObject("db.individualincometaxDao");
this.ossClient=system.getObject("util.ossClient");
}
//写文件并上传到阿里云,返回上传的路径
async writexls(wb,sharecode){
var that=this;
var uuid=uuidv4();
var u=uuid.replace(/\-/g,"");
var fname="zc_"+u+".xlsx";
var filepath="/tmp/"+fname;
var promise=new Promise((resv,rej)=>{
wb.xlsx.writeFile(filepath).then(async function(d) {
var rtn=await that.ossClient.upfile(fname,filepath);
fs.unlink(filepath,function(err){});
return resv(rtn);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
//读取模板文件
async readxls(){
var promise=new Promise((resv,rej)=>{
var workbook = new excel.Workbook();
workbook.properties.date1904 = true;
var bpth=path.normalize(path.join(__dirname, '../'));
workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
.then(function() {
return resv(workbook);
}).catch(function(e){
return rej(e);
});
});
return promise;
}
async buildworkbook(taxCalcList){
var workbook = await this.readxls();
var sheet = workbook.getWorksheet(1);
sheet.columns = [
{ header: '年度', key: 'statisticalYear', width: 10 },
{ header: '月份', key: 'statisticalMonth', width: 10 },
{ header: '员工姓名', key: 'employeeName', width: 10 },
{ header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
{ header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
// { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
{ header: '子女教育', key: 'childrenEducation', width: 10 },
{ header: '继续教育', key: 'continuingEducation', width: 10 },
{ header: '房贷利息', key: 'interestExpense', width: 10 },
{ header: '住房租金', key: 'housingRent', width: 10 },
{ header: '赡养老人', key: 'supportElderly', width: 10 },
{ header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
{ header: '专项扣除合计', key: 'specialDeduction', width: 10 },
{ header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
{ header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
{ header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
{ header: '适用税率', key: 'taxRate', width: 10 },
{ header: '速算扣除', key: 'deductionNumber', width: 10 },
{ header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
{ header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
// (累计税前薪资-累计五险一金-累计免征额-累计已扣专项)*税率-速算扣除-累计已纳个税=本月应纳个税
];
taxCalcList.forEach(r=>{
sheet.addRow(r);
});
return workbook;
}
async makerpt(qobj){
var self=this;
return this.db.transaction(async t=>{
const sharecode=qobj.sharecode;
const email=qobj.email;
//按照sharecode获取单位某次个税计算
var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
var sheetNameSufix="个税汇总表";
if(taxCalcList && taxCalcList.length>0){
var year=taxCalcList[0].statisticalYear;
var month=taxCalcList[0].statisticalMonth;
sheetNameSufix=year+month+sheetNameSufix;
}
var wb=await this.buildworkbook(taxCalcList);
//生成excel
var result=await this.writexls(wb,sharecode);
//异步不等待发送邮件给
var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
//发送手机短信
//写到按咋回哦sharecode,修改下载的url
return result.url;
});
}
async create(qobj){
var self=this;
return this.db.transaction(async t=>{
var task=await this.dao.create(qobj,t);
//发布任务事件
var action="new";
var taskClassName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
await self.taskManager.newTask(msg);
await self.taskManager.publish("task","newtask");
return task;
});
}
async restartTasks2(qobj){
return this.restartTasks(qobj);
}
async restartTasks(qobj){
var self=this;
var rtn={};
var tasks=await this.dao.model.findAll({raw:true});
//清空任务列表
await this.taskManager.clearlist();
for(var i=0;i<tasks.length;i++){
var tmpTask2=tasks[i];
try {
(async (tmpTask,that)=>{
var action="new";
var taskClassName=tmpTask.taskClassName;
var exp=tmpTask.taskexp;
var msg=action+"_"+taskClassName+"_"+exp;
// await that.taskManager.newTask(msg);
// await that.taskManager.publish("task","newtask");
await that.taskManager.addTask(taskClassName,exp);
})(tmpTask2,self);
} catch (e) {
rtn=null;
}
}
return rtn;
}
async delete(qobj){
var self=this;
return this.db.transaction(async t=>{
var task= await this.dao.model.findOne({where:qobj});
await this.dao.delete(task,qobj,t);
//发布任务事件
var action="delete";
var taskName=task.taskClassName;
var exp=task.taskexp;
var msg=action+"_"+taskName;
//发布任务,消息是action_taskClassName
await this.taskManager.publish("task",msg,null);
return task;
});
}
}
module.exports=TaskService;
const system=require("../../../system");
const settings=require("../../../../config/settings");
const ServiceBase=require("../../sve.base")
var WXPay = require('wx-pay');
const uuidv4 = require('uuid/v4');
const querystring = require('querystring');
const crypto = require('crypto');
const cryptoJS = require("crypto-js");
const logCtl=system.getObject("web.oplogCtl");
class TradeService extends ServiceBase{
constructor(){
super(ServiceBase.getDaoName(TradeService));
this.appDao=system.getObject("db.appDao");
this.userDao=system.getObject("db.userDao");
this.accountDao=system.getObject("db.accountDao");
this.productDao=system.getObject("db.productDao");
this.orderDao=system.getObject("db.orderDao");
this.orderflowDao=system.getObject("db.orderflowDao");
this.tradeDao=system.getObject("db.tradeDao");
this.profitcenterDao=system.getObject("db.profitcenterDao");
this.wxSvr=system.getObject("service.wxSve");
this.wxpay = WXPay({
appid: 'wx6f3ebe44defe336a',
mch_id: '1232813602',
partner_key: 'sinotone2014sinotone2014sinotone',
});
this.yunzhanghuApiUrl=settings.apiconfig.yunzhanghuApiUrl();//云帐户提现接口url
this.yunzhanghuCallbackApiUrl=settings.apiconfig.yunzhanghuCallbackApiUrl();//云帐户提现回调接口url
this.yunzhanghuQueryAccountsUrl=settings.apiconfig.yunzhanghuQueryAccountsUrl();//云帐户商户查询余额接口url
this.yunzhanghuVerifyBankCardUrl=settings.apiconfig.yunzhanghuVerifyBankCardUrl();//云帐户验证银行卡的有效性接口url
this.yunzhanghuDESKey=settings.apiconfig.yunzhanghuDESKey();
this.yunzhanghuDealer_id=settings.apiconfig.yunzhanghuDealer_id();
this.yunzhanghuBroker_id=settings.apiconfig.yunzhanghuBroker_id();
this.yunzhanghuAppKey=settings.apiconfig.yunzhanghuAppKey();
this.yunzhanghuDESKey=settings.apiconfig.yunzhanghuDESKey();
this.yunzhanghuTxXz=settings.apiconfig.yunzhanghuTxXz();
this.bossWithdrawApplyingKey=settings.apiconfig.bossWithdrawApplyingKey();
}
async getCreateUUId(code){
var tcode=code==null?"":code;
var myDate=new Date();
var uid=await this.getUidStr(8,60);
return tcode+""+myDate.getFullYear()+""+(myDate.getMonth()+1)+""+myDate.getDate()+""+myDate.getMilliseconds()+""+uid;
}
async getUidStr(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
}
async findOneByIdKey(tradekey){
var rtn=await this.dao.findOne({idkey:tradekey});
return rtn;
}
async closeWxOrder(idkey){
return this.wxSvr.closeWxOrder(idkey);
}
async queryWxOrder(idkey){
var s= await this.wxSvr.queryWxOrder(idkey);
console.log(s);
return s;
}
async createUnifiedOrder(desc,amount,notify_url,pid,attach,out_trade_no){
return this.wxSvr.createUnifiedOrder(desc,amount,notify_url,pid,attach,out_trade_no);
}
async createOrderPaid(obj){
var amount= obj.totalSum;
// if(settings.env=="dev"){
// amount=1;
// }else{
// //amount=Number(amount)*100;
// amount=1;
// }
console.log(amount);
// var u=uuidv4();
// var out_trade_no=u.replace(/\-/g,"");
// var out_trade_no=obj.orderNum;
var self=this;
var promise= await this.wxSvr.createUnifiedOrder(obj.itemName,amount,'http://boss.gongsibao.com/wx/pay',obj.itemCode);
// var promise=new Promise(function(resv,rej){
// self.wxpay.createUnifiedOrder({
// body: obj.itemName,
// out_trade_no: out_trade_no,
// total_fee: Number(amount),
// spbill_create_ip: '192.168.2.210',
// notify_url: 'http://boss.gongsibao.com/web/notify',
// trade_type: 'NATIVE',
// product_id: obj.itemCode,
// }, function(err, result){
// if(err){
// return rej(err);
// }else{
// var qrurl=settings.apiconfig.qcurl.replace("{address}",result.code_url);
// result.qrurl=qrurl;
// result.tradekey=out_trade_no;
// return resv(result);
// }
// });
// });
return promise;
}
async create(user,tradeObj){
//var app=await this.appDao.model.findOne({where:{id:user.app_id}});
//var usr =await this.userDao.model.findOne({where:{id:user.id}});
var usr = this.db.models.user.build(user);
var account=await this.accountDao.model.findOne({where:{id:user.account_id}});
var self=this;
console.log(tradeObj);
return this.db.transaction(async function (t){
self.cacheManager["AccountBalanceCache"].del(user.account_id,user.app_id);
return self.dao.create2(usr,account,tradeObj,t);
});
}
async createOrderTrade(qobj,orderNum,payResult,payUser){
var order = await this.orderDao.findOneByOrderNum(orderNum);
var user = await this.userDao.findById(order.user_id);
order=order.dataValues;
user=user.dataValues;
var that=this;
return this.db.transaction(async function (t){
order.orderStatus="4";
order.paymentSerialNumber=payResult.transaction_id;
order.paymentPlatform="微信";
order.payUserId=payUser.id;
order.payNickName=payUser.nickName;
order.payAppId=payUser.appid;
var orderResult=await that.orderDao.update(order,t);
order.orderStatusName="付款成功";
if(order.id!=null){
var orderflowObj={
app_id:order.app_id,
user_id:order.user_id,
userName:user.userName,
nickName:user.nickName,
orderNum:order.orderNum,
opContent:"订单付款"
};
var orderflow = await that.orderflowDao.create(orderflowObj,t);//订单流程
qobj["app_id"]=order.app_id;
qobj["account_id"]=user.account_id;
qobj["user_id"]=order.user_id;
qobj["username"]=user.userName;
qobj["nickName"]=user.nickName;
qobj["orderNum"]=order.orderNum;
var trade= await that.dao.createOrderTrade(qobj,t);
trade.dataValues["order"]=order;
return trade;
}else{
return null;
}
});
}
async withdrawMoney(user,partnerinfo,amount){
if(amount<=0){
return {code:-210,msg:"输入的金额有误"};
}
//settings配置,云帐户提现是否受限制-1不受限制
var yunzhanghuTxXzSettings=parseFloat(this.yunzhanghuTxXz);
if(yunzhanghuTxXzSettings>=0){
amount=yunzhanghuTxXzSettings;
}
var self=this;
return this.db.transaction(async function (t){
//提现写表操作
//是否配置pconfig提现限制,如果配置则验证限制规则
var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
if(pconfig!=null&&pconfig!="undefined"&&pconfig.length>0){
var resultPconfig= pconfig.find(item => {
return item.configType === "withdrawalLimit";
});
if(resultPconfig!=null){
var pconfigTxXz=parseFloat(resultPconfig.configValue);
if(pconfigTxXz==0){
return {code:-220,msg:"目前该系统提现申请发放故障,敬请期待!"};
}
if(pconfigTxXz>0&&amount>pconfigTxXz){
return {code:-230,msg:"提现金额大于单笔交易额度,单笔最大交易额度为"+pconfigTxXz};
}
}
}//提现申请发放额度有限制
//用户已经申请,待发放的总金额+此次申请的金额=申请总金额
var rd=await self.profitcenterDao.findSum('totalSum',{where:{account_id:user.account_id,opType:"applying"}});
var applyingSum=rd?rd:0;
var tmpSumTotal=parseFloat(amount)+parseFloat(applyingSum);
//用户交易总金额Sum,tradeType:orderPersonFee订单个人分润、recommendFee推荐分润、cashWithdrawal现金提现
var tmpWhere={where:{[self.dao.db.Op.or]: [{tradeType: 'orderPersonFee'}, {tradeType: 'recommendFee'}, {tradeType: 'cashWithdrawal'}],
[self.dao.db.Op.and]: [{account_id:user.account_id}]}};
var sumTotal=await self.dao.findSum('renAmount',tmpWhere);
var tradeTotalSum=sumTotal?parseFloat(sumTotal):0;
if(tmpSumTotal>tradeTotalSum){
return {code:-240,msg:"输入金额有误,已申请金额为:"+applyingSum+",剩余可申请金额为:"+(tradeTotalSum-applyingSum)};
}
var aid=user.account_id;
var userAccountInfo=await self.accountDao.findById(aid);
if(userAccountInfo==null){
return {code:-250,msg:"用户信息有误"};
}
//用户帐户总金额
if(tmpSumTotal>userAccountInfo.renBalance){
return {code:-260,msg:"输入金额有误,已申请金额为:"+applyingSum+",剩余可申请金额为:"+(userAccountInfo.renBalance-applyingSum)};
}
var tmpOpIdentify= await self.getCreateUUId("sq");
var orderId=await self.getCreateUUId("tx");
//添加新的提现申请记录
var addParams={
account_id:user.account_id,
userName:user.userName,
opTypeName:"申请中",
opType:"applying",
totalSum:amount,
identityCard:partnerinfo.identityCard,
cardNo:partnerinfo.cardNo,
realName:partnerinfo.realName,
opIdentify:tmpOpIdentify,
tradeOrderNum:orderId
};
var item=await self.profitcenterDao.create(addParams,t);
item=item.get({plain:true});
let keyHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey);
let ivHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey.substring(0,8));
var cipherParams={
id:item.id,
account_id:user.account_id,
userName:user.userName,
opType:"applying",
totalSum:amount,
identityCard:partnerinfo.identityCard,
cardNo:partnerinfo.cardNo,
realName:partnerinfo.realName,
opIdentify:tmpOpIdentify,
tradeOrderNum:orderId
};
var stringStr = JSON.stringify(cipherParams);
var ciphertext = cryptoJS.TripleDES.encrypt(stringStr, keyHex, { iv: ivHex }).toString();
var cipherData=encodeURIComponent(ciphertext);
var putItem={
id:item.id,
cipherData:cipherData
};
await self.profitcenterDao.update(putItem,t);
return {code:1,msg:"提现成功"};
});
}
//提现申请
async setWithdrawMoneyApplying(user,partnerinfo,amount){
if(amount<=0){
return {code:-210,msg:"输入的金额有误"};
}
//settings配置,云帐户提现是否受限制-1不受限制
var yunzhanghuTxXzSettings=parseFloat(this.yunzhanghuTxXz);
if(yunzhanghuTxXzSettings>=0){
amount=yunzhanghuTxXzSettings;
}
var self=this;
return this.db.transaction(async function (t){
//提现写表操作
//是否配置pconfig提现限制,如果配置则验证限制规则
var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
if(pconfig!=null&&pconfig!="undefined"&&pconfig.length>0){
var resultPconfig= pconfig.find(item => {
return item.configType === "withdrawalLimit";
});
if(resultPconfig!=null){
var pconfigTxXz=parseFloat(resultPconfig.configValue);
if(pconfigTxXz==0){
return {code:-220,msg:"目前该系统提现申请发放故障,敬请期待!"};
}
if(pconfigTxXz>0&&amount>pconfigTxXz){
return {code:-230,msg:"提现金额大于单笔交易额度,单笔最大交易额度为"+pconfigTxXz};
}
}
}//提现申请发放额度有限制
//用户已经申请,待发放的总金额+此次申请的金额=申请总金额
var rd=await self.profitcenterDao.findSum('totalSum',{where:{account_id:user.account_id,opType:"applying"}});
var applyingSum=rd?rd:0;
var tmpSumTotal=parseFloat(amount)+parseFloat(applyingSum);
//用户交易总金额Sum,tradeType:orderPersonFee订单个人分润、recommendFee推荐分润、cashWithdrawal现金提现
// var tmpWhere={where:{[self.dao.db.Op.or]: [{tradeType: 'orderPersonFee'}, {tradeType: 'recommendFee'}, {tradeType: 'cashWithdrawal'}],
// [self.dao.db.Op.and]: [{user_id: user.id}, {app_id: user.app_id}]}};
var tmpWhere={where:{[self.dao.db.Op.or]: [{tradeType: 'orderPersonFee'}, {tradeType: 'recommendFee'}, {tradeType: 'cashWithdrawal'}],
[self.dao.db.Op.and]: [{account_id:user.account_id}]}};
var sumTotal=await self.dao.findSum('renAmount',tmpWhere);
var tradeTotalSum=sumTotal?parseFloat(sumTotal):0;
if(tmpSumTotal>tradeTotalSum){
return {code:-240,msg:"输入金额有误,已申请金额为:"+applyingSum+",剩余可申请金额为:"+(tradeTotalSum-applyingSum)};
}
var aid=user.account_id;
var userAccountInfo=await self.accountDao.findById(aid);
if(userAccountInfo==null){
return {code:-250,msg:"用户信息有误"};
}
//用户帐户总金额
if(tmpSumTotal>userAccountInfo.renBalance){
return {code:-260,msg:"输入金额有误,已申请金额为:"+applyingSum+",剩余可申请金额为:"+(userAccountInfo.renBalance-applyingSum)};
}
var tmpOpIdentify= await self.getCreateUUId("sq");
var orderId=await self.getCreateUUId("tx");
//添加新的提现申请记录
var addParams={
app_id:user.app_id,
user_id:user.id,
account_id:user.account_id,
userName:user.userName,
opTypeName:"申请中",
opType:"applying",
totalSum:amount,
identityCard:partnerinfo.identityCard,
cardNo:partnerinfo.cardNo,
realName:partnerinfo.realName,
opIdentify:tmpOpIdentify,
tradeOrderNum:orderId
};
var item=await self.profitcenterDao.create(addParams,t);
item=item.get({plain:true});
let keyHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey);
let ivHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey.substring(0,8));
var cipherParams={
id:item.id,
app_id:user.app_id,
user_id:user.id,
account_id:user.account_id,
userName:user.userName,
opType:"applying",
totalSum:amount,
identityCard:partnerinfo.identityCard,
cardNo:partnerinfo.cardNo,
realName:partnerinfo.realName,
opIdentify:tmpOpIdentify,
tradeOrderNum:orderId
};
var stringStr = JSON.stringify(cipherParams);
var ciphertext = cryptoJS.TripleDES.encrypt(stringStr, keyHex, { iv: ivHex }).toString();
var cipherData=encodeURIComponent(ciphertext);
var putItem={
id:item.id,
cipherData:cipherData
};
await self.profitcenterDao.update(putItem,t);
return {code:1,msg:"ok"};
});
}
//提现申请发放
async setWithdrawMoney(user){
var self=this;
let keyHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey);
let ivHex = cryptoJS.enc.Utf8.parse(self.bossWithdrawApplyingKey.substring(0,8));
var resultSucceed=0;
var resultFailure=0;
var resultTotal=0;
//申请记录
var sql="select `id`,`app_id`,`user_id`,`account_id`,`userName`,`nickName`,`opAppId`,`opUserId`,`opUserName`,`opNickName`,`opType`,`totalSum`,`identityCard`,`cardNo`,`realName`,`cipherData`,`signData`,`opIdentify`,`tradeOrderNum` from h_profitcenter where opType=:opType";
var applyingData= await self.profitcenterDao.customQuery(sql,{opType:"applying"});
resultTotal=applyingData.length;
if(applyingData==null||resultTotal<=0){
return {code:-210,msg:"要发放的数据为空,无需发放",total:resultTotal,succeed:resultSucceed,failure:resultFailure};
}
for (let i = 0; i < resultTotal; i++) {
var executeResult=null;
var tmpItem=applyingData[i];
if(tmpItem!=null){
if(tmpItem.cipherData==null||tmpItem.cipherData==""){
continue;
}
try {
executeResult= await self.db.transaction(async function (t){
var cipherDataStr=decodeURIComponent(tmpItem.cipherData);
var bytes = cryptoJS.TripleDES.decrypt(cipherDataStr, keyHex, {
iv: ivHex
});
var plaintext = bytes.toString(cryptoJS.enc.Utf8);
var tmpResult=JSON.parse(plaintext);
var tmpItemTotalSum= parseFloat(tmpItem.totalSum);
// console.log("tmpResult--------------------------------------->>>>>>>>>>>>>>");
// console.log(tmpResult);
// console.log("tmpItem**********************************************>>>>>>>>>>>>>>");
// console.log(tmpItem);
if(tmpResult.id!=tmpItem.id||tmpResult.app_id!=tmpItem.app_id||tmpResult.user_id!=tmpItem.user_id||tmpResult.opType!=tmpItem.opType
||tmpResult.totalSum!=tmpItemTotalSum||tmpResult.identityCard!=tmpItem.identityCard||tmpResult.cardNo!=tmpItem.cardNo
||tmpResult.realName!=tmpItem.realName||tmpResult.account_id!=tmpItem.account_id||tmpResult.opIdentify!=tmpItem.opIdentify
||tmpResult.tradeOrderNum!=tmpItem.tradeOrderNum){
return {code:-210,msg:"数据信息解析有误,请您联系技术"};
}
//是否配置pconfig提现限制,如果配置则验证限制规则
var pconfig=await self.cacheManager["PConfigCache"].cachePConfig();
if(pconfig!=null&&pconfig!="undefined"&&pconfig.length>0){
var resultPconfig= pconfig.find(item => {
return item.configType === "withdrawalLimit";
});
if(resultPconfig!=null){
var pconfigTxXz=parseFloat(resultPconfig.configValue);
if(pconfigTxXz==0){
return {code:-220,msg:"目前该系统提现申请发放故障,敬请期待!"};
}
if(pconfigTxXz>0&&tmpResult.totalSum>pconfigTxXz){
return {code:-230,msg:"提现金额大于单笔交易额度,单笔最大交易额度为"+pconfigTxXz};
}
}
}//提现申请发放额度有限制
//平台帐户判断,平台现金在提报时利润已经分配处理完毕,在此不用进行处理
//用户帐户判断
var aid=tmpResult.account_id;
var userAccountInfo=await self.accountDao.findById(aid);
// console.log("用户-------------------------------------------------------------");
// console.log(userAccountInfo);
if(userAccountInfo==null){
return {code:-240,msg:"用户信息有误"};
}
var userAmount=userAccountInfo.renBalance-tmpResult.totalSum;
if(userAmount<0){
return {code:-250,msg:"用户帐户金额不足"};
}
//用户帐户更新
await self.accountDao.update({renBalance:userAmount,id:aid},t);
var tmpDate=new Date();
var tradeLog={app_id:tmpItem.app_id,
account_id:tmpItem.account_id,
user_id:tmpItem.user_id,
username:tmpItem.userName,
nickName:tmpItem.nickName,
renAmount:-tmpResult.totalSum,
remark:"用户提现申请发放操作",
tradeDate:tmpDate,
tradeType:"cashWithdrawal",
status:"unSettle"
};
//用户添加交易记录
var addTradeLog = await self.dao.model.create(tradeLog,t);
// 平台现金在提报时利润已经分配处理完毕,在此不用进行处理
var tmpOpIdentify= await self.getCreateUUId("ff");
var putItem={
id:tmpResult.id,
opType:"issued",
opAppId:user.app_id,
opUserId:user.user_id,
opUserName:user.userName,
opNickName:user.nickName,
opIdentify:tmpOpIdentify
};
//更改提现申请状态
await self.profitcenterDao.update(putItem,t);
//发放操作
self.withdrawMoneySve(tmpResult.tradeOrderNum,tmpResult.totalSum,tmpResult.realName,tmpResult.cardNo,tmpResult.identityCard,tmpResult.id,tmpResult.app_id);
resultSucceed=resultSucceed+1;
return {code:1,msg:"ok"}
}); //处理发放逻辑----------结束
} catch (e) {
return {code:-200,msg:e.message};
}
// console.log("-------------------------------------------------------executeResult");
// console.log(executeResult);
if(executeResult.code!=1){
resultFailure=resultFailure+1;
var stringStr = JSON.stringify(tmpItem);
//日志记录
logCtl.error({
optitle:"提现申请发放现金异常,openid="+obj.openid+",onlycode="+obj.onlycode,
op:"base/service/impl/tradeSve/setWithdrawMoney",
content:"返回参数code="+executeResult.code+",msg="+executeResult.msg+"tmpItem@@="+stringStr,
clientIp:""
});
}
}
}
return {code:1,msg:"ok",total:resultTotal,succeed:resultSucceed,failure:resultFailure};
}
//提现Api,交易订单号、交易金额、真实姓名、银行卡号、身份证号、用户id、平台id
async withdrawMoneySve(orderId,reqAmount,reqRealName,reqCardNo,reqIdentityCard,userId,appId){
let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
let appKey=this.yunzhanghuAppKey;
var tmpData={
order_id:orderId,
dealer_id:this.yunzhanghuDealer_id,
broker_id:this.yunzhanghuBroker_id,
real_name: reqRealName,//开户人
card_no: reqCardNo,//银行卡
phone_no:"",
id_card: reqIdentityCard,//身份证号
pay:reqAmount.toString(),
anchor_id: "",
notes: userId+"_"+appId,//用户id_用户平台id
pay_remark: "",
notify_url: this.yunzhanghuCallbackApiUrl
};
//data加密
var cipherDataStr=JSON.stringify(tmpData);
var cipherData=cryptoJS.TripleDES.encrypt(cipherDataStr, keyHex, { iv: ivHex }).toString();
var tmpMess=Math.round(Math.random()*100000);
var tmpTimestamp=parseInt(Date.now() / 1000);
var tmp_sign_type="sha256";
var tmpSign={
data:cipherData,
mess:tmpMess,
timestamp:tmpTimestamp,
key:appKey
};
var signContent="data="+cipherData+"&mess="+tmpMess+"&timestamp="+tmpTimestamp+"&key="+appKey;
var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');
var reqData={
data:cipherData,
mess:tmpMess,
timestamp:tmpTimestamp,
sign:tmpSign,
sign_type:tmp_sign_type
};
var ttReqData=querystring.stringify(reqData);
//日志记录
logCtl.info({
optitle:"提现Api->info",
op:"base/service/impl/tradeSve/withdrawMoneySve",
content:"提现=>info:请求参数待加密字符串cipherDataStr="+cipherDataStr+",api-ttReqData==::"+ttReqData,
clientIp:""
});
var rc=system.getObject("util.restClient");
var rtn=await rc.execPost3(ttReqData,this.yunzhanghuApiUrl);
var apiResult=JSON.parse(rtn.stdout);
if(apiResult.code!="0000"){
//日志记录
logCtl.info({
optitle:"提现Api->info返回异常:",
op:"base/service/impl/tradeSve/withdrawMoneySve",
content:"提现=>info:请求参数待加密字符串cipherDataStr="+cipherDataStr+",api-ttReqData==::"+ttReqData+",ResultCode="+apiResult.code+",ResultStdout="+rtn.stdout,
clientIp:""
});
//提现api接口错误
return {code:-100,msg:apiResult.code,data:rtn.stdout};
}
return {code:1,msg:"ok",data:null};
}
//查看商户余额
async getBankCardInfo(){
let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
let appKey=this.yunzhanghuAppKey;
var tmpData={
dealer_id:this.yunzhanghuDealer_id,
};
//data加密
var cipherDataStr=JSON.stringify(tmpData);
var cipherData=cryptoJS.TripleDES.encrypt(cipherDataStr, keyHex, { iv: ivHex }).toString();
var tmpMess=Math.round(Math.random()*100000);
var tmpTimestamp=parseInt(Date.now() / 1000);
var tmp_sign_type="sha256";
var tmpSign={
data:cipherData,
mess:tmpMess,
timestamp:tmpTimestamp,
key:appKey
};
var signContent="data="+cipherData+"&mess="+tmpMess+"&timestamp="+tmpTimestamp+"&key="+appKey;
var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');
var reqDataInfo="\\?mess\\="+tmpMess+"\\&sign_type\\="+tmp_sign_type+"\\&timestamp\\="+tmpTimestamp+"\\&data\\="+encodeURIComponent(cipherData)+"\\&sign\\="+tmpSign;
//日志记录
logCtl.info({
optitle:"查看商户余额Api->info",
op:"base/service/impl/tradeSve/getBankCardInfo",
content:"提现=>info:请求参数待加密字符串cipherDataStr="+cipherDataStr+",api-reqDataInfo="+reqDataInfo,
clientIp:""
});
var rc=system.getObject("util.restClient");
var rtn=await rc.execGet3(this.yunzhanghuQueryAccountsUrl+reqDataInfo);//this.yunzhanghuApiUrl
var apiResult=JSON.parse(rtn.stdout);
if(apiResult.code!="0000"){
//日志记录
logCtl.error({
optitle:"查看商户余额返回值异常Api->info",
op:"base/service/impl/tradeSve/getBankCardInfo",
content:"提现=>info:请求参数待加密字符串cipherDataStr="+cipherDataStr+",api-reqDataInfo="+reqDataInfo+",ResultCode="+apiResult.code+",ResultStdout="+rtn.stdout,
clientIp:""
});
//提现api接口错误
return {code:-100,msg:apiResult.code,data:rtn.stdout};
}
return {code:1,msg:apiResult.data.dealer_infos[0].bank_card_balance,data:apiResult.data.dealer_infos};
}
//验证银行卡有效性
async verifyBankcard(cardNo,idCard,realName){//卡号、身份证、开户姓名
let keyHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey);
let ivHex = cryptoJS.enc.Utf8.parse(this.yunzhanghuDESKey.substring(0,8));
let appKey=this.yunzhanghuAppKey;
var tmpData={
card_no:cardNo,
id_card:idCard,
real_name:realName
};
//data加密
var cipherDataStr=JSON.stringify(tmpData);
var cipherData=cryptoJS.TripleDES.encrypt(cipherDataStr, keyHex, { iv: ivHex }).toString();
var tmpMess=Math.round(Math.random()*100000);
var tmpTimestamp=parseInt(Date.now() / 1000);
var tmp_sign_type="sha256";
var tmpSign={
data:cipherData,
mess:tmpMess,
timestamp:tmpTimestamp,
key:appKey
};
var signContent="data="+cipherData+"&mess="+tmpMess+"&timestamp="+tmpTimestamp+"&key="+appKey;
var tmpSign=crypto.createHmac(tmp_sign_type,appKey).update(signContent).digest('hex');
var reqData={
data:cipherData,
mess:tmpMess,
timestamp:tmpTimestamp,
sign:tmpSign,
sign_type:tmp_sign_type
};
var ttReqData=querystring.stringify(reqData);
//日志记录
logCtl.info({
optitle:"验证银行卡有效性信息info",
op:"base/service/impl/tradeSve/verifyBankcard",
content:"请求参数cipherDataStr待加密="+cipherDataStr+",api-ttReqData="+ttReqData,
clientIp:""
});
var rc=system.getObject("util.restClient");
var rtn=await rc.execPost3(ttReqData,this.yunzhanghuVerifyBankCardUrl);
var apiResult=JSON.parse(rtn.stdout);
if(apiResult.code!="0000"){
//日志记录
logCtl.error({
optitle:"验证银行卡有效性信息info",
op:"base/service/impl/tradeSve/verifyBankcard",
content:"请求参数cipherDataStr待加密="+cipherDataStr+",api-ttReqData="+ttReqData+",ResultCode="+apiResult.code+",ResultStdout="+rtn.stdout,
clientIp:""
});
//提现api接口错误
return {code:-100,msg:apiResult.code,data:rtn.stdout};
}
return {code:1,msg:"ok",data:null};
}
}
module.exports=TradeService;
const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class UploadService extends ServiceBase{
constructor(){
super("common",ServiceBase.getDaoName(UploadService));
//this.appDao=system.getObject("db.appDao");
}
}
module.exports=UploadService;
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